robot.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import numpy as np
  2. import math
  3. import bluetooth
  4. class Robot( object ):
  5. """Move o robo distance centimetros"""
  6. def move(self, distance):
  7. raise NotImplementedError( "Should have implemented this" )
  8. """Roda o robo radians no sentido horario"""
  9. def rotate(self, radians):
  10. raise NotImplementedError( "Should have implemented this" )
  11. """Retornar verdadeiro ou falso, verdadeiro se leu branco."""
  12. def read(self):
  13. raise NotImplementedError( "Should have implemented this" )
  14. # ------------------------------------------------------------------------
  15. class VirtualRobot(Robot):
  16. def __init__(self, worldmap):
  17. self.x = np.random.rand()*worldmap.width
  18. self.y = np.random.rand()*worldmap.height
  19. self.heading = math.pi*2*np.random.rand()
  20. self.worldmap = worldmap
  21. def move(self, distance):
  22. self.x = self.x + (math.cos(self.heading) * distance)
  23. self.y = self.y + (math.sin(self.heading) * distance)
  24. def rotate(self, radians):
  25. self.heading += float(radians)
  26. self.heading %= 2 * math.pi
  27. def read(self):
  28. return self.worldmap.white(self.x, self.y)
  29. # ------------------------------------------------------------------------
  30. class LejosRobot(Robot):
  31. def __init__(self, mac):
  32. self.blt = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
  33. self.blt.connect((mac, 1))
  34. def move(self, distance):
  35. d = int(d)
  36. if d > 0 and d < 255:
  37. self.blt.send(bytes([0x1, byte(d)]))
  38. self.blt.recv(32)
  39. def rotate(self, radians):
  40. r = int(radians*255/(math.pi*2))
  41. if r > 0 and r < 255:
  42. self.blt.send(bytes([0x2, byte(r)]))
  43. self.blt.recv(32)
  44. def read(self):
  45. self.blt.send(bytes([0x3]))
  46. data = self.blt.recv(32)
  47. if data and int (data.decode("ascii")) < 40:
  48. return True
  49. else:
  50. return False