// simulate.c --- run mujoco simulation with serial control #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define BAUDRATE B115200 #define STEPS_TO_RADIANS (2*M_PI/360) enum { SERVO_LEFT, SERVO_RIGHT, SERVO_UPPER, SERVO_COUNT }; uint8_t servo_left_handed = 1 << SERVO_LEFT | 1 << SERVO_RIGHT; int servo_ids[SERVO_COUNT]; int shoulder_ids[SERVO_COUNT]; const char *progname; const char *modelfile; const char *serialdev; int16_t steps[8] = {0}; uint8_t ends = 0; uint32_t crc; char read_buf[sizeof (steps) + sizeof (crc)]; char write_buf[sizeof (ends) + sizeof (crc)]; volatile bool serial_read_ready = false; struct termios oldtio; // MuJoCo data structures mjModel *m = NULL; // MuJoCo model mjData *d = NULL; // MuJoCo data mjvCamera cam; // abstract camera mjvOption opt; // visualization options mjvScene scn; // abstract scene mjrContext con; // custom GPU context // mouse interaction bool button_left = false; bool button_middle = false; bool button_right = false; double lastx = 0; double lasty = 0; static void signal_handler_io (int status) { // printf ("received SIGIO\n"); serial_read_ready = true; } static int open_serial (const char *dev) { int fd; for (;;) { fd = open (dev, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd != -1) break; printf ("Error %i from open: %s\n", errno, strerror (errno)); sleep (1); } struct sigaction saio = {0}; saio.sa_handler = signal_handler_io; // saio.sa_flags = SA_RESTART; sigaction (SIGIO, &saio, NULL); fcntl (fd, F_SETOWN, getpid ()); // allow the process to receive SIGIO fcntl (fd, F_SETFL, FASYNC); // make the file descriptor asynchronous struct termios newtio = {0}; if (tcgetattr (fd, &oldtio) != 0) { printf ("Error %i from tcgetattr: %s\n", errno, strerror (errno)); exit (EXIT_FAILURE); } newtio.c_iflag = IGNPAR; newtio.c_cflag = CS8 | CLOCAL | CREAD; newtio.c_cc[VMIN ] = 0; newtio.c_cc[VTIME] = 0; cfsetspeed (&newtio, BAUDRATE); // tcflush (fd, TCIFLUSH); // if (tcsetattr (fd, TCSANOW, &newtio) != 0) { if (tcsetattr (fd, TCSAFLUSH, &newtio) != 0) { printf ("Error %i from tcsetattr: %s\n", errno, strerror (errno)); } return fd; } static uint32_t crc32 (uint32_t *data, size_t len) { uint32_t crc = 0xffffffff; for (size_t i = 0; i < len; ++i) { crc ^= data[i]; for (int j = 0; j < 32; ++j) { crc = crc & 1 << 31 ? crc << 1 ^ 0x04c11db7 : crc << 1; } } return crc; } void model_load (void) { char error[1000] = "Could not load binary model"; if (strlen (modelfile) > 4 && !strcmp (modelfile + strlen (modelfile) - 4, ".mjb")) { m = mj_loadModel (modelfile, 0); } else { m = mj_loadXML (modelfile, 0, error, 1000); } if (!m) mju_error ("Load model error: %s", error); } void keyboard (GLFWwindow *window, int key, int scancode, int act, int mods) { // Backspace: reset simulation if (act == GLFW_PRESS && key == GLFW_KEY_BACKSPACE) { mj_resetData (m, d); mj_forward (m, d); } // F5: reload if (act == GLFW_PRESS && key == GLFW_KEY_F5) { model_load (); } } void mouse_button (GLFWwindow *window, int button, int act, int mods) { button_left = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS; button_middle = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS; button_right = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_RIGHT ) == GLFW_PRESS; // update mouse position glfwGetCursorPos (window, &lastx, &lasty); } // mouse move callback void mouse_move (GLFWwindow *window, double xpos, double ypos) { // no buttons down: nothing to do if (!button_left && !button_middle && !button_right) return; // compute mouse displacement, save double dx = xpos - lastx; double dy = ypos - lasty; lastx = xpos; lasty = ypos; // get current window size int width, height; glfwGetWindowSize (window, &width, &height); // get shift key state bool mod_shift = (glfwGetKey (window, GLFW_KEY_LEFT_SHIFT ) == GLFW_PRESS || glfwGetKey (window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); // determine action based on mouse button mjtMouse action; if (button_right) action = mod_shift ? mjMOUSE_MOVE_H : mjMOUSE_MOVE_V; else if (button_left ) action = mod_shift ? mjMOUSE_ROTATE_H : mjMOUSE_ROTATE_V; else action = mjMOUSE_ZOOM; // move camera mjv_moveCamera (m, action, dx/height, dy/height, &scn, &cam); } // scroll callback void scroll (GLFWwindow *window, double xoffset, double yoffset) { // emulate vertical mouse motion = 5% of window height mjv_moveCamera (m, mjMOUSE_ZOOM, 0, -.05*yoffset, &scn, &cam); } int get_obj_id (const char *name, mjtObj obj) { // return 0; int id = mj_name2id (m, obj, name); if (id == -1) mju_error ("Object '%s' not found", name); return id; } void control (const mjModel* m, mjData* d) { d->ctrl[servo_ids[SERVO_LEFT ]] = steps[SERVO_LEFT ]*STEPS_TO_RADIANS; d->ctrl[servo_ids[SERVO_RIGHT]] = steps[SERVO_RIGHT]*STEPS_TO_RADIANS; d->ctrl[servo_ids[SERVO_UPPER]] = steps[SERVO_UPPER]*STEPS_TO_RADIANS; } int main (int argc, const char** argv) { progname = *argv++; modelfile = *argv++; if (!modelfile) { printf ("Usage: %s modelfile [serialdev]\n", progname); return EXIT_FAILURE; } serialdev = *argv++; if (serialdev && *argv) { printf ("Usage: %s modelfile [serialdev]\n", progname); return EXIT_FAILURE; } model_load (); d = mj_makeData (m); mjcb_control = control; servo_ids[SERVO_LEFT ] = get_obj_id ("servo-left", mjOBJ_ACTUATOR); servo_ids[SERVO_RIGHT] = get_obj_id ("servo-right", mjOBJ_ACTUATOR); servo_ids[SERVO_UPPER] = get_obj_id ("servo-upper", mjOBJ_ACTUATOR); shoulder_ids[SERVO_LEFT ] = get_obj_id ("shoulder-left", mjOBJ_JOINT); shoulder_ids[SERVO_RIGHT] = get_obj_id ("shoulder-right", mjOBJ_JOINT) + 1; shoulder_ids[SERVO_UPPER] = get_obj_id ("shoulder-upper", mjOBJ_JOINT) + 1; if (!glfwInit ()) mju_error ("Could not initialize GLFW"); // create window, make OpenGL context current, request v-sync GLFWwindow *window = glfwCreateWindow (1200, 900, "", NULL, NULL); glfwMakeContextCurrent (window); glfwSwapInterval (1); // initialize visualization data structures mjv_defaultCamera (&cam); mjv_defaultOption (&opt); mjv_defaultScene (&scn); mjr_defaultContext (&con); // create scene and context mjv_makeScene (m, &scn, 2000); mjr_makeContext (m, &con, mjFONTSCALE_150); // install GLFW mouse and keyboard callbacks glfwSetKeyCallback (window, keyboard); glfwSetCursorPosCallback (window, mouse_move); glfwSetMouseButtonCallback (window, mouse_button); glfwSetScrollCallback (window, scroll); int serial = serialdev ? open_serial (serialdev) : open ("/dev/null", O_RDWR); // run main loop, target real-time simulation and 60 fps rendering while (!glfwWindowShouldClose (window)) { // int id = mj_name2id (m, mjOBJ_BODY, "carriage"); // printf ("%.3f %.3f %.3f\n", d->xpos[id*3 + 0], d->xpos[id*3 + 1], d->xpos[id*3 + 2]); mjtNum simstart = d->time; while (d->time - simstart < 1./60) { if (serial_read_ready) { int bytes_available; if (ioctl (serial, FIONREAD, &bytes_available) == -1 || bytes_available < sizeof (read_buf)) { goto after_read; } serial_read_ready = false; ssize_t res = read (serial, read_buf, sizeof (read_buf)); tcflush (serial, TCIFLUSH); if (res != sizeof (read_buf)) { fprintf (stderr, "not enough bytes!\n"); goto after_read; } crc = *(uint32_t *) (read_buf + sizeof (steps)); if (crc != crc32 ((uint32_t *) read_buf, sizeof (steps)/4)) { fprintf (stderr, "CRC mismatch!\n"); goto after_read; } // memcpy (steps, read_buf, sizeof (steps)); // printf ("%hd %hd %hd %hd %hd %hd %hd %hd %u\n", // steps[0], steps[1], steps[2], steps[3], // steps[4], steps[5], steps[6], steps[7], crc); memset (write_buf, 0, sizeof (write_buf)); write_buf[0] = ends; *((uint32_t *) (write_buf + 1)) = crc32 ((uint32_t *) write_buf, 1); write (serial, write_buf, sizeof (write_buf)); tcflush (serial, TCOFLUSH); } else if (!serialdev) { steps[SERVO_LEFT ] = (M_PI/8 - 0.2 + sinf (8/8.*glfwGetTime () + 0)*M_PI/8)/STEPS_TO_RADIANS*(1 - 2*(servo_left_handed >> SERVO_LEFT & 1)); steps[SERVO_RIGHT] = (M_PI/8 - 0.2 + sinf (7/8.*glfwGetTime () + 4)*M_PI/8)/STEPS_TO_RADIANS*(1 - 2*(servo_left_handed >> SERVO_RIGHT & 1)); steps[SERVO_UPPER] = (M_PI/8 - 0.2 + sinf (6/8.*glfwGetTime () + 8)*M_PI/8)/STEPS_TO_RADIANS*(1 - 2*(servo_left_handed >> SERVO_UPPER & 1)); } after_read: mj_step (m, d); ends = 0; ends |= (d->qpos[shoulder_ids[SERVO_LEFT ]]*(1 - 2*(servo_left_handed >> SERVO_LEFT & 1)) < 0 ) << SERVO_LEFT; ends |= (d->qpos[shoulder_ids[SERVO_RIGHT]]*(1 - 2*(servo_left_handed >> SERVO_RIGHT & 1)) < 0 ) << SERVO_RIGHT; ends |= (d->qpos[shoulder_ids[SERVO_UPPER]]*(1 - 2*(servo_left_handed >> SERVO_UPPER & 1)) < 0 ) << SERVO_UPPER; // print actual angles and end cap states printf ("%+.3lf %+.3lf %+.3lf %b%b%b\n", d->qpos[shoulder_ids[SERVO_LEFT ]], d->qpos[shoulder_ids[SERVO_RIGHT]], d->qpos[shoulder_ids[SERVO_UPPER]], ends >> SERVO_LEFT & 1, ends >> SERVO_RIGHT & 1, ends >> SERVO_UPPER & 1); // print actual angle, desired angle, error and end cap state for one servo // int servo = SERVO_UPPER; // printf ("%+lf %+lf %+lf %0b\n", // d->qpos[shoulder_ids[servo]], d->ctrl[servo_ids[servo]], // d->qpos[shoulder_ids[servo]] - d->ctrl[servo_ids[servo]], // ends >> servo); // print error (actual - desired) // printf ("%+lf %+lf %+lf\n", // d->qpos[shoulder_ids[SERVO_LEFT ]] - d->ctrl[servo_ids[SERVO_LEFT ]], // d->qpos[shoulder_ids[SERVO_RIGHT]] - d->ctrl[servo_ids[SERVO_RIGHT]], // d->qpos[shoulder_ids[SERVO_UPPER]] - d->ctrl[servo_ids[SERVO_UPPER]]); } // get framebuffer viewport mjrRect viewport = { 0, 0, 0, 0 }; glfwGetFramebufferSize (window, &viewport.width, &viewport.height); // update scene and render mjv_updateScene (m, d, &opt, NULL, &cam, mjCAT_ALL, &scn); mjr_render (viewport, &scn, &con); glfwSwapBuffers (window); glfwPollEvents (); if (glfwGetKey (window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose (window, GLFW_TRUE); } if (serialdev) tcsetattr (serial, TCSANOW, &oldtio); close (serial); mjv_freeScene (&scn); mjr_freeContext (&con); glfwTerminate (); mj_deleteData (d); mj_deleteModel (m); return EXIT_SUCCESS; } // end of simulate.c