Esempio n. 1
0
"""
Test bandwidth of 915 MHz telemetry radios to explore streaming real-time data
from the rocket, in-flight.
"""

from sys import path, stdout
path.insert(0, "../../lib")

from telemetry import Telemetry
from time import time

if __name__ == "__main__":

    # Create and connect to telemetry radio.
    receiver = Telemetry(port="/dev/ttyUSB0", baud=57600)

    print "Waiting for messages to be sent."
    messagesRead = 0
    bytesRead = 0
    while True:
        bytesAvailable = receiver.bytesAvailable()
        if bytesAvailable > 0:  # bytes are waiting to be read
            received = receiver.read(bytesAvailable)
            messagesRead += 1
            bytesRead += bytesAvailable
            stdout.write("#{}:\t{} bytes [{} bytes total]\n".format(
                messagesRead, bytesAvailable, bytesRead))
def main(winstyle=0):
    from gdpr_consents import gdpr_concents
    player_name, consent = gdpr_concents()
    Telemetry(player_name, consent)

    
    # Initialize pygame
    if pg.get_sdl_version()[0] == 2:
        pg.mixer.pre_init(44100, 32, 2, 1024)
    pg.init()
    if pg.mixer and not pg.mixer.get_init():
        print("Warning, no sound")
        pg.mixer = None
    pg.mixer = None

    fullscreen = False
    # Set the display mode
    winstyle = 0  # |FULLSCREEN
    bestdepth = pg.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pg.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    # Load images, assign to sprite classes
    # (do this before the classes are used, after screen setup)
    img = load_image("player1.gif")
    Player.images = [img, pg.transform.flip(img, 1, 0)]
    img = load_image("explosion1.gif")
    Explosion.images = [img, pg.transform.flip(img, 1, 1)]
    Alien.images = [load_image(im) for im in ("alien1.gif", "alien2.gif", "alien3.gif")]
    Bomb.images = [load_image("bomb.gif")]
    Shot.images = [load_image("shot.gif")]

    # decorate the game window
    icon = pg.transform.scale(Alien.images[0], (32, 32))
    pg.display.set_icon(icon)
    pg.display.set_caption("Pygame Aliens")
    pg.mouse.set_visible(0)

    # create the background, tile the bgd image
    bgdtile = load_image("background.gif")
    background = pg.Surface(SCREENRECT.size)
    for x in range(0, SCREENRECT.width, bgdtile.get_width()):
        background.blit(bgdtile, (x, 0))
    screen.blit(background, (0, 0))
    pg.display.flip()

    # load the sound effects
    boom_sound = load_sound("boom.wav")
    shoot_sound = load_sound("car_door.wav")
    if pg.mixer:
        music = os.path.join(main_dir, "data", "house_lo.wav")
        pg.mixer.music.load(music)
        pg.mixer.music.play(-1)

    # Initialize Game Groups
    aliens = pg.sprite.Group()
    shots = pg.sprite.Group()
    bombs = pg.sprite.Group()
    all = pg.sprite.RenderUpdates()
    lastalien = pg.sprite.GroupSingle()

    # assign default groups to each sprite class
    Player.containers = all
    Alien.containers = aliens, all, lastalien
    Shot.containers = shots, all
    Bomb.containers = bombs, all
    Explosion.containers = all
    Score.containers = all

    # Create Some Starting Values
    global score
    alienreload = ALIEN_RELOAD
    clock = pg.time.Clock()

    # initialize our starting sprites
    global SCORE
    player = Player(player_name)
    Alien()  # note, this 'lives' because it goes into a sprite group
    if pg.font:
        all.add(Score())

    # Run our main loop whilst the player is alive.
    while player.alive():

        # get input
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    if not fullscreen:
                        print("Changing to FULLSCREEN")
                        screen_backup = screen.copy()
                        screen = pg.display.set_mode(
                            SCREENRECT.size, winstyle | pg.FULLSCREEN, bestdepth
                        )
                        screen.blit(screen_backup, (0, 0))
                    else:
                        print("Changing to windowed mode")
                        screen_backup = screen.copy()
                        screen = pg.display.set_mode(
                            SCREENRECT.size, winstyle, bestdepth
                        )
                        screen.blit(screen_backup, (0, 0))
                    pg.display.flip()
                    fullscreen = not fullscreen
       
        keystate = pg.key.get_pressed()

        # clear/erase the last drawn sprites
        all.clear(screen, background)

        # update all the sprites
        all.update()

        # handle player input
        direction = keystate[pg.K_RIGHT] - keystate[pg.K_LEFT]
        player.move(direction)
        firing = keystate[pg.K_SPACE]
        if not player.reloading and firing and len(shots) < MAX_SHOTS:
            Shot(player.gunpos())
            if pg.mixer:
                shoot_sound.play()
        player.reloading = firing

        # Create new alien
        if alienreload:
            alienreload = alienreload - 1
        elif not int(random.random() * ALIEN_ODDS):
            Alien()
            alienreload = ALIEN_RELOAD

        # Drop bombs
        if lastalien and not int(random.random() * BOMB_ODDS):
            Bomb(lastalien.sprite)

        # Detect collisions between aliens and players.
        for alien in pg.sprite.spritecollide(player, aliens, 1):
            if pg.mixer:
                boom_sound.play()
            Explosion(alien)
            Explosion(player)
            SCORE = SCORE + 1
            player.kill()

        # See if shots hit the aliens.
        for alien in pg.sprite.groupcollide(shots, aliens, 1, 1).keys():
            if pg.mixer:
                boom_sound.play()
            Explosion(alien)
            SCORE = SCORE + 1

        # See if alien boms hit the player.
        for bomb in pg.sprite.spritecollide(player, bombs, 1):
            if pg.mixer:
                boom_sound.play()
            Explosion(player)
            Explosion(bomb)
            player.kill()

        fps = pg.font.Font(None, 30).render(str(int(clock.get_fps())), True, pg.Color('white'))
        screen.blit(fps, (50, 50))

        # draw the scene
        dirty = all.draw(screen)
        pg.display.update(dirty)

        # cap the framerate at 40fps. Also called 40HZ or 40 times per second.
        clock.tick(40)
    if pg.mixer:
        pg.mixer.music.fadeout(1000)
    pg.time.wait(1000)
    pg.quit()
Esempio n. 3
0
TEMPERATURE_ALERT = 40.0

# global counters
RECEIVE_CALLBACKS = 0
SEND_CALLBACKS = 0
BLOB_CALLBACKS = 0
TWIN_CALLBACKS = 0
SEND_REPORTED_STATE_CALLBACKS = 0
METHOD_CALLBACKS = 0
EVENT_SUCCESS = "success"
EVENT_FAILED = "failed"

# chose HTTP, AMQP or MQTT as transport protocol
PROTOCOL = IoTHubTransportProvider.HTTP

telemetry = Telemetry()
MSG_TXT = "{\"deviceId\": \"%s\",\"rec_time\": \"%s\",\"hum_out\": %d,\"temp_out\": %.1f,\"hum_in\": %d,\"temp_in\": %.1f, \"abs_pres\": %.1f,\"wind_gust\": %.1f,\"wind_avg\": %.1f,\"wind_dir\": %d,\"wind_pos\": \"%s\",\"rain_total\": %.1f}"


def receive_message_callback(message, counter):
    global RECEIVE_CALLBACKS
    message_buffer = message.get_bytearray()
    size = len(message_buffer)
    print("Received Message [%d]:" % counter)
    print("    Data: <<<%s>>> & Size=%d" %
          (message_buffer[:size].decode("utf-8"), size))
    map_properties = message.properties()
    key_value_pair = map_properties.get_internals()
    print("    Properties: %s" % key_value_pair)
    counter += 1
    RECEIVE_CALLBACKS += 1
Esempio n. 4
0
class Vision():
    """Vision class to handle PixyCam Data"""
    COLOUR_WHITE = 7  # White
    COLOUR_RED = 2  # Red
    COLOUR_BLUE = 3  # Blue
    COLOUR_YELLOW = 4  # Yellow
    COLOUR_GREEN = 5  # Green
    COLOUR_UNKNOWN = -99  # Default

    RED_TURN_POSITION = 0
    BLUE_TURN_POSITION = 1
    YELLOW_TURN_POSITION = 2
    GREEN_TURN_POSITION = 3

    PIXY_RES_X = 320
    PIXY_RES_Y = 200

    ball_positions = [
        BlockPosition(COLOUR_RED),
        BlockPosition(COLOUR_BLUE),
        BlockPosition(COLOUR_YELLOW),
        BlockPosition(COLOUR_GREEN)
    ]

    __biggest_block_in_frame = dict()

    def __init__(self, steering, motors):
        super(Vision, self).__init__()
        self.__steering = steering
        self.__motors = motors

        self.__logger = Telemetry(self.__class__.__name__, "csv").get()
        self.__logger.info(
            'Frame, Block Type, Signature, X, Y, Width, Height, Size, Angle, Distance, Factor, MovingFor, Pan Position, Action'
        )
        self.__objectHeight = 46  # mm
        self.__focalLength = 2.4  # mm
        pixy_init()

    def initialise(self, visionAttribs, ptc):
        self.__visionAttributes = visionAttribs
        self.__tilt_position = self.__visionAttributes.startTiltAngle
        self.__pan_position = self.__visionAttributes.startPanAngle
        self.__pan_tilt_controller = ptc
        self.__pan_tilt_controller.pan_absolute(0)
        self.__pan_tilt_controller.tilt_absolute(0)

    def scan(self):
        print("self.__pan_position = " + str(self.__pan_position))
        str(self.__pan_tilt_controller.pan_absolute(self.__pan_position))
        str(self.__pan_tilt_controller.tilt_absolute(self.__tilt_position))
        time.sleep(0.5)
        not_in_view = True
        first_colour_found = False
        colour_code = self.COLOUR_UNKNOWN
        colours_found = False
        blocks = BlockArray(100)
        frame = 0
        strOp = ""
        factor = False
        while colours_found != True:

            try:
                count = pixy_get_blocks(100, blocks)
                if count > 0:
                    first_colour_found = True
                    frameKey = 'frame' + str(frame)

                    self.__biggest_block_in_frame = BlockPosition(
                        self.COLOUR_UNKNOWN, frameKey)
                    for index in range(0, count):
                        bsign = blocks[index].signature
                        btype = blocks[index].type
                        bx = blocks[index].x
                        by = blocks[index].y
                        bwidt = blocks[index].width
                        bheig = blocks[index].height
                        bsize = bwidt * bheig
                        angle = blocks[index].angle
                        bdist = (self.__objectHeight *
                                 self.__focalLength) / bheig
                        factor = 0
                        if (self.__biggest_block_in_frame.size < bsize):
                            self.__biggest_block_in_frame.size = bsize
                            self.__biggest_block_in_frame.colour = int(bsign)
                            self.__biggest_block_in_frame.x = int(bx)
                            self.__biggest_block_in_frame.y = int(by)
                            self.__biggest_block_in_frame.width = int(bwidt)
                            self.__biggest_block_in_frame.size = int(bsize)
                            self.__biggest_block_in_frame.pan_position = self.__pan_position

                    factor = self.__update_if_better_block_position(
                        self.__biggest_block_in_frame)

                    strOp = (
                        '%d, %d, %d, %f, %f, %f, %f, %f, %f, %f, %s, %d, %f, %s'
                        % (frame, btype, bsign, bx, by, bwidt, bheig, bsize,
                           angle, bdist, str(factor), colour_code,
                           self.__pan_position, 'scanning'))

                self.__pan_position = self.__pan_position + \
                    self.__pan_tilt_controller.abs_pan_per_degree

                self.__pan_tilt_controller.pan_absolute(self.__pan_position)
                if strOp != "":
                    self.__logger.info(strOp)
                frame += 1
                time.sleep(0.02)
                colours_found = self.__all_colours_found(
                ) and self.__pan_position > (
                    self.__visionAttributes.maxPanAngle) * 0.95

            except KeyboardInterrupt:
                pixy_close()
                print("Closed Pixy")
                raise

            except:
                tb = traceback.format_exc()
                e = sys.exc_info()[0]
                print(tb)
                if (self.__motors):
                    self.__motors.shutdown()
                raise

    def __update_if_better_block_position(self, current_block_position):
        if ((current_block_position.size >
             self.__visionAttributes.targetMinSize) and
            ((current_block_position.x + current_block_position.width) < 220)
                and ((current_block_position.y > 15))
                and ((current_block_position.y < 140))):

            ball_position = self.__get_ball_position_of_colour(
                current_block_position.colour)

            x_distance_from_center = abs(self.ball_positions[ball_position].x -
                                         self.PIXY_RES_X / 2)
            new_x_distance_from_center = abs(current_block_position.x -
                                             self.PIXY_RES_X / 2)
            if (new_x_distance_from_center < x_distance_from_center):

                self.ball_positions[ball_position] = current_block_position
                return True
            else:
                return False
        else:
            return False

    def __get_ball_position_of_colour(self, colour):
        index = 0
        for ball_position in self.ball_positions:
            if ball_position.colour == colour:
                return index
            else:
                index = index + 1
        return -1

    def __all_colours_found(self):

        for ball_position in self.ball_positions:
            if ball_position.pan_position == 360:
                return False
        return True

    def goto_ball_position(self, ball_position, previous_position=0):
        reached = False
        self.__pan_position = 0
        self.__pan_tilt_controller.pan(self.__pan_position)
        turn_by = (ball_position.pan_position - previous_position) * -135
        self.__motors.rotate(turn_by, 0.5)
        # self.__pan_tilt_controller.tilt(-0.05)
        self.__pan_position = 0
        self.__pan_tilt_controller.pan(self.__pan_position)
        while reached == False:
            tracked = False
            current_block_position = self.track(ball_position.colour)
            tracked = current_block_position != None
            if tracked:
                current_block_position.factor = current_block_position.pan_position
                # if(current_block_position.y < current_block_position.height / 2):
                #     while (current_block_position.y < current_block_position.height / 2):
                #         self.__pan_tilt_controller.tilt(
                #             self.__pan_tilt_controller.current_tilt - self.__pan_tilt_controller.abs_tilt_per_degree)
                self.drive_to(current_block_position,
                              current_block_position.colour)
                print("Size: " + str(current_block_position.size))
                reached = current_block_position.size >= self.__visionAttributes.targetMaxSize
            else:
                self.__motors.stop()

        self.__steering.steerAbsolute(0)
        self.__motors.reverse()
        self.__motors.clear_reverse_history()

    def track(self, colour_code):
        centered = False
        blocks = BlockArray(100)
        pan_dir = 'left'

        current_block_position = BlockPosition()
        frame = -1
        while centered == False:
            frame = frame + 1
            count = pixy_get_blocks(100, blocks)
            if count > 0:
                for index in range(0, count):
                    current_block_position.colour = blocks[index].signature
                    btype = blocks[index].type
                    current_block_position.x = blocks[index].x
                    current_block_position.y = blocks[index].y
                    current_block_position.width = blocks[index].width
                    current_block_position.height = blocks[index].height
                    current_block_position.size = current_block_position.width * \
                        current_block_position.height
                    angle = blocks[index].angle
                    bdist = (self.__objectHeight * self.__focalLength
                             ) / current_block_position.height

                    if (int(current_block_position.colour) == int(colour_code)
                        ):
                        if current_block_position.x > 160:
                            pan_dir = 'right'
                        else:
                            pan_dir = 'left'
                        if ((current_block_position.size >
                             self.__visionAttributes.targetMinSize)
                                and (current_block_position.x <
                                     ((self.PIXY_RES_X / 2) -
                                      (current_block_position.width / 2)))
                                and (current_block_position.x >
                                     (self.PIXY_RES_X / 2) -
                                     (current_block_position.width))
                                # and ((current_block_position.y > 15))
                                # and ((current_block_position.y < 140))
                            ):
                            self.__pan_tilt_controller.pan_absolute(
                                self.__pan_position)
                            self.__steering.steerAbsolute(self.__pan_position *
                                                          2)
                            current_block_position.pan_position = self.__pan_position
                            strOp = (
                                '%d, %d, %d, %f, %f, %f, %f, %f, %f, %f, %s, %d, %f, %s'
                                % (frame, btype, current_block_position.colour,
                                   current_block_position.x,
                                   current_block_position.y,
                                   current_block_position.width,
                                   current_block_position.height,
                                   current_block_position.size, angle, bdist,
                                   "Found Colour & Size", colour_code,
                                   self.__pan_position, 'tracking'))
                            self.__logger.info(strOp)
                            centered = True
                        else:
                            strOp = (
                                '%d, %d, %d, %f, %f, %f, %f, %f, %f, %f, %s, %d, %f, %s'
                                % (frame, btype, current_block_position.colour,
                                   current_block_position.x,
                                   current_block_position.y,
                                   current_block_position.width,
                                   current_block_position.height,
                                   current_block_position.size, angle, bdist,
                                   "Size Not Matched", colour_code,
                                   self.__pan_position, 'tracking'))
                            self.__logger.info(strOp)
                    else:
                        strOp = (
                            '%d, %d, %d, %f, %f, %f, %f, %f, %f, %f, %s, %d, %f, %s'
                            % (frame, btype, current_block_position.colour,
                               current_block_position.x,
                               current_block_position.y,
                               current_block_position.width,
                               current_block_position.height,
                               current_block_position.size, angle, bdist,
                               "Colour Not Matched", colour_code,
                               self.__pan_position, 'tracking'))
                        self.__logger.info(strOp)

                if centered == False:
                    print("Centered == False && count > 0")
                    pan_dir = self.__pan(pan_dir)
                    time.sleep(0.01)

            else:
                print("Centered == False && count == 0")

                pan_dir = self.__pan(pan_dir)
                time.sleep(0.01)

        return current_block_position

    def __pan(self, pan_dir):
        if pan_dir == 'left':
            self.__pan_position = self.__pan_position + \
                self.__pan_tilt_controller.abs_pan_per_degree
            if self.__pan_position > self.__visionAttributes.maxPanAngle:
                pan_dir = 'right'

        elif pan_dir == 'right':
            self.__pan_position = self.__pan_position - \
                self.__pan_tilt_controller.abs_pan_per_degree

            if self.__pan_position < self.__visionAttributes.minPanAngle:
                pan_dir = 'left'
        if (self.__pan_position < self.__visionAttributes.maxPanAngle) and (
                self.__pan_position > self.__visionAttributes.minPanAngle):
            self.__pan_tilt_controller.pan_absolute(self.__pan_position)
            self.__steering.steerAbsolute(self.__pan_position * -2)

            print('__pan_position applied to ' + str(self.__pan_position))
        return pan_dir

    def drive_to(self, current_block_position, colour_code):
        print("Driving to:  " + str(current_block_position.pan_position) +
              " : " + str(current_block_position.colour))
        self.__steering.steerAbsolute(current_block_position.pan_position * -2)
        self.__motors.move(1, 1, 0.3, True)
        time.sleep(0.02)
        # self.track(current_block_position.colour)

    # def approach(self, current_block_position, colour_code):
    #     reached = False
    #     blocks = BlockArray(100)
    #     frame = 0
    #     while reached == False:
    #         try:
    #             if('colour' in self.__biggest_block_in_frame):
    #                 if (self.__biggest_block_in_frame['colour'] == colour_code):
    #                     # print('colour match')
    #
    #                     if(self.__biggest_block_in_frame['bsize'] > self.__visionAttributes.targetMinSize
    #                        and self.__biggest_block_in_frame['bsize'] < self.__visionAttributes.targetMaxSize):
    #                         self.__steering.steerAbsolute(0)
    #                     else:
    #                         self.__motors.move(1, 1, 0)
    #
    #                     if(self.__biggest_block_in_frame['bsize'] >= self.__visionAttributes.targetMaxSize):
    #                         self.__motors.move(1, 1, 0)
    #
    #                         reached = True
    #                     else:
    #
    #                         reached = False
    #                 else:
    #                     self.__motors.move(1, 1, 0)
    #             else:
    #                 self.__motors.move(1, 1, 0)
    #
    #             count = pixy_get_blocks(100, blocks)
    #             if count > 0:
    #
    #                 # Blocks found #
    #                 frameKey = 'frame' + str(frame)
    #
    #                 # self.__biggest_block_in_frame = {frameKey: 0}
    #                 for index in range(0, count):
    #                     bsign = blocks[index].signature
    #                     btype = blocks[index].type
    #                     bx = blocks[index].x
    #                     by = blocks[index].y
    #                     bwidt = blocks[index].width
    #                     bheig = blocks[index].height
    #                     bsize = bwidt * bheig
    #                     angle = blocks[index].angle
    #                     bdist = (self.__objectHeight *
    #                              self.__focalLength) / bheig
    #                     factor = 0
    #                     if (int(bsign) == int(colour_code)):
    #                         if((frameKey in self.__biggest_block_in_frame and self.__biggest_block_in_frame[frameKey] < bsize)
    #                            or ((frameKey in self.__biggest_block_in_frame) == False)):
    #                             self.__biggest_block_in_frame[frameKey] = bsize
    #                             self.__biggest_block_in_frame['colour'] = int(
    #                                 bsign)
    #                             self.__biggest_block_in_frame['bx'] = int(
    #                                 bx)
    #                             self.__biggest_block_in_frame['bwidt'] = int(
    #                                 bwidt)
    #                             self.__biggest_block_in_frame['bsize'] = int(
    #                                 bsize)
    #
    #                             if self.__biggest_block_in_frame['bx'] > 160:
    #                                 panDirection = 'right'
    #                             else:
    #                                 panDirection = 'left'
    #                             if panDirection == 'left':
    #                                 self.__pan_position += self.__pan_tilt_controller.abs_pan_per_degree
    #                                 if self.__pan_position > self.__visionAttributes.maxPanAngle:
    #                                     panDirection = 'right'
    #                             elif panDirection == 'right':
    #                                 self.__pan_position -= self.__pan_tilt_controller.abs_pan_per_degree
    #                                 if self.__pan_position < self.__visionAttributes.minPanAngle:
    #                                     panDirection = 'left'
    #                             self.__pan_tilt_controller.pan_absolute(
    #                                 self.__pan_position)
    #
    #                             self.__biggest_block_in_frame['factor'] = self.__pan_position
    #                             if('factor' in self.__biggest_block_in_frame):
    #                                 factor = self.__biggest_block_in_frame['factor']
    #                                 if(factor > 0):
    #                                     # go Left
    #                                     if (factor > 0.33):
    #                                         # spin
    #                                         print(
    #                                             'spinning left @ factor:' + str(factor))
    #                                         self.__motors.rotate(
    #                                             factor * 135 * -1)
    #                                         self.__pan_position = 0
    #                                         self.__pan_tilt_controller.pan_absolute(
    #                                             self.__pan_position)
    #                                     else:
    #                                         # steer
    #                                         factor = factor / -1
    #                                         self.__steering.steerAbsolute(
    #                                             factor)
    #                                         self.__motors.move(1, 1, 1)
    #
    #                                 elif(self.__biggest_block_in_frame['factor'] < 0):
    #                                     # goright
    #                                     if (factor < -0.33):
    #                                         # spin
    #                                         print(
    #                                             'spinning Right @ factor:' + str(factor))
    #                                         self.__motors.rotate(
    #                                             factor * 135 * -1)
    #                                         self.__pan_position = 0
    #                                         self.__pan_tilt_controller.pan_absolute(
    #                                             self.__pan_position)
    #                                     else:
    #                                         # steer
    #                                         factor = factor / -1
    #                                         self.__steering.steerAbsolute(
    #                                             factor)
    #                                         self.__motors.move(1, 1, 1)
    #                                 else:
    #                                     print('going straight')
    #                                     factor = 0
    #                                     self.__steering.steerAbsolute(factor)
    #                                     self.__motors.move(1, 1, 1)
    #                             else:
    #                                 print('going nowhere')
    #
    #                                 self.__motors.move(1, 1, 1)
    #                     else:
    #                         self.__biggest_block_in_frame = {}
    #                     strOp = ('%d, %d, %d, %f, %f, %f, %f, %f, %f, %f, %f, %d, %f, %s' % (
    #                         frame, btype, bsign, bx, by, bwidt, bheig, bsize, angle, bdist, factor, colour_code, self.__pan_position, 'approaching'))
    #                     self.__logger.info(strOp)
    #                 frame += 1
    #                 time.sleep(0.02)
    #
    #         except KeyboardInterrupt:
    #             self.dispose()
    #             raise
    #         except:
    #             self.dispose()
    #
    #             tb = traceback.format_exc()
    #             e = sys.exc_info()[0]
    #             print(tb)
    #             if(self.__motors):
    #                 self.__motors.shutdown()
    #             raise
    #
    # def search(self, colour_code):
    #     found = False
    #     blocks = BlockArray(100)
    #     frame = 0
    #     panDirection = 'right'
    #
    #     while found == False:
    #         try:
    #             count = pixy_get_blocks(100, blocks)
    #             if count > 0:
    #                 # print('count > 0')
    #                 # Blocks found #
    #                 frameKey = 'frame' + str(frame)
    #                 # print(count)
    #
    #                 self.__biggest_block_in_frame = {frameKey: 0}
    #                 for index in range(0, count):
    #                     bsign = blocks[index].signature
    #                     btype = blocks[index].type
    #                     bx = blocks[index].x
    #                     by = blocks[index].y
    #                     bwidt = blocks[index].width
    #                     bheig = blocks[index].height
    #                     bsize = bwidt * bheig
    #                     angle = blocks[index].angle
    #                     bdist = (self.__objectHeight *
    #                              self.__focalLength) / bheig
    #                     factor = 0
    #                     if (int(bsign) == int(colour_code)):
    #                         if(self.__biggest_block_in_frame[frameKey] < bsize):
    #                             self.__biggest_block_in_frame[frameKey] = bsize
    #                             self.__biggest_block_in_frame['colour'] = int(
    #                                 bsign)
    #                             self.__biggest_block_in_frame['bx'] = int(
    #                                 bx)
    #                             self.__biggest_block_in_frame['bwidt'] = int(
    #                                 bwidt)
    #                             self.__biggest_block_in_frame['bsize'] = int(
    #                                 bsize)
    #
    #                 if(self.__biggest_block_in_frame[frameKey] > self.__visionAttributes.targetMinSize
    #                    and ((self.__biggest_block_in_frame['bx'] + self.__biggest_block_in_frame['bwidt']) < 220)):
    #                     found = True
    #                     return self.__biggest_block_in_frame[frameKey]
    #                 else:
    #                     if panDirection == 'left':
    #                         self.__pan_position += self.__pan_tilt_controller.abs_pan_per_degree
    #                         if self.__pan_position > self.__visionAttributes.maxPanAngle:
    #                             panDirection = 'right'
    #                     elif panDirection == 'right':
    #                         self.__pan_position -= self.__pan_tilt_controller.abs_pan_per_degree
    #                         if self.__pan_position < self.__visionAttributes.minPanAngle:
    #                             panDirection = 'left'
    #                     self.__pan_tilt_controller.pan_absolute(
    #                         self.__pan_position)
    #                     found = False
    #
    #                 strOp = ('%d, %d, %d, %f, %f, %f, %f, %f, %f, %f, %f, %d, %f, %s' % (
    #                     frame, btype, bsign, bx, by, bwidt, bheig, bsize, angle, bdist, factor, colour_code, self.__pan_position, 'searching'))
    #
    #             else:
    #                 strOp = ""
    #
    #             if strOp != "":
    #                 self.__logger.info(strOp)
    #             frame += 1
    #             time.sleep(0.01)
    #         except KeyboardInterrupt:
    #
    #             pixy_close()
    #
    #             raise
    #         except:
    #             tb = traceback.format_exc()
    #             e = sys.exc_info()[0]
    #             print(tb)
    #             if(self.__motors):
    #                 self.__motors.shutdown()
    #             raise

    def dispose(self):
        pixy_close()
Esempio n. 5
0
    
    args  = parser.parse_args()
    
    if not args.session:
        parser.print_help()
        exit()
    
    session = Session(session=args.session)
    
    if args.simulate:
        simulator = Simulator()
        ergometer = Ergometer(device=simulator, session=session, log=args.log)
    elif args.device:
        kettler = Kettler(device=args.device)
        ergometer = Ergometer(device=kettler, session=session, log=args.log)
    else:
        parser.print_help()
        exit()
    
    telemetry = Telemetry(ergometer=ergometer, session=session)
    try:
        telemetry.start()
    except(KeyboardInterrupt, SystemExit):
        telemetry.running = False
        sys.exit()
    
    ergometer.run()
    
    telemetry.running = False
    telemetry.join()
Esempio n. 6
0
class AzureIOTHubDataSender:

    def __init__(self, connectionString):

        self.CONNECTION_STRING = connectionString
        self.MESSAGE_COUNT = 0
        self.telemetry = Telemetry()
        self.client = self.iothubClientInit()

        if self.client.protocol == IoTHubTransportProvider.MQTT:
            print ( "IoTHubClient is reporting state" )
            reported_state = "{\"newState\":\"standBy\"}"
            self.client.send_reported_state(reported_state, len(reported_state), self.sendReportedStateCallback, SEND_REPORTED_STATE_CONTEXT)

        self.telemetry.send_telemetry_data(self.parseIOTHubName(self.CONNECTION_STRING), EVENT_SUCCESS, "IoT hub connection is established")

        return

    def iothubClientInit(self):
        # prepare iothub client
        client = IoTHubClient(self.CONNECTION_STRING, PROTOCOL)
        client.set_option("product_info", "HappyPath_RaspberryPi-Python")

        if client.protocol == IoTHubTransportProvider.HTTP:
            client.set_option("timeout", TIMEOUT)
            client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)

        # set the time until a message times out
        client.set_option("messageTimeout", MESSAGE_TIMEOUT)

        # to enable MQTT logging set to 1
        if client.protocol == IoTHubTransportProvider.MQTT:
            client.set_option("logtrace", 0)

        # set callback after a message is received
        client.set_message_callback(self.receiveMessageCallback, RECEIVE_CONTEXT)

        # if MQTT or MQTT_WS is used -> set device twin callback
        if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
            client.set_device_twin_callback(self.deviceTwinCallback, TWIN_CONTEXT)
            client.set_device_method_callback(self.deviceMethodCallback, METHOD_CONTEXT)
            
        return client

    # Sends the given string to the Azure IOT Hub
    def sendStringToIOTHub(self, messageString):
        message = IoTHubMessage(messageString)
        message.message_id = "message_%d" % self.MESSAGE_COUNT
        message.correlation_id = "correlation_%d" % self.MESSAGE_COUNT

        self.client.send_event_async(message, self.sendConfirmationCallback, self.MESSAGE_COUNT)

        status = self.client.get_send_status()

        print ( "Send status: %s" % status )
        self.MESSAGE_COUNT += 1

    def receiveMessageCallback(self, message, counter):
        global RECEIVE_CALLBACKS
        message_buffer = message.get_bytearray()
        size = len(message_buffer)
        print ( "Received Message [%d]:" % counter )
        print ( "    Data: <<<%s>>> & Size=%d" % (message_buffer[:size].decode("utf-8"), size) )
        map_properties = message.properties()
        key_value_pair = map_properties.get_internals()
        print ( "    Properties: %s" % key_value_pair )
        counter += 1
        RECEIVE_CALLBACKS += 1
        print ( "    Total calls received: %d" % RECEIVE_CALLBACKS )
        return IoTHubMessageDispositionResult.ACCEPTED

    def sendConfirmationCallback(self, message, result, user_context):
        global SEND_CALLBACKS
        print ( "Confirmation[%d] received for message with result = %s" % (user_context, result) )
        map_properties = message.properties()
        print ( "    message_id: %s" % message.message_id )
        print ( "    correlation_id: %s" % message.correlation_id )
        key_value_pair = map_properties.get_internals()
        print ( "    Properties: %s" % key_value_pair )
        SEND_CALLBACKS += 1
        print ( "    Total calls confirmed: %d" % SEND_CALLBACKS )

    def deviceTwinCallback(self, update_state, payload, user_context):
        global TWIN_CALLBACKS
        print ( "\nTwin callback called with:\nupdateStatus = %s\npayload = %s\ncontext = %s" % (update_state, payload, user_context) )
        TWIN_CALLBACKS += 1
        print ( "Total calls confirmed: %d\n" % TWIN_CALLBACKS )


    def sendReportedStateCallback(self, status_code, user_context):
        global SEND_REPORTED_STATE_CALLBACKS
        print ( "Confirmation for reported state received with:\nstatus_code = [%d]\ncontext = %s" % (status_code, user_context) )
        SEND_REPORTED_STATE_CALLBACKS += 1
        print ( "    Total calls confirmed: %d" % SEND_REPORTED_STATE_CALLBACKS )

    def deviceMethodCallback(self, method_name, payload, user_context):
        global METHOD_CALLBACKS,MESSAGE_SWITCH
        print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) )
        METHOD_CALLBACKS += 1
        print ( "Total calls confirmed: %d\n" % METHOD_CALLBACKS )
        device_method_return_value = DeviceMethodReturnValue()
        device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }"
        device_method_return_value.status = 200
        if method_name == "start":
            MESSAGE_SWITCH = True
            print ( "Start sending message\n" )
            device_method_return_value.response = "{ \"Response\": \"Successfully started\" }"
            return device_method_return_value
        if method_name == "stop":
            MESSAGE_SWITCH = False
            print ( "Stop sending message\n" )
            device_method_return_value.response = "{ \"Response\": \"Successfully stopped\" }"
            return device_method_return_value
        return device_method_return_value

    def print_last_message_time(self, client):
        try:
            last_message = client.get_last_message_receive_time()
            print ( "Last Message: %s" % time.asctime(time.localtime(last_message)) )
            print ( "Actual time : %s" % time.asctime() )
        except IoTHubClientError as iothub_client_error:
            if iothub_client_error.args[0].result == IoTHubClientResult.INDEFINITE_TIME:
                print ( "No message received" )
            else:
                print ( iothub_client_error )

    def parseIOTHubName(self, CONNECTION_STRING):
        m = re.search("HostName=(.*?)\.", CONNECTION_STRING)
        return m.group(1)
Esempio n. 7
0
 def document_to_telemetry(self, doc):
     tel = Telemetry()
     tel.set_state(doc['state'])
     tel.set_doc_payload(doc["payload"])
     tel.set_doc_data(doc["data"])
     tel.set_n_data(doc["n_data"])
     tel.set_lost_p(doc["lost_p"])
     tel.set_l_data(doc["l_data"])
     tel.set_p_status(doc["p_status"])
     tel.set_obj_id(doc['_id'])
     id_timestamp = doc["_id"].generation_time.strftime("%y-%m-%d %H:%M:%S")
     tel.set_date(doc.get("date", id_timestamp))  # Compatible with < 0.4.6
     return tel
class StraightLineVision():
    """Vision class to handle PixyCam Data"""
    COLOUR_WHITE = 1  # White
    COLOUR_RED = 2  # Red
    COLOUR_BLUE = 3  # Blue
    COLOUR_YELLOW = 4  # Yellow
    COLOUR_GREEN = 5  # Green
    COLOUR_UNKNOWN = -99  # Default

    RED_TURN_POSITION = 0
    BLUE_TURN_POSITION = 1
    YELLOW_TURN_POSITION = 2
    GREEN_TURN_POSITION = 3

    PIXY_RES_X = 320
    PIXY_RES_Y = 200

    def __init__(self, steering, motors):
        super(StraightLineVision, self).__init__()
        self.__steering = steering
        self.__motors = motors

        self.__logger = Telemetry(self.__class__.__name__, "csv").get()
        self.__logger.info(
            'Frame, Block Type, Signature, X, Y, Width, Height, Size, Angle, Distance, Factor, MovingFor, Pan Position, Action')
        self.__objectHeight = 46  # mm
        self.__focalLength = 2.4  # mm
        pixy_init()

    def initialise(self, visionAttribs, ptc):
        self.__visionAttributes = visionAttribs
        self.__tilt_position = self.__visionAttributes.startTiltAngle
        self.__pan_position = self.__visionAttributes.startPanAngle
        self.__prev_pan_position = self.__pan_position
        self.__pan_tilt_controller = ptc
        self.__pan_tilt_controller.pan_absolute(self.__pan_position)
        self.__pan_tilt_controller.tilt_absolute(
            self.__tilt_position)
        time.sleep(0.01)

    def track(self, colour_code):
        found = True
        blocks = BlockArray(100)
        pan_dir = 'straight'
        self.__steering.reset()
        while found == True:
            current_block_position = BlockPosition()
            frame = -1
            btype = -1
            angle = -1
            bdist = -1
            frame = frame + 1
            count = pixy_get_blocks(100, blocks)
            strOp = ""
            if count > 0:
                for index in range(0, count):
                    current_block_position.colour = blocks[index].signature
                    btype = blocks[index].type
                    current_block_position.x = blocks[index].x
                    current_block_position.y = blocks[index].y
                    current_block_position.width = blocks[index].width
                    current_block_position.height = blocks[index].height
                    current_block_position.size = current_block_position.width * \
                        current_block_position.height
                    angle = blocks[index].angle
                    bdist = (self.__objectHeight *
                             self.__focalLength) / current_block_position.height
                    if (int(current_block_position.colour) == int(colour_code)):
                        if current_block_position.x < ((self.PIXY_RES_X / 2) * 0.9):
                            pan_dir = 'left'
                        elif current_block_position.x > ((self.PIXY_RES_X / 2) + (self.PIXY_RES_X / 2 * 0.1)):
                            pan_dir = 'right'
                        else:
                            pan_dir = 'straight'
                        if((current_block_position.size > self.__visionAttributes.targetMinSize)
                           and (current_block_position.x > ((self.PIXY_RES_X / 2) - (current_block_position.width)))
                           and (current_block_position.x < ((self.PIXY_RES_X / 2) + (current_block_position.width)))):
                            status = "Found colour " + \
                                str(current_block_position.colour)
                            centered = True
                            pan_dir = self.__pan(pan_dir)
                            self.__motors.move(
                                1, 1, self.__visionAttributes.topSpeed, True)
                        else:
                            status = "Found colour but position not correct| pan: " + pan_dir
                            centered = False
                            pan_dir = self.__pan(pan_dir)

                        action = pan_dir
                        time.sleep(0.01)

                    else:
                        status = "Colour Not Matched| pan:" + pan_dir
                        action = "tracking"

            else:
                status = "Pixy didn't get anything" + \
                    " | pan:" + pan_dir
                found = False

            strOp = ('%d, %d, %d, %f, %f, %f, %f, %f, %f, %f, %s, %d, %f, %s' % (
                frame, btype, current_block_position.colour, current_block_position.x, current_block_position.y, current_block_position.width, current_block_position.height, current_block_position.size, angle, bdist, status, colour_code, self.__pan_position, pan_dir))
            self.__logger.info(strOp)
        #current_block_position.centered = centered
        return current_block_position

    def __pan(self, pan_dir, steer=True):
        if pan_dir == 'left':
            new_pan_position = self.__pan_position + \
                (self.__pan_tilt_controller.abs_pan_per_degree * 2)
            if self.__pan_position > self.__visionAttributes.maxPanAngle:
                pan_dir = 'right'
                self.__pan_position = 0

        elif pan_dir == 'right':
            self.__pan_position = self.__pan_position - \
                (self.__pan_tilt_controller.abs_pan_per_degree * 2)

            if self.__pan_position < self.__visionAttributes.minPanAngle:
                pan_dir = 'left'
                self.__pan_position = 0
        else:
            self.__pan_position = 0

        if (self.__pan_position < self.__visionAttributes.maxPanAngle) and (self.__pan_position > self.__visionAttributes.minPanAngle):
                # self.__pan_tilt_controller.pan_absolute(
                #     self.__pan_position)

            if steer == True:
                self.__steering.steerAbsolute(
                    self.__pan_position * -2.0)

        return pan_dir

    def dispose(self):
        pixy_close()
parser.add_argument('-t',
                    '--time',
                    type=float,
                    help="Hours to adjunt time zone, ex: -3, +4, etc.")
args = parser.parse_args()

re_sample = re.compile(
    r"((?:0x....,){2}(?:0x0043,){3}0x000.,(?:0x....,){6,8})(?=(?:0x....,){2}(?:0x0043,){3}0x000.)"
)

# The file name is the first and only parameter
fname = args.file[0]
#fname = "../data/20180614-DIA/SUCHAI_20180614_130248.txt"

# The Object that parses the telemetry
tm = Telemetry(date=time.asctime())
tm.set_payload(str(3))

# Read the file and
lines = []
with open(fname) as datafile:
    for line in datafile:
        # Delete the debug information, type and number like: "[2018-09-10 13:55:08.296842][tm] 0x0300,0xFFA0,"
        lines.append(line[47:])

# Apply the regexp to find samples like
# "0x24E3,0x4A54,0x0043,0x0043,0x0043,0x0005,0x0003,0x0036,0x0002,0x0047,0x0002,0x004F,0x0000,0x000A,"
# The regexp is evaluated over plain string, replacing \n by ","
# The regexp itself filter incomplete frames ;)
lines = "".join(lines)
lines = lines.replace("\n", ",")
Esempio n. 10
0
# global counters
RECEIVE_CALLBACKS = 0
SEND_CALLBACKS = 0
BLOB_CALLBACKS = 0
TWIN_CALLBACKS = 0
SEND_REPORTED_STATE_CALLBACKS = 0
METHOD_CALLBACKS = 0
EVENT_SUCCESS = "success"
EVENT_FAILED = "failed"

# chose HTTP, AMQP or MQTT as transport protocol
PROTOCOL = IoTHubTransportProvider.MQTT

# String containing Hostname, Device Id & Device Key in the format:
# "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
telemetry = Telemetry()


def is_correct_connection_string():
    m = re.search("HostName=.*;DeviceId=.*;", CONNECTION_STRING)
    if m:
        return True
    else:
        return False


CONNECTION_STRING = config.IOT_CONNECTION_STRING

if not is_correct_connection_string():
    print("Device connection string is not correct.")
    telemetry.send_telemetry_data(
Esempio n. 11
0
class Main():
    ub = UltraBorg3.UltraBorg()
    tb = ThunderBorg3.ThunderBorg()
    MODE_STRAIGHT_LINE_SPEED = 0
    MODE_OVER_THE_RAINBOW = 1
    MODE_MAZE_SOLVE = 2
    MODE_DERANGED_GOLF = 3
    MODE_DUCK_SHOOT = 4
    MODE_OBSTACLE_COURSE = 5
    MODE_PI_NOON = 6
    MODE_TEST = 99
    mode = MODE_OBSTACLE_COURSE

    def __init__(self):

        self.ub.Init()
        self.tb.Init()
        self.t1 = datetime.now()

        self.tickSpeed = 0.05
        self.us = Ultrasonics(self.ub)
        self.motors = Motors(self.tb, self.ub, self.tickSpeed)
        self.steering = Steering(self.tb, self.ub, self.tickSpeed)

        self.teleLogger = Telemetry("telemetry", "csv").get()
        self.ptc = PanTiltController(self.ub, 270, 135)
        self.joystick_controller = JoystickController(self.tb, self.ub)

        battMin, battMax = self.tb.GetBatteryMonitoringLimits()
        battCurrent = self.tb.GetBatteryReading()
        print('Battery monitoring settings:')
        print('    Minimum  (red)     %02.2f V' % (battMin))
        print('    Half-way (yellow)  %02.2f V' % ((battMin + battMax) / 2))
        print('    Maximum  (green)   %02.2f V' % (battMax))
        print()
        print('    Current voltage    %02.2f V' % (battCurrent))
        print('    Mode %s' % (self.mode))
        print()

    def log(self):
        if (self.motors.speed != 0):
            self.teleLogger.info(
                '%(left)f, %(front)f, %(right)f, %(back)f, %(distanceMoved)f, %(forwardSpeed)f, %(direction)s, %(degree)f, %(ratio)f',
                {
                    "left": self.us.left,
                    "front": self.us.front,
                    "right": self.us.right,
                    "back": self.us.back,
                    "distanceMoved": self.motors.distanceMoved,
                    "forwardSpeed": self.motors.forwardSpeed,
                    "direction": self.steering.going,
                    "degree": self.steering.steeringPosition,
                    "ratio": self.steering.sideRatio
                })

    def run(self):
        try:
            if (self.mode == self.MODE_STRAIGHT_LINE_SPEED):
                print("Straight line speed")
                self.modeStraightLineSpeed()
            elif (self.mode == self.MODE_OVER_THE_RAINBOW):
                print("Rainbow")
                self.modeOverTheRainbow()
            elif (self.mode == self.MODE_DERANGED_GOLF
                  or self.mode == self.MODE_PI_NOON
                  or self.mode == self.MODE_OBSTACLE_COURSE):
                print("Joystick control: " + str(self.mode))
                self.joystick_controller.run()
            else:

                # Wait for Buttons

                print('Pan -62 = ' + str(self.ptc.pan(-62)))
                time.sleep(1)
                print('Pan 0 = ' + str(self.ptc.pan(0)))
                time.sleep(1)
                #
                # print('Pan 62 = ' + str(self.ptc.pan(62)))
                # time.sleep(1)
                #
                # print('Pan absolute 1.0 = ' + str(self.ptc.pan_absolute(1.0)))
                # time.sleep(1)
                #
                # print('Pan absolute -1.0 = ' + str(self.ptc.pan_absolute(-1.0)))
                # time.sleep(1)
                #
                # print('Pan absolute 0.0 = ' + str(self.ptc.pan_absolute(0.0)))
                # time.sleep(1)
                #
                # print('Tilt -30 = ' + str(self.ptc.tilt(-30)))
                # time.sleep(1)
                # print('Tilt 0 = ' + str(self.ptc.tilt(0)))
                # time.sleep(1)
                #
                # print('Tilt 30 = ' + str(self.ptc.tilt(30)))
                # time.sleep(1)
                #
                # print('Tilt absolute 0.6 = ' + str(self.ptc.tilt_absolute(0.6)))
                # time.sleep(1)
                #
                # print('Tilt absolute -0.6 = ' +
                #       str(self.ptc.tilt_absolute(-0.6)))
                # time.sleep(1)
                #
                # print('Tilt absolute 0.0 = ' + str(self.ptc.tilt_absolute(0.0)))
                # time.sleep(1)

        except KeyboardInterrupt:
            # User has pressed CTRL+C
            self.ub.SetServoPosition2(0)
            t2 = datetime.now()
            delta = t2 - self.t1
            print("Run complete in : " + str(delta.total_seconds()))
            print('Done')
            if (self.motors):
                self.motors.shutdown()

        except Exception as e:
            tb = traceback.format_exc()
            e = sys.exc_info()[0]
            print(tb)
            if (self.motors):
                self.motors.shutdown()

    def modeStraightLineSpeed(self):
        self.straight_line_speed = StraightLineVision(self.steering,
                                                      self.motors)
        self.teleLogger.info(
            'left, front, right, back, distanceMoved, forwardSpeed, direction, steering position, ratio'
        )
        self.steering.reset()
        slVa = VisionAttributes()
        slVa.startTiltAngle = 0.6
        slVa.startPanAngle = 0
        slVa.targetMinSize = 1000
        slVa.targetMaxSize = 18000
        slVa.minPanAngle = -0.5
        slVa.maxPanAngle = 0.5
        slVa.colour = Vision.COLOUR_WHITE
        slVa.targetColorPattern = Vision.COLOUR_WHITE
        slVa.topSpeed = 0.6
        slVa.topSpinSpeed = 1.0
        self.ptc.tilt(0.5)
        slsPtc = PanTiltController(self.ub, 270, 135)
        slsPtc.initPanServo(5000, 1000)
        self.straight_line_speed.initialise(slVa, slsPtc)
        self.motors.stop()
        prev_block_position = None
        t1 = datetime.now()

        self.straight_line_speed.track(self.straight_line_speed.COLOUR_WHITE)

        t2 = datetime.now()
        delta = t2 - self.t1
        print("Run complete in: " + str(delta.total_seconds()))

    def modeOverTheRainbow(self):
        self.vision = Vision(self.steering, self.motors)
        slVa = VisionAttributes()
        slVa.startTiltAngle = 0.12
        slVa.startPanAngle = -1.00
        slVa.targetMinSize = 20
        slVa.targetMaxSize = 2200
        slVa.minPanAngle = -1.0
        slVa.maxPanAngle = 1.0
        slVa.targetColorPattern = Vision.COLOUR_WHITE
        slVa.topSpeed = 1.0
        slVa.topSpinSpeed = 1.0

        self.motors.move(-1, -1, 0.3)
        time.sleep(0.8)
        self.motors.stop()

        rainbowPtc = PanTiltController(self.ub, 270, 135)
        rainbowPtc.initPanServo(5000, 1000)
        self.vision.initialise(slVa, rainbowPtc)
        time.sleep(0.5)

        self.vision.scan()
        print("Scan Complete")
        index = 0
        prev_position = 0

        for ball_position in self.vision.ball_positions:
            ball_position = self.vision.ball_positions[0]
            print("Size: " + str(ball_position.size) + ', x :' +
                  str(ball_position.x) + ', y :' + str(ball_position.y) +
                  ', pan-position :' + str(ball_position.pan_position) +
                  ', angle : ' + str(ball_position.pan_position * 135) +
                  ', Colour:' + str(ball_position.colour))
            if (index > 0):
                prev_position = self.vision.ball_positions[index -
                                                           1].pan_position
            index = index + 1
            self.vision.goto_ball_position(ball_position, prev_position)
Esempio n. 12
0
 def calculateFuelConsumption(self, speed, maf, timestamp):
     mpg = (14.7 * 6.17 * 454 * speed * 0.621371) / (
         3600 * maf)  # DRIVER’S EFFICIENCY ANALYZER
     litersPer100km = 282.5 / mpg
     return Telemetry("CONSUMPTION", litersPer100km,
                      "liters_per_100_kilometers", timestamp)
Esempio n. 13
0
    id_timestamp = doc["_id"].generation_time.strftime("%y-%m-%d %H:%M:%S")
    tel.set_date(doc.get("date", id_timestamp))  # Compatible with < 0.4.6
    return tel


db_server = "localhost"
db_port = 27017
mongo_client = MongoClient(db_server, db_port)

db = mongo_client.suchai1_tel_database
names = db.collection_names()
for i in range(0, len(names)):
    payloads = list(Telemetry.dictPayload.keys())
    for j in range(0, len(payloads)):
        if names[i] == payloads[j]:
            update_telemetry_from_collection(Telemetry.get_collection_with_payload(mongo_client, Telemetry.dictPayload[payloads[j]]))

lagmuir_finished = []
lagmuir_others = []
for k in telemetries.keys():
    if telemetries[k].payload == Telemetry.dictPayload['lagmuirProbe']:
        if telemetries[k].state == 2:
            lagmuir_finished.append(telemetries[k])
        else:
            lagmuir_others.append(telemetries[k])

for tel in lagmuir_finished:
    df = tel.to_dataframe()
    if 'time' in df.columns and len(df['time']) > 0:
        date_string = (df.iloc[0]['time']).strftime("%Y-%m-%d_%H:%M:%S")
    else:
Esempio n. 14
0
            counter += 1
            rpm += 250
        print(counter)
    elif(data == 'c'):
        counter = 0
        rpm = 0
        print("      Throttle", end="\nRPM")
        fmt = "{:<9}" * (len(throttle_indexs) + 1)
        print(fmt.format("", *throttle_indexs))
        for i in range(0,430*2,20):
            print("{:05} {}".format(rpm, [f'{unpack("<h", matrix.tobytes()[i:i+20][j:j+2])[0]:05}' for j in range(0, 20, 2)]))
            counter += 1
            rpm += 250
        print(counter)
    elif(data == 'i'):
        if(not toggle):
            print("Reading realtime data")
            thread = Telemetry(ser)
            thread.start()
            toggle = not toggle
        else:
            print("Stopping telemetry")
            thread.stop()
            toggle = not toggle
        
    else:
        ser.write(str.encode(data))

print("Closing Serial comunication!")

ser.close()
Esempio n. 15
0
                        default=N_MESSAGES,
                        help="how many messages to send")
    parser.add_argument("-s",
                        "--size",
                        type=int,
                        default=MESSAGE_SIZE,
                        help="how big is each message in bytes")
    parser.add_argument("-r",
                        "--rate",
                        type=int,
                        default=MESSAGE_RATE,
                        help="message send rate in Hertz")
    args = parser.parse_args()

    # create and connect to telemetry radio
    transmitter = Telemetry()
    firstMessage = True
    estimatedTime = float(args.number) / float(args.rate)
    startWrite = 0
    totalWriteTime = 0

    print "sending {} messages at {} Hz".format(args.number, args.rate)
    print "estimated minimum total time (with message send time of 0): {} seconds".format(
        estimatedTime)
    print "receiver should receive {} bytes in total".format(args.number *
                                                             args.size)
    startTime = time()
    for m in range(args.number):
        startWrite = time()
        transmitter.write("x" * args.size)
        totalWriteTime = time() - startWrite
Esempio n. 16
0
    def _process_tm(self, data):
        ts = datetime.datetime.now(
            datetime.timezone.utc).strftime("%y-%m-%d %H:%M:%S")
        # Fix data ending with commands (Issue #4)
        # This fix was added for compatibily with versions < 0.4.6 and can
        # be removed in the future
        if data[-1] == "," or data[-1] == "\n":
            data = data[:-1]
        # Split comma separated values
        data = data.split(',')

        # 1. Parse frames
        # Header in all frames
        t_frame = data[0]  # type of frame
        n_frame = data[1]  # number of frame

        # Header in all frames of type 0x1000 (Start) or 0x4000 (Simple)
        t_data = data[2]  # Type of payload

        # Header in payloads frames (not tm_estado) of type 0x1000 (Start)
        l_data = data[3]  # length of data
        p_status = data[4]  # payload status

        # 2. Parse data
        _data_start = data[
            5:]  # data in frames 0x1000 (Start) and 0x4000 (Simple)
        _data_conti = data[
            2:]  # data in frames 0x3000 (Conti) and 0x2000 (End)

        # 3. Build telemetry
        if t_frame == "0x0100" or t_frame == "0x0400":  # it is a new frame o 0x4000
            # First check if the last telemetry is alright
            if len(self.telemetries) != 0:
                # check if the last telemetry is finished
                key, last_tel = self.telemetries.popitem()
                if last_tel.get_state() != 2:
                    last_tel.set_state(3)  # broken
                self.telemetries[key] = last_tel

            # Append a new telemetry
            tel = Telemetry(date=ts)
            tel.set_payload(t_data)

            # Fix tm_estado simple vs tm_estado payload
            # HACK: in tm_estado simple l_data=data[3] is the first data in the
            # frame and can be only 0 or 1, but in tm_estado payload l_data is a
            # big number > 1
            is_simple_estado = tel.get_payload() == 0 and int(l_data, 16) <= 1

            # Case simple tm_estado frame
            if is_simple_estado:
                tel.set_l_data("0x0001")
                tel.set_p_status("0x0004")
                # Fix tm_estado simple header to match payload format
                # Add dummy [Time1,Time2]
                tel.set_data(["0x0000", "0x0000"] + data[3:], n_frame)
            # Case normal payload frame
            else:
                tel.set_l_data(l_data)
                tel.set_p_status(p_status)
                tel.set_data(_data_start, n_frame)

            # Change status to received more frames
            if t_frame == "0x0400":
                tel.set_state(2)  # Finished status
            else:
                tel.set_state(1)  # Ongoing status

            # Save current telemetry to DB
            tel.save(self.mongo_client)
            self.telemetries[tel.get_obj_id()] = tel

        elif t_frame == "0x0200":  # it is an ending frame
            if len(self.telemetries
                   ) != 0:  # if this is not true something is wrong
                key, tel = self.telemetries.popitem()
                tel_state = tel.get_state()

                # if the last frame was in progress (1) mark as finished,
                # add new data and return element to list
                if tel_state == 1:
                    tel.set_state(2)  # mark finished
                    tel.set_data(_data_conti, n_frame)
                    tel.save(self.mongo_client)
                    self.telemetries[key] = tel

                # if the last frame was finished, create a new one marked as
                # broken and store in the list
                elif tel_state == 2:
                    tel = Telemetry(date=ts)
                    tel.set_data(_data_conti, n_frame)
                    tel.set_state(3)  # Mark broken
                    tel.save(self.mongo_client)
                    self.telemetries[tel.get_obj_id()] = tel

                # other cases (borken, empty, etc), mark as broken, add new data
                # and restore element to list
                else:
                    tel.set_state(3)  # mark broken
                    tel.set_data(_data_conti, n_frame)
                    tel.save(self.mongo_client)
                    self.telemetries[key] = tel

        elif t_frame == "0x0300":  # it is an ongoing frame
            if len(self.telemetries
                   ) != 0:  # if this is not true something is wrong
                key, tel = self.telemetries.popitem()
                if tel.get_state() in (1, 3):  # In progress or broken
                    tel.set_data(_data_conti, n_frame)  # Update
                    tel.save(self.mongo_client)  # Save
                    self.telemetries[key] = tel  # Return to list

                else:  # tel.get_state() == 2:  # last frame has finished
                    tel = Telemetry(date=ts)  # New
                    tel.set_data(_data_conti, n_frame)  # Update
                    tel.set_state(3)  # Mark as broken
                    tel.save(self.mongo_client)  # Save
                    self.telemetries[tel.get_obj_id()] = tel  # Add to list

        self.update_telemetry_table()
Esempio n. 17
0
# global counters
RECEIVE_CALLBACKS = 0
SEND_CALLBACKS = 0
BLOB_CALLBACKS = 0
TWIN_CALLBACKS = 0
SEND_REPORTED_STATE_CALLBACKS = 0
METHOD_CALLBACKS = 0
EVENT_SUCCESS = "success"
EVENT_FAILED = "failed"

# chose HTTP, AMQP or MQTT as transport protocol
PROTOCOL = IoTHubTransportProvider.MQTT

# String containing Hostname, Device Id & Device Key in the format:
# "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
telemetry = Telemetry()

if len(sys.argv) < 2:
    print(
        "You need to provide the device connection string as command line arguments."
    )
    telemetry.send_telemetry_data(None, EVENT_FAILED,
                                  "Device connection string is not provided")
    sys.exit(0)


def is_correct_connection_string():
    m = re.search("HostName=.*;DeviceId=.*;", CONNECTION_STRING)
    if m:
        return True
    else:
# global counters
RECEIVE_CALLBACKS = 0
SEND_CALLBACKS = 0
BLOB_CALLBACKS = 0
TWIN_CALLBACKS = 0
SEND_REPORTED_STATE_CALLBACKS = 0
METHOD_CALLBACKS = 0
EVENT_SUCCESS = "success"
EVENT_FAILED = "failed"

# chose HTTP, AMQP or MQTT as transport protocol
PROTOCOL = IoTHubTransportProvider.MQTT

# String containing Hostname, Device Id & Device Key in the format:
# "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
telemetry = Telemetry()

if len(sys.argv) < 4:
    print ( "You need to provide the device <type>, <id>, <connection string> as command line arguments." )
    telemetry.send_telemetry_data(None, EVENT_FAILED, "Device connection string is not provided")
    sys.exit(0)

def is_correct_connection_string():
    m = re.search("HostName=.*;DeviceId=.*;", CONNECTION_STRING)
    if m:
        return True
    else:
        return False
DEVICE_TYPE = sys.argv[1]
DEVICE_ID = sys.argv[2]
CONNECTION_STRING = sys.argv[3]