MainProgram.java 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import java.awt.BorderLayout;
  2. import java.awt.event.KeyEvent;
  3. import java.awt.event.KeyListener;
  4. import java.awt.event.WindowEvent;
  5. import java.awt.event.WindowListener;
  6. import java.util.ArrayList;
  7. import java.util.Iterator;
  8. import javax.swing.JFrame;
  9. import javax.swing.JOptionPane;
  10. import javax.swing.JPanel;
  11. import javax.swing.JSplitPane;
  12. import javax.swing.SwingUtilities;
  13. import config.Map;
  14. import config.Models;
  15. import lejos.robotics.mapping.LineMap;
  16. import lejos.robotics.navigation.Pose;
  17. import robots.BluetoothRobot;
  18. import robots.DataRead;
  19. import robots.LCPRobot;
  20. import robots.Robot;
  21. import robots.RobotReturn;
  22. import robots.VirtualRobot;
  23. public class MainProgram extends JPanel implements KeyListener, WindowListener, RobotReturn {
  24. private MapImage imap;
  25. private Robot robot;
  26. private ScannerImage scanner;
  27. private Models model;
  28. private ProbabilityMatriz matriz;
  29. public static final byte FORWARD = 0;
  30. public static final byte STOP = 1;
  31. public static final byte EXIT = 2;
  32. public static final byte LEFT = 3;
  33. public static final byte RIGHT = 4;
  34. public static final byte BACKWARD = 5;
  35. public MainProgram(LineMap map, Robot robot) {
  36. this.robot = robot;
  37. JFrame frame = new JFrame("Mapa MAC0318");
  38. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  39. frame.setLayout(new BorderLayout());
  40. imap = new MapImage(map);
  41. scanner = new ScannerImage();
  42. model = new Models(map);
  43. // frame.add(this.map);
  44. frame.setSize(800, 800);
  45. frame.setVisible(true);
  46. frame.setFocusable(true);
  47. frame.requestFocusInWindow();
  48. frame.addKeyListener(this);
  49. frame.addWindowListener(this);
  50. JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scanner, imap);
  51. splitPane.setOneTouchExpandable(true);
  52. splitPane.setDividerLocation((int) (frame.getHeight() / 2));
  53. frame.add(splitPane);
  54. matriz = new ProbabilityMatriz(map.getBoundingRect(), 10, 9);
  55. crenca();
  56. // showHelp();
  57. }
  58. private void crenca() {
  59. for (DiscretePoint p: matriz) {
  60. // System.out.println(n(p.midAng()));
  61. if (p.z == 4 && p.x == 3 && p.y == 3)
  62. p.set(1);
  63. else
  64. p.set(0);
  65. }
  66. matriz.normalize();
  67. imap.showMatriz(matriz);
  68. }
  69. private double n (double x) {
  70. x = Math.toRadians(x);
  71. return Math.toDegrees(Math.atan2(Math.sin(x), Math.cos(x)));
  72. }
  73. private void showHelp() {
  74. String text = "1,2,3 - Change global map view\n";
  75. text += "l - Show global map trace.\n";
  76. text += "c - Clean maps.\n";
  77. text += "m - Enter robot movement.\n";
  78. text += "r - Enter robo rotation.\n";
  79. text += "a - Colect sonar data.\n";
  80. text += "z - Make sonar continuous scanner.\n";
  81. text += "i - Stop continuous scanner.\n";
  82. text += "g - Save global map image.\n";
  83. text += "f - Save scanner image.\n";
  84. text += "<arrows> - Move robot.\n";
  85. text += "h - help.\n";
  86. JOptionPane.showMessageDialog(null, text, "HELP", JOptionPane.PLAIN_MESSAGE);
  87. }
  88. public void addPoint(Pose p) {
  89. imap.addPoint(p);
  90. }
  91. @Override
  92. public void keyPressed(KeyEvent e) {
  93. char input = e.getKeyChar();
  94. switch (input) {
  95. case '1':
  96. imap.setVisual(0);
  97. break;
  98. case '2':
  99. imap.setVisual(1);
  100. break;
  101. case '3':
  102. imap.setVisual(2);
  103. break;
  104. case 'l':
  105. imap.showLine();
  106. break;
  107. case 'g':
  108. imap.save();
  109. break;
  110. case 'f':
  111. scanner.save();
  112. break;
  113. case 'c':
  114. imap.clean();
  115. scanner.clean();
  116. break;
  117. case 'm':
  118. moveRobot();
  119. break;
  120. case 'r':
  121. rotateRobot();
  122. break;
  123. case 'b':
  124. crenca();
  125. break;
  126. case 'a':
  127. colectSonar();
  128. break;
  129. case 'h':
  130. showHelp();
  131. break;
  132. case 's':
  133. // reseta a contagem
  134. System.out.println("resetou");
  135. matriz.setAll(1);
  136. matriz.normalize();
  137. imap.repaint();
  138. break;
  139. default:
  140. break;
  141. }
  142. if (robot == null)
  143. return;
  144. switch (e.getKeyCode()) {
  145. case KeyEvent.VK_UP:
  146. robot.moveForward();
  147. scanner.clean();
  148. break;
  149. case KeyEvent.VK_DOWN:
  150. robot.moveBackward();
  151. scanner.clean();
  152. break;
  153. case KeyEvent.VK_LEFT:
  154. robot.moveLeft();
  155. scanner.clean();
  156. break;
  157. case KeyEvent.VK_RIGHT:
  158. robot.moveRight();
  159. scanner.clean();
  160. break;
  161. }
  162. }
  163. private void colectSonar() {
  164. int interval;
  165. try {
  166. String rs = JOptionPane.showInputDialog("Interval (degress):");
  167. interval = Integer.parseInt(rs);
  168. } catch (Exception e) {
  169. return;
  170. }
  171. ArrayList<DataRead> data = robot.scann(-90, 90, interval);
  172. if (data == null) return;
  173. /* PROBABILIDADES DEPOIS LEITURA */
  174. for (DiscretePoint p: matriz) {
  175. Pose pose = p.pose();
  176. double prob = model.readProbability(pose, data);
  177. p.set(prob*p.get());
  178. }
  179. matriz.normalize();
  180. imap.setMatriz(matriz);
  181. for (DataRead d : data) {
  182. robotData(d);
  183. }
  184. System.out.println("... "+matriz.sum());
  185. imap.repaint();
  186. }
  187. private void rotateRobot() {
  188. try {
  189. String rs = JOptionPane.showInputDialog("Enter rotation (degress-clockwise):");
  190. double r = Double.parseDouble(rs);
  191. robot.rotate(r);
  192. rotateAndMoveRobot(0, r);
  193. } catch (Exception e) {
  194. }
  195. }
  196. private void moveRobot() {
  197. try {
  198. String rs = JOptionPane.showInputDialog("Enter distance (cm) - need to bigger than "+matriz.ssize+" cm:");
  199. double r = Double.parseDouble(rs);
  200. robot.move(r);
  201. if (r < matriz.ssize)
  202. moveRobot();
  203. else
  204. rotateAndMoveRobot(r, 0);
  205. } catch (Exception e) {
  206. }
  207. }
  208. private void rotateAndMoveRobot(double move, double ang) {
  209. /* PROBABILIDADES DEPOIS MOVIMENTO */
  210. ProbabilityMatriz newmatriz = new ProbabilityMatriz(matriz.bounds, matriz.ssize, matriz.alphad);
  211. System.out.print("Iniciando...");
  212. // Verifica o numero de cores
  213. int cores = Runtime.getRuntime().availableProcessors();
  214. // tudo isso
  215. ArrayList<Thread> threads = new ArrayList<Thread>();
  216. for (int i = 0; i < cores; i++) {
  217. Iterator<DiscretePoint> iteretor = newmatriz.iteratorSet((newmatriz.totalsize*i)/cores, newmatriz.totalsize*(i+1)/cores);
  218. Thread thread = new Thread () {
  219. public void run() {
  220. while(iteretor.hasNext()) {
  221. DiscretePoint newp = iteretor.next();
  222. double sum = 0;
  223. for (DiscretePoint p: matriz) {
  224. Pose pa = p.pose();
  225. Pose pb = newp.pose();
  226. sum += model.motionModelOdometry(pa, pb, move, ang)*p.get();
  227. }
  228. newp.set(sum);
  229. }
  230. }
  231. };
  232. thread.start();
  233. threads.add(thread);
  234. }
  235. for (Thread thread: threads) {
  236. try {
  237. thread.join();
  238. } catch (InterruptedException e) {
  239. }
  240. }
  241. // OU ISSO
  242. // for (DiscretePoint newp: newmatriz) {
  243. // double sum = 0;
  244. // for (DiscretePoint p: matriz) {
  245. // Pose pa = p.pose();
  246. // Pose pb = newp.pose();
  247. // sum += model.motionModelOdometry(pa, pb, move, ang)*p.get();
  248. // }
  249. // newp.set(sum);
  250. // }
  251. matriz = newmatriz;
  252. imap.setMatriz(matriz);
  253. matriz.normalize();
  254. System.out.println("Finalizado "+matriz.sum());
  255. scanner.clean();
  256. imap.repaint();
  257. }
  258. @Override
  259. public void keyReleased(KeyEvent arg0) {
  260. if (robot == null)
  261. return;
  262. robot.stop();
  263. }
  264. @Override
  265. public void keyTyped(KeyEvent arg0) {
  266. }
  267. @Override
  268. public void windowOpened(WindowEvent e) {
  269. }
  270. @Override
  271. public void windowClosing(WindowEvent e) {
  272. System.err.println("Fechando...");
  273. if (robot == null)
  274. return;
  275. robot.disconnect();
  276. }
  277. @Override
  278. public void windowClosed(WindowEvent e) {
  279. }
  280. @Override
  281. public void windowIconified(WindowEvent e) {
  282. }
  283. @Override
  284. public void windowDeiconified(WindowEvent e) {
  285. }
  286. @Override
  287. public void windowActivated(WindowEvent e) {
  288. }
  289. @Override
  290. public void windowDeactivated(WindowEvent e) {
  291. }
  292. @Override
  293. public void robotData(DataRead data) {
  294. // posicao do robo
  295. // System.out.print(" sang:"+data.getSensorAngle());
  296. // System.out.println(" distance:"+data.getDistance());
  297. scanner.addRead(data.getDistance(), data.getSensorAngle()-90);
  298. }
  299. public static void main(String[] args) {
  300. LineMap map = Map.makeMap();
  301. Robot robotv = new VirtualRobot(map);
  302. Robot robotbt = new BluetoothRobot("NXT");
  303. String s = "LCPRobot";
  304. Object[] possibleValues = { robotv, robotbt, s };
  305. Object robottmp = JOptionPane.showInputDialog(null, "Choose one", "Input", JOptionPane.PLAIN_MESSAGE, null,
  306. possibleValues, possibleValues[0]);
  307. Robot robot;
  308. boolean result = false;
  309. if (robottmp == s) {
  310. robot = new LCPRobot();
  311. } else {
  312. robot = (Robot) robottmp;
  313. }
  314. if (robot != null)
  315. result = ((Robot) robot).connect();
  316. if (result == false) {
  317. JOptionPane.showMessageDialog(null, "Não foi possível conectar ao robô");
  318. System.exit(ERROR);
  319. }
  320. SwingUtilities.invokeLater(new Runnable() {
  321. public void run() {
  322. new MainProgram(map, (Robot) robot);
  323. }
  324. });
  325. }
  326. }