+ hostsim_lock();
+ write(fdw, buf, len);
+ hostsim_unlock();
+}
+
+/* must be called periodically */
+void robotsim_update(void)
+{
+ static int32_t l_pwm_shift[SHIFT];
+ static int32_t r_pwm_shift[SHIFT];
+ static int32_t l_speed, r_speed;
+ static unsigned i = 0;
+ static unsigned cpt = 0;
+ int32_t local_l_pwm, local_r_pwm;
+ double x, y, a, a2, d;
+ char cmd = 0;
+
+ /* corners of the robot */
+ double xfl, yfl; /* front left */
+ double xrl, yrl; /* rear left */
+ double xrr, yrr; /* rear right */
+ double xfr, yfr; /* front right */
+
+ /* time shift the command */
+ l_pwm_shift[i] = l_pwm;
+ r_pwm_shift[i] = r_pwm;
+ i ++;
+ i %= SHIFT;
+ local_l_pwm = l_pwm_shift[i];
+ local_r_pwm = r_pwm_shift[i];
+
+ /* read command */
+ if (((cpt ++) & 0x7) == 0) {
+ if (read(fdr, &cmd, 1) != 1)
+ cmd = 0;
+ }
+
+ x = position_get_x_double(&mainboard.pos);
+ y = position_get_y_double(&mainboard.pos);
+ a = position_get_a_rad_double(&mainboard.pos);
+
+ l_speed = ((l_speed * FILTER) / 100) +
+ ((local_l_pwm * 1000 * FILTER2)/1000);
+ r_speed = ((r_speed * FILTER) / 100) +
+ ((local_r_pwm * 1000 * FILTER2)/1000);
+
+ /* basic collision detection */
+ a2 = atan2(ROBOT_WIDTH/2, ROBOT_LENGTH/2);
+ d = norm(ROBOT_WIDTH/2, ROBOT_LENGTH/2);
+
+ xfl = x + cos(a+a2) * d;
+ yfl = y + sin(a+a2) * d;
+ if (!is_in_area(xfl, yfl, 0) && l_speed > 0)
+ l_speed = 0;
+
+ xrl = x + cos(a+M_PI-a2) * d;
+ yrl = y + sin(a+M_PI-a2) * d;
+ if (!is_in_area(xrl, yrl, 0) && l_speed < 0)
+ l_speed = 0;
+
+ xrr = x + cos(a+M_PI+a2) * d;
+ yrr = y + sin(a+M_PI+a2) * d;
+ if (!is_in_area(xrr, yrr, 0) && r_speed < 0)
+ r_speed = 0;
+
+ xfr = x + cos(a-a2) * d;
+ yfr = y + sin(a-a2) * d;
+ if (!is_in_area(xfr, yfr, 0) && r_speed > 0)
+ r_speed = 0;
+
+ /* perturbation */
+ if (cmd == 'l')
+ l_enc += 5000; /* push 1 cm */
+ if (cmd == 'r')
+ r_enc += 5000; /* push 1 cm */
+
+ /* XXX should lock */
+ l_enc += (l_speed / 1000);
+ r_enc += (r_speed / 1000);