wrapper_flipro.cpp 52.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
/*
Make the extension with:
python setup.py build_ext --inplace

Test the extension:
python test_wrapper_flipro.py

 */

#include "wrapper_flipro.h"

// ===================================================================================
// ===================================================================================
// === all devices
// ===================================================================================
// ===================================================================================

/// <summary>
/// Extract argc, **argv from a char* cmd. Use free_argv after using this function.
/// </summary>
/// <param name="cmd">The input string to extract words</param>
/// <param name="pargv">The pointer of **argv</param>
/// <returns>argc</returns>
/// <example>
/// int argc;
/// char **argv = NULL;
/// argc = get_argv(cmd, &argv);
/// </example>
int get_argv(char *cmd, char ***pargv) {
   int argc = 0;
   char str[1024];

   // === Compute argc
   strcpy(str, cmd);
   char* token = strtok(str, " ");
   while (token != NULL) {
      token = strtok(NULL, " ");
      argc++;
   }

   // === Alloc argv
   char **argv = NULL;
   argv = (char **)malloc(argc * sizeof(char));
   *pargv = (char **)argv;
   argc = 0;

   // === Compute argv
   strcpy(str, cmd);
   token = strtok(str, " ");
   while (token != NULL) {
      argv[argc] = (char *)malloc((strlen(token)+2) * sizeof(char));
      //printf("STEP 220-%d argv = %p\n", argc, argv[argc]);
      strcpy(argv[argc], token);
      token = strtok(NULL, " ");
      argc++;
   }
   return argc;
}

/// <summary>
/// Free memory of the **argv array.
/// </summary>
/// <param name="argc">The number of elements of pargv</param>
/// <param name="pargv">The pointer of **argv</param>
/// <example>
/// free_argv(argc, &argv);
/// </example>
void free_argv(int argc, char ***pargv) {
   char **argv;
   argv = *pargv;
   for (int k=0 ; k<argc ; k++) {
      //printf("===> argv[%d] = %s\n", k, argv[k]);
      free(argv[k]);
   }
   free(argv);
}

PyObject *set_np_array2d(int nd, int w, int h, int typenum, void *p) {
    npy_intp dims[2];
    dims[0] = w;
    dims[1] = h;
    return PyArray_SimpleNewFromData(nd, dims, typenum, p);
}

float *calloc_pf(size_t nmemb, size_t size) {
    if (pf != NULL) {
        free(pf);
        pf = NULL;
    }
    pf = (float*)calloc(nmemb, size);
    if (pf == NULL) {
        PyErr_SetString(exampleException, "Pointer pf not allocated");
        return NULL;
    }
    return pf;
}

void dict_append_d(PyObject* dico, const char* key, int value, const char* comment) {
    PyObject *mylist;
    mylist = PyList_New(2);
    PyList_SetItem(mylist, 0, Py_BuildValue("i", value));
    PyList_SetItem(mylist, 1, Py_BuildValue("s", comment));
    PyDict_SetItemString(dico, key, mylist);
    Py_DECREF(mylist);
}

void dict_append_s(PyObject* dico, const char* key, wchar_t *value, const char* comment) {
    int nline = 10000;
    char line[10000];
    wcstombs(line, value, nline);
    PyObject *mylist;
    mylist = PyList_New(2);
    PyList_SetItem(mylist, 0, Py_BuildValue("s", line));
    PyList_SetItem(mylist, 1, Py_BuildValue("s", comment));
    PyDict_SetItemString(dico, key, mylist);
    Py_DECREF(mylist);
}

// ===================================================================================
// ===================================================================================
// === camera devices
// ===================================================================================
// ===================================================================================

void* malloc_camheaders(void) {
    // on appelle cam_specific_header pour completer eventuellement le header par des infos propres a cette camera.
    if (cam.camheaders==NULL) {
        cam.nheadercard = 50;
        cam.camheaders = (struct CamHeader*)malloc(cam.nheadercard*sizeof(struct CamHeader));
        for (int kkey=0; kkey<cam.nheadercard; kkey++) {
            strcpy(cam.camheaders[kkey].key,"");
            strcpy(cam.camheaders[kkey].value,"");
            strcpy(cam.camheaders[kkey].type_value,"");
            strcpy(cam.camheaders[kkey].comment,"");
            strcpy(cam.camheaders[kkey].unit,"");                  
        }
    }
    return &cam.camheaders;
}

PyObject* fill_camheaders(void) {
    PyObject *pyheadert=NULL, *pyheaders;
    pyheaders = PyList_New(0);
    if (cam.camheaders==NULL) {
        return pyheaders;
    }
    // --- Fill the C structure
    cam_specific_header(&cam);
    // --- Convert C into PyObject
    for (int kkey=0; kkey<cam.nheadercard; kkey++) {
        if (strcmp(cam.camheaders[kkey].key,"")==0) {
            continue;
        }
        if (strcmp(cam.camheaders[kkey].type_value,"int")==0) {
            int val = atoi(cam.camheaders[kkey].value);
            pyheadert = Py_BuildValue("(sisss)", cam.camheaders[kkey].key, val, cam.camheaders[kkey].type_value, cam.camheaders[kkey].comment, cam.camheaders[kkey].unit);
        } else if (strcmp(cam.camheaders[kkey].type_value,"float")==0) {
            float val = (float)atof(cam.camheaders[kkey].value);
            pyheadert = Py_BuildValue("(sfsss)", cam.camheaders[kkey].key, val, cam.camheaders[kkey].type_value, cam.camheaders[kkey].comment, cam.camheaders[kkey].unit);
        } else if (strcmp(cam.camheaders[kkey].type_value,"double")==0) {
            double val = atof(cam.camheaders[kkey].value);
            pyheadert = Py_BuildValue("(sdsss)", cam.camheaders[kkey].key, val, cam.camheaders[kkey].type_value, cam.camheaders[kkey].comment, cam.camheaders[kkey].unit);
        } else {
            pyheadert = Py_BuildValue("(sssss)", cam.camheaders[kkey].key, cam.camheaders[kkey].value, cam.camheaders[kkey].type_value, cam.camheaders[kkey].comment, cam.camheaders[kkey].unit);
        }
        PyList_Append(pyheaders, pyheadert);
    }
    Py_XDECREF(pyheadert);
    return pyheaders;
}

void free_camheaders(void) {
    if (cam.camheaders!=NULL) {
        free(cam.camheaders);
    }
    cam.camheaders=NULL;
}

PyObject* append_camheaders(const char* key, void *val, const char *type_value, const char *comment, const char *unit) {
    PyObject *pyheader;
    // --- Convert C into PyObject
    if (strcmp(type_value,"int")==0) {
        int *value = (int*)val;
        pyheader = Py_BuildValue("(sisss)", key, *value, type_value, comment, unit);
    } else if (strcmp(type_value,"float")==0) {
        float *value = (float*)val;
        pyheader = Py_BuildValue("(sfsss)", key, *value, type_value, comment, unit);
    } else if (strcmp(type_value,"double")==0) {
        double *value = (double*)val;
        pyheader = Py_BuildValue("(sdsss)", key, *value, type_value, comment, unit);
    } else {
        pyheader = Py_BuildValue("(sssss)", key, val, type_value, comment, unit);
    }
    return pyheader;
}

// =====================================================================
// =====================================================================
// Internal functions
// =====================================================================
// =====================================================================

void isotime(char *iso) 
{
    char iso0[BUFFER_TIME_SIZE];
    struct timespec now;
    timespec_get( &now, TIME_UTC );
    strftime( iso0, BUFFER_TIME_SIZE, "%FT%T", gmtime( &now.tv_sec ) );
    sprintf(iso, "%s.%09ld", iso0, now.tv_nsec);
    iso[23] = '\0'; // ms
}

PyObject* ExplainMode(int ii)
{
    int32_t iResult = 0;
    uint32_t     uiModeCount;
    FPROSENSMODE modeInfo;
    uint32_t     i,i1,i2;

    // Get the numer of available modes and the current mode setting (index)
    uiModeCount = cam_get_total_mode(&cam);
    if (uiModeCount < 0) {
        PyErr_SetString(exampleException, "FPROSensor_GetModeCount result is negative; check camera is functional");
        return NULL;
    }

    if (ii >= 0) {
        i1 = (uint32_t)(ii);
        i2 = (uint32_t)(ii+1);
    }
    else {
        i1 = (uint32_t)(0);
        i2 = (uint32_t)(uiModeCount);
    }

    PyObject *mylists;
    mylists = PyList_New(0);
    PyObject *dico;
    dico = PyDict_New();
    PyObject *mylist;
    mylist = PyList_New(2);

    for (i = i1 ; (i < i2) && (iResult >= 0) ; ++i)
    {
        iResult = FPROSensor_GetMode(cam.s_iDeviceHandle, i, &modeInfo);
        //
        PyList_SetItem(mylist, 0, Py_BuildValue("i", modeInfo.uiModeIndex));
        PyList_SetItem(mylist, 1, Py_BuildValue("s", "The corresponding index of the mode name"));
        PyDict_SetItemString(dico, "uiModeIndex", mylist);
        //
        PyList_SetItem(mylist, 0, Py_BuildValue("s", modeInfo.wcModeName));
        PyList_SetItem(mylist, 1, Py_BuildValue("s", "A descriptive human readable name for the mode suitable for a user interface"));
        PyDict_SetItemString(dico, "wcModeName", mylist);
        
        PyList_Append(mylists, mylist);
    }
    Py_DECREF(dico);
    Py_DECREF(mylist);
    return Py_BuildValue("O", mylists);
}

// =====================================================================
// =====================================================================
// Python extension - Common functions
// =====================================================================
// =====================================================================

static PyObject* init(PyObject* self, PyObject* args) {
    char cmd[1024];
    strcpy(cmd, "");
    int argc = (int)PyTuple_GET_SIZE(args);
    if (argc > 1) {
        // TODO
    }
    char **argv;
    argc = get_argv(cmd, &argv);
    int res = cam_init(&cam, argc, (const char **)argv);
    if (res != 0) {
        PyErr_SetString(exampleException, cam.msg);
        return NULL;
    }
    free_argv(argc, &argv);
    pycam_state = PYCAM_IDLE;
    timer = -1;
    pf = NULL;
    return PyLong_FromLong( res );
}

static PyObject* close(PyObject* self, PyObject* args) {
    int res = cam_close(&cam);
    pycam_state = PYCAM_UNCONNECTED;
    return PyLong_FromLong( res );
}

static PyObject* update_window(PyObject* self, PyObject* args) {
    int x1, y1, x2, y2;
    if (PyTuple_GET_SIZE(args) >= 4) {
        if ( ! PyArg_ParseTuple(args, "iiii", &x1, &y1, &x2, &y2) ) return NULL;
        cam.x1 = x1;
        cam.y1 = y1;
        cam.x2 = x2;
        cam.y2 = y2;
        cam_update_window(&cam);
    }
    return Py_BuildValue("iiii", &cam.x1, &cam.y1, &cam.x2, &cam.y2);
}

static PyObject* bin(PyObject* self, PyObject* args) {
    int binx, biny;
    if (PyTuple_GET_SIZE(args) > 1) {
        if ( ! PyArg_ParseTuple(args, "ii", &binx, &biny) ) return NULL;
        cam_set_binning(binx, biny, &cam);
    }
    return Py_BuildValue("(ii)", cam.binx, cam.biny);
}

static PyObject* exptime(PyObject* self, PyObject* args) {
    double exptime = cam.exptime;
    if (PyTuple_GET_SIZE(args) > 0) {
        if ( ! PyArg_ParseTuple(args, "d", &exptime) ) return NULL;
        cam.exptime = (float)exptime;
    }
    return Py_BuildValue("d", cam.exptime);
}

static PyObject* stop_exp(PyObject* self, PyObject* args) {
    if (pycam_state == PYCAM_ACQ) {
        cam_stop_exp(&cam);
        timer = -1;
        pycam_state = PYCAM_STOPED;
    }
    return Py_BuildValue("s", NULL );
}

static PyObject* start_exp(PyObject* self, PyObject* args) {
    if (pycam_state == PYCAM_IDLE) {
        cam_start_exp(&cam, "off");
        pycam_state = PYCAM_ACQ;
        isotime(cam.date_obs);
        timer = cam.exptime;
        //clock_t0 = clock();
        timespec_get( &clock_t0, TIME_UTC );
    }
    return Py_BuildValue("s", NULL );
}

static PyObject* Date(PyObject* self, PyObject* args) {
    char iso[BUFFER_TIME_SIZE];
    isotime(iso);
    return Py_BuildValue("s", iso);
}

static PyObject* Timer(PyObject* self, PyObject* args) {
    if (timer >=0) {
        //clock_t clock_tt = clock();
        //printf("clock_tt=%ld clock_t0=%ld CLOCKS_PER_SEC=%lu dt=%f\n",clock_tt,clock_t0, CLOCKS_PER_SEC, (double)(clock_tt - clock_t0) / CLOCKS_PER_SEC);
        //timer = cam.exptime - (double)(clock_tt - clock_t0) / CLOCKS_PER_SEC;
        struct timespec clock_t;
        timespec_get( &clock_t, TIME_UTC );
        double dt = (double)(clock_t.tv_sec-clock_t0.tv_sec) + (double)(clock_t.tv_nsec-clock_t0.tv_nsec)/1e9;
        timer = cam.exptime - dt;
        if (timer < 0) {
            timer = -1;
        }
    }
    return Py_BuildValue("d", timer );
}

static PyObject* read_ccd(PyObject* self, PyObject* args) {
    pycam_state = PYCAM_READ;
    calloc_pf(cam.h*cam.w, sizeof(float));
    // --- call the read
    cam_read_ccd(&cam, pf);
    // --- fill the header
    malloc_camheaders();
    PyObject *pyheaders;
    pyheaders = fill_camheaders();
    free_camheaders();
    // --- C pointer pf -> numpy.array
    PyObject *aout = set_np_array2d(2, cam.w, cam.h, NPY_FLOAT, pf);
    // --- Add header cards
    PyObject *pyheader;
    int vali;
    vali = 2 ; pyheader = append_camheaders("NAXIS", &vali, "int", "Number of axes", ""); PyList_Append(pyheaders, pyheader);
    vali = cam.w ; pyheader = append_camheaders("NAXIS1", &vali, "int", "Number of pixels along axis 1", ""); PyList_Append(pyheaders, pyheader);
    vali = cam.h ; pyheader = append_camheaders("NAXIS2", &vali, "int", "Number of pixels along axis 2", ""); PyList_Append(pyheaders, pyheader);
    vali = 16 ; pyheader = append_camheaders("BITPIX", &vali, "int", "Bits for a pixel", ""); PyList_Append(pyheaders, pyheader);
    pyheader = append_camheaders("DATE-PC", cam.date_obs, "string", "DATE-OBS of computer (NTP)", "ISO8601"); PyList_Append(pyheaders, pyheader);
    Py_XDECREF(pyheader);
    // --- Return the numpy.array
    PyObject* res = Py_BuildValue("OO",aout, pyheaders);
    Py_XDECREF(aout);
    Py_XDECREF(pyheaders);
    pycam_state = PYCAM_IDLE;
    return res;
}

static PyObject* shutter(PyObject* self, PyObject* args) {
    if (PyTuple_GET_SIZE(args) >= 1) {
        const char *state;
        if ( ! PyArg_ParseTuple(args, "s", &state) ) return NULL;
        if (strcmp(state, cam_shutters[0])==0) {
            cam_shutter_off(&cam);
            cam.shutterindex = 0;
        }
        else if (strcmp(state, cam_shutters[1])==0) {
            cam_shutter_synchro(&cam);
            cam.shutterindex = 1;
        }
        else if (strcmp(state, cam_shutters[2])==0) {
            cam_shutter_on(&cam);
            cam.shutterindex = 2;
        }
    }
    return Py_BuildValue("s", cam_shutters[cam.shutterindex]);
}

static PyObject* measure_temperature(PyObject* self, PyObject* args) {
    cam_measure_temperature(&cam);
    return Py_BuildValue("f", cam.temperature);
}

static PyObject* cooler(PyObject* self, PyObject* args) {
    const char *state;
    if (PyTuple_GET_SIZE(args) == 1) {
        if ( ! PyArg_ParseTuple(args, "s", &state) ) return NULL;
        if (strcmp(state, cam_coolers[0])==0) {
            cam_cooler_off(&cam);
        }
        else if (strcmp(state, cam_coolers[1])==0) {
            cam_cooler_on(&cam);
        }
        else if (strcmp(state, cam_coolers[2])==0) {
            cam_cooler_check(&cam);
            return Py_BuildValue("d", cam.check_temperature);
        }
    }
    else if (PyTuple_GET_SIZE(args) == 2) {
        double check_temperature;
        if ( ! PyArg_ParseTuple(args, "sd", &state, &check_temperature) ) return NULL;
        if (strcmp(state, cam_coolers[2])==0) {
            cam.check_temperature = check_temperature;
            cam_cooler_check(&cam);
            return Py_BuildValue("d", cam.check_temperature);
        }
    }
    return Py_BuildValue("s", cam_shutters[cam.shutterindex]);
}

// =====================================================================
// =====================================================================
// Python extension - Specific functions
// =====================================================================
// =====================================================================

#if LIB == 2
static PyObject* FingerlakesProCapabilities(PyObject* self, PyObject* args) {
    PyObject* dico = PyDict_New();
    dict_append_d(dico, "uiSize", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_NUM-1], "Size of this structure (including uiSize)");
    dict_append_d(dico, "uiCapVersion", LIB, "Version of this structure");
    dict_append_d(dico, "uiDeviceType", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_DEVICE_TYPE], "General device type- see documentation");
    dict_append_d(dico, "uiMaxPixelImageWidth", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_MAX_PIXEL_WIDTH], "Max allowed image width in pixels");
    dict_append_d(dico, "uiMaxPixelImageHeight", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_MAX_PIXEL_HEIGHT], "Max allowed image height in pixels");
    dict_append_d(dico, "uiAvailablePixelDepths", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_PIXEL_BIT_DEPTHS], "Bit is set if pixel depth allowed (lsb= pixel depth 1)");
    dict_append_d(dico, "uiBinningsTableSize", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_BINNING_TABLE_SIZE], "0= 1:1 binning only");
    dict_append_d(dico, "uiBlackLevelMax", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_BLACK_LEVEL_MAX], "Max Value Allowed");
    dict_append_d(dico, "uiBlackSunMax", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_BLACK_SUN_MAX], "Max Value Allowed");
    dict_append_d(dico, "uiLowGain", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_LOW_GAIN_TABLE_SIZE], "Number of Gain Values (Low Gain channel for low gain frame in HDR Modes)");
    dict_append_d(dico, "uiHighGain", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_HIGH_GAIN_TABLE_SIZE], "Number Of Gain Values (High Gain channel for LDR Modes)");
    dict_append_d(dico, "uiMerge", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_MERGE_REFERENCE_FRAMES_SUPPORTED], "Support of merge reference frames (0= not supported, otherwise supported)");
    dict_append_d(dico, "uiRowScanTime", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_ROW_SCAN_TIME], "Row Scan Time in nano secs (LDR)");
    dict_append_d(dico, "uiDummyPixelNum", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_ROW_REFERENCE_PIXELS], "Number of Pre and Post Row Dummy Pixels when enabled");
    dict_append_d(dico, "bScanInvertable", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_IMAGE_INVERTABLE], "False= Normal scan direction only, True= Inverse Scan Available");
    dict_append_d(dico, "uiNVStorageAvailable", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_NV_STORAGE_AVAILABLE], "Number of bytes of Non-Volatile Storage available on the camera");
    dict_append_d(dico, "uiPostFrameReferenceRows", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_FRAME_REFERENCE_ROWS], "Number of Post-Frame Reference rows available");
    dict_append_d(dico, "uiMetaDataSize", cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_META_DATA_SIZE], "Number of bytes used for the pre-frame image meta data");
    return dico;
}
#elif LIB == 1
static PyObject* FingerlakesProCapabilities(PyObject* self, PyObject* args) {
    FPROCAP s_camCapabilities = cam.s_camCapabilities;
    PyObject* dico = PyDict_New();
    dict_append_d(dico, "uiSize", s_camCapabilities.uiSize, "Size of this structure (including uiSize)");
    dict_append_d(dico, "uiCapVersion", s_camCapabilities.uiCapVersion, "Version of this structure");
    dict_append_d(dico, "uiDeviceType", s_camCapabilities.uiDeviceType, "General device type- see documentation");
    dict_append_d(dico, "uiMaxPixelImageWidth", s_camCapabilities.uiMaxPixelImageWidth, "Max allowed image width in pixels");
    dict_append_d(dico, "uiMaxPixelImageHeight", s_camCapabilities.uiMaxPixelImageHeight, "Max allowed image height in pixels");
    dict_append_d(dico, "uiAvailablePixelDepths", s_camCapabilities.uiAvailablePixelDepths, "Bit is set if pixel depth allowed (lsb= pixel depth 1)");
    dict_append_d(dico, "uiBinningsTableSize", s_camCapabilities.uiBinningsTableSize, "0= 1:1 binning only");
    dict_append_d(dico, "uiBlackLevelMax", s_camCapabilities.uiBlackLevelMax, "Max Value Allowed");
    dict_append_d(dico, "uiBlackSunMax", s_camCapabilities.uiBlackSunMax, "Max Value Allowed");
    dict_append_d(dico, "uiLowGain", s_camCapabilities.uiLowGain, "Number of Gain Values (Low Gain channel for low gain frame in HDR Modes)");
    dict_append_d(dico, "uiHighGain", s_camCapabilities.uiHighGain, "Number Of Gain Values (High Gain channel for LDR Modes)");
    dict_append_d(dico, "uiReserved", s_camCapabilities.uiReserved, "Reserved");
    dict_append_d(dico, "uiRowScanTime", s_camCapabilities.uiRowScanTime, "Row Scan Time in nano secs (LDR)");
    dict_append_d(dico, "uiDummyPixelNum", s_camCapabilities.uiDummyPixelNum, "Number of Pre and Post Row Dummy Pixels when enabled");
    dict_append_d(dico, "bHorizontalScanInvertable", s_camCapabilities.bHorizontalScanInvertable, "False= Normal scan direction only, True= Inverse Scan Available");
    dict_append_d(dico, "bVerticalScanInvertable", s_camCapabilities.bVerticalScanInvertable, "False= Normal scan direction only, True= Inverse Scan Available");
    dict_append_d(dico, "bScanInvertable", s_camCapabilities.bVerticalScanInvertable, "False= Normal scan direction only, True= Inverse Scan Available");
    dict_append_d(dico, "uiNVStorageAvailable", s_camCapabilities.uiNVStorageAvailable, "Number of bytes of Non-Volatile Storage available on the camera");
    dict_append_d(dico, "uiPostFrameReferenceRows", s_camCapabilities.uiPostFrameReferenceRows, "Number of Post-Frame Reference rows available");
    dict_append_d(dico, "uiMetaDataSize", s_camCapabilities.uiMetaDataSize, "Number of bytes used for the pre-frame image meta data");
    return dico;
}
#endif

#if LIB == 2
static PyObject* FingerlakesProDeviceInfo(PyObject* self, PyObject* args) {
    wchar_t value[DIM_WS];
    FPRODEVICEINFO s_camDeviceInfo_selected = cam.s_camDeviceInfo_selected;
    FPRODEVICEVERS device_version_info = cam.device_version_info;
    PyObject* dico = PyDict_New();
    dict_append_s(dico, "cFriendlyName", s_camDeviceInfo_selected.cFriendlyName, "Human readable friendly name of the USB device. This string along with the cSerialNo field provide a unique name for your device suitable for a user interface");
    dict_append_s(dico, "cSerialNo", s_camDeviceInfo_selected.cSerialNo, "The manufacturing serial number of the device");
    dict_append_d(dico, "uiVendorId", s_camDeviceInfo_selected.conInfo.uiVendorId, "The USB vendor ID. This field is applicable only when the eCOnnType is USB");
    dict_append_d(dico, "uiProdId", s_camDeviceInfo_selected.conInfo.uiProdId, "The USB Product ID. This field is applicable only when the eCOnnType is USB");
    if (s_camDeviceInfo_selected.conInfo.eConnType == FPROCONNECTION::FPRO_CONNECTION_USB) {
        wcscpy(value, L"USB");
    } else if (s_camDeviceInfo_selected.conInfo.eConnType == FPROCONNECTION::FPRO_CONNECTION_FIBRE) {
        wcscpy(value, L"FIBRE");
    } else {
        wcscpy(value, L"UNKNOWN");
    }
    dict_append_s(dico, "eConnType", value, "The physical connection type");
    dict_append_s(dico, "cFirmwareVersion", device_version_info.cFirmwareVersion, "Firmware version");
    dict_append_s(dico, "cFPGAVersion", device_version_info.cFPGAVersion, "FPGA version");
    dict_append_s(dico, "cControllerVersion", device_version_info.cControllerVersion, "Controller version");
    dict_append_s(dico, "cHostHardwareVersion", device_version_info.cHostHardwareVersion, "Host Hardware version");
    return dico;
}
#elif LIB == 1
static PyObject* FingerlakesProDeviceInfo(PyObject* self, PyObject* args) {
    char line[DIM_S];
    FPRODEVICEINFO s_camDeviceInfo_selected = cam.s_camDeviceInfo_selected;
    FPRODEVICEVERS device_version_info = cam.device_version_info;
    PyObject* dico = PyDict_New();
    dict_append_s(dico, "cFriendlyName", s_camDeviceInfo_selected.cFriendlyName, "Human readable friendly name of the USB device. This string along with the cSerialNo field provide a unique name for your device suitable for a user interface");
    dict_append_s(dico, "cSerialNo", s_camDeviceInfo_selected.cSerialNo, "The manufacturing serial number of the device");
    dict_append_d(dico, "uiVendorId", s_camDeviceInfo_selected.uiVendorId, "The USB vendor ID. This field is applicable only when the eCOnnType is USB");
    dict_append_d(dico, "uiProdId", s_camDeviceInfo_selected.uiProdId, "The USB Product ID. This field is applicable only when the eCOnnType is USB");
    if (s_camDeviceInfo_selected.eConnType == FPRO_CONNECTION_USB) {
        dict_append_s(dico, "eConnType", L"USB", "The physical connection type");
        strcpy(line, "The USB connection speed of the device. This field is applicable only when the eCOnnType is FPRO_CONNECTION_USB. FLI Cameras require a FPRO_USB_SUPERSPEED USB connection in order to transfer image data reliably");
        if (s_camDeviceInfo_selected.eUSBSpeed == FPRO_USB_FULLSPEED) {
            dict_append_s(dico, "eUSBSpeed", L"FULLSPEED", line);
        } else if (s_camDeviceInfo_selected.eUSBSpeed == FPRO_USB_HIGHSPEED) {
            dict_append_s(dico, "eUSBSpeed", L"HIGHSPEED", line);
        } else if (s_camDeviceInfo_selected.eUSBSpeed == FPRO_USB_SUPERSPEED) {
            dict_append_s(dico, "eUSBSpeed", L"SUPERSPEED", line);
        }
    } else if (s_camDeviceInfo_selected.eConnType == FPRO_CONNECTION_FIBRE) {
        dict_append_s(dico, "eConnType", L"FIBRE", "The physical connection type");
    }
    dict_append_s(dico, "cFirmwareVersion", device_version_info.cFirmwareVersion, "Firmware version");
    dict_append_s(dico, "cFPGAVersion", device_version_info.cFPGAVersion, "FPGA version");
    dict_append_s(dico, "cControllerVersion", device_version_info.cControllerVersion, "Controller version");
    dict_append_s(dico, "cHostHardwareVersion", device_version_info.cHostHardwareVersion, "Host Hardware version");
    return dico;
}
#endif

#if LIB == 2
static PyObject* SelectGain(PyObject* self, PyObject* args) {
    uint32_t gain_low, gain_high;
    //int32_t s_iDeviceHandle;
    //s_iDeviceHandle = cam.s_iDeviceHandle;
    if (PyTuple_GET_SIZE(args) >= 2) {
        if ( ! PyArg_ParseTuple(args, "ii", &gain_low, &gain_high) ) return NULL;
        if (gain_low < 0) {
            gain_low = 0;
        }
        if (gain_low >= cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_LOW_GAIN_TABLE_SIZE]) {
            gain_low = cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_LOW_GAIN_TABLE_SIZE] - 1;
        }
        if (gain_high < 0) {
            gain_high = 0;
        }
        if (gain_high >= cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_HIGH_GAIN_TABLE_SIZE]) {
            gain_high = cam.s_camCapabilities[(uint32_t)FPROCAPS::FPROCAP_HIGH_GAIN_TABLE_SIZE] - 1;
        }
        dev_set_gain(&cam, gain_low, gain_high);
    }
    dev_get_gain(&cam, &gain_low, &gain_high);
    return Py_BuildValue("ii", gain_low, gain_high);
}
#elif LIB == 1
static PyObject* SelectGain(PyObject* self, PyObject* args) {
    uint32_t gain_low, gain_high;
    int32_t s_iDeviceHandle;
    FPROCAP s_camCapabilities = cam.s_camCapabilities;
    s_iDeviceHandle = cam.s_iDeviceHandle;
    if (PyTuple_GET_SIZE(args) >= 2) {
        if ( ! PyArg_ParseTuple(args, "ii", &gain_low, &gain_high) ) return NULL;
        if (gain_low < 0) {
            gain_low = 0;
        }
        if (gain_low >= s_camCapabilities.uiLowGain) {
            gain_low = s_camCapabilities.uiLowGain - 1;
        }
        if (gain_high < 0) {
            gain_high = 0;
        }
        if (gain_high >= s_camCapabilities.uiHighGain) {
            gain_high = s_camCapabilities.uiHighGain - 1;
        }
        FPROSensor_SetGainIndex(s_iDeviceHandle, FPRO_GAIN_TABLE_LOW_CHANNEL, gain_low);
        FPROSensor_SetGainIndex(s_iDeviceHandle, FPRO_GAIN_TABLE_HIGH_CHANNEL, gain_high);
    }
    FPROSensor_GetGainIndex(s_iDeviceHandle, FPRO_GAIN_TABLE_LOW_CHANNEL, &gain_low);
    FPROSensor_GetGainIndex(s_iDeviceHandle, FPRO_GAIN_TABLE_HIGH_CHANNEL, &gain_high);
    dev_get_gain(&cam, &gain_low, &gain_high);
    return Py_BuildValue("ii", gain_low, gain_high);
}
#endif

#if LIB == 2
static PyObject* GPSStatus(PyObject* self, PyObject* args) {
    char ligne[DIM_S];
    int32_t s_iDeviceHandle;
    uint32_t pOption;
    FPROGPSSTATE pState;
    s_iDeviceHandle = cam.s_iDeviceHandle;
    FPROCtrl_GetGPSState(s_iDeviceHandle, &pState, &pOption);
    if (pState == FPROGPSSTATE::FPRO_GPS_NOT_DETECTED) {
        sprintf(ligne, "%d {GPS unit has not been detected by the camera}", (int)pState);
    }
    if (pState == FPROGPSSTATE::FPRO_GPS_DETECTED_NO_SAT_LOCK) {
        sprintf(ligne, "%d {GPS unit has been detected by the camera but the satellite lock has not been made}", (int)pState);
    }
    if (pState == FPROGPSSTATE::FPRO_GPS_DETECTED_AND_SAT_LOCK) {
        sprintf(ligne, "%d {GPS unit has been detected by the camera and the satellite lock has been made. This is the only value that will provide accurate results in the Meta Data}", (int)pState);
    }
    return Py_BuildValue("s", ligne);
}
#elif LIB == 1
static PyObject* GPSStatus(PyObject* self, PyObject* args) {
    char ligne[DIM_S];
    int32_t s_iDeviceHandle;
    FPROGPSSTATE pState;
    s_iDeviceHandle = cam.s_iDeviceHandle;
    FPROCtrl_GetGPSState(s_iDeviceHandle, &pState);
    if (pState == FPRO_GPS_NOT_DETECTED) {
        sprintf(ligne, "%d {GPS unit has not been detected by the camera}", pState);
    }
    if (pState == FPRO_GPS_DETECTED_NO_SAT_LOCK) {
        sprintf(ligne, "%d {GPS unit has been detected by the camera but the satellite lock has not been made}", pState);
    }
    if (pState == FPRO_GPS_DETECTED_AND_SAT_LOCK) {
        sprintf(ligne, "%d {GPS unit has been detected by the camera and the satellite lock has been made. This is the only value that will provide accurate results in the Meta Data}", pState);
    }
    return Py_BuildValue("s", ligne);
}
#endif

static PyObject* FingerlakesProListModes(PyObject* self, PyObject* args) {
#if LIB == 1
    return ExplainMode(-1);
#else
    return Py_BuildValue("s", NULL);
#endif
}

static PyObject* FingerlakesProSetMode(PyObject* self, PyObject* args) {
    int retour = 0;
#if LIB == 1
    int32_t iResult;

    int ii = -1;
    
    if (PyTuple_GET_SIZE(args) >= 1) {
        if ( ! PyArg_ParseTuple(args, "i", &ii) ) return NULL;
    } else {
        ii = cam_get_current_mode(&cam);
    }
    
    iResult = cam_set_mode(&cam, ii);
    if (iResult == -1) cam_set_mode(&cam, 0);
    if (iResult == -1) {
        strcpy(cam.msg, "cam_set_mode problem");
        PyErr_SetString(exampleException, cam.msg);
        return NULL;
    }
    
    if (iResult == -3) {
        strcpy(cam.msg, "cam_set_mode strong problem");
        PyErr_SetString(exampleException, cam.msg);
        return NULL;
    }
    
    return ExplainMode(ii);
#endif
    return Py_BuildValue("d", retour);
}

static PyObject* SelectImage(PyObject* self, PyObject* args) {
    char ligne[DIM_S];
    const char *select;
    if (PyTuple_GET_SIZE(args) >= 1) {
        if ( ! PyArg_ParseTuple(args, "s", &select) ) return NULL;
        if (strcmp(select, "low") == 0) {
            io_buffer_change_mode(&cam, 0);
        }
        if (strcmp(select, "high") == 0) {
            io_buffer_change_mode(&cam, 1);
        }
        if (strcmp(select, "merge") == 0) {
            io_buffer_change_mode(&cam, 2);
        }
        if (strcmp(select, "all") == 0) {
            io_buffer_change_mode(&cam, 3);
        }
    }
    if (cam.selectedimage == 0) {
        strcpy(ligne, "low");
    }
    if (cam.selectedimage == 1) {
        strcpy(ligne, "high");
    }
    if (cam.selectedimage == 2) {
        strcpy(ligne, "merge");
    }
    if (cam.selectedimage == 3) {
        strcpy(ligne, "all");
    }
    return Py_BuildValue("s", ligne);
}

static PyObject* SelectShutter(PyObject* self, PyObject* args) {
    int iOpen, iOverride; // 0=false 1=true
    bool bOpen, bOverride; // 0=false 1=true
    int32_t s_iDeviceHandle;
    s_iDeviceHandle = cam.s_iDeviceHandle;
    if (PyTuple_GET_SIZE(args) >= 2) {
        if ( ! PyArg_ParseTuple(args, "ii", &iOpen, &iOverride) ) return NULL;
        if (iOpen == 0) {
            bOpen = false;
        } else {
            bOpen = true;
        }
        if (iOverride == 0) {
            bOverride = false;
        } else {
            bOverride = true;
        }
        FPROCtrl_SetShutterOverride(s_iDeviceHandle, bOverride);
        FPROCtrl_SetShutterOpen(s_iDeviceHandle, bOpen);
    }
    FPROCtrl_GetShutterOverride(s_iDeviceHandle, &bOverride);
    FPROCtrl_GetShutterOpen(s_iDeviceHandle, &bOpen);
    return Py_BuildValue("ii", (int)bOpen, (int)bOverride);
}

static PyObject* measure_temperatures(PyObject* self, PyObject* args) {
    cam_measure_temperature(&cam);
    return Py_BuildValue("fff", cam.temperature, cam.ambient_temp, cam.base_temp);
}

static PyObject* DewPower(PyObject* self, PyObject* args) {
    const char *select;
    char ligne[DIM_S];
    int32_t  iResult;
    if (PyTuple_GET_SIZE(args) >= 1) {
        if ( ! PyArg_ParseTuple(args, "i", &select) ) return NULL;
        if (strcmp(select, "?") == 0) {
            iResult = dev_get_dewpower(&cam);
            cam.antidew_power = iResult;
        } else {
            if (strcmp(select, "off") == 0) cam.antidew_power = 0;
            if (strcmp(select, "low") == 0) cam.antidew_power = 33;
            if (strcmp(select, "high") == 0) cam.antidew_power = 66;
            if (strcmp(select, "full") == 0) cam.antidew_power = 100;
            iResult = dev_set_dewpower(&cam);
        }
        snprintf(ligne, DIM_S, "FLIDewPower return %d", iResult);
        if (iResult < 0) {
            strcpy(cam.msg, "Dew power problem");
            PyErr_SetString(exampleException, cam.msg);
            return NULL;
        }
        return Py_BuildValue("s", ligne);
    }
    return Py_BuildValue("s", NULL);
}

static PyObject* ListGain(PyObject* self, PyObject* args) {
    wchar_t wline[DIM_WS];
    char line[DIM_S];
    dev_get_gaintable(&cam, wline);
    wcstombs(line, wline, DIM_S);
    return Py_BuildValue("s", line);
}

static PyObject* Merge(PyObject* self, PyObject* args) {
    /*
    Merging calibration

    1) Compute the bias for the given binning. Shutter closed
    cam1 bin {1 1}
    cam1 merge lin makebias
    acq 0 1

    2) Compute the (a,b) factors. Adapt the exposure time to obtain a mean level of 3000
    cam1 merge lin compute_ab 3800
    cam1 selectimage high
    cam1 shutter opened
    acq 0.002 1
    cam1 merge lin

    3) Search for the offset with the Moon
    cam1 selectimage merge
    cam1 merge lin applybias 3800 -3500 1 0 0
    acq 0.002 1

    Other functions 

    A1) Clear the bias effect
    cam1 merge lin clearbias

    A2) Return to the FLi merger algorithm
    cam1 merge fli

    proc makebias_kepler { {n 10} {bins 12} } {
       set bias_path "C:/Data/darkflat"
       set mirrorh [cam1 mirrorh]
       set mirrorv [cam1 mirrorv]
       set shutter [cam1 shutter]
       cam1 mirrorh 0
       cam1 mirrorv 0
       cam1 shutter closed
       set configs { {1 low} {1 high} {2 low} {2 high} }
       if {$bins==1} {
          set configs { {1 low} {1 high} }
       } elseif {$bins==2} {
          set configs { {2 low} {2 high} }
       }
       foreach config $configs {
          lassign $config bin gain
          cam1 selectimage $gain
          set name bias_bin${bin}_${gain}
          for {set k 1} {$k<=$n} {incr k} {
             console::affiche_resultat "Acq ${name}-${k}\n"
             acq 0 $bin
             saveima ${name}-${k}
          }
          console::affiche_resultat "Pile kappa sigma ${name}\n"
          ssk ${name}- ${name} $n 3
          loadima ${name}
          saveima ${bias_path}/${name}
          console::affiche_resultat "Bias final: ${bias_path}/${name}\n"
       }
       cam1 mirrorh $mirrorh
       cam1 mirrorv $mirrorv
       cam1 shutter $shutter
       loadbias_kepler
       console::affiche_resultat "Bias terminés\n"
    }

    proc loadbias_kepler { } {
       if {[cam1 name]=="Kepler-4040"} {
          set bias_path "C:/Data/darkflat"
          cam1 merge lin loadbias $bias_path
          #cam1 merge lin apply
          cam1 merge lin apply 3800 0 1 20.62 0
          cam1 selectimage merge
        }
    }

    */
    const char *algo;
    char path[DIM_S];
    char method[DIM_S];
    char ligne[DIM_S];

    // args
    PyObject* obj1=NULL;
    PyObject* obj2=NULL;
    PyObject* obj3=NULL;
    PyObject* obj4=NULL;
    PyObject* obj5=NULL;
    PyObject* obj6=NULL;
    PyObject* obj7=NULL;
    PyObject* obj8=NULL;
    PyObject* obj9=NULL;
    
    strcpy(path, ".");

    if (PyTuple_GET_SIZE(args) == 0) {
        strcpy(cam.msg, "Usage : merge algo(fli|lin) ?params?");
        PyErr_SetString(exampleException, cam.msg);
        return NULL;
    }
    if (PyTuple_GET_SIZE(args) >= 1) {
        if ( ! PyArg_ParseTuple(args, "s|OO", &algo, obj1, obj2) ) return NULL;
        // algo
        if (strcmp(algo, "fli") == 0) {
            cam.merge_algo = MERGE_ALGO_FLI;
        }
        if (strcmp(algo, "lin") == 0) {
            cam.merge_algo = MERGE_ALGO_LIN;
        }
    }
    if (cam.merge_algo == MERGE_ALGO_FLI) {
        // algo=fli
        snprintf(ligne, DIM_S, "{algo fli}");
    } else if (cam.merge_algo == MERGE_ALGO_LIN) {
        // algo=lin
        if (obj1 != NULL) {
            PyArg_ParseTuple(obj1, "s", method);
            if (strcmp(method, "makebias") == 0) {
                cam.merge_lin_mode = MERGE_LIN_MODE_MAKEBIAS; 
                io_buffer_change_mode(&cam, 2);
            }
            else if (strcmp(method, "loadbias") == 0) {
                PyArg_ParseTuple(obj2, "s", path);
                char filename[DIM_S];
                int naxis1, naxis2;
                // --- bin1_low
                sprintf(filename, "%s/bias_bin1_low.fit", path);
                img_loadfits(filename, &naxis1, &naxis2, cam.bias_low_bin1);
                if (naxis1 == 0) {
                    snprintf(ligne, DIM_S, "Usage : merge lin loadbias. The file %s does not exists.", filename);
                    PyErr_SetString(exampleException, ligne);
                    return NULL;
                }
                // --- bin1_high
                sprintf(filename, "%s/bias_bin1_high.fit", path);
                img_loadfits(filename, &naxis1, &naxis2, cam.bias_high_bin1);
                if (naxis1 == 0) {
                    snprintf(ligne, DIM_S, "Usage : merge lin loadbias. The file %s does not exists.", filename);
                    PyErr_SetString(exampleException, ligne);
                    return NULL;
                }
                // --- bin2_low
                sprintf(filename, "%s/bias_bin2_low.fit", path);
                img_loadfits(filename, &naxis1, &naxis2, cam.bias_low_bin2);
                if (naxis1 == 0) {
                    snprintf(ligne, DIM_S, "Usage : merge lin loadbias. The file %s does not exists.", filename);
                    PyErr_SetString(exampleException, ligne);
                    return NULL;
                }
                // --- bin2_high
                sprintf(filename, "%s/bias_bin2_high.fit", path);
                img_loadfits(filename, &naxis1, &naxis2, cam.bias_high_bin2);
                if (naxis1 == 0) {
                    snprintf(ligne, DIM_S, "Usage : merge lin loadbias. The file %s does not exists.", filename);
                    PyErr_SetString(exampleException, ligne);
                    return NULL;
                }
            }
            else if (strcmp(method, "compute_ab") == 0) { 
                cam.merge_lin_mode = MERGE_LIN_MODE_COMPUTEAB; 
                io_buffer_change_mode(&cam, 2);
            }
            else if (strcmp(method, "clearbias") == 0) {
                int h = cam.h;
                int w = cam.w;
                switch (cam.binx) {
                case 1:
                    delete[] cam.bias_low_bin1;
                    cam.bias_low_bin1 = new uint16_t[h * w];
                    delete[] cam.bias_high_bin1;
                    cam.bias_high_bin1 = new uint16_t[h * w];
                    break;
                case 2:
                    delete[] cam.bias_low_bin2;
                    cam.bias_low_bin2 = new uint16_t[h * w / 4];
                    delete[] cam.bias_high_bin2;
                    cam.bias_high_bin2 = new uint16_t[h * w / 4];
                }
            }
            else {
                // strcmp(method, "applybias")
                cam.merge_lin_mode = MERGE_LIN_MODE_APPLYBIAS;
                double val;
                if (obj2 != NULL) { PyArg_ParseTuple(obj2, "d", &val); cam.merge_lin_threshold = val; }
                if (obj3 != NULL) { PyArg_ParseTuple(obj3, "d", &val); cam.merge_lin_offset_bin1 = val; }
                if (obj4 != NULL) { PyArg_ParseTuple(obj4, "d", &val); cam.merge_lin_a_bin1 = val; }
                if (obj5 != NULL) { PyArg_ParseTuple(obj5, "d", &val); cam.merge_lin_b_bin1 = val; }
                if (obj6 != NULL) { PyArg_ParseTuple(obj6, "d", &val); cam.merge_lin_offset_bin2 = val; }
                if (obj7 != NULL) { PyArg_ParseTuple(obj7, "d", &val); cam.merge_lin_alpha_bin2 = val; }
                if (obj8 != NULL) { PyArg_ParseTuple(obj8, "d", &val); cam.merge_lin_a_bin2 = val; }
                if (obj9 != NULL) { PyArg_ParseTuple(obj9, "d", &val); cam.merge_lin_b_bin2 = val; }
            }
        }
        PyObject* dico = PyDict_New();
        PyDict_SetItemString(dico, "algo", Py_BuildValue("s", "lin"));
        PyDict_SetItemString(dico, "threshhold", Py_BuildValue("d", cam.merge_lin_threshold));
        PyDict_SetItemString(dico, "offset_bin1", Py_BuildValue("d", cam.merge_lin_offset_bin1));
        PyDict_SetItemString(dico, "alpha_bin1", Py_BuildValue("d", cam.merge_lin_alpha_bin1));
        PyDict_SetItemString(dico, "a_bin1", Py_BuildValue("d", cam.merge_lin_a_bin1));
        PyDict_SetItemString(dico, "b_bin1", Py_BuildValue("d", cam.merge_lin_b_bin1));
        PyDict_SetItemString(dico, "offset_bin2", Py_BuildValue("d", cam.merge_lin_offset_bin2));
        PyDict_SetItemString(dico, "alpha_bin2", Py_BuildValue("d", cam.merge_lin_alpha_bin2));
        PyDict_SetItemString(dico, "a_bin2", Py_BuildValue("d", cam.merge_lin_a_bin2));
        PyDict_SetItemString(dico, "b_bin2", Py_BuildValue("d", cam.merge_lin_b_bin2));
        return Py_BuildValue("O", dico);
    }
    return NULL;
}

static PyObject* Stream(PyObject* self, PyObject* args) {
    char ligne[DIM_S];
    int32_t  iResult;
    uint32_t uiFrameSizeBytes;
    wchar_t pRootPath[STREAMER_PATH_MAX];
    wchar_t pFilePrefix[STREAMER_PATH_MAX];
    uint32_t uiFrameCount;
    uint64_t uiFrameIntervalMS;
    FPROSTREAMSTATS streamStats;
    /* pStats:
    uint32_t            uiNumFramesReceived;
    uint64_t            uiTotalBytesReceived;
    uint64_t            uiDiskFramesWritten;
    double              dblDiskAvgMBPerSec;
    double              dblDiskPeakMBPerSec;
    double              dblOverallFramesPerSec;
    double              dblOverallMBPerSec;
    */

    swprintf(pRootPath, STREAMER_PATH_MAX, L"C:\\Data");
    swprintf(pFilePrefix, STREAMER_PATH_MAX, L"streamfli");
    uiFrameSizeBytes = FPROFrame_ComputeFrameSize(cam.s_iDeviceHandle); // Size of the frames that will be streamed.
    uiFrameCount = 10 ; // Number of frames to stream.Zero(0) == infinite
    uiFrameIntervalMS = 10; // The frame interval in milliseconds() (exposure time + delay).

    iResult = FPROFrame_StreamInitialize(cam.s_iDeviceHandle, uiFrameSizeBytes, pRootPath, pFilePrefix);
    if (iResult >= 0) {
        iResult = FPROFrame_StreamStart(cam.s_iDeviceHandle, uiFrameCount, uiFrameIntervalMS);
        if (iResult >= 0) {

            iResult = FPROFrame_StreamGetStatistics(cam.s_iDeviceHandle, &streamStats);
            while ((iResult >= 0) &&
                (!((streamStats.iStatus == FPROSTREAMERSTATUS::FPRO_STREAMER_STOPPED) && (streamStats.uiDiskFramesWritten == uiFrameCount)) || (streamStats.iStatus == FPROSTREAMERSTATUS::FPRO_STREAMER_STOPPED_ERROR))) {
                // Check the stats again- you can check as often as you like
                libcam_sleep(1000);
                iResult = FPROFrame_StreamGetStatistics(cam.s_iDeviceHandle, &streamStats);
            }

            // check the reasons for leaving the loop
            if ((iResult < 0) || (streamStats.iStatus == FPROSTREAMERSTATUS::FPRO_STREAMER_STOPPED_ERROR))
            {
                snprintf(ligne, DIM_S, "Stream Error");
                PyErr_SetString(exampleException, ligne);
                return NULL;
            }

            iResult = FPROFrame_StreamStop(cam.s_iDeviceHandle);
            if (iResult >= 0) {
                iResult = FPROFrame_StreamDeinitialize(cam.s_iDeviceHandle);
            }
        }
    }
    return Py_BuildValue("O", NULL);
}

static PyObject* Reconnect(PyObject* self, PyObject* args) {
    char ligne[DIM_S];
    dev_reconnect(&cam);
    snprintf(ligne, DIM_S, "%s", cam.msg);
    return Py_BuildValue("s", ligne);
};

static PyObject* Led(PyObject* self, PyObject* args) {
    uint32_t led_state;
    //int32_t s_iDeviceHandle;
    //s_iDeviceHandle = cam.s_iDeviceHandle;
    if (PyTuple_GET_SIZE(args) >= 1) {
        if ( ! PyArg_ParseTuple(args, "i", &led_state) ) return NULL;
        if (led_state <= 0) {
            led_state = (int32_t)dev_set_led(&cam, false);
        }
        if (led_state >= 1) {
            led_state = (int32_t)dev_set_led(&cam, true);
        }
    }
    else {
        led_state = (int32_t)dev_get_led(&cam);
    }
    return Py_BuildValue("i", led_state);
}

static PyObject* LedDuration(PyObject* self, PyObject* args) {
    // milliseconds
    const char *duration;
    char ligne[DIM_S];
    uint32_t led_duration;
    //int32_t s_iDeviceHandle;
    //s_iDeviceHandle = cam.s_iDeviceHandle;
    if (PyTuple_GET_SIZE(args) >= 1) {
        if ( ! PyArg_ParseTuple(args, "s", &duration) ) return NULL;
        if (strcmp(duration, "infinite") == 0) {
            led_duration = 0xFFFFFFFF;
        }
        else {
            led_duration = atoi(duration);
        }
        led_duration  = (int32_t)dev_set_led_duration(&cam, led_duration);
    }
    else {
        led_duration = (int32_t)dev_get_led_duration(&cam);
    }
    if (led_duration == 0xFFFFFFFF) {
        strcpy(ligne, "infinite");
        return Py_BuildValue("s", ligne);
    }
    return Py_BuildValue("i", led_duration);
}

static PyObject* Preflash(PyObject* self, PyObject* args) {
    uint32_t preflash;
    //int32_t s_iDeviceHandle;
    //s_iDeviceHandle = cam.s_iDeviceHandle;
    if (PyTuple_GET_SIZE(args) >= 1) {
        if ( ! PyArg_ParseTuple(args, "i", &preflash) ) return NULL;
        if (preflash <= 0) {
            preflash = 0;
        }
        if (preflash >= 1) {
            preflash = 1;
        }
        cam.preflash = preflash;
    }
    return Py_BuildValue("i", cam.preflash);
}

static PyObject* Library(PyObject* self, PyObject* args) {
    return Py_BuildValue("i", LIB);
}

// =====================================================================
// =====================================================================
// Python extension - Test functions
// =====================================================================
// =====================================================================

static PyObject* matrix(PyObject* self, PyObject* args) {
    int w, h;
    double v;
    printf("PyTuple_GET_SIZE(args)=%d\n", (int)PyTuple_GET_SIZE(args));
    if (PyTuple_GET_SIZE(args) >=3) {
        if ( ! PyArg_ParseTuple(args, "iid", &w, &h, &v) ) return NULL;
    }
    printf("w=%d h=%d v=%f\n", w, h, v);
    // --- C pointer
    calloc_pf(h*w, sizeof(float));
    for (int i=0; i<w*h; i++){
        pf[i] = (float)v;
    }
    // --- C pointer -> numpy.array
    int nd = 2;
    npy_intp dims[2];
    dims[0] = w;
    dims[1] = h;
    int typenum = NPY_FLOAT;
    //import_array();
    PyObject *aout;
    aout = PyArray_SimpleNewFromData(nd, dims, typenum, (void*)pf);
    // --- Return the numpy.array 
    PyObject* res = Py_BuildValue("O", aout);
    Py_XDECREF(aout);
    return res;
}

static PyObject* example2(PyObject* self, PyObject* args) {
    printf( "C/C++ code fire an exception\n" );
    
    // Levée d'une exception Python : elle sera rattrapée en Python.
    PyErr_SetString(exampleException, "Exemple de levée d'erreur en C");
    
    // On ne renvoie donc pas de valeur de retour particulière.
    return NULL;
}

// =====================================================================
// =====================================================================
// Python extension - Method definitions
// =====================================================================
// =====================================================================

static PyMethodDef functions[] = {
    // --- Common for devices
    {"init",        init,                METH_VARARGS, "Init connection of the device"},
    {"close",       close,               METH_VARARGS, "Close the connection of the device"},
    {"bin",         bin,                 METH_VARARGS, "Set/get the binning"},
    {"exptime",     exptime,             METH_VARARGS, "Set/get the exposure time (s)"},
    {"start_exp",   start_exp,           METH_VARARGS, "Start an exposure"},
    {"read_ccd",    read_ccd,            METH_VARARGS, "Read the image at the end of the exposure"},
    {"window",      update_window,       METH_VARARGS, "Set/get the window cells"},
    {"abort",       stop_exp,            METH_VARARGS, "Abort the current acquisition"},
    {"stop",        stop_exp,            METH_VARARGS, "Abort the current acquisition"},
    {"shutter",     shutter,             METH_VARARGS, "Set/get the shutter state: 'closed' or 'opened' or 'synchro'"},
    {"cooler",      cooler,              METH_VARARGS, "Set/get the cooler state: 'on' or 'off' or 'check' or 'check temperature'"},
    {"temperature", measure_temperature, METH_VARARGS, "Get the camera temperature"},
    {"timer",       Timer,               METH_VARARGS, "Get the remaining time of an acquisition (-1 means no acquisition)"},
    {"date",        Date,                METH_VARARGS, "Get current date ISO format"},
    // --- Specific for devices
    {"flicapabilities", FingerlakesProCapabilities, METH_VARARGS, "Get the FLI camera capabilities"},
    {"deviceinfo",      FingerlakesProDeviceInfo,   METH_VARARGS, "Get the FLI device informations"},
    {"selectgain",      SelectGain,                 METH_VARARGS, "Get/set low and high gains"},
    {"GPSstatus",       GPSStatus,                  METH_VARARGS, "Get the GPS status"},
    {"flimodes",        FingerlakesProListModes,    METH_VARARGS, "Get the FLI modes"},
    {"flimode",         FingerlakesProSetMode,      METH_VARARGS, "Set the FLI mode"},
    {"selectimage",     SelectImage,                METH_VARARGS, "Get/set the image selected (low, high, merge, all)"},
    {"selectshutter",   SelectShutter,              METH_VARARGS, "Get/set the shutter selected (low, high, merge, all)"},
    {"temperatures",    measure_temperatures,       METH_VARARGS, "Get the camera temperatures"},
    {"dewpower",        DewPower,                   METH_VARARGS, "Usage : FLIDewPower (? off low high full)"},
    {"listgain",        ListGain,                   METH_VARARGS, "List gains"},
    {"merge",           Merge,                      METH_VARARGS, "Merging methods and parameters"},
    {"stream",          Stream,                     METH_VARARGS, "Video stream test"},
    {"reconnect",       Reconnect,                  METH_VARARGS, "Reconnection"},
    {"led",             Led,                        METH_VARARGS, "Get/set the LED manual state"},
    {"ledduration",     LedDuration,                METH_VARARGS, "Get/set the LED duration (ms)"},
    {"preflash",        Preflash,                   METH_VARARGS, "Get/set the preflash state (use also ledduration)"},
    {"library",         Library,                    METH_VARARGS, "Get the FLI library version"},
    // --- Tests
    {"example2",    example2,            METH_VARARGS, "Une fonction levant une exception"},
    {"matrix",      matrix,              METH_VARARGS, "Create a matrix"},
    {NULL, NULL, 0, NULL}
};

// =====================================================================
// =====================================================================
// Python extension - Module definition
// =====================================================================
// =====================================================================

static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,
    "wrapper_flipro",   /* nom du module */
    NULL,         /* documentation du module, ou NULL si non proposée */
    -1,           /* -1 => état du module stocké en global */
    functions      /* Tableau des fonctions exposées */
};

// =====================================================================
// =====================================================================
// Python extension - Module initialisation
// =====================================================================
// =====================================================================

PyMODINIT_FUNC PyInit_wrapper_flipro(void) {
    // Création du module
    PyObject * module = PyModule_Create( &myModule );
    if ( module == NULL ) return NULL;

    // Création d'une instance d'exception
    exampleException = PyErr_NewException( "wrapper_flipro.error", NULL, NULL );
    Py_INCREF( exampleException );
    PyModule_AddObject( module, "error", exampleException );

    import_array(); // for numpy
    pycam_state = PYCAM_UNCONNECTED;

    // On doit renvoyer le module nouvellement créé
    return module;
}