Statistics
| Branch: | Revision:

root / scout / scoutsim / src / scout.cpp @ 68b23184

History | View | Annotate | Download (14.7 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
#include "scout.h"
49

    
50
#include <wx/wx.h>
51

    
52
#define DEFAULT_PEN_R 0xb3
53
#define DEFAULT_PEN_G 0xb8
54
#define DEFAULT_PEN_B 0xff
55

    
56
using namespace std;
57

    
58
namespace scoutsim
59
{
60
    Scout::Scout(const ros::NodeHandle& nh,
61
                 const wxImage& scout_image,
62
                 const Vector2& pos,
63
                 wxBitmap *path_bitmap,
64
                 float orient)
65
        : path_bitmap(path_bitmap)
66
          , sonar_on(sonar_on)
67
          , node (nh)
68
          , scout_image(scout_image)
69
          , pos(pos)
70
          , orient(orient)
71
          , motor_fl_speed(0)
72
          , motor_fr_speed(0)
73
          , motor_bl_speed(0)
74
          , motor_br_speed(0)
75
          , fl_ticks(0)
76
          , fr_ticks(0)
77
          , bl_ticks(0)
78
          , br_ticks(0)
79
          , pen_on(true)
80
          , pen(wxColour(DEFAULT_PEN_R, DEFAULT_PEN_G, DEFAULT_PEN_B))
81
    {
82
        pen.SetWidth(3);
83
        scout = wxBitmap(scout_image);
84

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

    
87
        pose_pub = node.advertise<Pose>("pose", 1);
88
        color_pub = node.advertise<Color>("color_sensor", 1);
89
        sonar_pub = node.advertise<sonar::sonar_distance>("sonar_distance", 1);
90
        set_pen_srv = node.advertiseService("set_pen",
91
                                            &Scout::setPenCallback,
92
                                            this);
93
        query_encoders_srv =
94
            node.advertiseService("query_encoders",
95
                                  &Scout::query_encoders_callback,
96
                                  this);
97

    
98
        query_linesensor_srv =
99
            node.advertiseService("query_linesensor",
100
                                  &Scout::query_linesensor_callback,
101
                                  this);
102

    
103
        for (unsigned int i = 0; i < NUM_LINESENSORS; i++)
104
        {
105
            linesensor_readings.push_back(0);
106
        }
107

    
108
        meter = scout.GetHeight();
109

    
110
        // Initialize sonar
111
        sonar_position = 0;
112
        sonar_stop_l = 0;
113
        sonar_stop_r = 23;
114
        sonar_direction = 1;
115
        sonar_tick_time = ros::Duration(scoutsim::SONAR_HALF_SPIN_TIME / 24.0);
116
    }
117

    
118
    /**
119
     * A callback function that sets velocity based on a set_motors
120
     * request.
121
     * @todo Use "callback" in all callback function names? Or remove?
122
     */
123
    void Scout::setMotors(const motors::set_motors::ConstPtr& msg)
124
    {
125
        last_command_time = ros::WallTime::now();
126

    
127
        if(msg->fl_set)
128
        {
129
            motor_fl_speed = msg->fl_speed;
130
        }
131
        if(msg->fr_set)
132
        {
133
            motor_fr_speed = msg->fr_speed;
134
        }
135
        if(msg->bl_set)
136
        {
137
            motor_bl_speed = msg->bl_speed;
138
        }
139
        if(msg->br_set)
140
        {
141
            motor_br_speed = msg->br_speed;
142
        }
143

    
144
    }
145

    
146
    bool Scout::setPenCallback(scoutsim::SetPen::Request& req,
147
                               scoutsim::SetPen::Response&)
148
    {
149
        pen_on = !req.off;
150
        if (req.off)
151
        {
152
            return true;
153
        }
154

    
155
        wxPen pen(wxColour(req.r, req.g, req.b));
156
        if (req.width != 0)
157
        {
158
            pen.SetWidth(req.width);
159
        }
160

    
161
        pen = pen;
162
        return true;
163
    }
164

    
165
    bool Scout::query_encoders_callback(encoders::query_encoders::Request&,
166
                                        encoders::query_encoders::Response& res)
167
    {
168
        res.fl_distance = fl_ticks;
169
        res.fr_distance = fr_ticks;
170
        res.bl_distance = bl_ticks;
171
        res.br_distance = br_ticks;
172

    
173
        return true;
174
    }
175

    
176
    bool Scout::query_linesensor_callback(linesensor::query_linesensor::Request&,
177
                                          linesensor::query_linesensor::Response& res)
178
    {
179
        res.readings = linesensor_readings;
180

    
181
        return true;
182
    }
183

    
184
    // Scale to linesensor value
185
    unsigned int Scout::rgb_to_grey(unsigned char r,
186
                                    unsigned char g,
187
                                    unsigned char b)
188
    {
189
        // Should be 0 to 255
190
        unsigned int grey = ((unsigned int) r + (unsigned int) g + (unsigned int) b) / 3;
191

    
192
        /// @todo Convert to the proper range
193
        return 255 - grey;
194
    }
195

    
196
    unsigned int Scout::trace_sonar(const wxImage& walls_image, int x, int y,
197
                                    double robot_theta, int sonar_pos, wxMemoryDC& sonar_dc, bool sonar_on)
198
    {
199
        double angle = robot_theta + (PI * ((float) sonar_pos) / 24.0) - PI / 2;
200
        unsigned int d = 0;
201

    
202
        unsigned int reading = 0;
203
        int d_x = 0;
204
        int d_y = 0;
205
        do
206
        {
207
            d_x = x + (int) floor(d * cos(angle));
208
            d_y = y + (int) floor(d * sin(angle));
209

    
210
            // Out of image boundary
211
            if (d_x < 0 || d_x >= walls_image.GetWidth() ||
212
                d_y < 0 || d_y >= walls_image.GetHeight())
213
            {
214
                return d;
215
            }
216

    
217
            // Max range
218
            if (d > scoutsim::SONAR_MAX_RANGE)
219
            {
220
                return d;
221
            }
222

    
223
            // Get the sonar reading at the current position of the sonar
224
            unsigned char r = walls_image.GetRed(d_x, d_y);
225
            unsigned char g = walls_image.GetGreen(d_x, d_y);
226
            unsigned char b = walls_image.GetBlue(d_x, d_y);
227
        
228
            reading = rgb_to_grey(r, g, b);
229
            
230

    
231
            d++;
232
        }
233
        /// @todo Consider using different cutoffs for different features
234
        while (reading < 128); /// @todo Get rid of hardcoded stuff like this
235
        
236
        if(sonar_on == TRUE)
237
        {        
238
                // draw a circle at the wall_x, wall_y where reading > 128
239
                sonar_dc.SelectObject(*path_bitmap);
240
                sonar_dc.SetBrush(*wxRED_BRUSH); //old value
241
                sonar_dc.DrawCircle(wxPoint(old_dx,old_dy), 2);
242

    
243
                sonar_dc.SetBrush(*wxGREEN_BRUSH);  //newest value
244
                sonar_dc.DrawCircle( wxPoint(d_x,d_y), 2);
245
                old_dx = d_x;
246
                old_dy = d_y;
247
        }
248
        return d;
249
    }
250

    
251
    // x and y is current position of the sonar
252
    void Scout::update_sonar(const wxImage& walls_image, int x, int y,
253
                             double robot_theta,wxMemoryDC& sonar_dc, bool sonar_on)
254
    {
255
        // Only rotate the sonar at the correct rate.
256
        if (ros::Time::now() - last_sonar_time < sonar_tick_time)
257
        {
258
            return;
259
        }
260
        last_sonar_time = ros::Time::now();
261

    
262
        unsigned int d_front = trace_sonar(walls_image, x, y, robot_theta,
263
                                           sonar_position,sonar_dc, sonar_on);
264
        unsigned int d_back = trace_sonar(walls_image, x, y, robot_theta,
265
                                          sonar_position + 24,sonar_dc, sonar_on);
266

    
267
        // Publish
268
        sonar::sonar_distance msg;
269
        msg.pos = sonar_position;
270
        msg.distance0 = d_front;
271
        msg.distance1 = d_back;
272

    
273
        sonar_pub.publish(msg);
274

    
275
        // Update the sonar rotation
276
        if (sonar_position + sonar_direction <= sonar_stop_r &&
277
            sonar_position + sonar_direction >= sonar_stop_l)
278
        {
279
            sonar_position = sonar_position + sonar_direction;
280
        }
281
        else
282
        {
283
            sonar_direction = -sonar_direction;
284
        }
285
    }
286

    
287
    void Scout::update_linesensor(const wxImage& lines_image, int x, int y,
288
                                  double robot_theta)
289
    {
290
        linesensor_readings.clear();
291

    
292
        double spacing = scout_image.GetWidth() / (NUM_LINESENSORS - 1);
293
        for (int s = 0; s < NUM_LINESENSORS; s++)
294
        {
295
            double offset = -(scout_image.GetWidth() / 2) + s * spacing;
296

    
297
            int sensor_x = (int) (x - LNSNSR_D * cos(robot_theta) -
298
                                  offset * sin(robot_theta));
299
            int sensor_y = (int) (y + LNSNSR_D * sin(robot_theta) -
300
                                  offset * cos(robot_theta));
301

    
302
            unsigned char r = lines_image.GetRed(sensor_x, sensor_y);
303
            unsigned char g = lines_image.GetGreen(sensor_x, sensor_y);
304
            unsigned char b = lines_image.GetBlue(sensor_x, sensor_y);
305

    
306
            unsigned int reading = rgb_to_grey(r, g, b);
307

    
308
            linesensor_readings.push_back(reading);
309
        }
310
    }
311

    
312
    /// Sends back the position of this scout so scoutsim can save
313
    /// the world state
314
    geometry_msgs::Pose2D Scout::update(double dt, wxMemoryDC& path_dc,
315
                                        wxMemoryDC& sonar_dc,
316
                                        bool sonar_on,
317
                                        const wxImage& path_image,
318
                                        const wxImage& lines_image,
319
                                        const wxImage& walls_image,
320
                                        wxColour background_color,
321
                                        wxColour sonar_color,
322
                                        world_state state)
323
    {
324
        // Assume that the two motors on the same side will be set to
325
        // roughly the same speed. Does not account for slip conditions
326
        // when they are set to different speeds.
327
        float l_speed = (float (motor_fl_speed + motor_bl_speed)) / 2;
328
        float r_speed = (float (motor_fr_speed + motor_br_speed)) / 2;
329

    
330
        // Set the linear and angular speeds
331
        float lin_vel = SPEED_SCALE_FACTOR * (l_speed + r_speed) / 2;
332
        float ang_vel = SPEED_SCALE_FACTOR * (r_speed - l_speed);
333

    
334
        Vector2 old_pos = pos;
335

    
336
        // Update encoders
337
        /// @todo replace
338
        fl_ticks += (unsigned int) motor_fl_speed;
339
        fr_ticks += (unsigned int) motor_fr_speed;
340
        bl_ticks += (unsigned int) motor_bl_speed;
341
        br_ticks += (unsigned int) motor_br_speed;
342

    
343
        orient = fmod(orient + ang_vel * dt, 2*PI);
344
        pos.x += sin(orient + PI/2.0) * lin_vel * dt;
345
        pos.y += cos(orient + PI/2.0) * lin_vel * dt;
346

    
347
        // Clamp to screen size
348
        if (pos.x < 0 || pos.x >= state.canvas_width
349
                || pos.y < 0 || pos.y >= state.canvas_height)
350
        {
351
            ROS_WARN("Oh no! I hit the wall! (Clamping from [x=%f, y=%f])", pos.x, pos.y);
352
        }
353

    
354
        pos.x = min(max(pos.x, 0.0f), state.canvas_width);
355
        pos.y = min(max(pos.y, 0.0f), state.canvas_height);
356

    
357
        int canvas_x = pos.x * meter;
358
        int canvas_y = pos.y * meter;
359

    
360
        {
361
            wxImage rotated_image =
362
                scout_image.Rotate(orient - PI/2.0,
363
                                   wxPoint(scout_image.GetWidth() / 2,
364
                                           scout_image.GetHeight() / 2),
365
                                   false);
366

    
367
            for (int y = 0; y < rotated_image.GetHeight(); ++y)
368
            {
369
                for (int x = 0; x < rotated_image.GetWidth(); ++x)
370
                {
371
                    if (rotated_image.GetRed(x, y) == 255
372
                            && rotated_image.GetBlue(x, y) == 255
373
                            && rotated_image.GetGreen(x, y) == 255)
374
                    {
375
                        rotated_image.SetAlpha(x, y, 0);
376
                    }
377
                }
378
            }
379

    
380
            scout = wxBitmap(rotated_image);
381
        }
382

    
383
        Pose p;
384
        p.x = pos.x;
385
        p.y = state.canvas_height - pos.y;
386
        p.theta = orient;
387
        p.linear_velocity = lin_vel;
388
        p.angular_velocity = ang_vel;
389
        pose_pub.publish(p);
390

    
391
        update_linesensor(lines_image, canvas_x, canvas_y, p.theta);
392
        update_sonar(walls_image,
393
                     canvas_x + scoutsim::SCOUT_SONAR_X,
394
                     canvas_y + scoutsim::SCOUT_SONAR_Y,
395
                     p.theta,sonar_dc,sonar_on);
396

    
397
        // Figure out (and publish) the color underneath the scout
398
        {
399
            //wxSize scout_size = wxSize(scout.GetWidth(), scout.GetHeight());
400
            Color color;
401
            color.r = path_image.GetRed(canvas_x, canvas_y);
402
            color.g = path_image.GetGreen(canvas_x, canvas_y);
403
            color.b = path_image.GetBlue(canvas_x, canvas_y);
404
            color_pub.publish(color);
405
        }
406

    
407
        ROS_DEBUG("[%s]: pos_x: %f pos_y: %f theta: %f",
408
                  node.getNamespace().c_str(), pos.x, pos.y, orient);
409

    
410
        if (pen_on)
411
        {
412
            if (pos != old_pos)
413
            {
414
                path_dc.SelectObject(*path_bitmap);
415
                path_dc.SetPen(pen);
416
                path_dc.DrawLine(pos.x * meter, pos.y * meter,
417
                                 old_pos.x * meter, old_pos.y * meter);
418
            }
419
        }
420

    
421
        geometry_msgs::Pose2D my_pose;
422
        my_pose.x = pos.x;
423
        my_pose.y = pos.y;
424
        my_pose.theta = orient;
425

    
426
        return my_pose;
427
    }
428

    
429
    void Scout::paint(wxDC& dc)
430
    {
431
        wxSize scout_size = wxSize(scout.GetWidth(), scout.GetHeight());
432
        dc.DrawBitmap(scout, pos.x * meter - (scout_size.GetWidth() / 2),
433
                      pos.y * meter - (scout_size.GetHeight() / 2), true);
434
    }
435

    
436
}