Statistics
| Branch: | Revision:

scoutos / scout / scoutsim / src / scout.cpp @ 3a73516c

History | View | Annotate | Download (19.4 KB)

1
/**
2
 * The code in this package was developed using the structure of Willow
3
 * Garage's turtlesim package.  It was modified by the CMU Robotics Club
4
 * to be used as a simulator for the Colony Scout robot.
5
 *
6
 * All redistribution of this code is limited to the terms of Willow Garage's
7
 * licensing terms, as well as under permission from the CMU Robotics Club.
8
 * 
9
 * Copyright (c) 2011 Colony Project
10
 * 
11
 * Permission is hereby granted, free of charge, to any person
12
 * obtaining a copy of this software and associated documentation
13
 * files (the "Software"), to deal in the Software without
14
 * restriction, including without limitation the rights to use,
15
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the
17
 * Software is furnished to do so, subject to the following
18
 * conditions:
19
 * 
20
 * The above copyright notice and this permission notice shall be
21
 * included in all copies or substantial portions of the Software.
22
 * 
23
 * Copyright (c) 2009, Willow Garage, Inc.
24
 * All rights reserved.
25
 * 
26
 * Redistribution and use in source and binary forms, with or without
27
 * modification, are permitted provided that the following conditions are met:
28
 * 
29
 *    Redistributions of source code must retain the above copyright
30
 *       notice, this list of conditions and the following disclaimer.
31
 *    Redistributions in binary form must reproduce the above copyright
32
 *       notice, this list of conditions and the following disclaimer in the
33
 *       documentation and/or other materials provided with the distribution.
34
 *    Neither the name of the Willow Garage, Inc. nor the names of its
35
 *       contributors may be used to endorse or promote products derived from
36
 *       this software without specific prior written permission.
37
 * 
38
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
39
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
40
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
41
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
42
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
43
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
44
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
45
 * OTHER DEALINGS IN THE SOFTWARE.
46
 */
47

    
48
/**
49
 * @file scout.cpp
50
 *
51
 * @ingroup scoutsim
52
 * @{
53
 */
54

    
55
#include "scout.h"
56

    
57
#include <wx/wx.h>
58

    
59
#define DEFAULT_PEN_R 0xb3
60
#define DEFAULT_PEN_G 0xb8
61
#define DEFAULT_PEN_B 0xff
62

    
63
using namespace std;
64

    
65
namespace scoutsim
66
{
67
    /**
68
     * The scout object, which is responsible for refreshing itself and
69
     * updating its position and simulated sensors.
70
     *
71
     * @ingroup scoutsim
72
     */
73
    Scout::Scout(const ros::NodeHandle& nh,
74
                 const wxImage& scout_image,
75
                 const Vector2& pos,
76
                 wxBitmap *path_bitmap,
77
                 float orient)
78
        : path_bitmap(path_bitmap)
79
          , sonar_visual_on(false)
80
          , sonar_on(true)
81
          , ignore_behavior(false)
82
          , node (nh)
83
          , scout_image(scout_image)
84
          , pos(pos)
85
          , orient(orient)
86
          , motor_fl_speed(0)
87
          , motor_fr_speed(0)
88
          , motor_bl_speed(0)
89
          , motor_br_speed(0)
90
          , fl_ticks(0)
91
          , fr_ticks(0)
92
          , bl_ticks(0)
93
          , br_ticks(0)
94
          , pen_on(true)
95
          , pen(wxColour(DEFAULT_PEN_R, DEFAULT_PEN_G, DEFAULT_PEN_B))
96
    {
97
        pen.SetWidth(3);
98
        scout = wxBitmap(scout_image);
99

    
100
        motors_sub = node.subscribe("set_motors", 1, &Scout::setMotors, this);
101

    
102
        pose_pub = node.advertise<Pose>("pose", 1);
103
        color_pub = node.advertise<Color>("color_sensor", 1);
104
        sonar_pub = node.advertise< ::messages::sonar_distance>("sonar_distance", 1);
105
        set_pen_srv = node.advertiseService("set_pen",
106
                                            &Scout::setPenCallback,
107
                                            this);
108
        toggle_sonar_srv = node.advertiseService("sonar_toggle",
109
                                            &Scout::handle_sonar_toggle,
110
                                            this);
111
        set_sonar_srv = node.advertiseService("sonar_set_scan",
112
                                            &Scout::handle_sonar_set_scan,
113
                                            this);
114
        query_encoders_srv =
115
            node.advertiseService("query_encoders",
116
                                  &Scout::query_encoders_callback,
117
                                  this);
118

    
119
        query_linesensor_srv =
120
            node.advertiseService("query_linesensor",
121
                                  &Scout::query_linesensor_callback,
122
                                  this);
123

    
124
        for (unsigned int i = 0; i < NUM_LINESENSORS; i++)
125
        {
126
            linesensor_readings.push_back(0);
127
        }
128

    
129
        // Initialize sonar
130
        sonar_position = 0;
131
        sonar_stop_l = 0;
132
        sonar_stop_r = 23;
133
        sonar_direction = 1;
134
        sonar_tick_time = ros::Duration(scoutsim::SONAR_HALF_SPIN_TIME / 24.0);
135
        
136
        // Init latch
137
        teleop_latch = 0;
138
    }
139

    
140
    float Scout::absolute_to_mps(int absolute_speed)
141
    {
142
        return ((float) absolute_speed) * MAX_SPEED_MPS / MAX_ABSOLUTE_SPEED;
143
    }
144

    
145
    /**
146
     * A callback function that sets velocity based on a set_motors
147
     * request.
148
     * @todo Use "callback" in all callback function names? Or remove?
149
     */
150
    void Scout::setMotors(const ::messages::set_motors::ConstPtr& msg)
151
    {
152
        last_command_time = ros::WallTime::now();
153

    
154
        //ignore non-teleop commands if commands if teleop is ON
155
        //if (node.getNamespace() != current_teleop_scout || msg->teleop_ON)
156
        //{
157

    
158
        //latch value indicates number of uninterrupted teleop messages
159
        //before teleop latch shifts again
160
        if (!(msg->teleop_ON) && teleop_latch < 3)
161
        {
162
            teleop_latch++;
163
        }
164

    
165
        if (!(msg->teleop_ON) || teleop_latch ==0)
166
        {
167
            if(msg->fl_set)
168
            {
169
                motor_fl_speed = absolute_to_mps(msg->fl_speed);
170
            }
171
            if(msg->fr_set)
172
            {
173
                motor_fr_speed = absolute_to_mps(msg->fr_speed);
174
            }
175
            if(msg->bl_set)
176
            {
177
                motor_bl_speed = absolute_to_mps(msg->bl_speed);
178
            }
179
            if(msg->br_set)
180
            {
181
                motor_br_speed = absolute_to_mps(msg->br_speed);
182
            }
183
        }        
184

    
185
        //if a teleop message comes through, decrease the latch
186
        //latch code works on the assumption there will be more behavior messages
187
        //than teleop messages
188
        if (msg->teleop_ON && teleop_latch>0)
189
        {
190
            teleop_latch--;
191
        }
192
        //}
193

    
194
    }
195

    
196
    bool Scout::handle_sonar_toggle(::messages::sonar_toggle::Request  &req,
197
                         ::messages::sonar_toggle::Response &res)
198
    {
199
        if (req.set_on && !sonar_on)
200
        {
201
            ROS_INFO("Turning on the sonar");
202
            sonar_on = true;
203

    
204
        }
205
        else if (!req.set_on && sonar_on)
206
        {
207
            ROS_INFO("Turning off the sonar");
208
            sonar_on = false;
209
        }
210
        else
211
        {
212
            ROS_INFO("Sonar state remains unchanged");
213
        }
214
        res.ack = true;
215
        return true;
216
    }
217

    
218
    bool Scout::handle_sonar_set_scan(::messages::sonar_set_scan::Request  &req,
219
                                      ::messages::sonar_set_scan::Response &res)
220
    {
221
        // Code to set the sonar to scan from
222
        // req.stop_l to req.stop_r
223
        if (req.stop_l>=0 and req.stop_r<=23 and req.stop_l<=req.stop_r)
224
        {
225
            ROS_INFO("Setting sonar scan range to [%i, %i]",
226
                     req.stop_l,
227
                     req.stop_r);
228
            sonar_stop_l = req.stop_l;
229
            sonar_stop_r = req.stop_r;
230
            sonar_position = req.stop_l;
231
            sonar_direction = 1;
232
            res.ack = true;
233
        }
234
        else
235
        {
236
            ROS_INFO("Bad Input: Input should be integers 0-23, stop_l<stop_r");
237
        }
238
        return true;
239
    }
240

    
241
    bool Scout::setPenCallback(scoutsim::SetPen::Request& req,
242
                               scoutsim::SetPen::Response&)
243
    {
244
        pen_on = !req.off;
245
        if (req.off)
246
        {
247
            return true;
248
        }
249

    
250
        wxPen pen(wxColour(req.r, req.g, req.b));
251
        if (req.width != 0)
252
        {
253
            pen.SetWidth(req.width);
254
        }
255

    
256
        pen = pen;
257
        return true;
258
    }
259

    
260
    bool Scout::query_encoders_callback(::messages::query_encoders::Request&,
261
                                        ::messages::query_encoders::Response& res)
262
    {
263
        res.fl_distance = fl_ticks;
264
        res.fr_distance = fr_ticks;
265
        res.bl_distance = bl_ticks;
266
        res.br_distance = br_ticks;
267

    
268
        return true;
269
    }
270

    
271
    bool Scout::query_linesensor_callback(::messages::query_linesensor::Request&,
272
                                          ::messages::query_linesensor::Response& res)
273
    {
274
        res.readings = linesensor_readings;
275

    
276
        return true;
277
    }
278

    
279
    // Scale to linesensor value
280
    unsigned int Scout::rgb_to_grey(unsigned char r,
281
                                    unsigned char g,
282
                                    unsigned char b)
283
    {
284
        // Should be 0 to 255
285
        unsigned int grey = ((unsigned int) r + (unsigned int) g + (unsigned int) b) / 3;
286

    
287
        /// @todo Convert to the proper range
288
        return 255 - grey;
289
    }
290

    
291
    unsigned int Scout::trace_sonar(const wxImage& walls_image, int x, int y,
292
                                    double robot_theta, int sonar_pos, 
293
                                    wxMemoryDC& sonar_dc)
294
    {
295
        double angle = robot_theta + (PI * ((float) sonar_pos) / 24.0) - PI / 2;
296
        unsigned int d = 0;
297

    
298
        unsigned int reading = 0;
299

    
300
        int d_x = 0;
301
        int d_y = 0;
302

    
303
        do
304
        {
305
            d_x = x + (int) floor(d * cos(angle));
306
            d_y = y - (int) floor(d * sin(angle));
307

    
308
            // Out of image boundary
309
            if (d_x < 0 || d_x >= walls_image.GetWidth() ||
310
                d_y < 0 || d_y >= walls_image.GetHeight())
311
            {
312
                break;
313
            }
314

    
315
            // Max range
316
            if (d > scoutsim::SONAR_MAX_RANGE_PIX)
317
            {
318
                break;
319
            }
320

    
321
            // Get the sonar reading at the current position of the sonar
322
            unsigned char r = walls_image.GetRed(d_x, d_y);
323
            unsigned char g = walls_image.GetGreen(d_x, d_y);
324
            unsigned char b = walls_image.GetBlue(d_x, d_y);
325
    
326
            reading = rgb_to_grey(r, g, b);
327
        
328
            d++;
329
        }
330
        /// @todo Consider using different cutoffs for different features
331
        while (reading < 128); /// @todo Get rid of hardcoded stuff like this
332
        
333
        if (sonar_visual_on)
334
        {   
335
            if (isFront)
336
            {
337
                // draw a circle at the wall_x, wall_y where reading > 128
338
                sonar_dc.SelectObject(*path_bitmap);
339
                sonar_dc.SetBrush(*wxRED_BRUSH); //old value
340
                sonar_dc.DrawCircle(wxPoint(old_front_dx, old_front_dy), 2);
341
                old_front_dx = d_x;
342
                old_front_dy = d_y;
343
            }
344
            else
345
            {
346
                // draw a circle at the wall_x, wall_y where reading > 128
347
                sonar_dc.SelectObject(*path_bitmap);
348
                sonar_dc.SetBrush(*wxRED_BRUSH); //old value
349
                sonar_dc.DrawCircle(wxPoint(old_back_dx,old_back_dy), 2);
350
                old_back_dx = d_x;
351
                old_back_dy = d_y;
352
            }
353

    
354
            sonar_dc.SetBrush(*wxGREEN_BRUSH);  //newest value
355
            sonar_dc.DrawCircle(wxPoint(d_x,d_y), 2);
356
            if (isFront) // @todo for some reason isFront = (!isFront) is not working
357
            {
358
                isFront = FALSE;
359
            }
360
            else
361
            {
362
                isFront = TRUE; 
363
            }
364
        }
365

    
366
        // Convert from pixels to mm and return
367
        return (unsigned int) ((1000 / PIX_PER_METER) * d);
368
    }
369

    
370
    // x and y is current position of the sonar
371
    void Scout::update_sonar(const wxImage& walls_image, int x, int y,
372
                             double robot_theta,wxMemoryDC& sonar_dc)
373
    {
374
        // Only rotate the sonar at the correct rate.
375
        if (ros::Time::now() - last_sonar_time < sonar_tick_time)
376
        {
377
            return;
378
        }
379
        last_sonar_time = ros::Time::now();
380

    
381
        unsigned int d_front = trace_sonar(walls_image, x, y, robot_theta,
382
                                           sonar_position, sonar_dc);
383
        unsigned int d_back = trace_sonar(walls_image, x, y, robot_theta,
384
                                          sonar_position + 24, sonar_dc);
385

    
386
        // Publish
387
        ::messages::sonar_distance msg;
388
        msg.pos = sonar_position;
389
        msg.distance0 = d_front;
390
        msg.distance1 = d_back;
391
        msg.stamp = ros::Time::now();
392

    
393
        sonar_pub.publish(msg);
394

    
395
        // Update the sonar rotation
396
        if (sonar_position + sonar_direction <= sonar_stop_r &&
397
            sonar_position + sonar_direction >= sonar_stop_l)
398
        {
399
            sonar_position = sonar_position + sonar_direction;
400
        }
401
        else
402
        {
403
            sonar_direction = -sonar_direction;
404
        }
405
    }
406

    
407
    void Scout::update_linesensor(const wxImage& lines_image, int x, int y,
408
                                  double robot_theta)
409
    {
410
        linesensor_readings.clear();
411

    
412
        double spacing = scout_image.GetWidth() / (NUM_LINESENSORS - 1);
413
        for (int s = 0; s < NUM_LINESENSORS; s++)
414
        {
415
            double offset = -(scout_image.GetWidth() / 2) + s * spacing;
416

    
417
            int sensor_x = (int) (x - LNSNSR_D * cos(robot_theta) -
418
                                  offset * sin(robot_theta));
419
            int sensor_y = (int) (y + LNSNSR_D * sin(robot_theta) -
420
                                  offset * cos(robot_theta));
421

    
422
            unsigned char r = lines_image.GetRed(sensor_x, sensor_y);
423
            unsigned char g = lines_image.GetGreen(sensor_x, sensor_y);
424
            unsigned char b = lines_image.GetBlue(sensor_x, sensor_y);
425

    
426
            unsigned int reading = rgb_to_grey(r, g, b);
427

    
428
            linesensor_readings.push_back(reading);
429
        }
430
    }
431

    
432
    /// Sends back the position of this scout so scoutsim can save
433
    /// the world state
434
    /// TODO remove dt param
435
    geometry_msgs::Pose2D Scout::update(double dt, wxMemoryDC& path_dc,
436
                                        wxMemoryDC& sonar_dc,
437
                                        const wxImage& path_image,
438
                                        const wxImage& lines_image,
439
                                        const wxImage& walls_image,
440
                                        wxColour background_color,
441
                                        wxColour sonar_color,
442
                                        world_state state)
443
    {
444
        // Assume that the two motors on the same side will be set to
445
        // roughly the same speed. Does not account for slip conditions
446
        // when they are set to different speeds.
447
        float l_speed = (float (motor_fl_speed + motor_bl_speed)) / 2;
448
        float r_speed = (float (motor_fr_speed + motor_br_speed)) / 2;
449

    
450
        // Find linear and angular movement in m
451
        float lin_dist = SIM_TIME_REFRESH_RATE * (l_speed + r_speed) / 2;
452
        float ang_dist = SIM_TIME_REFRESH_RATE * (r_speed - l_speed) / SCOUT_WIDTH;
453

    
454
        //store currently teleop'd scoutname
455
        //std::stringstream ss;
456
        //ss << "/" << teleop_scoutname;
457
        //current_teleop_scout = ss.str();
458

    
459
        Vector2 old_pos = pos;
460

    
461
        // Update encoders
462
        fl_ticks += (unsigned int) (motor_fl_speed * SIM_TIME_REFRESH_RATE *
463
                                    ENCODER_TICKS_PER_METER);
464
        fr_ticks += (unsigned int) (motor_fr_speed * SIM_TIME_REFRESH_RATE *
465
                                    ENCODER_TICKS_PER_METER);
466
        bl_ticks += (unsigned int) (motor_bl_speed * SIM_TIME_REFRESH_RATE *
467
                                    ENCODER_TICKS_PER_METER);
468
        br_ticks += (unsigned int) (motor_br_speed * SIM_TIME_REFRESH_RATE *
469
                                    ENCODER_TICKS_PER_METER);
470

    
471
        orient = fmod((float) (orient + ang_dist), (float) (2.0 * PI));
472

    
473
        pos.x += cos(orient) * lin_dist;
474
        pos.y -= sin(orient) * lin_dist; //Subtract because of the way the simulator handles y directions.
475

    
476
        // Clamp to screen size
477
        if (pos.x < 0 || pos.x >= state.canvas_width
478
                || pos.y < 0 || pos.y >= state.canvas_height)
479
        {
480
            ROS_WARN("I hit the wall! (Clamping from [x=%f, y=%f])", pos.x, pos.y);
481
        }
482

    
483
        pos.x = min(max(pos.x, 0.0f), state.canvas_width);
484
        pos.y = min(max(pos.y, 0.0f), state.canvas_height);
485

    
486
        int canvas_x = pos.x * PIX_PER_METER;
487
        int canvas_y = pos.y * PIX_PER_METER;
488

    
489

    
490
        {
491
            wxImage rotated_image =
492
                scout_image.Rotate(orient - PI/2.0,
493
                                   wxPoint(scout_image.GetWidth() / 2,
494
                                           scout_image.GetHeight() / 2),
495
                                   false);
496

    
497
            for (int y = 0; y < rotated_image.GetHeight(); ++y)
498
            {
499
                for (int x = 0; x < rotated_image.GetWidth(); ++x)
500
                {
501
                    if (rotated_image.GetRed(x, y) == 255
502
                            && rotated_image.GetBlue(x, y) == 255
503
                            && rotated_image.GetGreen(x, y) == 255)
504
                    {
505
                        rotated_image.SetAlpha(x, y, 0);
506
                    }
507
                }
508
            }
509

    
510
            scout = wxBitmap(rotated_image);
511
        }
512

    
513
        Pose p;
514
        p.x = pos.x;
515
        p.y = pos.y;
516
        p.theta = orient;
517
        p.linear_velocity = l_speed;
518
        p.angular_velocity = r_speed;
519
        pose_pub.publish(p);
520

    
521
        update_linesensor(lines_image, canvas_x, canvas_y, p.theta);
522
        if (sonar_on)
523
        {
524
            update_sonar(walls_image,
525
                         canvas_x + scoutsim::SCOUT_SONAR_X,
526
                         canvas_y + scoutsim::SCOUT_SONAR_Y,
527
                         p.theta,sonar_dc);
528

    
529
        }
530

    
531
        // Figure out (and publish) the color underneath the scout
532
        {
533
            //wxSize scout_size = wxSize(scout.GetWidth(), scout.GetHeight());
534
            Color color;
535
            color.r = path_image.GetRed(canvas_x, canvas_y);
536
            color.g = path_image.GetGreen(canvas_x, canvas_y);
537
            color.b = path_image.GetBlue(canvas_x, canvas_y);
538
            color_pub.publish(color);
539
        }
540

    
541
        ROS_DEBUG("[%s]: pos_x: %f pos_y: %f theta: %f",
542
                  node.getNamespace().c_str(), pos.x, pos.y, orient);
543

    
544
        if (pen_on)
545
        {
546
            if (pos != old_pos)
547
            {
548
                path_dc.SelectObject(*path_bitmap);
549
                path_dc.SetPen(pen);
550
                path_dc.DrawLine(pos.x * PIX_PER_METER, pos.y * PIX_PER_METER,
551
                                 old_pos.x * PIX_PER_METER, old_pos.y * PIX_PER_METER);
552
            }
553
        }
554

    
555
        geometry_msgs::Pose2D my_pose;
556
        my_pose.x = pos.x;
557
        my_pose.y = pos.y;
558
        my_pose.theta = orient;
559

    
560
        return my_pose;
561
    }
562

    
563
    void Scout::paint(wxDC& dc)
564
    {
565
        wxSize scout_size = wxSize(scout.GetWidth(), scout.GetHeight());
566
        dc.DrawBitmap(scout, pos.x * PIX_PER_METER - (scout_size.GetWidth() / 2),
567
                      pos.y * PIX_PER_METER - (scout_size.GetHeight() / 2), true);
568
    }
569

    
570
    void Scout::set_sonar_visual(bool on)
571
    {
572
        sonar_visual_on = on;
573
    }
574
}
575

    
576
/** @} */