summaryrefslogtreecommitdiff
path: root/i/marvin/src/ai/ai.cc
blob: 373fe2a450671f251ac571b0615f85d83b60effb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// AI.CC
// marvin - programme du robot 2006. {{{
//
// Copyright (C) 2006 Nicolas Haller
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Contact :
//        Web: http://perso.efrei.fr/~haller/
//      Email: <nicolas@boiteameuh.org>
// }}}
#include "ai.hh"
#include "config/config.hh"
#include "timer/timer.hh"

/// Fonction callback useless
static void
callback (void)
{}

//constructeur
Ai::Ai (const Config & config)
    :es_(config), log_ ("Ai"),
     schedulableMotor_(callback, motor_.getFd()),
     schedulableEs_(callback, es_.getFd()),
     round_duration_ (config.get<int> ("ai.round_duration")),
     schedule_time_ (config.get<int> ("ai.schedule_time")),
     reference_sensor_mask_ (config.get<int> ("ai.ref_sensor_mask"))
{
    scheduler_.insert (schedulableMotor_);
    scheduler_.insert (schedulableEs_);
}

Ai::~Ai(void)
{
    // On r�initialise
    // Initialise les moteurs
    // XXX
    motor_.reset  ();
    // initialise la carte es
    es_.reset ();
    // On sync
    do
      {
	scheduler_.schedule (500, true);
      }
    while (!sync ());
}

// Initialisation du robal
void
Ai::init (void)
{
    // Initialisation de motor
    motor_.reset ();
    // Initialisation de la carte Es
    es_.reset ();
    // Paf on sync
    while (!update ());
}

/// Stop the mouvement of the motor
void
Ai::stop (void)
{
    motor_.stop ();
    // XXX In fact, we should wait a little here...
    while (!update ());
}

/// Synchronize data of under class
bool
Ai::sync (void)
{
	bool motor = motor_.sync ();
	bool es = es_.sync ();
    return es && motor;
}

/// Wait for something to happened
bool
Ai::update (void)
{
    /// Wait schedule_time 
    scheduler_.schedule (schedule_time_, true);
    bool retour = sync ();
    // On v�rifie que le match n'est pas fini
    if (Timer::getRoundTime () > round_duration_)
	throw std::runtime_error ("End of match ! You win !");
    return retour;
}

/// Function to wait a little but still syncing data
void
Ai::temporisation(int msec)
{
    // Get current time of process
    int time = Timer::getProgramTime();
    time += msec;
    // Update until we have spend enough time
    do
    {
        update();
    }
    while (time > Timer::getProgramTime());
}

/// Wait until jack is out (true) or in (false)
void
Ai::waitJack (bool out)
{
    do
      {
	update ();
      }
    while (es_.isJackOut () != out);
}

/// Init things for a match.
void
Ai::prepare (void)
{
    es_.lcdPrint("");
    es_.lcdPrint("Prepa match...");
    es_.lcdPrint("Inserer Jack");
    es_.setOthersStat (10);
    while (!update ());
    // XXX We should check if the jack is not already in
    // We first wait for the jack to be put inside
    waitJack (false);
    // We reference all the color
    referenceSensors ();
    es_.barilletInit();
    es_.lcdPrint("Barillet pret ?");
    es_.lcdPrint("Virer le jack !");
    while (!update ());
    // We first wait for the jack to be put inside
    waitJack (true);
    // Set actual position
    motor_.getAsserv().setPos(0,0,0);
    // Ok the match begin ! Go go go !
    Timer::startRound ();
    es_.setOthersStat (0);
    // Shut up fucking beach !
    es_.setOthersStat (0);
    es_.setOthersStat (0);
    while (!update ());
}

/// Some after after a match
void
Ai::afterMatch(void)
{
    // On attend de mettre le jack apr�s le match
    es_.lcdPrint("FIN DU MATCH");
//     es_.lcdPrint("Inserer jack...");
    while (!update());
    waitJack(false);
    // On vide le barillet
    es_.barilletEmpty();
    es_.lcdPrint("Vidange barillet");
    while (!update());
    waitJack(true);
    // On init les cartes histoire de
    es_.reset();
    motor_.reset();
    es_.lcdPrint("Power off!!");
    while (!update());
}
    
/// Reference sensors
void
Ai::referenceSensors (void)
{
    // Reference sensors
    es_.refColor (reference_sensor_mask_);
    // Update data
    while (!update ());
    // Disable capturing all sensors
    es_.enableAllSensors (false);
    // Update data
    while (!update ());
}

/// programme d'homologation du robal
void Ai::progHomoloRobal(void)
{
    /// On init le robal
    prepare();
    es_.barilletDebutLancement();
    while (!update ());
    temporisation (1000);
    es_.barilletLancement();
    while (!update ());
    /// on avance un poil parce que le mur c'est mal
    std::cout << "Move !" << std::endl;
    motorMove(500, 0);
    std::cout << "Rotate !" << std::endl;
    motorRotate(-0.54);
    std::cout << "Move !" << std::endl;
    motorMove(1200, 0);
    std::cout << "Rotate !" << std::endl;
    motorRotate(1.40);
    motorMove(500, 0);
//    temporisation (100);
    std::cout << "Find hole !" << std::endl;
    motorBasicFindHole ();
    
    /// On tourne XXX
///     motorRotate(-M_PI/4);
    /// On cherche au moins une balle (sinon c'est con)
///     motorMove(1000, 0); /// XXX Voir la distance
    /// XXX Avancer d'une certaine facon pour choper des balles
    /// XXX Ouais ba y'a encore ddes truc � faire l�
    /// On cherche un tru (repositionnement??)
///     motor_.lockGoodHole();
///     while (!update ());
///     motor_.findHole();
///     while (!update ());
    /// On trouve un trou, chouette
    /// Aspirer le trou
    //es_.extraitBalle();
    /// mettre une baballe
    es_.dropWhiteBall();
    while (!update ());
    temporisation (3000);
    es_.deposeBalle ();
    while (!update ());
    temporisation (3000);
    motorMove(300, 0);

    std::cout << "Find hole !" << std::endl;
    motorBasicFindHole ();
    es_.dropWhiteBall();
    while (!update ());
    temporisation (3000);
    es_.deposeBalle ();
    while (!update ());
    temporisation (3000);
    motorMove(300, 0);
    /// Tourner 3 fois en chantant du Mickael Jackson
    /// Again....
    /// Fin du match
    afterMatch();
}

void
Ai::progMatch(void)
{
    double dummy, aStart, aEnd;
    init ();
//     bool isFinish;
    /// On pr�pare le robot
    prepare();
    /// Faire des cr�pes...
    /// Init du barillet
    es_.barilletDebutLancement();
    while (!update ());
    temporisation (1000);
    es_.barilletLancement();
    while (!update ());
    log_ ("match") << "Totem activator";
    es_.totemActivator (true);
    /// En avant guingamp
    log_ ("match") << "Eloignement du bord";
    motorMove(480,0);
    /// On tourner de -90�
    log_ ("match") << "Petite rotation de 90�";
    motorMove(216,-216);
    /// On dit bonjour au mur
    log_ ("match") << "Va � l'oppos�";
    if (!motorMove (1000, 0))
      {
	log_ ("match") << "Un mur ! Reculons";
	motorMove (-60, 0);
      }
// 	motorMove(200, 0);
    /// On tourne bizarrement mais de 90�
    log_ ("match") << "On tourne � 90� en deux fois";
    motorMove(-36,36);
    motorMove(180, 180);
    /// On avance un peu
//     log_ ("match") << "On recule un peu";
//     motorMove (-110, 0);
//     // On tourne de 90�
//     log_ ("match") << "On tourne vers le totem";
//     motorMove (216, 216);
//     log_ ("match") << "On avance";
//     motorMove (950, 0);
//     log_ ("match") << "Petite rotation de 90� droite";
//     motorMove (316, -316);
//     motorMove (800, 0);
//     motorBasicFindHole ();
    log_ ("match") << "On avance de l'autre cot�";
    motorMove (1420, 0);
    log_ ("match") << "On recule un peu";
    motorMove (-150, 0);
    log_ ("match") << "On tourne";
    motorMove (216, 216);
    motorMove (-150, 0);

    /* Here, we are in front of all our holes */

    int rotationSens = 1;
    const double distanceMax[2] = { -1600, -200 };
    double distanceCur;

    motor_.getPosition (dummy, distanceCur, aStart);
    do
      {
	// TODO compute remaining value
	// alors une petite blague : Comment les alsacien aime-t-il les oeufs
	// ?
	// r�ponse : Hopla !!!! (Tb) :-)
	log_ ("match") << "Start loop for find hole";

	
	motor_.getPosition (dummy, distanceCur, dummy);
	
	int ret = motorSmartFindHole (distanceCur - distanceMax[rotationSens % 2]);
	switch (ret)
	  {
	  case 0:
	    log_ ("match") << "Trop long, demi tour !";
	    if (rotationSens % 2)
		motor_.move (432, -432);
	    else
		motor_.move (432, 432);
	    rotationSens++;
	    // Distance d�pass�
	    // Here we should turn back in the other way
	    break;
	  case -2:
	    /// La couleur est unknown
	    log_ ("match") << "Hooooo une couleur de l'espace!!!!";
	    // break;
	  case 2:
	  case 1:
	      {
		log_ ("match") << "Ok on a une couleur!";
		bool retDrop;
		//if (((ret == es_.blueColor_) && es_.isColorModeBlue () )
		//    || ((ret != es_.blueColor_) && !es_.isColorModeBlue ()))
		if(true)
		  {
		    log_ ("match") << "C'est notre couleur!";
		    // If it is our colour, put a white ball,
		    log_ ("match") << "Drop blanc!";
		    retDrop = es_.dropWhiteBall();
		    while (!update ());
		    if (retDrop)
		      {
			log_ ("match") << "Tempo & depot!";
			temporisation (3000);
			es_.deposeBalle ();
			while (!update ());
		      }
		  }
		else
		  {
		    log_ ("match") << "Drop noir!";
		    retDrop = es_.dropBlackBall();
		    while (!update ());
		    if (retDrop)
		      {
			log_ ("match") << "Tempo & depot!";
			temporisation (3000);
			es_.deposeBalle ();
			while (!update ());
			// otherwise, put a black one.
		      }
		  }
	      }
	    break;
	  default:
	    log_ ("match") << "Hooooo on a default!!!!";
	    break;
	  }
	motor_.getPosition (dummy, dummy, aEnd);
	log_ ("match") << "Remise en place de l'angle! " << aStart - aEnd;
	motor_.rotate (aStart - aEnd);
	motor_.getPosition (dummy, dummy, aStart);
      } while (true);

    afterMatch();
}

/// Avance le robal et dit si il a finit (true) ou si il a bloqu�
bool
Ai::motorMove (int d, int a)
{
    motor_.move(d, a); /// XXX Voir la distance
    do
      {
	update ();
      }
    while (!motor_.finish ()/* && !motor_.blocked()*/);
    if(motor_.finish())
	return true;
    return false;
}

void
Ai::motorRotate (double d)
{
    motor_.rotate (d);
    do
	{
	  update ();
	}
    while (!motor_.finish ());
}

void
Ai::motorBasicFindHole (void)
{
    motor_.findHole ();
    do
      {
	update ();
      }
    while (!motor_.finish ());
}

/// Renvoie une couleur d�finie dans es ou -1 si on s'est mang� un mur ou 0 si
/// distanceOut
int
Ai::motorSmartFindHole (double distOut)
{
    /// On sauvegarde la position actuelle
    double bx, x, by, y, ba, a;
    double dist;
    motor_.getPosition(bx, by, ba);
    /// on lance le robal � la recherche d'un tru
    motor_.findHole();
    do
      {
	update();
	if (distOut != 0)
	  {
	    /// On regarde si on a pas atteint la distOut
	    motor_.getPosition(x, y, a);
	    /// XXX C'est propre �a?
	    dist = sqrt(((x - bx)*(x - bx)) + ((y - by)*(y - by)));
	    if (dist > distOut)
		return 0;
	  }
	/// on regarde si les capteurs voit un trou
	if(es_.colorSeen(es_.leftFrontRVB_) == es_.redColor_ ||
	   es_.colorSeen(es_.leftFrontRVB_) == es_.blueColor_)
	  {
	    // Si c'est le cas on repositionne le robot
	    motor_.stop();
	    while(!update());
	    // XXX V�rifier l'angle
	    motorRotate(0.21);
	    motor_.findHole();
	  }
	else if(es_.colorSeen(es_.rightFrontRVB_) == es_.redColor_ ||
		es_.colorSeen(es_.rightFrontRVB_) == es_.blueColor_)
	  {
	    // Si c'est le cas on repositionne le robot
	    motor_.stop();
	    while(!update());
	    // XXX V�rifier l'angle
	    log_ ("SmartFindHole") << "Rotation sp�ciale ho un trou sous le capteur";
	    motorRotate(-0.21);
	    motor_.findHole();
	  }
      }
    while (!motor_.finish() /*&& !motor_.blocked()*/);
    /// On regarde si on a block�
//    if(motor_.blocked())
//	return -1;
    if(motor_.finish())
      {
	es_.enableAllSensors (true);
	temporisation (100);
	int ret = es_.colorSeen(es_.holeRVB_);
	es_.enableAllSensors (false);
	return ret;
      }
    /// XXX Le return qui ne doit jamais arriver normalement...
    return 0;
}

/// Procedure to unblock the robal
void
Ai::motorDeblock (void)
{
}