Beispiel #1
0
Datei: emit_c.c Projekt: tbeu/lcm
/** Emit output that is common to every header file **/
static void emit_header_top(lcmgen_t *lcm, FILE *f, char *name)
{
    emit_auto_generated_warning(f);

    fprintf(f, "#include <stdint.h>\n");
    fprintf(f, "#include <stdlib.h>\n");
    fprintf(f, "#include <lcm/lcm_coretypes.h>\n");
//    fprintf(f, "#include \"%s%slcm_lib.h\"\n",
//            getopt_get_string(lcm->gopt, "cinclude"),
//            strlen(getopt_get_string(lcm->gopt, "cinclude"))>0 ? "/" : "");

    if(!getopt_get_bool(lcm->gopt, "c-no-pubsub")) {
        fprintf(f, "#include <lcm/lcm.h>\n");
    }
    if(strlen(getopt_get_string(lcm->gopt, "c-export-include"))) {
        fprintf(f, "#include \"%s%s%s\"\n",
                getopt_get_string(lcm->gopt, "cinclude"),
                strlen(getopt_get_string(lcm->gopt, "cinclude"))>0 ? "/" : "",
                getopt_get_string(lcm->gopt, "c-export-include"));
    }
    fprintf(f, "\n");

    fprintf(f, "#ifndef _%s_h\n", name);
    fprintf(f, "#define _%s_h\n", name);
    fprintf(f, "\n");

    fprintf(f, "#ifdef __cplusplus\n");
    fprintf(f, "extern \"C\" {\n");
    fprintf(f, "#endif\n");
    fprintf(f, "\n");

}
int
main (int argc, char *argv[])
{
    getopt_t *gopt = getopt_create ();
    getopt_add_bool (gopt, 'h', "help", 0, "Show this help screen");
    getopt_add_string (gopt, 'd', "device", "/dev/ttyUSB0", "Device name");
    getopt_add_int (gopt, 'b', "baud", "1000000", "Device baud rate");
    getopt_add_int (gopt, 'n', "num_servos", "6", "Number of servos");
    getopt_add_string (gopt, '\0', "status-channel", "ARM_STATUS2", "LCM status channel");
    getopt_add_string (gopt, '\0', "command-channel", "ARM_COMMAND2", "LCM command channel");

    if (!getopt_parse (gopt, argc, argv, 1) || getopt_get_bool (gopt, "help")) {
        getopt_do_usage (gopt);
        exit (-1);
    }

    arm_state_t *arm_state = arm_state_create (getopt_get_string (gopt, "device"),
                                               getopt_get_int (gopt, "baud"),
                                               getopt_get_int (gopt, "num_servos"));

    // LCM Initialization
    arm_state->lcm = lcm_create (NULL);
    arm_state->command_channel = getopt_get_string (gopt, "command-channel");
    arm_state->status_channel = getopt_get_string (gopt, "status-channel");
    if (!arm_state->lcm)
        return -1;
    dynamixel_command_list_t_subscribe (arm_state->lcm,
                                        arm_state->command_channel,
                                        command_handler,
                                        arm_state);

    pthread_create (&arm_state->status_thread, NULL, status_loop, arm_state);
    pthread_create (&arm_state->driver_thread, NULL, driver_loop, arm_state);

    // Probably not needed, given how this operates
    pthread_join (arm_state->status_thread, NULL);
    pthread_join (arm_state->driver_thread, NULL);

    // Cleanup
    arm_state_destroy (arm_state);
    getopt_destroy (gopt);
}
Beispiel #3
0
    AprilTagDetector(const std::unique_ptr<getopt_t, void(*)(getopt_t*)> &options){
        tf = tag16h5_create();
        tf->black_border = getopt_get_int(options.get(), "border");
        td = apriltag_detector_create();
        apriltag_detector_add_family(td, tf);
        show_window = getopt_get_bool(options.get(), "window");

        td->quad_decimate = getopt_get_double(options.get(), "decimate");
        td->quad_sigma = getopt_get_double(options.get(), "blur");
        td->nthreads = getopt_get_int(options.get(), "threads");
        td->debug = getopt_get_bool(options.get(), "debug");
        td->refine_edges = getopt_get_bool(options.get(), "refine-edges");
        td->refine_decode = getopt_get_bool(options.get(), "refine-decode");
        td->refine_pose = getopt_get_bool(options.get(), "refine-pose");

        quiet = getopt_get_bool(options.get(), "quiet");
        tag_size = getopt_get_double(options.get(), "size");
        tag_id = getopt_get_int(options.get(), "tag_id");
    }
Beispiel #4
0
int main(int argc, char *argv[])
{
    getopt_t *getopt = getopt_create();

    getopt_add_bool(getopt, 'h', "help", 0, "Show this help");
    getopt_add_bool(getopt, 'd', "debug", 0, "Enable debugging output (slow)");
    getopt_add_bool(getopt, 'q', "quiet", 0, "Reduce output");
    getopt_add_string(getopt, 'f', "family", "tag36h11", "Tag family to use");
    getopt_add_int(getopt, '\0', "border", "1", "Set tag family border size");
    getopt_add_int(getopt, 'i', "iters", "1", "Repeat processing on input set this many times");
    getopt_add_int(getopt, 't', "threads", "4", "Use this many CPU threads");
    getopt_add_double(getopt, 'x', "decimate", "1.0", "Decimate input image by this factor");
    getopt_add_double(getopt, 'b', "blur", "0.0", "Apply low-pass blur to input");
    getopt_add_bool(getopt, '1', "refine-decode", 0, "Spend more time trying to decode tags");
    getopt_add_bool(getopt, '2', "refine-pose", 0, "Spend more time trying to precisely localize tags");

    if (!getopt_parse(getopt, argc, argv, 1) || getopt_get_bool(getopt, "help")) {
        printf("Usage: %s [options] <input files>\n", argv[0]);
        getopt_do_usage(getopt);
        exit(0);
    }

    const zarray_t *inputs = getopt_get_extra_args(getopt);

    apriltag_family_t *tf = NULL;
    const char *famname = getopt_get_string(getopt, "family");
    if (!strcmp(famname, "tag36h11"))
        tf = tag36h11_create();
    else if (!strcmp(famname, "tag36h10"))
        tf = tag36h10_create();
    else if (!strcmp(famname, "tag36artoolkit"))
        tf = tag36artoolkit_create();
    else if (!strcmp(famname, "tag25h9"))
        tf = tag25h9_create();
    else if (!strcmp(famname, "tag25h7"))
        tf = tag25h7_create();
    else {
        printf("Unrecognized tag family name. Use e.g. \"tag36h11\".\n");
        exit(-1);
    }

    tf->black_border = getopt_get_int(getopt, "border");

    apriltag_detector_t *td = apriltag_detector_create();
    apriltag_detector_add_family(td, tf);
    td->quad_decimate = getopt_get_double(getopt, "decimate");
    td->quad_sigma = getopt_get_double(getopt, "blur");
    td->nthreads = getopt_get_int(getopt, "threads");
    td->debug = getopt_get_bool(getopt, "debug");
    td->refine_decode = getopt_get_bool(getopt, "refine-decode");
    td->refine_pose = getopt_get_bool(getopt, "refine-pose");

    int quiet = getopt_get_bool(getopt, "quiet");

    int maxiters = getopt_get_int(getopt, "iters");

    const int hamm_hist_max = 10;

    for (int iter = 0; iter < maxiters; iter++) {

        if (maxiters > 1)
            printf("iter %d / %d\n", iter + 1, maxiters);

        for (int input = 0; input < zarray_size(inputs); input++) {

            int hamm_hist[hamm_hist_max];
            memset(hamm_hist, 0, sizeof(hamm_hist));

            char *path;
            zarray_get(inputs, input, &path);
            if (!quiet)
                printf("loading %s\n", path);

            image_u8_t *im = image_u8_create_from_pnm(path);
            if (im == NULL) {
                printf("couldn't find %s\n", path);
                continue;
            }

            zarray_t *detections = apriltag_detector_detect(td, im);

            for (int i = 0; i < zarray_size(detections); i++) {
                apriltag_detection_t *det;
                zarray_get(detections, i, &det);

                if (!quiet)
                    printf("detection %3d: id (%2dx%2d)-%-4d, hamming %d, goodness %8.3f, margin %8.3f\n",
                           i, det->family->d*det->family->d, det->family->h, det->id, det->hamming, det->goodness, det->decision_margin);

                hamm_hist[det->hamming]++;

                apriltag_detection_destroy(det);
            }

            zarray_destroy(detections);


            if (!quiet) {
                timeprofile_display(td->tp);
                printf("nedges: %d, nsegments: %d, nquads: %d\n", td->nedges, td->nsegments, td->nquads);
            }

            if (!quiet)
                printf("Hamming histogram: ");

            for (int i = 0; i < hamm_hist_max; i++)
                printf("%5d", hamm_hist[i]);

            if (quiet) {
                printf("%12.3f", timeprofile_total_utime(td->tp) / 1.0E3);
            }

            printf("\n");

            image_u8_destroy(im);
        }
    }

    // don't deallocate contents of inputs; those are the argv
    apriltag_detector_destroy(td);

    tag36h11_destroy(tf);
    return 0;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
    auto options = std::unique_ptr<getopt_t, void(*)(getopt_t*)> (getopt_create(), getopt_destroy);
    // getopt_t *options = getopt_create();

    getopt_add_bool(options.get(), 'h', "help", 0, "Show this help");
    getopt_add_bool(options.get(), 'd', "debug", 0, "Enable debugging output (slow)");
    getopt_add_bool(options.get(), 'w', "window", 1, "Show the detected tags in a window");
    getopt_add_bool(options.get(), 'q', "quiet", 0, "Reduce output");
    getopt_add_int(options.get(), '\0', "border", "1", "Set tag family border size");
    getopt_add_int(options.get(), 't', "threads", "4", "Use this many CPU threads");
    getopt_add_double(options.get(), 'x', "decimate", "1.0", "Decimate input image by this factor");
    getopt_add_double(options.get(), 'b', "blur", "0.0", "Apply low-pass blur to input");
    getopt_add_bool(options.get(), '0', "refine-edges", 1, "Spend more time trying to align edges of tags");
    getopt_add_bool(options.get(), '1', "refine-decode", 0, "Spend more time trying to decode tags");
    getopt_add_bool(options.get(), '2', "refine-pose", 0, "Spend more time trying to precisely localize tags");
    getopt_add_double(options.get(), 's', "size", "0.04047", "Physical side-length of the tag (meters)");
    getopt_add_int(options.get(), 'c', "camera", "0", "Camera ID");
    getopt_add_int(options.get(), 'i', "tag_id", "-1", "Tag ID (-1 for all tags in family)");

    

    if (!getopt_parse(options.get(), argc, argv, 1) || getopt_get_bool(options.get(), "help")) {
        printf("Usage: %s [options]\n", argv[0]);
        getopt_do_usage(options.get());
        exit(0);
    }  
    AprilTagDetector tag_detector(options);
    auto lcm = std::make_shared<lcm::LCM>();

    Eigen::Matrix3d camera_matrix = Eigen::Matrix3d::Identity();
    // camera_matrix(0,0) = bot_camtrans_get_focal_length_x(mCamTransLeft);
    // camera_matrix(1,1) = bot_camtrans_get_focal_length_y(mCamTransLeft);
    // camera_matrix(0,2) = bot_camtrans_get_principal_x(mCamTransLeft);
    // camera_matrix(1,2) = bot_camtrans_get_principal_y(mCamTransLeft);
    camera_matrix(0,0) = 535.04778754;
    camera_matrix(1,1) = 533.37100256;
    camera_matrix(0,2) = 302.83654976;
    camera_matrix(1,2) = 237.69023961;

    Eigen::Vector4d distortion_coefficients(-7.74010810e-02, -1.97835565e-01, -4.47956948e-03, -5.42361499e-04);

    // camera matrix:
    // [[ 535.04778754    0.          302.83654976]
    //  [   0.          533.37100256  237.69023961]
    //  [   0.            0.            1.        ]]
    // distortion coefficients:  [ -7.74010810e-02  -1.97835565e-01  -4.47956948e-03  -5.42361499e-04
    //    9.30985112e-01]


    cv::VideoCapture capture(getopt_get_int(options.get(), "camera"));
    if (!capture.isOpened()) {
        std::cout << "Cannot open the video cam" << std::endl;
        return -1;
    }

    cv::Mat frame;
    Eigen::Isometry3d tag_to_camera = Eigen::Isometry3d::Identity();
    crazyflie_t::webcam_pos_t tag_to_camera_msg;
    while (capture.read(frame)) {
        std::vector<TagMatch> tags = tag_detector.detectTags(frame);
        if (tags.size() > 0) {
            tag_to_camera = getRelativeTransform(tags[0], camera_matrix, distortion_coefficients, tag_detector.getTagSize());
            tag_to_camera_msg = encodeWebcamPos(tag_to_camera);
            tag_to_camera_msg.frame_id = 1;
        } else {
            tag_to_camera_msg = encodeWebcamPos(tag_to_camera);
            tag_to_camera_msg.frame_id = -1;
        }
        tag_to_camera_msg.timestamp = timestamp_now();
        lcm->publish("WEBCAM_POS", &tag_to_camera_msg);
    }

    return 0;
}
Beispiel #6
0
int main(int argc, char *argv[])
{
    getopt_t *gopt = getopt_create();

    getopt_add_bool  (gopt, 'h',  "help",     0,    "Show this help");
    getopt_add_bool  (gopt, 't',  "tokenize", 0,    "Show tokenization");
    getopt_add_bool  (gopt, 'd',  "debug",    0,    "Show parsed file");
    getopt_add_bool  (gopt, 0,    "lazy",     0,    "Generate output file only if .lcm is newer");
    getopt_add_string(gopt, 0,    "package-prefix",     "",
                      "Add this package name as a prefix to the declared package");
    getopt_add_bool  (gopt, 0,  "version",    0,    "Show version information and exit");

    // we only support portable declarations now.
    // getopt_add_bool  (gopt, 0,    "warn-unsafe", 1, "Warn about unportable declarations");

    getopt_add_spacer(gopt, "**** C options ****");
    getopt_add_bool  (gopt, 'c', "c",         0,     "Emit C code");
    setup_c_options(gopt);

    getopt_add_spacer(gopt, "**** C++ options ****");
    getopt_add_bool  (gopt, 'x', "cpp",         0,     "Emit C++ code");
    setup_cpp_options(gopt);

    getopt_add_spacer(gopt, "**** Java options ****");
    getopt_add_bool  (gopt, 'j', "java",      0,     "Emit Java code");
    setup_java_options(gopt);

    getopt_add_spacer(gopt, "**** Python options ****");
    getopt_add_bool  (gopt, 'p', "python",      0,     "Emit Python code");
    setup_python_options(gopt);

    getopt_add_spacer(gopt, "**** Lua options ****");
    getopt_add_bool  (gopt, 'l', "lua",      0,     "Emit Lua code");
    setup_lua_options(gopt);

    getopt_add_spacer(gopt, "**** C#.NET options ****");
    getopt_add_bool  (gopt, 0, "csharp",      0,     "Emit C#.NET code");
    setup_csharp_options(gopt);

    if (!getopt_parse(gopt, argc, argv, 1) || getopt_get_bool(gopt,"help")) {
        printf("Usage: %s [options] <input files>\n\n", argv[0]);
        getopt_do_usage(gopt);
        return 0;
    }

    lcmgen_t *lcm = lcmgen_create();
    lcm->gopt = gopt;

    for (unsigned int i = 0; i < g_ptr_array_size(gopt->extraargs); i++) {
        char *path = (char *) g_ptr_array_index(gopt->extraargs, i);

        int res = lcmgen_handle_file(lcm, path);
        if (res)
            return res;
    }

    // If "--version" was specified, then show version information and exit.
    if (getopt_get_bool(gopt, "version")) {
      printf("lcm-gen %d.%d.%d\n", LCM_MAJOR_VERSION, LCM_MINOR_VERSION,
          LCM_MICRO_VERSION);
      return 0;
    }

    // If "-t" or "--tokenize" was specified, then show tokenization
    // information and exit.
    if (getopt_get_bool(gopt, "tokenize")) {
        return 0;
    }

    int did_something = 0;
    if (getopt_get_bool(gopt, "debug")) {
        did_something = 1;
        lcmgen_dump(lcm);
    }

    if (getopt_get_bool(gopt, "c")) {
        did_something = 1;
        if (emit_c(lcm)) {
            printf("An error occurred while emitting C code.\n");
        }
    }

    if (getopt_get_bool(gopt, "cpp")) {
        did_something = 1;
        if (emit_cpp(lcm)) {
            printf("An error occurred while emitting C++ code.\n");
        }
    }

    if (getopt_get_bool(gopt, "java")) {
        did_something = 1;
        if (emit_java(lcm)) {
            perror("An error occurred while emitting Java code.\n");
        }
    }

    if (getopt_get_bool(gopt, "python")) {
        did_something = 1;
        if (emit_python(lcm)) {
            printf("An error occurred while emitting Python code.\n");
        }
    }

    if (getopt_get_bool(gopt, "lua")) {
    	did_something = 1;
    	if (emit_lua(lcm)) {
    		printf("An error occurred while emitting Lua code.\n");
    	}
    }

    if (getopt_get_bool(gopt, "csharp")) {
        did_something = 1;
        if (emit_csharp(lcm)) {
            printf("An error occurred while emitting C#.NET code.\n");
        }
    }

    if (did_something == 0) {
        printf("No actions specified. Try --help.\n");
    }

    return 0;
}
Beispiel #7
0
static int
emit_package (lcmgen_t *lcm, _package_contents_t *pc)
{
    // create the package directory, if necessary
    char **dirs = g_strsplit (pc->name, ".", 0);
    char *pdname = build_filenamev (dirs);
    char package_dir[PATH_MAX];
    char package_dir_prefix[PATH_MAX];
    int have_package = dirs[0] != NULL;
    int write_init_py = !getopt_get_bool(lcm->gopt, "python-no-init");

    sprintf (package_dir_prefix, "%s%s", getopt_get_string(lcm->gopt, "ppath"), 
            strlen(getopt_get_string(lcm->gopt, "ppath")) > 0 ? 
            G_DIR_SEPARATOR_S : "");
    sprintf(package_dir, "%s%s%s", package_dir_prefix, pdname,
            have_package ? G_DIR_SEPARATOR_S : "");
    free (pdname);
    if (strlen (package_dir)) {
        if (! g_file_test (package_dir, G_FILE_TEST_EXISTS)) {
//            g_mkdir_with_parents (package_dir, 0755);
            mkdir_with_parents (package_dir, 0755);
        }
        if (!g_file_test (package_dir, G_FILE_TEST_IS_DIR)) {
            err ("Could not create directory %s\n", package_dir);
            return -1;
        }
    }

    // write the package __init__.py files, if necessary
    FILE *init_py_fp = NULL;
    GHashTable * init_py_imports = g_hash_table_new_full(g_str_hash, 
            g_str_equal, free, NULL);
    if (have_package && write_init_py) {
        int ndirs = 0;
        for (ndirs=0; dirs[ndirs]; ndirs++);

        for (int i=0 ; i<ndirs; i++) {
            char *initpy_fname_parts[1024];
            assert(ndirs + 4 < 1024);

            initpy_fname_parts[0] = package_dir_prefix;
            for (int j=0; j<=i; j++) {
                initpy_fname_parts[j+1] = dirs[j];
            }
            initpy_fname_parts[i+2] = "__init__.py";
            initpy_fname_parts[i+3] = NULL;

            char *initpy_fname = build_filenamev (initpy_fname_parts);
            int created_initpy = 0;

            // close init_py_fp if already open
            if(init_py_fp) {
                fclose(init_py_fp);
                init_py_fp = NULL;
            }

            if (! g_file_test (initpy_fname, G_FILE_TEST_EXISTS)) {
                // __init__.py does not exist for this package.  Create it.
                created_initpy = 1;
                init_py_fp = fopen(initpy_fname, "w");
            } else {
                // open the existing __init__.py file, and make note of the
                // modules it imports
                created_initpy = 0;
                init_py_fp = fopen(initpy_fname, "r+");
            }

            if (!init_py_fp) {
                perror ("fopen");
                free (initpy_fname);
                return -1;
            }
#ifndef WIN32
            // lock __init__.py for exclusive write access
            // TODO do the equivalent in windows
            struct flock lockinfo;
            lockinfo.l_type = F_WRLCK;
            lockinfo.l_start = 0;
            lockinfo.l_whence = SEEK_SET;
            lockinfo.l_len = 0 ;
            lockinfo.l_pid = getpid();
            if(0 != fcntl(fileno(init_py_fp), F_SETLKW, &lockinfo)) {
                perror("locking __init__.py");
                free(initpy_fname);
                fclose(init_py_fp);
                return -1;
            }
#endif

            if(created_initpy) {
                fprintf (init_py_fp, "\"\"\"LCM package __init__.py file\n"
                        "This file automatically generated by lcm-gen.\n"
                        "DO NOT MODIFY BY HAND!!!!\n"
                        "\"\"\"\n\n");
            } else {
                while(!feof(init_py_fp)) {
                    char buf[4096];
                    memset(buf, 0, sizeof(buf));
                    char *result = fgets(buf, sizeof(buf)-1, init_py_fp);
                    if(!result)
                        break;

                    g_strstrip(buf);
                    char **words = g_strsplit(buf, " ", -1);
                    if(!words[0] || !words[1] || !words[2] || !words[3])
                        continue;
                    if(!strcmp(words[0], "from") && !strcmp(words[2], "import")) {
                        char *module_name = strdup(words[1]+1); // ignore leading dot
                        g_hash_table_replace(init_py_imports, module_name, 
                                module_name);
                    }

                    g_strfreev(words);
                }
            }
            free (initpy_fname);
        }
    }
    g_strfreev (dirs);

    ////////////////////////////////////////////////////////////
    // ENUMS
    for (int i=0; i<pc->enums->len; i++) {
        lcm_enum_t *le = (lcm_enum_t *) g_ptr_array_index (pc->enums, i);

        char path[PATH_MAX];
        sprintf (path, "%s%s.py", package_dir, le->enumname->shortname);

        if(init_py_fp && 
           !g_hash_table_lookup(init_py_imports, le->enumname->shortname))
            fprintf(init_py_fp, "from .%s import %s\n", 
                    le->enumname->shortname,
                    le->enumname->shortname);

        if (!lcm_needs_generation(lcm, le->lcmfile, path))
            continue;

        FILE *f = fopen(path, "w");
        if (f==NULL) return -1;

        fprintf(f, "\"\"\"LCM type definitions\n"
                "This file automatically generated by lcm.\n"
                "DO NOT MODIFY BY HAND!!!!\n"
                "\"\"\"\n"
                "\n"
                "try:\n"
                "    import cStringIO.StringIO as BytesIO\n"
                "except ImportError:\n"
                "    from io import BytesIO\n"
                "import struct\n\n");

        // enums always encoded as int32
        emit (0, "class %s(object):", le->enumname->shortname);
        emit (1, "__slots__ = [ \"value\" ]");
        for (unsigned int v = 0; v < le->values->len; v++) {
            lcm_enum_value_t *lev = (lcm_enum_value_t *) g_ptr_array_index(le->values, v);
            emit(1, "%s = %i", lev->valuename, lev->value);
        }

        emit (1, "_packed_fingerprint = struct.pack(\">Q\", 0x%"PRIx64")",
                le->hash);
        fprintf (f, "\n");

        emit (1, "def __init__ (self, value):");
        emit (2,     "self.value = value");
        fprintf (f, "\n");

        emit (1, "def _get_hash_recursive(parents):");
        emit (2,     "return 0x%"PRIx64, le->hash);
        emit (1, "_get_hash_recursive=staticmethod(_get_hash_recursive)");
        emit (1, "def _get_packed_fingerprint():");
        emit (2,     "return %s._packed_fingerprint", le->enumname->shortname);
        emit (1, "_get_packed_fingerprint = staticmethod(_get_packed_fingerprint)");
        fprintf (f, "\n");

        emit (1, "def encode(self):");
        emit (2,     "return struct.pack(\">Qi\", 0x%"PRIx64", self.value)",
                le->hash);

        emit (1, "def _encode_one(self, buf):");
        emit (2,     "buf.write (struct.pack(\">i\", self.value))");
        fprintf (f, "\n");

        emit (1, "def decode(data):");
        emit (2,     "if hasattr (data, 'read'):");
        emit (3,         "buf = data");
        emit (2,     "else:");
        emit (3,         "buf = BytesIO(data)");
        emit (2,     "if buf.read(8) != %s._packed_fingerprint:", 
                le->enumname->shortname);
        emit (3,         "raise ValueError(\"Decode error\")");
        emit (2,     "return %s(struct.unpack(\">i\", buf.read(4))[0])",
                le->enumname->shortname);
        emit (1, "decode = staticmethod(decode)");

        emit (1, "def _decode_one(buf):");
        emit (2,     "return %s(struct.unpack(\">i\", buf.read(4))[0])",
                le->enumname->shortname);
        emit (1, "_decode_one = staticmethod(_decode_one)");

        fprintf (f, "\n");
        fclose (f);
    }

    ////////////////////////////////////////////////////////////
    // STRUCTS
    for (int i = 0; i<pc->structs->len; i++) {
        lcm_struct_t *ls = (lcm_struct_t *) g_ptr_array_index(pc->structs, i);

        char path[PATH_MAX];
        sprintf (path, "%s%s.py", package_dir, ls->structname->shortname);

        if(init_py_fp && 
           !g_hash_table_lookup(init_py_imports, ls->structname->shortname))
            fprintf(init_py_fp, "from .%s import %s\n", 
                    ls->structname->shortname,
                    ls->structname->shortname);

        if (!lcm_needs_generation(lcm, ls->lcmfile, path))
            continue;

        FILE *f = fopen(path, "w");
        if (f==NULL) return -1;

        fprintf(f, "\"\"\"LCM type definitions\n"
                "This file automatically generated by lcm.\n"
                "DO NOT MODIFY BY HAND!!!!\n"
                "\"\"\"\n"
                "\n"
                "try:\n"
                "    import cStringIO.StringIO as BytesIO\n"
                "except ImportError:\n"
                "    from io import BytesIO\n"
                "import struct\n\n");

        emit_python_dependencies (lcm, f, ls);

        fprintf(f, "class %s(object):\n", ls->structname->shortname);
        fprintf (f,"    __slots__ = [");
        for (unsigned int member = 0; member < ls->members->len; member++) {
            lcm_member_t *lm = (lcm_member_t *) g_ptr_array_index (ls->members, member);
            fprintf (f, "\"%s\"%s", lm->membername, 
                    member < ls->members->len-1 ? ", " : "");
        }
        fprintf (f, "]\n\n");

        // CONSTANTS
        for (unsigned int cn = 0; cn < g_ptr_array_size(ls->constants); cn++) {
            lcm_constant_t *lc = (lcm_constant_t *) g_ptr_array_index(ls->constants, cn);
            assert(lcm_is_legal_const_type(lc->lctypename));
            emit(1, "%s = %s", lc->membername, lc->val_str);
        }
        if (g_ptr_array_size(ls->constants) > 0)
            emit(0, "");

        emit_python_init (lcm, f, ls);
        emit_python_encode (lcm, f, ls);
        emit_python_encode_one (lcm, f, ls);
        emit_python_decode (lcm, f, ls);
        emit_python_decode_one (lcm, f, ls);
        emit_python_fingerprint (lcm, f, ls);
        fclose (f);
    }

    if(init_py_fp)
        fclose(init_py_fp);
    g_hash_table_destroy(init_py_imports);
    return 0;
}
Beispiel #8
0
int emit_java(zcmgen_t *zcm)
{
    GHashTable *type_table = g_hash_table_new(g_str_hash, g_str_equal);

    g_hash_table_insert(type_table, "byte",   prim("byte",
                                             "# = ins.readByte();",
                                             "outs.writeByte(#);"));
    g_hash_table_insert(type_table, "int8_t",   prim("byte",
                                               "# = ins.readByte();",
                                               "outs.writeByte(#);"));
    g_hash_table_insert(type_table, "int16_t",  prim("short",
                                               "# = ins.readShort();",
                                               "outs.writeShort(#);"));
    g_hash_table_insert(type_table, "int32_t",  prim("int",
                                               "# = ins.readInt();",
                                               "outs.writeInt(#);"));
    g_hash_table_insert(type_table, "int64_t",  prim("long",
                                               "# = ins.readLong();",
                                               "outs.writeLong(#);"));

    g_hash_table_insert(type_table, "string",   prim("String",
                                                     "__strbuf = new char[ins.readInt()-1]; for (int _i = 0; _i < __strbuf.length; _i++) __strbuf[_i] = (char) (ins.readByte()&0xff); ins.readByte(); # = new String(__strbuf);",
                                                     "__strbuf = new char[#.length()]; #.getChars(0, #.length(), __strbuf, 0); outs.writeInt(__strbuf.length+1); for (int _i = 0; _i < __strbuf.length; _i++) outs.write(__strbuf[_i]); outs.writeByte(0);"));

//    g_hash_table_insert(type_table, "string",   prim("String",
//                                               "__strbuf = new byte[ins.readInt()-1]; ins.readFully(__strbuf); ins.readByte(); # = new String(__strbuf, \"UTF-8\");",
//                                               "__strbuf = #.getBytes(\"UTF-8\"); outs.writeInt(__strbuf.length+1); outs.write(__strbuf, 0, __strbuf.length); outs.writeByte(0);"));

    g_hash_table_insert(type_table, "boolean",  prim("boolean",
                                               "# = ins.readByte()!=0;",
                                               "outs.writeByte( # ? 1 : 0);"));
    g_hash_table_insert(type_table, "float",    prim("float",
                                               "# = ins.readFloat();",
                                               "outs.writeFloat(#);"));
    g_hash_table_insert(type_table, "double",   prim("double",
                                               "# = ins.readDouble();",
                                               "outs.writeDouble(#);"));

    //////////////////////////////////////////////////////////////
    // ENUMS
    for (unsigned int en = 0; en < g_ptr_array_size(zcm->enums); en++) {
        zcm_enum_t *le = (zcm_enum_t *) g_ptr_array_index(zcm->enums, en);

        const char *classname = make_fqn(zcm, le->enumname->lctypename);
        char *path = g_strdup_printf("%s%s%s.java",
                                  getopt_get_string(zcm->gopt, "jpath"),
                                  strlen(getopt_get_string(zcm->gopt, "jpath")) > 0 ? G_DIR_SEPARATOR_S : "",
                                  dots_to_slashes(classname));

        if (!zcm_needs_generation(zcm, le->zcmfile, path))
            continue;

        if (getopt_get_bool(zcm->gopt, "jmkdir"))
            make_dirs_for_file(path);

        FILE *f = fopen(path, "w");
        if (f==NULL)
            return -1;

        if (strlen(le->enumname->package) > 0)
            emit(0, "package %s;", le->enumname->package);
        else
            emit(0, "package %s;", getopt_get_string(zcm->gopt, "jdefaultpkg"));

        emit(0, " ");
        emit(0, "import java.io.*;");
        emit(0, "import java.util.*;");
        emit(0, " ");

        emit(0, "public final class %s %s", le->enumname->shortname, getopt_get_string(zcm->gopt, "jdecl"));

        emit(0, "{");
        emit(1, "public int value;");
        emit(0, " ");

        for (unsigned int v = 0; v < g_ptr_array_size(le->values); v++) {
            zcm_enum_value_t *lev = (zcm_enum_value_t *) g_ptr_array_index(le->values, v);
            emit(1, "public static final int %-16s = %i;",
                    lev->valuename, lev->value);
        }
        emit(0," ");

        emit(1,"public %s(int value) { this.value = value; }",
                le->enumname->shortname);
        emit(0," ");

        emit(1,"public int getValue() { return value; }");
        emit(0," ");

        emit(1,"public void _encodeRecursive(DataOutput outs) throws IOException");
        emit(1,"{");
        emit(2,"outs.writeInt(this.value);");
        emit(1,"}");
        emit(0," ");

        emit(1,"public void encode(DataOutput outs) throws IOException");
        emit(1,"{");
        emit(2,"outs.writeLong(ZCM_FINGERPRINT);");
        emit(2,"_encodeRecursive(outs);");
        emit(1,"}");
        emit(0," ");

        emit(1,"public static %s _decodeRecursiveFactory(DataInput ins) throws IOException", make_fqn(zcm, le->enumname->lctypename));
        emit(1,"{");
        emit(2,"%s o = new %s(0);", make_fqn(zcm, le->enumname->lctypename), make_fqn(zcm, le->enumname->lctypename));
        emit(2,"o._decodeRecursive(ins);");
        emit(2,"return o;");
        emit(1,"}");
        emit(0," ");

        emit(1,"public void _decodeRecursive(DataInput ins) throws IOException");
        emit(1,"{");
        emit(2,"this.value = ins.readInt();");
        emit(1,"}");
        emit(0," ");

        emit(1,"public %s(DataInput ins) throws IOException", le->enumname->shortname);
        emit(1,"{");
        emit(2,"long hash = ins.readLong();");
        emit(2,"if (hash != ZCM_FINGERPRINT)");
        emit(3,     "throw new IOException(\"ZCM Decode error: bad fingerprint\");");
        emit(2,"_decodeRecursive(ins);");
        emit(1,"}");
        emit(0," ");

        emit(1,"public %s copy()", classname);
        emit(1,"{");
        emit(2,"return new %s(this.value);", classname);
        emit(1,"}");
        emit(0," ");

        emit(1,"public static final long _hashRecursive(ArrayList<Class<?>> clss)");
        emit(1,"{");
        emit(2,"return ZCM_FINGERPRINT;");
        emit(1,"}");
        emit(0," ");
        emit(1, "public static final long ZCM_FINGERPRINT = 0x%016"PRIx64"L;", le->hash);
        emit(0, "}");
        fclose(f);
    }

    for (unsigned int st = 0; st < g_ptr_array_size(zcm->structs); st++) {
        zcm_struct_t *lr = (zcm_struct_t *) g_ptr_array_index(zcm->structs, st);

        const char *classname = make_fqn(zcm, lr->structname->lctypename);
        char *path = g_strdup_printf("%s%s%s.java",
                                  getopt_get_string(zcm->gopt, "jpath"),
                                  strlen(getopt_get_string(zcm->gopt, "jpath")) > 0 ? G_DIR_SEPARATOR_S : "",
                                  dots_to_slashes(classname));

        if (!zcm_needs_generation(zcm, lr->zcmfile, path))
            continue;

        if (getopt_get_bool(zcm->gopt, "jmkdir"))
            make_dirs_for_file(path);

        FILE *f = fopen(path, "w");
        if (f==NULL)
            return -1;

        emit(0, "/* ZCM type definition class file\n"
                " * This file was automatically generated by zcm-gen\n"
                " * DO NOT MODIFY BY HAND!!!!\n"
                " */\n");

        if (strlen(lr->structname->package) > 0)
            emit(0, "package %s;", lr->structname->package);
        else
            emit(0, "package %s;", getopt_get_string(zcm->gopt, "jdefaultpkg"));

        emit(0, " ");
        emit(0, "import java.io.*;");

        if (0) {
            // Determine if we even need the java.nio.* package.
            int usenio = 0;
            for (unsigned int member = 0; member < g_ptr_array_size(lr->members); member++) {
                zcm_member_t *lm = (zcm_member_t *) g_ptr_array_index(lr->members, member);
                primitive_info_t *pinfo = (primitive_info_t*) g_hash_table_lookup(type_table, lm->type->lctypename);
                if (pinfo!=NULL && !strcmp(pinfo->storage, "float")) {
                    usenio = 1;
                    break;
                }
            }
            if (usenio)
                emit(0, "import java.nio.*;");
        }

        emit(0, "import java.util.*;");
        emit(0, "import zcm.zcm.*;");
        emit(0, " ");
        emit(0, "public final class %s %s", lr->structname->shortname, getopt_get_string(zcm->gopt, "jdecl"));
        emit(0, "{");

        for (unsigned int member = 0; member < g_ptr_array_size(lr->members); member++) {
            zcm_member_t *lm = (zcm_member_t *) g_ptr_array_index(lr->members, member);
            primitive_info_t *pinfo = (primitive_info_t*) g_hash_table_lookup(type_table, lm->type->lctypename);

            emit_start(1, "public ");

            if (pinfo==NULL)  {
                emit_continue("%s", make_fqn(zcm, lm->type->lctypename));
            } else {
                emit_continue("%s", pinfo->storage);
            }

            emit_continue(" %s", lm->membername);
            for (unsigned int i = 0; i < g_ptr_array_size(lm->dimensions); i++)
                emit_continue("[]");
            emit_end(";");
        }
        emit(0," ");

        // public constructor
        emit(1,"public %s()", lr->structname->shortname);
        emit(1,"{");

        // pre-allocate any fixed-size arrays.
        for (unsigned int member = 0; member < g_ptr_array_size(lr->members); member++) {
            zcm_member_t *lm = (zcm_member_t *) g_ptr_array_index(lr->members, member);
            primitive_info_t *pinfo = (primitive_info_t*) g_hash_table_lookup(type_table, lm->type->lctypename);

            if (g_ptr_array_size(lm->dimensions)==0 || !zcm_is_constant_size_array(lm))
                continue;

            emit_start(2, "%s = new ", lm->membername);
            if (pinfo != NULL)
                emit_continue("%s", pinfo->storage);
            else
                emit_continue("%s", make_fqn(zcm, lm->type->lctypename));

            for (unsigned int i = 0; i < g_ptr_array_size(lm->dimensions); i++) {
                zcm_dimension_t *dim = (zcm_dimension_t*) g_ptr_array_index(lm->dimensions, i);
                emit_continue("[%s]", dim->size);
            }
            emit_end(";");
        }
        emit(1,"}");
        emit(0," ");

        emit(1, "public static final long ZCM_FINGERPRINT;");
        emit(1, "public static final long ZCM_FINGERPRINT_BASE = 0x%016"PRIx64"L;", lr->hash);
        emit(0," ");

        //////////////////////////////////////////////////////////////
        // CONSTANTS
        for (unsigned int cn = 0; cn < g_ptr_array_size(lr->constants); cn++) {
            zcm_constant_t *lc = (zcm_constant_t *) g_ptr_array_index(lr->constants, cn);
            assert(zcm_is_legal_const_type(lc->lctypename));

            if (!strcmp(lc->lctypename, "int8_t")) {
                emit(1, "public static final byte %s = (byte) %s;", lc->membername, lc->val_str);
            } else if (!strcmp(lc->lctypename, "int16_t")) {
                emit(1, "public static final short %s = (short) %s;", lc->membername, lc->val_str);
            } else if (!strcmp(lc->lctypename, "int32_t")) {
                emit(1, "public static final int %s = %s;", lc->membername, lc->val_str);
            } else if (!strcmp(lc->lctypename, "int64_t")) {
                emit(1, "public static final long %s = %sL;", lc->membername, lc->val_str);
            } else if (!strcmp(lc->lctypename, "float")) {
                emit(1, "public static final float %s = %sf;", lc->membername, lc->val_str);
            } else if (!strcmp(lc->lctypename, "double")) {
                emit(1, "public static final double %s = %s;", lc->membername, lc->val_str);
            } else {
                assert(0);
            }
        }
        if (g_ptr_array_size(lr->constants) > 0)
            emit(0, "");

        ///////////////// compute fingerprint //////////////////
        emit(1, "static {");
        emit(2, "ZCM_FINGERPRINT = _hashRecursive(new ArrayList<Class<?>>());");
        emit(1, "}");
        emit(0, " ");

        emit(1, "public static long _hashRecursive(ArrayList<Class<?>> classes)");
        emit(1, "{");
        emit(2, "if (classes.contains(%s.class))", make_fqn(zcm, lr->structname->lctypename));
        emit(3,     "return 0L;");
        emit(0, " ");
        emit(2, "classes.add(%s.class);", make_fqn(zcm, lr->structname->lctypename));

        emit(2, "long hash = ZCM_FINGERPRINT_BASE");
        for (unsigned int member = 0; member < g_ptr_array_size(lr->members); member++) {
            zcm_member_t *lm = (zcm_member_t *) g_ptr_array_index(lr->members, member);
            primitive_info_t *pinfo = (primitive_info_t*) g_hash_table_lookup(type_table, lm->type->lctypename);

            if (pinfo)
                continue;

            emit(3, " + %s._hashRecursive(classes)", make_fqn(zcm, lm->type->lctypename));
        }
        emit(3,";");

        emit(2, "classes.remove(classes.size() - 1);");
        emit(2, "return (hash<<1) + ((hash>>63)&1);");

        emit(1, "}");
        emit(0, " ");

        ///////////////// encode //////////////////

        emit(1,"public void encode(DataOutput outs) throws IOException");
        emit(1,"{");
        emit(2,"outs.writeLong(ZCM_FINGERPRINT);");
        emit(2,"_encodeRecursive(outs);");
        emit(1,"}");
        emit(0," ");

        emit(1,"public void _encodeRecursive(DataOutput outs) throws IOException");
        emit(1,"{");
        if(struct_has_string_member(lr))
            emit(2, "char[] __strbuf = null;");
        char accessor[1024];

        for (unsigned int member = 0; member < g_ptr_array_size(lr->members); member++) {
            zcm_member_t *lm = (zcm_member_t *) g_ptr_array_index(lr->members, member);
            primitive_info_t *pinfo = (primitive_info_t*) g_hash_table_lookup(type_table, lm->type->lctypename);
            make_accessor(lm, "this", accessor);

            encode_recursive(zcm, lm, f, pinfo, accessor, 0);
            emit(0," ");
        }
        emit(1,"}");
        emit(0," ");

        ///////////////// decode //////////////////

        // decoding constructors
        emit(1, "public %s(byte[] data) throws IOException", lr->structname->shortname);
        emit(1, "{");
        emit(2, "this(new ZCMDataInputStream(data));");
        emit(1, "}");
        emit(0, " ");

        emit(1,"public %s(DataInput ins) throws IOException", lr->structname->shortname);
        emit(1,"{");
        emit(2,"if (ins.readLong() != ZCM_FINGERPRINT)");
        emit(3,     "throw new IOException(\"ZCM Decode error: bad fingerprint\");");
        emit(0," ");
        emit(2,"_decodeRecursive(ins);");
        emit(1,"}");
        emit(0," ");

        emit(1,"public static %s _decodeRecursiveFactory(DataInput ins) throws IOException", make_fqn(zcm, lr->structname->lctypename));
        emit(1,"{");
        emit(2,"%s o = new %s();", make_fqn(zcm, lr->structname->lctypename), make_fqn(zcm, lr->structname->lctypename));
        emit(2,"o._decodeRecursive(ins);");
        emit(2,"return o;");
        emit(1,"}");
        emit(0," ");

        emit(1,"public void _decodeRecursive(DataInput ins) throws IOException");
        emit(1,"{");
        if(struct_has_string_member(lr))
            emit(2, "char[] __strbuf = null;");
        for (unsigned int member = 0; member < g_ptr_array_size(lr->members); member++) {
            zcm_member_t *lm = (zcm_member_t *) g_ptr_array_index(lr->members, member);
            primitive_info_t *pinfo = (primitive_info_t*) g_hash_table_lookup(type_table, lm->type->lctypename);

            make_accessor(lm, "this", accessor);

            // allocate an array if necessary
            if (g_ptr_array_size(lm->dimensions) > 0) {

                emit_start(2, "this.%s = new ", lm->membername);

                if (pinfo != NULL)
                    emit_continue("%s", pinfo->storage);
                else
                    emit_continue("%s", make_fqn(zcm, lm->type->lctypename));

                for (unsigned int i = 0; i < g_ptr_array_size(lm->dimensions); i++) {
                    zcm_dimension_t *dim = (zcm_dimension_t*) g_ptr_array_index(lm->dimensions, i);
                    emit_continue("[(int) %s]", dim->size);
                }
                emit_end(";");
            }

            decode_recursive(zcm, lm, f, pinfo, accessor, 0);
            emit(0," ");
        }

        emit(1,"}");
        emit(0," ");


        ///////////////// copy //////////////////

        emit(1,"public %s copy()", classname);
        emit(1,"{");
        emit(2,"%s outobj = new %s();", classname, classname);

        for (unsigned int member = 0; member < g_ptr_array_size(lr->members); member++) {
            zcm_member_t *lm = (zcm_member_t *) g_ptr_array_index(lr->members, member);
            primitive_info_t *pinfo = (primitive_info_t*) g_hash_table_lookup(type_table, lm->type->lctypename);
            make_accessor(lm, "", accessor);

            // allocate an array if necessary
            if (g_ptr_array_size(lm->dimensions) > 0) {

                emit_start(2, "outobj.%s = new ", lm->membername);

                if (pinfo != NULL)
                    emit_continue("%s", pinfo->storage);
                else
                    emit_continue("%s", make_fqn(zcm, lm->type->lctypename));

                for (unsigned int i = 0; i < g_ptr_array_size(lm->dimensions); i++) {
                    zcm_dimension_t *dim = (zcm_dimension_t*) g_ptr_array_index(lm->dimensions, i);
                    emit_continue("[(int) %s]", dim->size);
                }
                emit_end(";");
            }

            copy_recursive(zcm, lm, f, pinfo, accessor, 0);
            emit(0," ");
        }

        emit(2,"return outobj;");
        emit(1,"}");
        emit(0," ");

        ////////
        emit(0, "}\n");
        fclose(f);
    }

/* XXX deallocate our storage. unfinished since memory leaks are non-critical for zcm-gen.

    hashtable_iterator_t *hit = hashtable_iterator_create(type_table);
    hashtable_entry_t *entry;
    while ((entry = hashtable_iterator_next(hit)) != NULL) {
        free((char*) entry->value);
    }
    hashtable_iterator_destroy(hit);

    hashtable_destroy(type_table);
*/
    return 0;
}
Beispiel #9
0
int main(int argc, char *argv[])
{
    getopt_t *gopt = getopt_create();

    getopt_add_bool  (gopt, 'h',  "help",     0,    "Show this help");
    getopt_add_bool  (gopt, 't',  "tokenize", 0,    "Show tokenization");
    getopt_add_bool  (gopt, 'd',  "debug",    0,    "Show parsed file");
    getopt_add_bool  (gopt, 0,    "lazy",     0,    "Generate output file only if .lcm is newer");

    // we only support portable declarations now.
    // getopt_add_bool  (gopt, 0,    "warn-unsafe", 1, "Warn about unportable declarations");

    getopt_add_spacer(gopt, "**** C options ****");
    getopt_add_bool  (gopt, 'c', "c",         0,     "Emit C code");
    setup_c_options(gopt);

    getopt_add_spacer(gopt, "**** C++ options ****");
    getopt_add_bool  (gopt, 'x', "cpp",         0,     "Emit C++ code");
    setup_cpp_options(gopt);

    getopt_add_spacer(gopt, "**** Java options ****");
    getopt_add_bool  (gopt, 'j', "java",      0,     "Emit Java code");
    setup_java_options(gopt);

    getopt_add_spacer(gopt, "**** Python options ****");
    getopt_add_bool  (gopt, 'p', "python",      0,     "Emit Python code");
    setup_python_options(gopt);

    getopt_add_spacer(gopt, "**** Lua options ****");
    getopt_add_bool  (gopt, 'l', "lua",      0,     "Emit Lua code");
    setup_lua_options(gopt);

    getopt_add_spacer(gopt, "**** C#.NET options ****");
    getopt_add_bool  (gopt, 0, "csharp",      0,     "Emit C#.NET code");
    setup_csharp_options(gopt);

    if (!getopt_parse(gopt, argc, argv, 1) || getopt_get_bool(gopt,"help")) {
        printf("Usage: %s [options] <input files>\n\n", argv[0]);
        getopt_do_usage(gopt);
        return 0;
    }

    lcmgen_t *lcm = lcmgen_create();
    lcm->gopt = gopt;

    for (unsigned int i = 0; i < g_ptr_array_size(gopt->extraargs); i++) {
        char *path = (char *) g_ptr_array_index(gopt->extraargs, i);

        int res = lcmgen_handle_file(lcm, path);
        if (res)
            return -1;
    }

    int did_something = 0;
    // if they requested tokenizing (debug) output, we've done that now. Exit.
    if (getopt_get_bool(gopt, "tokenize")) {
        did_something = 1;
        return 0;
    }

    if (getopt_get_bool(gopt, "debug")) {
        did_something = 1;
        lcmgen_dump(lcm);
    }

    if (getopt_get_bool(gopt, "c")) {
        did_something = 1;
        if (emit_c(lcm)) {
            printf("An error occurred while emitting C code.\n");
        }
    }

    if (getopt_get_bool(gopt, "cpp")) {
        did_something = 1;
        if (emit_cpp(lcm)) {
            printf("An error occurred while emitting C++ code.\n");
        }
    }

    if (getopt_get_bool(gopt, "java")) {
        did_something = 1;
        if (emit_java(lcm)) {
            perror("An error occurred while emitting Java code.\n");
        }
    }

    if (getopt_get_bool(gopt, "python")) {
        did_something = 1;
        if (emit_python(lcm)) {
            printf("An error occurred while emitting Python code.\n");
        }
    }

    if (getopt_get_bool(gopt, "lua")) {
    	did_something = 1;
    	if (emit_lua(lcm)) {
    		printf("An error occurred while emitting Lua code.\n");
    	}
    }

    if (getopt_get_bool(gopt, "csharp")) {
        did_something = 1;
        if (emit_csharp(lcm)) {
            printf("An error occurred while emitting C#.NET code.\n");
        }
    }

    if (did_something == 0) {
        printf("No actions specified. Try --help.\n");
    }

    return 0;
}
Beispiel #10
0
int
main (int argc, char *argv[])
{
    // so that redirected stdout won't be insanely buffered.
    setvbuf (stdout, (char *) NULL, _IONBF, 0);

    state_t *state = calloc (1, sizeof *state);

    state->meters_per_tick = METERS_PER_TICK; // IMPLEMENT ME
    state->alpha = ALPHA;
    state->beta = BETA;

    // file for gyro integration test
    //state->fp = fopen("gyro-yaw-integration.txt","w");
    state->fp = fopen("yaw.txt","w");
    // Tests for the position estimate 
    /*
    update_position(state,4456,4456);
    update_position(state,0,1208);
    update_position(state,4456,4456);
    
    while(1);
    */


    // Used for testing the gyro bias
    /*
    for(int i=0; i<100; i++){
      state->yaw_cal_array[i] = 15*i;
    }

    state->gyro_bias = find_gyro_bias(state); 
    printf("Gyro Bias: %llu\n", state->gyro_bias);
    */


    //printf("getting options\n");
    
    state->gopt = getopt_create ();
    getopt_add_bool   (state->gopt, 'h', "help", 0, "Show help");
    getopt_add_bool   (state->gopt, 'g', "use-gyro", 0, "Use gyro for heading instead of wheel encoders");
    getopt_add_string (state->gopt, '\0', "odometry-channel", "BOTLAB_ODOMETRY", "LCM channel name");
    getopt_add_string (state->gopt, '\0', "feedback-channel", "MAEBOT_MOTOR_FEEDBACK", "LCM channel name");
    getopt_add_string (state->gopt, '\0', "sensor-channel", "MAEBOT_SENSOR_DATA", "LCM channel name");
    getopt_add_double (state->gopt, '\0', "alpha", ALPHA_STRING, "Longitudinal covariance scaling factor");
    getopt_add_double (state->gopt, '\0', "beta", BETA_STRING, "Lateral side-slip covariance scaling factor");
    getopt_add_double (state->gopt, '\0', "gyro-rms", GYRO_RMS_STRING, "Gyro RMS deg/s");

    if (!getopt_parse (state->gopt, argc, argv, 1) || getopt_get_bool (state->gopt, "help")) {
        printf ("Usage: %s [--url=CAMERAURL] [other options]\n\n", argv[0]);
        getopt_do_usage (state->gopt);
        exit (EXIT_FAILURE);
    }

    state->use_gyro = getopt_get_bool (state->gopt, "use-gyro");
    state->odometry_channel = getopt_get_string (state->gopt, "odometry-channel");
    state->feedback_channel = getopt_get_string (state->gopt, "feedback-channel");
    state->sensor_channel = getopt_get_string (state->gopt, "sensor-channel");
    state->alpha = getopt_get_double (state->gopt, "alpha");
    state->beta = getopt_get_double (state->gopt, "beta");
    state->gyro_rms = getopt_get_double (state->gopt, "gyro-rms") * DTOR;
    state->yaw_calibrated = 0;
    state->yaw     = 0;
    state->yaw_old = 0;
    
    //printf("subscribing to channels\n");

    // initialize LCM
    state->lcm = lcm_create (NULL);
    maebot_motor_feedback_t_subscribe (state->lcm, state->feedback_channel,
                                       motor_feedback_handler, state);
    maebot_sensor_data_t_subscribe (state->lcm, state->sensor_channel,
                                    sensor_data_handler, state);

    printf ("ticks per meter: %f\n", 1.0/state->meters_per_tick);

    while (1){
        lcm_handle (state->lcm);
    }
    
    
   
	
}
int main(int argc, char ** argv)
{	
	eecs467_init(argc, argv);

	state_t * state = (state_t*) calloc(1, sizeof(state_t));
	global_state = state;
	state->gopt = getopt_create();
	state->app.display_finished = display_finished;
	state->app.display_started = display_started;
	state->app.impl = state;
	state->update_arm_cont = 0;
	state->update_arm = 0;
	state->arm = new RexArm();
	state->body = new Body();
	state->ds = new DataSmoother(0.4, 0.3, 0, 0);
	state->running = 1;
	state->set_cbs = 0;

	state->controlBoxColor[GRIPPER] = vx_green;
	state->controlBoxColor[WRIST] = vx_yellow;
	state->controlBoxColor[ARM] = vx_orange;
	state->controlBoxColor[ROTATE] = vx_red;

	for (int i = 0; i < NUM_CONTROL_BOXES; i++) {
		state->controlBoxes[i] = new BoundingBox();
		state->controlBoxes[i]->setDimensions(CB_WIDTH, CB_HEIGHT, CB_DEPTH);
	}

	lcm_t * lcm = lcm_create (NULL);
	state->lcm = lcm;
	
	BoundingBox floorBoard, base;

	floorBoard.setPosition(0, 0, 0);
	floorBoard.setDimensions(100, 100, 10);
	state->cfs.addBoundingBox(&floorBoard);
	base.setPosition(0, 0, 4);
	base.setDimensions(7, 7, 8);
	state->cfs.addBoundingBox(&base);

	//signal(SIGINT, terminal_signal_handler);

	pthread_mutex_init(&state->layer_mutex, NULL);
	pthread_mutex_init(&state->lcm_mutex, NULL);
	pthread_mutex_init(&state->running_mutex, NULL);
	pthread_mutex_init(&state->fsm_mutex, NULL);

	state->layer_map = zhash_create(sizeof(vx_display_t*), sizeof(vx_layer_t*), zhash_uint64_hash, zhash_uint64_equals);

	getopt_add_bool(state->gopt, 'h', "help", 0, "Show this help");
	//getopt_add_bool(state->gopt, 'v', "verbose", 0, "Show extra debugging output");
	//getopt_add_int (state->gopt, 'l', "limitKBs", "-1", "Remote display bandwidth limit. < 0: unlimited.");
	//getopt_add_double (state->gopt, 'd', "decimate", "0", "Decimate image by this amount before showing in vx");

	if (!getopt_parse(state->gopt, argc, argv, 0) ||
		getopt_get_bool(state->gopt,"help")) {
		getopt_do_usage(state->gopt);
		exit(-1);
	}

	pthread_create(&state->lcm_handle_thread, NULL, lcm_handle_loop, state);
	//pthread_create(&state->gui_thread,  NULL, gui_create, state);
	pthread_create(&state->arm_commander_thread, NULL, arm_commander, state);
	pthread_create(&state->fsm_thread, NULL, FSM, state);
	//pthread_join(state->gui_thread, NULL);
	gui_create(state);
	printf("after gui_create\n");

	// clean up
	delete state->arm;
	delete state->body;
	delete state->ds;
	for (int i = 0; i < NUM_CONTROL_BOXES; i++) {
		delete state->controlBoxes[i];
	}
	vx_global_destroy();
    getopt_destroy(state->gopt);

    printf("Exited Cleanly!\n");
    return 0;
}
Beispiel #12
0
int main(int argc, char ** argv)
{
    getopt_t *gopt = getopt_create();
    getopt_add_bool   (gopt, 'h', "help", 0, "Show help");
    getopt_add_bool (gopt, '\0', "no-gtk", 0, "Don't show gtk window, only advertise remote connection");
    getopt_add_string (gopt, '\0', "pnm", "", "Path for pnm file to render as texture (.e.g BlockM.pnm)");
    getopt_add_bool (gopt, '\0', "stay-open", 0, "Stay open after gtk exits to continue handling remote connections");

    // parse and print help
    if (!getopt_parse(gopt, argc, argv, 1) || getopt_get_bool(gopt,"help")) {
        printf ("Usage: %s [options]\n\n", argv[0]);
        getopt_do_usage (gopt);
        exit (1);
    }

    vx_global_init(); // Call this to initialize the vx-wide lock. Required to start the GL thread or to use the program library

    state_t * state = state_create();

    // Load a pnm from file, and repack the data so that it's understandable by vx
    if (strcmp(getopt_get_string(gopt,"pnm"),"")) {
        state->img = image_u32_create_from_pnm(getopt_get_string(gopt, "pnm"));

        printf("Loaded image %d x %d from %s\n",
               state->img->width, state->img->height,
               getopt_get_string(gopt, "pnm"));
    }

    draw(state, state->world);

    vx_remote_display_source_attr_t remote_attr;
    vx_remote_display_source_attr_init(&remote_attr);
    remote_attr.advertise_name = "Vx Demo";
    vx_remote_display_source_t * cxn = vx_remote_display_source_create_attr(&state->app, &remote_attr);
    pthread_create(&state->animate_thread, NULL, render_loop, state);

    if (!getopt_get_bool(gopt,"no-gtk")) {
        gdk_threads_init ();
        gdk_threads_enter ();

        gtk_init (&argc, &argv);

        vx_gtk_display_source_t * appwrap = vx_gtk_display_source_create(&state->app);
        GtkWidget * window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
        GtkWidget * canvas = vx_gtk_display_source_get_widget(appwrap);
        gtk_window_set_default_size (GTK_WINDOW (window), 400, 400);
        gtk_container_add(GTK_CONTAINER(window), canvas);
        gtk_widget_show (window);
        gtk_widget_show (canvas); // XXX Show all causes errors!

        g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

        gtk_main (); // Blocks as long as GTK window is open
        gdk_threads_leave ();

        vx_gtk_display_source_destroy(appwrap);

        // quit when gtk closes? Or wait for remote displays/Ctrl-C
        if (!getopt_get_bool(gopt, "stay-open"))
            state->running = 0;
    }

    pthread_join(state->animate_thread, NULL);
    vx_remote_display_source_destroy(cxn);

    state_destroy(state);
    vx_global_destroy();
    getopt_destroy(gopt);
}
Beispiel #13
0
Datei: emit_c.c Projekt: tbeu/lcm
static void emit_header_prototypes(lcmgen_t *lcmgen, FILE *f, lcm_struct_t *ls)
{
    char *xd = getopt_get_string(lcmgen->gopt, "c-export-symbol");
    char *xd_ = add_space_or_empty(xd);
    char *tn = ls->structname->lctypename;
    char *tn_ = dots_to_underscores(tn);

    emit(0, "/**");
    emit(0, " * Create a deep copy of a %s.", tn_);
    emit(0, " * When no longer needed, destroy it with %s_destroy()", tn_);
    emit(0, " */");
    emit(0,"%s%s* %s_copy(const %s* to_copy);", xd_, tn_, tn_, tn_);
    emit(0, "");
    emit(0, "/**");
    emit(0, " * Destroy an instance of %s created by %s_copy()", tn_, tn_);
    emit(0, " */");
    emit(0,"%svoid %s_destroy(%s* to_destroy);", xd_, tn_, tn_);
    emit(0,"");

    if (!getopt_get_bool(lcmgen->gopt, "c-no-pubsub")) {
        emit(0, "/**");
        emit(0, " * Identifies a single subscription.  This is an opaque data type.");
        emit(0, " */");
        emit(0,"typedef struct _%s_subscription_t %s_subscription_t;", tn_, tn_);
        emit(0, "");
        emit(0, "/**");
        emit(0, " * Prototype for a callback function invoked when a message of type");
        emit(0, " * %s is received.", tn_);
        emit(0, " */");
        emit(0,"typedef void(*%s_handler_t)(const lcm_recv_buf_t *rbuf,\n"
               "             const char *channel, const %s *msg, void *userdata);",
               tn_, tn_);
        emit(0, "");
        emit(0, "/**");
        emit(0, " * Publish a message of type %s using LCM.", tn_);
        emit(0, " *");
        emit(0, " * @param lcm The LCM instance to publish with.");
        emit(0, " * @param channel The channel to publish on.");
        emit(0, " * @param msg The message to publish.");
        emit(0, " * @return 0 on success, <0 on error.  Success means LCM has transferred");
        emit(0, " * responsibility of the message data to the OS.");
        emit(0, " */");
        emit(0,"%sint %s_publish(lcm_t *lcm, const char *channel, const %s *msg);", xd_, tn_, tn_);
        emit(0, "");
        emit(0, "/**");
        emit(0, " * Subscribe to messages of type %s using LCM.", tn_);
        emit(0, " *");
        emit(0, " * @param lcm The LCM instance to subscribe with.");
        emit(0, " * @param channel The channel to subscribe to.");
        emit(0, " * @param handler The callback function invoked by LCM when a message is received.");
        emit(0, " *                This function is invoked by LCM during calls to lcm_handle() and");
        emit(0, " *                lcm_handle_timeout().");
        emit(0, " * @param userdata An opaque pointer passed to @p handler when it is invoked.");
        emit(0, " * @return 0 on success, <0 if an error occured");
        emit(0, " */");
        emit(0,"%s%s_subscription_t* %s_subscribe(lcm_t *lcm, const char *channel, %s_handler_t handler, void *userdata);",
                xd_, tn_, tn_, tn_);
        emit(0, "");
        emit(0, "/**");
        emit(0, " * Removes and destroys a subscription created by %s_subscribe()", tn_);
        emit(0, " */");
        emit(0,"%sint %s_unsubscribe(lcm_t *lcm, %s_subscription_t* hid);", xd_, tn_, tn_);
        emit(0, "");
        emit(0, "/**");
        emit(0, " * Sets the queue capacity for a subscription.");
        emit(0, " * Some LCM providers (e.g., the default multicast provider) are implemented");
        emit(0, " * using a background receive thread that constantly revceives messages from");
        emit(0, " * the network.  As these messages are received, they are buffered on");
        emit(0, " * per-subscription queues until dispatched by lcm_handle().  This function");
        emit(0, " * how many messages are queued before dropping messages.");
        emit(0, " *");
        emit(0, " * @param subs the subscription to modify.");
        emit(0, " * @param num_messages The maximum number of messages to queue");
        emit(0, " *  on the subscription.");
        emit(0, " * @return 0 on success, <0 if an error occured");
        emit(0, " */");
        emit(0,"%sint %s_subscription_set_queue_capacity(%s_subscription_t* subs,\n"
            "                              int num_messages);\n", xd_, tn_, tn_);
    }

    emit(0, "/**");
    emit(0, " * Encode a message of type %s into binary form.", tn_);
    emit(0, " *");
    emit(0, " * @param buf The output buffer.");
    emit(0, " * @param offset Encoding starts at this byte offset into @p buf.");
    emit(0, " * @param maxlen Maximum number of bytes to write.  This should generally");
    emit(0, " *               be equal to %s_encoded_size().", tn_);
    emit(0, " * @param msg The message to encode.");
    emit(0, " * @return The number of bytes encoded, or <0 if an error occured.");
    emit(0, " */");
    emit(0,"%sint %s_encode(void *buf, int offset, int maxlen, const %s *p);", xd_, tn_, tn_);
    emit(0, "");
    emit(0, "/**");
    emit(0, " * Decode a message of type %s from binary form.", tn_);
    emit(0, " * When decoding messages containing strings or variable-length arrays, this");
    emit(0, " * function may allocate memory.  When finished with the decoded message,");
    emit(0, " * release allocated resources with %s_decode_cleanup().", tn_);
    emit(0, " *");
    emit(0, " * @param buf The buffer containing the encoded message");
    emit(0, " * @param offset The byte offset into @p buf where the encoded message starts.");
    emit(0, " * @param maxlen The maximum number of bytes to read while decoding.");
    emit(0, " * @param msg Output parameter where the decoded message is stored");
    emit(0, " * @return The number of bytes decoded, or <0 if an error occured.");
    emit(0, " */");
    emit(0,"%sint %s_decode(const void *buf, int offset, int maxlen, %s *msg);", xd_, tn_, tn_);
    emit(0, "");
    emit(0, "/**");
    emit(0, " * Release resources allocated by %s_decode()", tn_);
    emit(0, " * @return 0");
    emit(0, " */");
    emit(0,"%sint %s_decode_cleanup(%s *p);", xd_, tn_, tn_);
    emit(0, "");
    emit(0, "/**");
    emit(0, " * Check how many bytes are required to encode a message of type %s", tn_);
    emit(0, " */");
    emit(0,"%sint %s_encoded_size(const %s *p);", xd_, tn_, tn_);
    if(getopt_get_bool(lcmgen->gopt, "c-typeinfo")) {
        emit(0,"%ssize_t %s_struct_size(void);", xd_, tn_);
        emit(0,"%sint %s_num_fields(void);", xd_, tn_);
        emit(0,"%sint %s_get_field(const %s *p, int i, lcm_field_t *f);", xd_, tn_, tn_);
        emit(0,"%sconst lcm_type_info_t *%s_get_type_info(void);", xd_, tn_);
    }
    emit(0,"");

    emit(0,"// LCM support functions. Users should not call these");
    emit(0,"%sint64_t __%s_get_hash(void);", xd_, tn_);
    emit(0,"%suint64_t __%s_hash_recursive(const __lcm_hash_ptr *p);", xd_, tn_);
    emit(0,"%sint __%s_encode_array(void *buf, int offset, int maxlen, const %s *p, int elements);", xd_, tn_, tn_);
    emit(0,"%sint __%s_decode_array(const void *buf, int offset, int maxlen, %s *p, int elements);", xd_, tn_, tn_);
    emit(0,"%sint __%s_decode_array_cleanup(%s *p, int elements);", xd_, tn_, tn_);
    emit(0,"%sint __%s_encoded_array_size(const %s *p, int elements);", xd_, tn_, tn_);
    emit(0,"%sint __%s_clone_array(const %s *p, %s *q, int elements);", xd_, tn_, tn_, tn_);
    emit(0,"");

}
Beispiel #14
0
Datei: emit_c.c Projekt: tbeu/lcm
int emit_struct(lcmgen_t *lcmgen, lcm_struct_t *lr)
{
    char *tn = lr->structname->lctypename;
    char *tn_ = dots_to_underscores(tn);
    char *header_name = g_strdup_printf("%s/%s.h", getopt_get_string(lcmgen->gopt, "c-hpath"), tn_);
    char *c_name      = g_strdup_printf("%s/%s.c", getopt_get_string(lcmgen->gopt, "c-cpath"), tn_);

    if (lcm_needs_generation(lcmgen, lr->lcmfile, header_name)) {
        FILE *f = fopen(header_name, "w");
        if (f == NULL)
            return -1;

        emit_header_top(lcmgen, f, tn_);
        emit_header_struct(lcmgen, f, lr);
        emit_header_prototypes(lcmgen, f, lr);

        emit_header_bottom(lcmgen, f);
        fclose(f);
    }

    // STRUCT C file
    if (lcm_needs_generation(lcmgen, lr->lcmfile, c_name)) {
        FILE *f = fopen(c_name, "w");
        if (f == NULL)
            return -1;

        emit_auto_generated_warning(f);
        fprintf(f, "#include <string.h>\n");
        fprintf(f, "#include \"%s%s%s.h\"\n",
                getopt_get_string(lcmgen->gopt, "cinclude"),
                strlen(getopt_get_string(lcmgen->gopt, "cinclude"))>0 ? "/" : "",
                tn_);
        fprintf(f, "\n");

        emit_c_struct_get_hash(lcmgen, f, lr);
        emit_c_encode_array(lcmgen, f, lr);
        emit_c_encode(lcmgen, f, lr);
        emit_c_encoded_array_size(lcmgen, f, lr);
        emit_c_encoded_size(lcmgen, f, lr);

        if(getopt_get_bool(lcmgen->gopt, "c-typeinfo")) {
            emit_c_struct_size(lcmgen, f, lr);
            emit_c_num_fields(lcmgen, f, lr);
            emit_c_get_field(lcmgen, f, lr);
            emit_c_get_type_info(lcmgen, f, lr);
        }

        emit_c_decode_array(lcmgen, f, lr);
        emit_c_decode_array_cleanup(lcmgen, f, lr);
        emit_c_decode(lcmgen, f, lr);
        emit_c_decode_cleanup(lcmgen, f, lr);

        emit_c_clone_array(lcmgen, f, lr);
        emit_c_copy(lcmgen, f, lr);
        emit_c_destroy(lcmgen, f, lr);

        if(!getopt_get_bool(lcmgen->gopt, "c-no-pubsub")) {
            emit_c_struct_publish(lcmgen, f, lr );
            emit_c_struct_subscribe(lcmgen, f, lr );
        }

        fclose(f);
    }

    return 0;
}
Beispiel #15
0
int main(int argc, char ** argv)
{
    getopt_t *gopt = getopt_create();
    getopt_add_bool   (gopt, 'h', "help", 0, "Show help");
    getopt_add_bool (gopt, '\0', "no-gtk", 0, "Don't show gtk window, only advertise remote connection");
    getopt_add_int (gopt, 'l', "limitKBs", "-1", "Remote display bandwidth limit. < 0: unlimited.");
    getopt_add_string (gopt, '\0', "pnm", "", "Path for pnm file to render as texture (.e.g BlockM.pnm)");
    getopt_add_bool (gopt, '\0', "stay-open", 0, "Stay open after gtk exits to continue handling remote connections");

    // parse and print help
    if (!getopt_parse(gopt, argc, argv, 1) || getopt_get_bool(gopt,"help")) {
        printf ("Usage: %s [options]\n\n", argv[0]);
        getopt_do_usage (gopt);
        exit (1);
    }

    signal(SIGPIPE, SIG_IGN); // potential fix for Valgrind "Killed" on
    // remote viewer exit

    state_t * state = state_create();

    // Load a pnm from file, and repack the data so that it's understandable by vx
    if (strcmp(getopt_get_string(gopt,"pnm"),"")) {
        image_u8_t * img2 = image_u8_create_from_pnm(getopt_get_string(gopt, "pnm"));
        state->img = image_util_convert_rgb_to_rgba (img2);
        image_u8_destroy (img2);
    }

    vx_global_init(); // Call this to initialize the vx-wide lock. Required to start the GL thread or to use the program library

    vx_application_t app = {.impl=state, .display_started=display_started, .display_finished=display_finished};

    vx_remote_display_source_attr_t remote_attr;
    vx_remote_display_source_attr_init(&remote_attr);
    remote_attr.max_bandwidth_KBs = getopt_get_int(gopt, "limitKBs");
    remote_attr.advertise_name = "Vx Stress Test";

    vx_remote_display_source_t * cxn = vx_remote_display_source_create_attr(&app, &remote_attr);
    for (int i = 0; i < NRENDER; i++) {
        tinfo_t * tinfo = calloc(1,sizeof(tinfo_t));
        tinfo->state = state;
        tinfo->id = i;
        pthread_create(&state->render_threads[i], NULL, render_loop, tinfo);
    }

    pthread_create(&state->camera_thread, NULL, camera_loop, state);

    if (!getopt_get_bool(gopt,"no-gtk")) {
        gdk_threads_init ();
        gdk_threads_enter ();

        gtk_init (&argc, &argv);

        vx_gtk_display_source_t * appwrap = vx_gtk_display_source_create(&app);
        GtkWidget * window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
        GtkWidget * canvas = vx_gtk_display_source_get_widget(appwrap);
        gtk_window_set_default_size (GTK_WINDOW (window), 400, 400);
        gtk_container_add(GTK_CONTAINER(window), canvas);
        gtk_widget_show (window);
        gtk_widget_show (canvas); // XXX Show all causes errors!

        g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

        gtk_main (); // Blocks as long as GTK window is open
        gdk_threads_leave ();

        vx_gtk_display_source_destroy(appwrap);

        // quit when gtk closes? Or wait for remote displays/Ctrl-C
        if (!getopt_get_bool(gopt, "stay-open"))
            state->running = 0;
    }

    for (int i = 0; i < NRENDER; i++)
        pthread_join(state->render_threads[i], NULL);
    vx_remote_display_source_destroy(cxn);

    state_destroy(state);
    vx_global_destroy();
    getopt_destroy(gopt);
}
Beispiel #16
0
int main(int argc, char *argv[])
{
    g_type_init ();

    dbg_init ();

    // initialize application state and zero out memory
    g_self = (state_t*) calloc( 1, sizeof(state_t) );
    state_t *self = g_self;



    // run the main loop
    self->loop = g_main_loop_new(NULL, FALSE);

    getopt_t *gopt = getopt_create();

    getopt_add_bool  (gopt, 'h',   "help",    0,        "Show this help");
    getopt_add_bool  (gopt, 'v',   "verbose",    0,     "Be verbose");

    if (!getopt_parse(gopt, argc, argv, 1) || getopt_get_bool(gopt,"help")) {
        printf("Usage: %s [options]\n\n", argv[0]);
        getopt_do_usage(gopt);
        return 0;
    }

    self->verbose = getopt_get_bool(gopt, "verbose");

    self->lcm = lcm_create(NULL);
    if (!self->lcm)
        return 1;

    // read config file
    if (!(self->config = read_config_file ())) {
        dbg (DBG_ERROR, "[viewer] failed to read config file.");
        return -1;
    }


    // attach lcm to main loop
    glib_mainloop_attach_lcm (self->lcm);

    // publish cam settings every now and then
    // g_timeout_add_seconds (2, &publish_log_info_data, self);
    // g_timeout_add_seconds (2, &dump_to_index_file, self);

    // listen to tablet event
    navlcm_log_info_t_subscribe (self->lcm, "LOG_INFO", on_log_info_set_event, self);

    list_files (self);

    publish_log_info_data (self);

    // connect to kill signal
    signal_pipe_glib_quit_on_kill (self->loop);

    // run main loop
    g_main_loop_run (self->loop);

    // cleanup
    g_main_loop_unref (self->loop);

    return 0;
}