commit a58ba5fd6dcaa0b6dbdd55d83c66238f11026f52 Author: Lars Haferkamp <> Date: Tue Feb 14 17:43:41 2023 +0100 Initial code with Python stubs for Lego Spike API, Go Robot Code and an example how to structure our code diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..86feca0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST diff --git a/README.md b/README.md new file mode 100644 index 0000000..52bfe29 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ + +# Entwickler Setup + +- Installiere VS Code +- Installiere Git +- Installiere VS Code Extension: +https://marketplace.visualstudio.com/items?itemName=PeterStaev.lego-spikeprime-mindstorms-vscode +- Clone unsere Code Vorlage aus Git + +In der VSCode Extension pre-compile einstellen: +![VSCode Lego Settings](vscode-lego-extension-settings.png "VSCode Lego Settings") +![VSCode Lego Precompile](vscode-lego-extension-precompile.png "VSCode Lego Precompile") + +# Code auf den Spike laufen lassen + +1. Über die VSCode Extension auf einen Slot hochladen (Extension Button oder F1->LEGO) +2. Slot starten (kann auch über die "autostart" Option im Kopf des Codes automatisiert werden) + + ``` + # LEGO type:standard slot:5 autostart + ``` + +# Code als gemeinsame Bibiothek entwickeln und auf dem Spike ausführen + +1. Eigene Python Datei anlegen zB `meincode.py` +2. Auf einen Slot hochladen (am besten Pre-Compile unter VS Code Settings einstellen, siehe Entwickeler Setup) +3. `importFile` Funktion aus der `main.py` nutzen: + + ``` + importFile(slotid=6, precompiled=True, module_name="meincode") + import meincode as mc + print(mc.HELLO) + ``` + +Siehe auch +https://forums.firstinspires.org/forum/general-discussions/first-programs/first-lego-league/the-challenge/programming-ab/93873-spike-prime-programming-lessons-for-first-lego-league-challenge-teams + + +# Project Setup History + +``` +git clone https://github.com/fluffyhuskystudio/spike-prime-api.git +mkdir spike-all-py +cd spike-all-py +cp -r ../spike-prime-api/hub ./ +cp -r ../spike-prime-api/spike ./ +``` + diff --git a/gorobot.py b/gorobot.py new file mode 100644 index 0000000..d15c6b7 --- /dev/null +++ b/gorobot.py @@ -0,0 +1,984 @@ +# LEGO type:standard slot:3 autostart + +import math +from spike import PrimeHub, Motor, MotorPair, ColorSensor +from spike.control import wait_for_seconds, Timer +from hub import battery +hub = PrimeHub() + + +import hub as hub2 + +import sys + + +""" +Initialize motor and color Sensors +""" +# adjust the sensor ports until they match your configuration, +# we recommend assigning your ports to the ones in the program for ease of use +colorE = ColorSensor('E') +colorF = ColorSensor('E') +smallMotorA = Motor('A') +smallMotorD = Motor('B') + +#Preperation for parallel code execution +accelerate = True +run_generator = True +runSmall = True + +lastAngle = 0 +oldAngle = 0 + +gyroValue = 0 + +# Create your objects here. +hub = PrimeHub() + +#PID value Definition +pRegler = 0.0 +iRegler = 0.0 +dRegler = 0.0 + +pReglerLight = 0.0 +iReglerLight = 0.0 +dReglerLight = 0.0 + +#Set variables based on robot +circumference = 17.6 #circumference of the wheel powered by the robot in cm +sensordistance = 7 #distance between the two light sensors in cm. Used in Tangent alignment 6.4 in studs + + + +cancel = False +inMain = True + +class DriveBase: + + def __init__(self, hub, leftMotor, rightMotor): + self.hub = hub + self.leftMotor = Motor(leftMotor) + self.rightMotor = Motor(rightMotor) + self.movement_motors = MotorPair(leftMotor, rightMotor) + + def lineFollower(self, distance, startspeed, maxspeed, endspeed, sensorPort, side, addspeed = 0.2, brakeStart = 0.7 , stopMethod=None, generator = None, stop = True): + """ + This is the function used to let the robot follow a line until either the entered distance has been achieved or the other sensor of the robot senses a line. + Like all functions that drive the robot this function has linear acceleration and breaking. It also uses PID values that are automatically set depending on the + current speed of the robot (See function PIDCalculationLight) + Parameters + ------------- + distance: The value tells the program the distance the robot has to drive. Type: Integer. Default: No default value + speed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value + maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value + endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value + addspeed: The percentage after which the robot reaches its maxspeed. Type: Float. Default: No default value + brakeStart: The value which we use to tell the robot after what percentage of the distance we need to slow down. Type: Float. Default: No default value + stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance + generator: the generator that runs something parallel while driving. Default: No default value + stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True + """ + + if cancel: + return + + global run_generator, runSmall + + if generator == None: + run_generator = False + + #set the speed the robot starts at + speed = startspeed + #reset PID values to eliminate bugs + change = 0 + old_change = 0 + integral = 0 + #reset the driven distance of the robot to eliminate bugs + + #specifies the color sensor + colorsensor = ColorSensor(sensorPort) + #Get degrees of motors turned before robot has moved, allows for distance calculation without resetting motors + loop = True + #Going backwards is not supported on our robot due to the motors then being in front of the colour sensors and the program not working + if distance < 0: + print('ERR: distance < 0') + distance = abs(distance) + #Calculate target values for the motors to turn to + finalDistance = (distance / 17.6) * 360 + #Calculate after what distance the robot has to reach max speed + accelerateDistance = finalDistance * addspeed + deccelerateDistance = finalDistance * (1 - brakeStart) + + invert = 1 + + #Calculation of steering factor, depending on which side of the line we are on + if side == "left": + invert = 1 + elif side == "right": + invert = -1 + + #Calculation of the start of the robot slowing down + + self.left_Startvalue = self.leftMotor.get_degrees_counted() + self.right_Startvalue = self.rightMotor.get_degrees_counted() + drivenDistance = getDrivenDistance(self) + + brakeStartValue = brakeStart * finalDistance + while loop: + if cancel: + print("cancel") + break + + if run_generator: #run parallel code execution + next(generator) + + #Checks the driven distance as an average of both motors for increased accuracy + oldDrivenDistance = drivenDistance + drivenDistance = getDrivenDistance(self) + #Calculates target value for Robot as the edge of black and white lines + old_change = change + + change = colorsensor.get_reflected_light() - 50 + + + #Steering factor calculation using PID, sets new I value + + + steering = (((change * pReglerLight) + (integral * iReglerLight) + (dReglerLight * (change - old_change)))) * invert + integral = change + integral + #Calculation of current speed for robot, used for acceleratiion, braking etc. + speed = speedCalculation(speed, startspeed, maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, drivenDistance, oldDrivenDistance) + + pidCalculationLight(speed) + #PID value updates + steering = max(-100, min(steering, 100)) + + #Driving using speed values calculated with PID and acceleration for steering, use of distance check + self.movement_motors.start_at_power(int(speed), int(steering)) + + if stopMethod != None: + if stopMethod.loop(): + loop = False + else: + if finalDistance < drivenDistance: + break + + if stop: + self.movement_motors.stop() + + run_generator = True + runSmall = True + generator = 0 + return + + def gyroRotation(self, angle, startspeed, maxspeed, endspeed, addspeed = 0.3, brakeStart = 0.7, rotate_mode = 0, stopMethod = None, generator = None, stop = True): + """ + This is the function that we use to make the robot turn the length of a specific angle or for the robot to turn until it senses a line. Even in this function the robot + can accelerate and slow down. It also has Gyrosensor calibrations based on our experimental experience. + Parameters + ------------- + angle: The angle which the robot is supposed to turn. Use negative numbers to turn counterclockwise. Type: Integer. Default value: No default value + startspeed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value + maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value + endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value + addspeed: The percentage after which the robot reaches the maxspeed. Type: Float. Default: No default value + brakeStart: The percentage after which the robot starts slowing down until it reaches endspeed. Type: Float. Default: No default value + rotate_mode: Different turning types. 0: Both motors turn, robot turns on the spot. 1: Only the outer motor turns, resulting in a corner. Type: Integer. Default: 0 + stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance + generator: the generator that runs something parallel while driving. Default: No default value + stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True + """ + + if cancel: + return + + global run_generator, runSmall + + if generator == None: + run_generator = False + + if rotate_mode == 0: + startspeed = abs(startspeed) + maxspeed = abs(maxspeed) + endspeed = abs(endspeed) + + speed = startspeed + + #set standard variables + rotatedDistance = 0 + steering = 1 + + accelerateDistance = abs(angle * addspeed) + deccelerateDistance = abs(angle * (1 - brakeStart)) + + #gyro sensor calibration + angle = angle * (2400/2443) #experimental value based on 20 rotations of the robot + + #Setting variables based on inputs + loop = True + gyroStartValue = getGyroValue() #Yaw angle used due to orientation of the self.hub. This might need to be changed + brakeStartValue = (angle + gyroStartValue) * brakeStart + + #Inversion of steering value for turning counter clockwise + if angle < 0: + steering = -1 + + #Testing to see if turining is necessary, turns until loop = False + + while loop: + if cancel: + break + + if run_generator: #run parallel code execution + next(generator) + + oldRotatedDistance = rotatedDistance + rotatedDistance = getGyroValue() #Yaw angle used due to orientation of the self.hub. This might need to be changed + + #Checking for variants + #Both Motors turn, robot moves on the spot + if rotate_mode == 0: + self.movement_motors.start_tank_at_power(int(speed) * steering, -int(speed) * steering) + #Only outer motor turns, robot has a wide turning radius + + elif rotate_mode == 1: + + if angle * speed > 0: + self.leftMotor.start_at_power(- int(speed)) + else: + self.rightMotor.start_at_power(+ int(speed)) + + if stopMethod != None: + if stopMethod.loop(): + loop = False + break + elif abs(angle) <= abs(rotatedDistance - gyroStartValue): + loop = False + break + + + + #Stops movement motors for increased accuracy while stopping + if stop: + self.movement_motors.stop() + + run_generator = True + runSmall = True + + return # End of gyroStraightDrive + + def gyroStraightDrive(self, distance, startspeed, maxspeed, endspeed, addspeed = 0.3, brakeStart = 0.7, stopMethod=None, offset = 0, generator = None, stop = True): + """ + This is the function that we use to make the robot go forwards or backwards without drifting. It can accelerate, it can slow down and there's also PID. You can set the values + in a way where you can either drive until the entered distance has been achieved or until the robot senses a line. + Parameters + ------------- + distance: the distance that the robot is supposed to drive. Type: Integer. Default: No default value + speed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value + maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value + endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value + addspeed: The speed which the robot adds in order to accelerate. Type: Float. Default: 0.2 + brakeStart: The value which we use to tell the robot after what percentage of the distance we need to slow down. Type: Float. Default: 0.8 + port: This value tells the program whether the robot is supposed to check for a black line with the specified light snsor. Type: String. Default: 0 + lightValue: This value tells the program the value the robot should stop at if port sees it. Type: Integer. Default: 0 + align_variant: Tells the robot to align itself to a line if it sees one. 0: No alignment. 1: standard alignment. 2: tangent based alignment Type: Integer. Default: 0 + detectLineStart: The value which we use to tell the robot after what percentage of the distance we need to look for the line to drive to. Type: Float. Default: 0 + offset: The value sends the robot in a direction which is indicated by the value entered. Type: Integer. Default: 0 + generator: Function executed while robot is executing gyroStraightDrive. Write the wanted function and its parameters here. Type: . Default: 0 + stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance + generator: the generator that runs something parallel while driving. Default: No default value + stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True + """ + + if cancel: + return + + global run_generator, runSmall + global pRegler, iRegler, dRegler + + if generator == None: + run_generator = False + + #Set starting speed of robot + speed = startspeed + #Sets PID values + + change = 0 + old_change = 0 + integral = 0 + steeringSum = 0 + + invert = -1 + + #Sets values based on user inputs + loop = True + + + gyroStartValue = getGyroValue() + + #Error check for distance + if distance < 0: + print('ERR: distance < 0') + distance = abs(distance) + + #Calulation of degrees the motors should turn to + #17.6 is wheel circumference in cm. You might need to adapt it + rotateDistance = (distance / 17.6) * 360 + accelerateDistance = rotateDistance * addspeed + deccelerateDistance = rotateDistance * (1 - brakeStart) + + #Inversion of target rotation value for negative values + if speed < 0: + invert = 1 + + #Calculation of braking point + self.left_Startvalue = self.leftMotor.get_degrees_counted() + self.right_Startvalue = self.rightMotor.get_degrees_counted() + brakeStartValue = brakeStart * rotateDistance + drivenDistance = getDrivenDistance(self) + + while loop: + if cancel: + break + if run_generator: #run parallel code execution + next(generator) + + #Calculation of driven distance and PID values + oldDrivenDistance = drivenDistance + drivenDistance = getDrivenDistance(self) + + pidCalculation(speed) + change = getGyroValue() - gyroStartValue #yaw angle used due to orientation of the self.hub + + + currenSteering = (change * pRegler + integral * iRegler + dRegler * (change - old_change)) + offset + steeringSum*0.02 + + currenSteering = max(-100, min(currenSteering, 100)) + #print("steering: " + str(currenSteering) + " gyro: " + str(change) + " integral: " + str(integral)) + + steeringSum += change + integral += change - old_change + old_change = change + + #Calculation of speed based on acceleration and braking, calculation of steering value for robot to drive perfectly straight + speed = speedCalculation(speed, startspeed,maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, drivenDistance, oldDrivenDistance) + self.movement_motors.start_at_power(int(speed), invert * int(currenSteering)) + + + if stopMethod != None: + if stopMethod.loop(): + loop = False + elif rotateDistance < drivenDistance: + loop = False + + + if stop: + self.movement_motors.stop() + + run_generator = True + runSmall = True + + return #End of gyroStraightDrive + + def arcRotation(self, radius, angle, startspeed, maxspeed, endspeed, addspeed = 0.3, brakeStart = 0.7, stopMethod=None, generator = None, stop = True): + """ + This is the function that we use to make the robot drive a curve with a specified radius and to a given angle + Parameters + ------------- + radius: the radius of the curve the robot is supposed to drive; measured from the outside edge of the casing. Type: Integer. Default: 0 + angle: the angle that the robot is supposed to rotate on the curve. Type: Integer. Default: 0 + speed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value + maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value + endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value + addspeed: The speed which the robot adds in order to accelerate. Type: Float. Default: 0.2 + brakeStart: The value which we use to tell the robot after what percentage of the distance we need to slow down. Type: Float. Default: 0.8 + stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance + generator: the generator that runs something parallel while driving. Default: No default value + stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True + """ + + if cancel: + print("cancel") + return + + global run_generator, runSmall + + if generator == None: + run_generator = False + + angle = angle * (336/360) #gyro calibration + + gyroStartValue = getGyroValue() + finalGyroValue = gyroStartValue + angle + currentAngle = gyroStartValue + + accelerateDistance = abs(angle * addspeed) + deccelerateDistance = abs(angle * (1 - brakeStart)) + brakeStartValue = abs(angle * brakeStart) + + loop = True + + #Calculating the speed ratios based on the given radius + if angle * startspeed > 0: + speed_ratio_left = (radius+14) / (radius+2) #calculate speed ratios for motors. These will need to be adapted based on your robot design + speed_ratio_right = 1 + else: + speed_ratio_left = 1 + speed_ratio_right = (radius+14) / (radius+2) + + #Calculating the first speed to drive with + left_speed = speedCalculation(startspeed, startspeed, maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0) + right_speed = speedCalculation(startspeed, startspeed , maxspeed , endspeed , accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0) + while loop: + #when the cancel button is pressed stop the gyrostraight drive directly + if cancel: + break + + if run_generator: #run parallel code execution + next(generator) + + currentAngle = getGyroValue() #Yaw angle used due to orientation of the self.hub. This might need to be changed + + #Calculating the current speed the robot should drive + left_speed = speedCalculation(left_speed, startspeed, maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0) + right_speed = speedCalculation(right_speed, startspeed , maxspeed , endspeed , accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0) + + + self.movement_motors.start_tank_at_power(int(left_speed* speed_ratio_left), int(right_speed* speed_ratio_right)) + + #if there is a stopMethod passed use it and stop the loop if it returns true otherwise check if the robot has rotated to the given angle + if stopMethod != None: + #print("stoMeth") + if stopMethod.loop(): + loop = False + break + + (angle / abs(angle)) + if finalGyroValue * (angle / abs(angle)) < currentAngle * (angle / abs(angle)): + #print("finalGyroValue: " + str(finalGyroValue) + " rotatedDistance: " + str(currentAngle)) + loop = False + break + + + + + #if stop is true then stop the motors otherwise don't stop the motor + if stop: + self.movement_motors.stop() + + run_generator = True + runSmall = True + return #End of arcRotation + +def resetGyroValue(): + global gyroValue + hub2.motion.yaw_pitch_roll(0) + + gyroValue = 0 + +def getGyroValue(): + + #this method is used to return the absolute gyro Angle and the angle returned by this method doesn't reset at 180 degree + global lastAngle + global oldAngle + global gyroValue + + #gets the angle returned by the spike prime program. The problem is the default get_yaw_angle resets at 180 and -179 back to 0 + angle = hub.motion_sensor.get_yaw_angle() + + if angle != lastAngle: + oldAngle = lastAngle + + lastAngle = angle + + if angle == 179 and oldAngle == 178: + hub2.motion.yaw_pitch_roll(0)#reset + gyroValue += 179 + angle = 0 + + if angle == -180 and oldAngle == -179: + hub2.motion.yaw_pitch_roll(0) #reset + gyroValue -= 180 + angle = 0 + + return gyroValue + angle + +def getDrivenDistance(data): + + + #print(str(abs(data.leftMotor.get_degrees_counted() - data.left_Startvalue)) + " .:. " + str(abs(data.rightMotor.get_degrees_counted() - data.right_Startvalue))) + + drivenDistance = ( + abs(data.leftMotor.get_degrees_counted() - data.left_Startvalue) + + abs(data.rightMotor.get_degrees_counted() - data.right_Startvalue)) / 2 + + return drivenDistance + +def defaultClass(object, db): + object.db = db + object.leftMotor = db.leftMotor + object.rightMotor = db.rightMotor + + object.left_Startvalue = abs(db.leftMotor.get_degrees_counted()) + object.right_Startvalue = abs(db.rightMotor.get_degrees_counted()) + return object + +class stopMethods(): #This class has all our stopmethods for easier coding and less redundancy + + class stopLine(): + """ + Drive until a Line is detected + Parameters + ------------- + db: the drivebase of the robot + port: Port to detect line on + lightvalue: Value of the light to detect + detectLineDistance: Distance until start detecting a line + """ + def __init__(self, db, port, lightvalue, detectLineDistance): + self = defaultClass(self, db) + + self.port = port + self.detectLineDistance = (detectLineDistance / 17.6) * 360 + + #if lightvalue bigger 50 stop when lightvalue is higher + self.lightvalue = lightvalue + + + def loop(self): + + + drivenDistance = getDrivenDistance(self) + + if abs(self.detectLineDistance) < abs(drivenDistance): + if self.lightvalue > 50: + if ColorSensor(self.port).get_reflected_light() > self.lightvalue: + return True + else: + if ColorSensor(self.port).get_reflected_light() < self.lightvalue: + return True + + return False + + class stopAlign(): + """ + Drive until a Line is detected + Parameters + ------------- + db: the drivebase of the robot + port: Port to detect line on + lightvalue: Value of the light to detect + speed: speed at which the robot searches for other line + """ + def __init__(self, db, lightvalue, speed): + self = defaultClass(self, db) + self.speed = speed + + + #if lightvalue bigger 50 stop when lightvalue is higher + self.lightValue = lightvalue + + + def loop(self): + + if colorE.get_reflected_light() < self.lightValue: + self.rightMotor.stop() + #Turning robot so that other colour sensor is over line + while True: + + self.leftMotor.start_at_power(-int(self.speed)) + + #Line detection and stopping + if colorF.get_reflected_light() < self.lightValue or cancel: + self.leftMotor.stop() + return True + + + #Colour sensor F sees line first + elif colorF.get_reflected_light() < self.lightValue: + + self.leftMotor.stop() + + #Turning robot so that other colour sensor is over line + while True: + self.rightMotor.start_at_power(int(self.speed)) + + #Line detection and stopping + if colorE.get_reflected_light() < self.lightValue or cancel: + self.rightMotor.stop() + return True + + + return False + + class stopTangens(): + """ + Drive until a Line is detected + Parameters + ------------- + db: the drivebase of the robot + port: Port to detect line on + lightvalue: Value of the light to detect + speed: Distance until start detecting a line + """ + def __init__(self, db, lightvalue, speed): + self.count = 0 + self = defaultClass(self, db) + self.speed = speed + #if lightvalue bigger 50 stop when lightvalue is higher + self.lightValue = lightvalue + self.detectedLineDistance = 0 + + self.invert = 1 + if speed < 0: + self.invert = -1 + + def loop(self): + drivenDistance = getDrivenDistance(self) + if colorE.get_reflected_light() < self.lightValue: + #measuring the distance the robot has driven since it has seen the line + if(self.detectedLineDistance == 0): + self.detectedLineDistance = getDrivenDistance(self) + self.detectedPort = 'E' + + elif self.detectedPort == 'F': + db.movement_motors.stop() #Stops robot with sensor F on the line + angle = math.degrees(math.atan(((drivenDistance - self.detectedLineDistance) / 360 * circumference) / sensordistance)) #Calculating angle that needs to be turned using tangent + #print("angle: " + str(angle)) + db.gyroRotation(-angle, self.invert * self.speed, self.invert * self.speed, self.invert * self.speed, rotate_mode=1) #Standard gyrorotation for alignment, but inverting speed values if necessary + + db.movement_motors.stop() #Stopping robot for increased reliability + return True + + #Colour sensor F sees line first + elif colorF.get_reflected_light() < self.lightValue: + #measuring the distnace the robot has driven since it has seen the line + if(self.detectedLineDistance == 0): + self.detectedLineDistance = drivenDistance + self.detectedPort = 'F' + + elif self.detectedPort == 'E': + db.movement_motors.stop() #Stops robot with sensor E on the line + angle = math.degrees(math.atan(((drivenDistance - self.detectedLineDistance) / 360 * circumference) / sensordistance)) #Calculation angle that needs to be turned using tangent + db.gyroRotation(angle, self.invert * self.speed, self.invert * self.speed, self.invert * self.speed, rotate_mode=1) #Standard gyrorotation for alignment, but inverting speed values if necessary + db.movement_motors.stop() #Stopping robot for increased reliablity + return True + + return False + class stopDegree(): + """ + Roates until a certain degree is reached + Parameters + ------------- + db: the drivebase of the robot + angle: the angle to rotate + """ + def __init__(self, db, angle): + self.angle = angle * (336/360) + + self.gyroStartValue = getGyroValue() #Yaw angle used due to orientation of the self.hub. + + + def loop(self): + rotatedDistance = getGyroValue() #Yaw angle used due to orientation of the self.hub. + + if abs(self.angle) <= abs(rotatedDistance - self.gyroStartValue): + return True + else: + return False + + class stopTime(): + + """ + Drive until a certain time is reached + Parameters + ------------- + db: the drivebase of the robot + time: the time to drive + """ + + def __init__(self, db, time) -> None: + self = defaultClass(self, db) + self.time = time + self.timer = Timer() + self.startTime = self.timer.now() + + def loop(self): + if self.timer.now() > self.startTime + self.time: + return True + else: + return False + + class stopResistance(): + + """ + Drive until the Robot doesn't move anymore + Parameters + ------------- + db: the drivebase of the robot + restistance: the value the resistance has to be below to stop + """ + def __init__(self, db, resistance): + self = defaultClass(self, db) + self.resistance = resistance + self.timer = Timer() + + self.startTime = 0 + self.lower = False + self.runs = 0 + + def loop(self): + + self.runs += 1 + motion = abs(hub2.motion.accelerometer(True)[2]) + + if motion < self.resistance: + self.lower = True + + if self.runs > 15: + if self.lower: + if self.startTime == 0: + self.startTime = self.timer.now() + + if self.timer.now() > self.startTime: + return True + + else: + self.lower = False + return False + +def motorResistance(speed, port, resistancevalue): + """ + lets the motor stop when it hits an obstacle + """ + if abs(resistancevalue) > abs(speed): + return + + + if cancel: + return + + if port == "A": + smallMotorA.start_at_power(speed) + while True: + old_position = smallMotorA.get_position() + wait_for_seconds(0.4) + if abs(old_position - smallMotorA.get_position())= 1 else 1) * subSpeedPerDegree + addition = (abs(drivenDistance) - abs(oldDrivenDistance) if abs(drivenDistance) - abs(oldDrivenDistance) >= 1 else 1) * addSpeedPerDegree + + if abs(drivenDistance) > abs(brakeStartValue): + + if abs(speed) > abs(endspeed): + speed = speed - subtraction + + elif abs(speed) < abs(maxspeed): + + speed = speed + addition + + return speed + +def breakFunction(args): + """ + Allows you to manually stop currently executing round but still stays in main. + This is much quicker and more reliable than pressing the center button. + """ + global cancel, inMain + if not inMain: + cancel = True + +def pidCalculation(speed): + #golbally sets PID values based on current speed of the robot, allows for fast and accurate driving + global pRegler + global iRegler + global dRegler + #Important note: These PID values are experimental and based on our design for the robot. You will need to adjust them manually. You can also set them statically as you can see below + if speed > 0: + pRegler = -0.17 * speed + 12.83 + iRegler = 12 + dRegler = 1.94 * speed - 51.9 + if pRegler < 3.2: + pRegler = 3.2 + else: + pRegler = (11.1 * abs(speed))/(0.5 * abs(speed) -7) - 20 + iRegler = 10 + #iRegler = 0.02 + dRegler = 1.15**(- abs(speed)+49) + 88 + +def pidCalculationLight(speed): + #Sets the PID values for the lineFollower based on current speed. Allows for accurate and fast driving + #Important note: these PID values are experimental and based on our design for the robot. You will need to adjust them. See above on how to do so + global pReglerLight + global dReglerLight + + pReglerLight = -0.04 * speed + 4.11 + dReglerLight = 0.98 * speed - 34.2 + #set hard bottom for d value, as otherwise the values don't work + if dReglerLight < 5: + dReglerLight = 5 + +def driveMotor(rotations, speed, port): + """ + Allows you to drive a small motor in parallel to driving with gyroStraightDrive + Parameters + ------------- + rotations: the rotations the motor turns + speed: the speed at which the motor turns + port: the motor used. Note: this cannot be the same motors as configured in the motor Drivebase + """ + + global runSmall + global run_generator + + if cancel: + runSmall = False + run_generator = False + + while runSmall: + smallMotor = Motor(port) + smallMotor.set_degrees_counted(0) + + loop_small = True + while loop_small: + drivenDistance = smallMotor.get_degrees_counted() + smallMotor.start_at_power(speed) + if (abs(drivenDistance) > abs(rotations) * 360): + loop_small = False + if cancel: + loop_small = False + yield + + smallMotor.stop() + runSmall = False + run_generator = False + yield + +hub2.motion.yaw_pitch_roll(0) + +db = DriveBase(hub, 'A', 'B') #this lets us conveniently hand over our motors (B: left driver; C: right driver). This is necessary for the cancel function + +def exampleOne(): + #This example aims to show all the options for following a line. See the specific documentation of the function for further information. + db.lineFollower(15, 25, 35, 25, 'E', 'left') #follows the left side of a line on the E sensor for 15cm. Accelerates from speed 25 to 35 and ends on 25 again + hub.left_button.wait_until_pressed() + db.lineFollower(15, 25, 35, 25, 'E', 'left', 0.4, 0.6) #same line follower as before but with a longer acceleration and breaking period + hub.left_button.wait_until_pressed() + db.lineFollower(15, 25, 35, 25, 'E', 'left', stopMethod=stopMethods.stopLine(db, 'F', 0.7)) #same linefollower as the first, but this time stopping, when the other sensor sees a black line after at least 70% of the driven distance + hub.left_button.wait_until_pressed() + db.lineFollower(15, 25, 35, 25, 'E', 'left', stopMethod=stopMethods.stopResistance(db, 20)) #same as first linefollower, but stops when desired resistance is reached. Test the resistance value based on your robot + hub.left_button.wait_until_pressed() + generator = driveMotor(5, 100, 'A') + db.lineFollower(15, 25, 35, 25, 'E', 'left', generator=generator) #same as first linefollower, but drives while turning the A-Motor for 5 rotations + hub.left_button.wait_until_pressed() + db.lineFollower(15, 25, 35, 25, 'E', 'left', stop=False) #same as first linefollower, but does not actively brake the motors. The transistion form this action to the next is then smoother + return + +def exampleTwo(): + #This example aims to show all the options for turning the robot. See the specific documentation of the function for further information. + db.gyroRotation(90, 25, 35, 25) #turns the robot 90° clockwise while accelerating from speed 25 to 35 and back down to 25 + hub.left_button.wait_until_pressed() + db.gyroRotation(90, 25, 35, 25, 0.4, 0.5) #same turning as in first rotation but with longer acceleration/braking phase + hub.left_button.wait_until_pressed() + db.gyroRotation(90, 25, 35, 25, rotate_mode=1) #same turn as in first rotation but this time turning using only one wheel rather than turning on the spot. Your speeds may need to be higher for this + hub.left_button.wait_until_pressed() + db.gyroRotation(90, 25, 35, 25, stopMethod=stopMethods.stopAlign(db, 25, 25)) #aligns the robot with a line in turning path + hub.left_button.wait_until_pressed() + db.gyroRotation(90, 25, 35, 25, stopMethod=stopMethods.stopLine(db, 'E', 25, 0.7)) #turns until the robot sees a line on sensor E after at least 70% of turning + hub.left_button.wait_until_pressed() + db.gyroRotation(90, 25, 35, 25, stopMethod=stopMethods.stopTangens(db, 25, 25)) #aligns the robot like stopAlign but is a bit more precise + hub.left_button.wait_until_pressed() + #remaining parameters are the same as in linefollower. Please refer to exampleOne or the documentation of the individual functions + return + +def exampleThree(): + #This example aims to show all the options for driving in a straight line. See the specific documentation of the function for further information. + db.gyroStraightDrive(30, 25, 35, 25) #drives in a straight line for 30cm + hub.left_button.wait_until_pressed() + db.gyroStraightDrive(30, 25, 55, 25, 0.1, 0.9) #same as first drive, but faster and with harder acceleration/braking + hub.left_button.wait_until_pressed() + db.gyroStraightDrive(30, 25, 35, 25, offset=15) #same as first drive, but aims 15° in clockwise direction as target orientation + #remaining features of code are explained in previous examples. Please refer to exampleOne, exampleTwo and additional documentation within individual functions + return + +def exampleFour(): + #This example aims to show all the options for turning in a large curve. See the specific documentation of the function for further information. + db.arcRotation(5, 35, 25, 30, 25) #robot drives 35° on a circle with a radius of 5cm measured from the inside edge of the robot + #remaining features of code are explained in previous examples. Please refer to exampleOne, exampleTwo and additional documentation within individual functions + return + +def exampleFive(): + #add your own code here + + + return + +def exampleSix(): + #add your own code here + + + return + +class bcolors: + BATTERY = '\033[32m' + BATTERY_LOW = '\033[31m' + + ENDC = '\033[0m' + +pReglerLight = 1.6 +iReglerLight = 0.009 +dReglerLight = 16 + +accelerate = True + +# see comment for breakFunction +#hub2.button.right.callback(breakFunction) + +gyroValue = 0 + + +#Battery voltage printout in console for monitoring charge +if battery.voltage() < 8000: #set threshold for battery level + print(bcolors.BATTERY_LOW + "battery voltage is too low: " + str(battery.voltage()) + " \n ----------------------------- \n >>>> please charge robot <<<< \n ----------------------------- \n"+ bcolors.ENDC) +else: + print(bcolors.BATTERY + "battery voltage: " + str(battery.voltage()) + bcolors.ENDC) + + +db.movement_motors.set_stop_action("hold") #hold motors on wait for increased reliability + + +print("successfully loaded the Go-Robot code :)") \ No newline at end of file diff --git a/hub/__init__.py b/hub/__init__.py new file mode 100644 index 0000000..5cbd0a2 --- /dev/null +++ b/hub/__init__.py @@ -0,0 +1,50 @@ +from typing import Tuple, overload +from hub import port, battery, bluetooth, button, display, motion, sound, supervision +from hub.display import Image + +__version__ = 'v1.0.0.0000-0000000' +config = {} + +TOP = 0 +FRONT = 1 +RIGHT = 2 +BOTTOM = 3 +BACK = 4 +LEFT = 5 + +def info() -> dict: + pass + +def status() -> dict: + pass + +def temperature() -> float: + pass + +@overload +def power_off(fast=True, restart=False): + pass + +@overload +def power_off(timeout=0): + pass + +def repl_restart(restart: bool): + pass + +@overload +def led(color: int): + pass + +@overload +def led(red: int, green: int, blue: int): + pass + +@overload +def led(color: Tuple[int, int, int]): + pass + +def file_transfer(filename: str, filesize: int, packetsize=1000, timeout=2000, mode=None): + pass + + diff --git a/hub/battery.py b/hub/battery.py new file mode 100644 index 0000000..e0feb9a --- /dev/null +++ b/hub/battery.py @@ -0,0 +1,96 @@ +from typing import Union + +def voltage() -> int: + """ + Gets the battery voltage. + + ### Returns + - The voltage in mV. + """ + pass + +def current() -> int: + """ + Gets current flowing out of the battery. + + ### Returns + - The current in in mA. + """ + pass + +def capacity_left() -> int: + """ + Gets the remaining capacity as a percentage of a fully charged battery. + + ### Returns + - The remaining battery capacity. + """ + pass + +def temperature() -> float: + """ + Gets the temperature of the battery. + + ### Returns + - The temperature in degrees Celsius. + """ + pass + +def charger_detect() -> Union[bool, int]: + """ + Checks what type of charger was detected. + + ### Returns + - See charging constants for all possible return values. Returns False if it failed to detect a charger. + """ + pass + +def info() -> dict: + """ + Gets status information about the battery. + + This returns a dictionary of the form: + + ``` + { + # Battery measurements as documented above. + 'battery_capacity_left': 100 + 'temperature': 25.7, + 'charge_current': 248, + 'charge_voltage': 8294, + + # Filtered version of the battery voltage. + 'charge_voltage_filtered': 8287, + + # A list of active errors. See constants given below. + 'error_state': [0], + + # Charging state. See constants given below. + 'charger_state': 2, + } + ``` + ### Returns + - Battery status information. + """ + pass + +# Battery status values +BATTERY_NO_ERROR = 0 #The battery is happy. +BATTERY_HUB_TEMPERATURE_CRITICAL_OUT_OF_RANGE= -1 #The battery temperature is outside of the expected range. +BATTERY_TEMPERATURE_OUT_OF_RANGE= -2 #The battery temperature is outside of the critical range. +BATTERY_TEMPERATURE_SENSOR_FAIL= -3 #The battery temperature sensor is not working. +BATTERY_BAD_BATTERY= -4 #Something is wrong with the battery. +BATTERY_VOLTAGE_TOO_LOW= -5 #The battery voltage is too low. +BATTERY_MISSING= -6 #No battery detected. + +#Charger types +USB_CH_PORT_NONE= 0 #No charger detected. +USB_CH_PORT_SDP= 1 #Standard downstream port (typical USB port). +USB_CH_PORT_CDP= 2 #Charging Downstream Port (wall charger). +USB_CH_PORT_DCP= 3 #Dedicated charging port (high current USB port). + +#Charging states +CHARGER_STATE_FAIL= -1 #There was a problem charging the battery. +CHARGER_STATE_DISCHARGING= 0 #The battery is discharging. +CHARGER_STATE_CHARGING_ONGOING= 1 #The battery is charging. +CHARGER_STATE_CHARGING_COMPLETED= 2 #The battery is fully charged. \ No newline at end of file diff --git a/hub/bluetooth.py b/hub/bluetooth.py new file mode 100644 index 0000000..bab3286 --- /dev/null +++ b/hub/bluetooth.py @@ -0,0 +1,144 @@ +from typing import Callable, overload + +# The Bluetooth module. + +@overload +def discoverable() -> int: + pass + +@overload +def discoverable(time: int): + """ + Gets or sets the Bluetooth classic discoverability state. + + ### Parameters + - `time` - For how many seconds the hub should be discoverable. During this time, you can find the hub when you search for Bluetooth devices using your computer or phone. + + ### Returns + - If no argument is given, this returns the remaining number of seconds that the hub is discoverable. Once the hub is no longer discoverable, it returns 0. + """ + pass + +@overload +def rfcomm_connect() -> str: + pass + +@overload +def rfcomm_connect(address: str) -> bool: + """ + Connects to a Bluetooth Classic MAC address. + + ### Parameters + - `address` - A string of format aa:bb:cc:dd:ee:ff that represents the MAC address of the Bluetooth Classic device to connect with. + + ### Returns + - If no argument is given, returns the MAC address that the RFCOMM service is conneted to. If there is no active connection the address is 00:00:00:00:00:00. + - True if a valid address was given, or False if the address is not a valid MAC address string. + - The result does not reflect the status of the connection attempt. + """ + pass + +def rfcomm_disconnect() -> None: + """ + Disconnects an active RFCOMM channel + + The result does not reflect the status of the disconnection attempt. + """ + pass + +def info() -> dict: + """ + Gets a dictionary of the form: + + ``` + { + # The Bluetooth device MAC address. + 'mac_addr': '38:0B:3C:A2:E1:E4', + + # The Bluetooth device UUID. + 'device_uuid': '03970000-1800-3500-1551-383235373836' + + # The outgoing service UUID. + 'service_uuid': '', + + # Bluetooth name of the device. + 'name': 'LEGO Hub 38:0B:3C:A2:E1:E4', + + # iPod Accessory Protocol (iAP) status dictionary. + 'iap': { + 'device_version': 7, + 'authentication_revision': 1, + 'device_id': -1, + 'certificate_serial_no': '54D2891DEC5E5104F7132BC3059365CB', + 'protocol_major_version': 3, + 'protocol_minor_version': 0 + }, + + # A list of devices that the hub has been connected to. + 'known_devices': ['8C:8D:28:2D:E0:0F', 'E8:6D:CB:77:64:D5'], + } + ``` + ### Returns + - Bluetooth subsystem information dictionary similar to the example above, or None if the Bluetooth subsystem is not running. + - The MAC address in known_devices is reversed for Windows devices. + """ + pass + +def forget(address) -> bool: + """ + Removes a device from the list of known Bluetooth devices. + + ### Parameters + - `address` - Bluetooth address of the form '01:23:45:67:89:AB'. + + ### Returns + - True if a valid address was given, or False if not. + - Functions for the LEGO Wireless Protocol + """ + pass + +@overload +def lwp_advertise() -> int: + pass + +@overload +def lwp_advertise(timeout: int): + """ + Gets or sets the Bluetooth Low Energy LEGO Wireless protocol advertising state. + + ### Parameters + - `time` - For how many seconds the hub should advertise the LEGO Wireless Protocol. During this time, you can find the hub when you search for Bluetooth devices using your computer or phone. + + ### Returns + - If no argument is given, this returns the remaining number of seconds that the hub will advertise. Once the hub is no longer advertising, it returns 0. + """ + pass + +@overload +def lwp_bypass() -> bool: + pass + +@overload +def lwp_bypass(bypass: bool): + """ + Controls whether the LEGO Wireless Protocol is bypassed when using Bluetooth Low Energy. + + ### Parameters + - `bypass` - Choose True to bypass the LEGO Wireless protocol or choose False to enable it. + + ### Returns + - If no argument is given, this returns the current bypass state. + """ + pass + +def lwp_monitor(self, handler: Callable[[int], None]): + """ + Sets the callback function that is called when a connection is made using the LEGO Wireless Protocol. + + The function must accept one argument, which provides information about the incoming connection. + + ### Parameters + - `handler` - Callable function that takes one argument. Choose None to disable the callback. + """ + pass + diff --git a/hub/button.py b/hub/button.py new file mode 100644 index 0000000..7aeb922 --- /dev/null +++ b/hub/button.py @@ -0,0 +1,57 @@ +from typing import Callable + + +class Button: + """ + Provides access to button state and callback. + + Each of the buttons listed below are instances of this class. You cannot instantiate additional button objects. + """ + + def is_pressed(self) -> bool: + """ + Gets the state of the button. + + ### Returns + - True if it is pressed, False otherwise. + """ + pass + + def was_pressed() -> bool: + """ + Checks if this button was pressed since this method was last called. + + ### Returns + - True if it was pressed at least once since the previous call, False otherwise. + """ + pass + + def presses() -> int: + """ + Gets the number of times this button was pressed since this method was last called. + + ### Returns + - The number of presses since the last call. + """ + pass + + def callback(function: Callable[[int], None]) -> None: + """ + Sets the callback function that is called when the button is pressed and when it is released. + + The function must accept one argument, whose value indicates why the callback was called: + + If the value is 0, the button is now pressed. + + Otherwise, the button is now released. The value represents how many milliseconds it was pressed before it was released. + + ### Parameters + - `function` - Callable function that takes one argument. Choose None to disable the callback. + """ + pass + + +left: Button # The left button. +right: Button # The right button. +center: Button # The center button. +connect: Button # The button with the Bluetooth symbol. \ No newline at end of file diff --git a/hub/display.py b/hub/display.py new file mode 100644 index 0000000..f46a313 --- /dev/null +++ b/hub/display.py @@ -0,0 +1,378 @@ +from __future__ import annotations +from typing import Callable, Iterable + +""" +The Image class lets you create and modify images that you can show on the hub matrix display using the hub.display module. +""" +class Image: + + def __init__(self, *args): + """ + Create a new image object for use with the hub.display.show() function. + + ``` + Image(string: str) + Image(width: int, height: int) + Image(width: int, height: int, buffer: bytes) + ``` + + You can use one of the signatures above to initialize an image, depending on what you need. + + ### Parameters + + - `string` - String of the form "00900:09990:99999:09990:09090:", representing the brightness of each pixel (0 to 9). Pixels are listed row by row, separated by a colon (:) or line break (\\n). + - `width` - Number of pixels in one row of the new image. + - `height` - Number of pixels in one column of the new image. + - `buffer` - Bytes representing the brightness values of each pixel in the new image. The buffer size must be equal to width * height. If you give a with and height but no buffer, you will get an image where all pixels are zero. + """ + pass + + def width(self) -> int: + """ + Gets the width of the image as a number of pixels. + """ + pass + + def height(self) -> int: + """ + Gets the width of the image as a number of pixels. + """ + pass + + def shift_left(n: int) -> 'Image': + """ + Shifts the image to the left. + + ### Parameters + - `n1 - By how many pixels to shift the image. + + ### Returns + - A new, shifted image. + """ + pass + + def shift_right(n: int) -> 'Image': + """ + Shifts the image to the right. + + ### Parameters + - `n` - By how many pixels to shift the image. + + ### Returns + - A new, shifted image. + """ + pass + + def shift_up(n: int) -> 'Image': + """ + Shifts the image up. + + ### Parameters + - `n` - By how many pixels to shift the image. + + ### Returns + - A new, shifted image. + """ + pass + + def shift_down(n: int) -> 'Image': + """ + Shifts the image down. + + ### Parameters + - `n` - By how many pixels to shift the image. + + ### Returns + - A new, shifted image. + """ + pass + + def get_pixel(x: int, y: int, brightness: int) -> int: + """ + Gets the brightness of one pixel in the image. + + ### Parameters + - `x` - Pixel position counted from the left, starting at zero. + - `y` - Pixel position counted from the top, starting at zero. + + ### Returns + - Brightness (0-9) of the requested pixel. + """ + pass + + def set_pixel(x: int, y: int, brightness: int) -> None: + """ + Sets the brightness of one pixel in the image. + + ### Parameters + - `x` - Pixel position counted from the left, starting at zero. + - `y` - Pixel position counted from the top, starting at zero. + - `brightness` - Brightness between 0 (fully off) and 9 (fully on). + + ### Raises + - `ValueError` - If x or y are negative or larger than the image size. + - `TypeError` - If you try to modify a built-in image such as HEART. + """ + pass + + ANGRY: Image + ARROW_E: Image + ARROW_N: Image + ARROW_NE: Image + ARROW_NW: Image + ARROW_S: Image + ARROW_SE: Image + ARROW_SW: Image + ARROW_W: Image + ASLEEP: Image + BUTTERFLY: Image + CHESSBOARD: Image + CLOCK1: Image + CLOCK2: Image + CLOCK3: Image + CLOCK4: Image + CLOCK5: Image + CLOCK6: Image + CLOCK7: Image + CLOCK8: Image + CLOCK9: Image + CLOCK10: Image + CLOCK11: Image + CLOCK12: Image + CONFUSED: Image + COW: Image + DIAMOND: Image + DIAMOND_SMALL: Image + DUCK: Image + FABULOUS: Image + GHOST: Image + GIRAFFE: Image + GO_DOWN: Image + GO_LEFT: Image + GO_RIGHT: Image + GO_UP: Image + HAPPY: Image + HEART: Image + HEART_SMALL: Image + HOUSE: Image + MEH: Image + MUSIC_CROTCHET: Image + MUSIC_QUAVER: Image + MUSIC_QUAVERS: Image + NO: Image + PACMAN: Image + PITCHFORK: Image + RABBIT: Image + ROLLERSKATE: Image + SAD: Image + SILLY: Image + SKULL: Image + SMILE: Image + SNAKE: Image + SQUARE: Image + SQUARE_SMALL: Image + STICKFIGURE: Image + SURPRISED: Image + SWORD: Image + TARGET: Image + TORTOISE: Image + TRIANGLE: Image + TRIANGLE_LEFT: Image + TSHIRT: Image + UMBRELLA: Image + XMAS: Image + YES: Image + ALL_CLOCKS: Image + ALL_ARROWS: Image + +#Built-in images +Image.ANGRY = Image('90009:09090:00000:99999:90909:') +Image.ARROW_E = Image('00900:00090:99999:00090:00900:') +Image.ARROW_N = Image('00900:09990:90909:00900:00900:') +Image.ARROW_NE = Image('00999:00099:00909:09000:90000:') +Image.ARROW_NW = Image('99900:99000:90900:00090:00009:') +Image.ARROW_S = Image('00900:00900:90909:09990:00900:') +Image.ARROW_SE = Image('90000:09000:00909:00099:00999:') +Image.ARROW_SW = Image('00009:00090:90900:99000:99900:') +Image.ARROW_W = Image('00900:09000:99999:09000:00900:') +Image.ASLEEP = Image('00000:99099:00000:09990:00000:') +Image.BUTTERFLY = Image('99099:99999:00900:99999:99099:') +Image.CHESSBOARD = Image('09090:90909:09090:90909:09090:') +Image.CLOCK1 = Image('00090:00090:00900:00000:00000:') +Image.CLOCK2 = Image('00000:00099:00900:00000:00000:') +Image.CLOCK3 = Image('00000:00000:00999:00000:00000:') +Image.CLOCK4 = Image('00000:00000:00900:00099:00000:') +Image.CLOCK5 = Image('00000:00000:00900:00090:00090:') +Image.CLOCK6 = Image('00000:00000:00900:00900:00900:') +Image.CLOCK7 = Image('00000:00000:00900:09000:09000:') +Image.CLOCK8 = Image('00000:00000:00900:99000:00000:') +Image.CLOCK9 = Image('00000:00000:99900:00000:00000:') +Image.CLOCK10 = Image('00000:99000:00900:00000:00000:') +Image.CLOCK11 = Image('09000:09000:00900:00000:00000:') +Image.CLOCK12 = Image('00900:00900:00900:00000:00000:') +Image.CONFUSED = Image('00000:09090:00000:09090:90909:') +Image.COW = Image('90009:90009:99999:09990:00900:') +Image.DIAMOND = Image('00900:09090:90009:09090:00900:') +Image.DIAMOND_SMALL = Image('00000:00900:09090:00900:00000:') +Image.DUCK = Image('09900:99900:09999:09990:00000:') +Image.FABULOUS = Image('99999:99099:00000:09090:09990:') +Image.GHOST = Image('99999:90909:99999:99999:90909:') +Image.GIRAFFE = Image('99000:09000:09000:09990:09090:') +Image.GO_DOWN = Image('00000:99999:09990:00900:00000:') +Image.GO_LEFT = Image('00090:00990:09990:00990:00090:') +Image.GO_RIGHT = Image('09000:09900:09990:09900:09000:') +Image.GO_UP = Image('00000:00900:09990:99999:00000:') +Image.HAPPY = Image('00000:09090:00000:90009:09990:') +Image.HEART = Image('09090:99999:99999:09990:00900:') +Image.HEART_SMALL = Image('00000:09090:09990:00900:00000:') +Image.HOUSE = Image('00900:09990:99999:09990:09090:') +Image.MEH = Image('09090:00000:00090:00900:09000:') +Image.MUSIC_CROTCHET = Image('00900:00900:00900:99900:99900:') +Image.MUSIC_QUAVER = Image('00900:00990:00909:99900:99900:') +Image.MUSIC_QUAVERS = Image('09999:09009:09009:99099:99099:') +Image.NO = Image('90009:09090:00900:09090:90009:') +Image.PACMAN = Image('09999:99090:99900:99990:09999:') +Image.PITCHFORK = Image('90909:90909:99999:00900:00900:') +Image.RABBIT = Image('90900:90900:99990:99090:99990:') +Image.ROLLERSKATE = Image('00099:00099:99999:99999:09090:') +Image.SAD = Image('00000:09090:00000:09990:90009:') +Image.SILLY = Image('90009:00000:99999:00909:00999:') +Image.SKULL = Image('09990:90909:99999:09990:09990:') +Image.SMILE = Image('00000:00000:00000:90009:09990:') +Image.SNAKE = Image('99000:99099:09090:09990:00000:') +Image.SQUARE = Image('99999:90009:90009:90009:99999:') +Image.SQUARE_SMALL = Image('00000:09990:09090:09990:00000:') +Image.STICKFIGURE = Image('00900:99999:00900:09090:90009:') +Image.SURPRISED = Image('09090:00000:00900:09090:00900:') +Image.SWORD = Image('00900:00900:00900:09990:00900:') +Image.TARGET = Image('00900:09990:99099:09990:00900:') +Image.TORTOISE = Image('00000:09990:99999:09090:00000:') +Image.TRIANGLE = Image('00000:00900:09090:99999:00000:') +Image.TRIANGLE_LEFT = Image('90000:99000:90900:90090:99999:') +Image.TSHIRT = Image('99099:99999:09990:09990:09990:') +Image.UMBRELLA = Image('09990:99999:00900:90900:09900:') +Image.XMAS = Image('00900:09990:00900:09990:99999:') +Image.YES = Image('00000:00009:00090:90900:09000:') + +#Built-in tuples of images +Image.ALL_CLOCKS = (Image('00900:00900:00900:00000:00000:'), Image('00090:00090:00900:00000:00000:'), Image('00000:00099:00900:00000:00000:'), Image('00000:00000:00999:00000:00000:'), Image('00000:00000:00900:00099:00000:'), Image('00000:00000:00900:00090:00090:'), Image('00000:00000:00900:00900:00900:'), Image('00000:00000:00900:09000:09000:'), Image('00000:00000:00900:99000:00000:'), Image('00000:00000:99900:00000:00000:'), Image('00000:99000:00900:00000:00000:'), Image('09000:09000:00900:00000:00000:')) +Image.ALL_ARROWS = (Image('00900:09990:90909:00900:00900:'), Image('00999:00099:00909:09000:90000:'), Image('00900:00090:99999:00090:00900:'), Image('90000:09000:00909:00099:00999:'), Image('00900:00900:90909:09990:00900:'), Image('00009:00090:90900:99000:99900:'), Image('00900:09000:99999:09000:00900:'), Image('99900:99000:90900:00090:00009:')) + + +""" +The display module lets you control the light matrix display on the hub. +""" + +def clear(): + """ + Turns off all the pixels. + """ + pass + +def rotation(rotation: int) -> None: + """ + Rotates the display clockwise relative to its current orientation. + + DEPRECATION WARNING - In the next release this is a do-nothing operation. Use the def align() API instead! + + Following the next release this call will be removed. + """ + pass + +def align() -> int: + pass + +def align(face: int) -> int: + """ + Rotates the display by aligning the top with the given face of the hub. + + ### Parameters + - `face` - Choose hub.FRONT, hub.BACK, hub.LEFT, or hub.RIGHT. + + ### Returns + - The new or current alignment. + """ + pass + +def invert() -> bool: + pass + +def invert(invert: bool) -> bool: + """ + Inverts all pixels. This affects what is currently displayed, as well as everything you display afterwards. + + In the inverted state, the brightness of each pixel is the opposite of the normal state. If a pixel has brightness b, it will be displayed with brightness 9 - b. + + ### Parameters + - `invert` - Choose True to activate the inverted state. Choose False to restore the normal state. + + ### Returns + - The new or current inversion state. + """ + pass + +def callback(self, function: Callable[[int], None]) -> None: + """ + Sets the callback function that is called when a display operation is completed or interrupted. + + The function must accept one argument, which indicates why the callback was called. It will receive 0 if a display operation completed successfully, or 1 if it was interrupted. + + ### Parameters + - `function` - Callable function that takes one argument. Choose None to disable the callback. + """ + pass + +def pixel(x: int, y: int) -> int: + pass + +def pixel(x: int, y: int, brightness: int) -> None: + """ + Gets or sets the brightness of one pixel. + + ### Parameters + - `x` - Pixel position counted from the left, starting at zero. + - `y` - Pixel position counted from the top, starting at zero. + - `brightness` - Brightness between 0 (fully off) and 9 (fully on). + + ### Returns + - If no brightness is given, this returns the brightness of the selected pixel. Otherwise it returns None. + """ + pass + +def show(image: Image) -> None: + pass + +def show(image: Iterable[Image], delay=400, level=9, clear=False, wait=True, loop=False, fade=0) -> None: + """ + Shows an image or a sequence of images. + + Except for image, all arguments must be specified as keywords. + + ### Parameters + - `image` - The image or iterable of images to be displayed. + + ### Keyword Arguments + - `delay` - Delay between each image in the iterable. + - `level` - Scales the brightness of each pixel in and image or character to a value between 0 (fully off) and 9 (fully on). + - `clear` - Choose `True` to clear the display after showing the last image in the iterable. + - `wait` - Choose `True` to block your program until all images are shown. Choose `False` to show all images in the background while your program continues. + - `loop` - Choose `True` repeat the sequence of images for ever. Choose `False` to show it only once. + - `fade` - + + Sets the transitional behavior between images in the sequence: + + The image will appear immediately. + + The image will appear immediately. + + The image fades out while the next image fades in. + + Images will scroll to the right. + + Images will scroll to the left. + + Images will fade in, starting from an empty display. + + Images will fade out, starting from the original image. + """ + pass \ No newline at end of file diff --git a/hub/motion.py b/hub/motion.py new file mode 100644 index 0000000..703ced3 --- /dev/null +++ b/hub/motion.py @@ -0,0 +1,125 @@ +from typing import Tuple, Callable +from typing import overload + +def accelerometer(filtered=False) -> Tuple[int, int, int]: + """ + Gets the acceleration of the hub along the x, y, and z axis. + + #### Parameters + - `filtered` - Selecting True gives a more stable value, but it is delayed by 10-100 milliseconds. Selecting False gives the unfiltered value. + + #### Returns + - Acceleration of the hub with units of `cm/s^2`. On a perfectly level surface, this gives (0, 0, 981). + """ + pass + +def gyroscope(filtered=False) -> Tuple[int, int, int]: + """ + Gets the angular velocity of the hub along the x, y, and z axis. + + ### Parameters + - `filtered` - Selecting True gives a more stable value, but it is delayed by 10-100 milliseconds. Selecting False gives the unfiltered value. + + ### Returns + - Angular velocity with units of degrees per second. + """ + pass + +@overload +def align_to_model(top: int, front: int) -> None: + pass + +@overload +def align_to_model(nsamples: int, callback: Callable[[int], None]) -> None: + pass + +@overload +def align_to_model(top: int, front: int, nsamples: int, callback: Callable[[int], None]) -> None: + """ + Sets the default hub orientation and/or calibrates the gyroscope. + + The hub must not move while calibrating. It takes about one second by default. + + Changing the model alignment affects most other methods in this module. They will now be relative to the hub alignment that you specify. + + ### Keyword Arguments + - `top` - Which hub side is at the top of your model. See the hub `constants` for all possible values. + - `front` - Which hub side is on the front of your model. + - `nsamples` - Number of samples for calibration between 0 and 10000. It is 100 by default. + - `callback` - Function that will be called when calibration is complete. It must accept one argument. Choose None to disable the callback. This is the default. + """ + pass + +@overload +def yaw_pitch_roll() -> Tuple[int, int, int]: + pass + +@overload +def yaw_pitch_roll(yaw_preset: int) -> None: + pass + +@overload +def yaw_pitch_roll(yaw_correction: float) -> None: + """ + Gets the yaw, pitch, and roll angles of the hub, or resets the yaw. + + The yaw_correction is an optional keyword argument to improve the accuracy of the yaw value after one full turn. To use it: + + Reset the yaw angle to zero using def yaw_pitch_roll(0). + + Rotate the hub smoothly exactly one rotation clockwise. + + Call error = def yaw_pitch_roll()[0] to get the yaw error. + + The error should be 0. If it is not, you can set the correction using def yaw_pitch_roll(yaw_correction=error). + + For even more accuracy, you can turn clockwise 5 times, and use error / 5 as the correction factor. + + ### Keyword Arguments + - `yaw_preset` - Sets the current yaw to the given value (-180 to 179). + - `yaw_correction` - Adjusts the gain of the yaw axis values. See the yaw adjustment section below. + + ### Returns + - If no arguments are given, this returns a tuple of yaw, pitch, and roll values in degrees. + """ + pass + +@overload +def orientation() -> int: + pass + +@overload +def orientation(callback: Callable[[int], None]) -> int: + """ + Gets which hub side of the hub is mostly pointing up. + + ### Keyword Arguments + - `callback` - Function that will be called when the orientation changes. It must accept one argument, which will tell you which hub side is up. Choose None to disable the callback. This is the default. + + ### Returns + - Number representing which side is up. See hub constants for all possible values. + """ + pass + +@overload +def gesture() -> int: + pass + +@overload +def gesture(callback: Callable[[int], None]) -> int: + """ + Gets the most recent gesture that the hub has made since this function was last called. + + ### Keyword Arguments + - `callback` - Function that will be called when a gesture is detected. It must accept one argument, which will tell you which gesture was detected. Choose None to disable the callback. This is the default. + + ### Returns + - Number representing the gesture. See motion constants for all possible values. If no gesture was detected since this function was last called, it returns None. + """ + pass + +#These values are used by the gesture() function. +TAPPED = 0 #The hub was tapped. +DOUBLETAPPED = 1 #The hub was quickly tapped twice. +SHAKE = 2 #The hub was shaken. +FREEFALL = 3 #The hub fell. \ No newline at end of file diff --git a/hub/port.py b/hub/port.py new file mode 100644 index 0000000..1b34ed7 --- /dev/null +++ b/hub/port.py @@ -0,0 +1,456 @@ +from __future__ import annotations +from typing import Callable, Union, Optional, Iterable, Tuple, overload + + +class Pin(): + """ + This class can be used to read and control the two logic pins on pins 5 and 6 of each port. You can access two `Pin` objects via each `Port` instance if the port has been set to `MODE_GPIO` mode. + + Control a general purpose input/output (GPIO) pin. + """ + + def direction(self, direction: Optional[int]) -> int: + """ + Gets and sets the direction of the pin. + + ### Parameters + - `direction` - Choose 0 to make the pin an input or 1 to make it an output. + + ### Returns + - The configured direction. + """ + pass + + def value(self, value: Optional[int]) -> int: + """ + Gets and sets the logic value of the pin. + + ### Parameters + - `value` - Choose 1 to make the pin high or 0 to make it low. If the pin is configured as an input, this argument is ignored. + + ### Returns + - Logic value of the pin. + """ + pass + +class Device(): + + """ + This class is the blueprint for the device attributes of the ports in the `hub.port` module, which in turn are instances of the `Port` class. You cannot import or instantiate this class manually. + + Read values from a Powered Up device and configure its modes. + """ + FORMAT_RAW = 0 + FORMAT_PCT= 1 + FORMAT_SI= 2 + + def get(self, format: Optional[int]) -> list: + """ + Gets the values that the active device mode provides. + + ### Parameters + - `format` - Format of the data. Choose `FORMAT_RAW`, `FORMAT_PCT`, or `FORMAT_SI`. + + ### Returns + - Values or measurements representing the device state. + """ + pass + + @overload + def mode(self, mode: int) -> None: + pass + + @overload + def mode(self, mode: int, data: bytes) -> None: + pass + + @overload + def mode(self, mode: Iterable[Tuple[int, int]]) -> None: + pass + + @overload + def mode(self) -> Iterable[Tuple[int, int]]: + pass + + def pwm(self, value: int) -> None: + pass + + def write_direct(self, data: bytes) -> None: + pass + +class Motor(Device): + """ + This class is the blueprint for the motor attributes of the ports in the hub.port module, which in turn are instances of the Port class. You cannot import or instantiate this class manually. + + Control a motor. + + """ + BUSY_MODE = 0 #The port is busy configuring the device mode.""" + BUSY_MOTOR = 1 #The motor is busy executing a command. + STOP_FLOAT = 0 #When stopping, the motor floats. See also float(). + STOP_BRAKE = 1 #When stopping, the motor brakes. See also brake(). + STOP_HOLD = 2 #When stopping, the motor holds position. See also hold(). + EVENT_COMPLETED = 0 #The motor command completed successfully. + EVENT_INTERRUPTED = 1 #The motor command was interrupted. + EVENT_STALLED = 2 #The motor command stopped because the motor was stalled. + + def __init__(self): + pass + + def float(self) -> None: + """ + Floats (coasts) the motor, as if disconnected from the hub. + """ + pass + + def brake(self) -> None: + """ + Passively brakes the motor, as if shorting the motor terminals. + """ + pass + + def hold(self) -> None: + """ + Actively hold the motor in its current position. + """ + pass + + def busy(self, type:int = BUSY_MODE) -> bool: + """ + Checks whether the motor is busy changing modes, or executing a motor command such as running to a position. + + ### Parameters + - `type` - Choose `BUSY_MODE` or `BUSY_MOTOR`. + + ### Returns + - Whether the motor is busy with the specified activity. + """ + pass + + @overload + def run_at_speed(self, speed: int) -> None: + pass + + @overload + def run_at_speed(self, speed: int, max_power: int, acceleration: int, deceleration: int, stall: bool) -> None: + """ + Starts running a motor at the given speed. + + If a keyword argument is not given, its default value will be used. + + ### Parameters + - `speed` - Sets the speed as a percentage of the rated speed for this motor. Positive means clockwise, negative means counterclockwise. + + ### Keyword Arguments + - `max_power` - Sets percentage of maximum power used during this command. + - `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill. + - `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed. + - `stall` - Selects whether the motor should stop when stalled (True) or not (False). + """ + pass + + @overload + def run_for_time(self, msec: int) -> None: + pass + + @overload + def run_for_time(self, msec: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None: + """ + Runs a motor for a given amount of time. + + If a keyword argument is not given, its default value will be used. + + ### Parameters + - `msec` - How long the motor should run in milliseconds. Negative values will be treated as zero. + + ### Keyword Arguments + - `speed` - Sets the speed as a percentage of the rated speed for this motor. Positive means clockwise, negative means counterclockwise. + - `max_power` - Sets percentage of maximum power used during this command. + - `stop` - How to stop. Choose type: Choose `STOP_FLOAT`, `STOP_BRAKE`, or `STOP_HOLD`. + - `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill. + - `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed. + - `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False). + """ + pass + + @overload + def run_for_degrees(self, degrees: int) -> None: + pass + + @overload + def run_for_degrees(self, degrees: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None: + """ + Runs a motor for a given number of degrees at a given speed. + + If a keyword argument is not given, its default value will be used. + + ### Parameters + - `degrees` - How many degrees to rotate relative to the starting point. + + ### Keyword Arguments + - `speed` - + + Sets the speed as a percentage of the rated speed for this motor. + + If degrees > 0 and speed > 0, the motor turns clockwise. + + If degrees > 0 and speed < 0, the motor turns counterclockwise. + + If degrees < 0 and speed > 0, the motor turns clockwise. + + If degrees < 0 and speed < 0, the motor turns counterclockwise. + + - `max_power` - Sets percentage of maximum power used during this command. + - `stop` - How to stop. Choose type: Choose `STOP_FLOAT`, `STOP_BRAKE`, or `STOP_HOLD`. + - `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill. + - `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed. + - `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False). + """ + pass + + @overload + def run_to_position(self, position: int) -> None: + pass + + @overload + def run_to_position(self, position: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None: + """ + Runs a motor to the given position. + + The angular position is measured relative to the motor position when the hub was turned on or when the motor was plugged in. You can preset this starting position using preset. + + If a keyword argument is not given, its default value will be used. + + ### Parameters + - `position` - Position to rotate to. + + ### Keyword Arguments + - `speed` - Sets the speed as a percentage of the rated speed for this motor. The sign of the speed will be ignored. + - `max_power` - Sets percentage of maximum power used during this command. + - `stop` - How to stop. Choose type: Choose STOP_FLOAT, STOP_BRAKE, or STOP_HOLD. + - `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill. + - `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed. + - `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False). + """ + pass + + def preset(self, position: int) -> None: + """ + Presets the starting position used by run_to_position. + + ### Parameters + - `position` - The new position preset. + """ + pass + + def callback(self, function: Callable[[int], None]) -> None: + """ + Sets the callback function that is called when a command is completed, interrupted, or stalled. + + The function must accept one argument, which indicates why the callback was called. It will receive either EVENT_COMPLETED, EVENT_INTERRUPTED, or EVENT_STALLED. + + ### Parameters + - `function` - Callable function that takes one argument. Choose None to disable the callback. + """ + pass + + @overload + def pid(self) -> tuple: + pass + + @overload + def pid(self, p: int, i: int, d: int) -> None: + """ + Sets the p, i, and d constants of the motor PID controller. + + ### Parameters + - `p` - Proportional constant. + - `i` - Integral constant. + - `d` - Derivative constant. + + ### Returns + - If no arguments are given, this returns the values previously set by the user, if any. The system defaults cannot be read. + """ + pass + + @overload + def default(self) -> dict: + pass + + @overload + def default(self, speed: int, max_power: int, acceleration: int, deceleration: int, stop: int, pid: tuple, stall: bool, callback: Optional[Callable[[int], None]]): + """ + Gets or sets the motor default settings. These are used by some of the methods listed above, when no explicit argument is given. + + ### Keyword Arguments + - `speed` - The default speed. + - `max_power` - The default max_power. + - `acceleration` - The default acceleration. + - `deceleration` - The default deceleration. + - `stop` - The default stop argument. + - `pid` - Tuple of p, i, and d. See also pid. + - `stall` - The default stall argument. + + ### Returns + - If no arguments are given, this returns the current settings. + """ + pass + + def pair(self, other_motor: Motor) -> MotorPair: + """ + Pairs this motor to other_motor to create a MotorPair object. + + You can only pair two different motors that are not already part of another pair. Both motors must be of the same type. + + ### Parameters + - `other_motor` - The motor to pair to. + + ### Returns + - On success, this returns the MotorPair object. It returns False to indicate an incompatible pair or None for other errors. + """ + pass + + +class MotorPair(): + """ + This class can be used to control pairs of motors. You create `MotorPair` objects using the `pair()` method of a `Motor` object. + + Control two motors simultaneously in a synchronized way. + """ + def __init__(self): + pass + + def id(self) -> int: + pass + + def primary(self) -> Motor: + pass + + def secondary(self) -> Motor: + pass + + def unpair(self) -> bool: + pass + + def float(self) -> None: + """ + Floats (coasts) the motor, as if disconnected from the hub. + """ + pass + + def brake(self) -> None: + """ + Passively brakes the motor, as if shorting the motor terminals. + """ + pass + + def hold(self) -> None: + """ + Actively hold the motor in its current position. + """ + pass + + def pwm(self, pwm_0: int, pwm_1: int) -> None: + pass + + @overload + def run_at_speed(self, speed_0: int, speed_1: int) -> None: + pass + + @overload + def run_at_speed(self, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int) -> None: + pass + + @overload + def run_for_time(self, msec: int) -> None: + pass + + @overload + def run_for_time(self, msec: int, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None: + pass + + @overload + def run_for_degrees(self, degrees: int) -> None: + pass + + @overload + def run_for_degrees(self, degrees: int, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None: + pass + + @overload + def run_to_position(self, position_0: int, position_1: int) -> None: + pass + + @overload + def run_to_position(self, position_0: int, position_1: int, speed: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None: + pass + + def preset(self, position_0: int, position_1: int) -> None: + pass + + def callback(self, function: Callable[[int], None]) -> None: + pass + + def pid(self, p: int, i: int, d: int) -> None: + pass + +class Port(): + """ + This class is the blueprint for the port instances in the `hub.port` module. Those instances are automatically instantiated on boot, and further populated when devices are plugged in. You cannot import or instantiate this class manually. + + Provides access to port configuration and devices on a port. Some methods and attributes can only be used if the port is in the right mode, as shown below. + + Attributes for use with MODE_DEFAULT + + - `device`: Powered Up Device on this port. If no device is attached or the port is in a different mode, this attribute is None. + - `motor`: Powered Up Motor on this port. If no motor is attached or the port is in a different mode, this attribute is None. + """ + # motor: Motor + # device: Device + # p5: Pin + # p6: Pin + + def __init__(self): + self.motor: Motor + self.device: Device + self.p5: Pin + self.p6: Pin + + def info(self) -> dict: + pass + + def pwm(self, value: int) -> None: + pass + + def callback(self, function: Callable[[int], None]) -> None: + pass + + def mode(self, mode: int, baud_rate=2400) -> None: + pass + + def baud(self, baud: int) -> None: + pass + + def read(self, read: Union[int, any]) -> int: + pass + + def write(self, write: bytes) -> int: + pass + + +A: Port +B: Port +C: Port +D: Port +E: Port +F: Port + +# Constants +## Port events +DETACHED = 0 +ATTACHED = 1 +## Port modes +MODE_DEFAULT = 0 +MODE_FULL_DUPLEX = 1 +MODE_HALF_DUPLEX = 2 +MODE_GPIO = 3 \ No newline at end of file diff --git a/hub/sound.py b/hub/sound.py new file mode 100644 index 0000000..6c210df --- /dev/null +++ b/hub/sound.py @@ -0,0 +1,72 @@ +from typing import Callable, overload + +""" +The sound module lets you control the hub speaker to play sound files and beeps. +""" + +@overload +def volume() -> int: + pass + +@overload +def volume(volume: int) -> None: + """ + Sets the volume of the speaker. + + ### Parameters + - volume - Volume between 0 (no sound) and 10 (maximum volume). + + ### Returns + - If no argument is given, this returns the current volume. + """ + pass + +def beep(freq=1000, time=1000, waveform=0) -> None: + """ + Starts beeping with a given frequency, duration, and wave form. + + ### Keyword Arguments + - `freq` - Frequency of the beep in Hz (100 - 10000). + - `time` - Duration of the beep in milliseconds (0 - 32767). + - `waveform` - Wave form used for the beep. See constants for all possible values. + """ + pass + +def play(filename: str, rate=16000) -> None: + """ + Starts playing a sound file. + + The sound file must be raw 16 bit data at 16 kHz. + + ### Parameters + - `filename` - Absolute path to the sound file. + + ### Keyword Arguments + - `rate` - Playback speed in Hz. + + ### Raises + - `OSError (ENOENT)` - If the file does not exist. + """ + pass + +def callback(self, function: Callable[[int], None]) -> None: + """ + Sets the callback function that is called when a sound finished playing or when it is interrupted. + + The function must accept one argument, whose value indicates why the callback was called: + + If the value is 0, the sound completed successfully. + + If the value is 1, the sound was interrupted. + + ### Parameters + - `function` - Callable function that takes one argument. Choose None to disable the callback. + """ + pass + +#These values are used by the beep() function. +SOUND_SIN = 0 #The beep is a smooth sine wave. +SOUND_SQUARE = 1 #The beep is a loud and raw square wave. +SOUND_TRIANGLE = 2 #The beep has a triangular wave form. +SOUND_SAWTOOTH = 3 #The beep has a sawtooth-shaped wave form. + diff --git a/hub/supervision.py b/hub/supervision.py new file mode 100644 index 0000000..946ef7a --- /dev/null +++ b/hub/supervision.py @@ -0,0 +1,42 @@ +from typing import Callable + +""" +The supervision module lets you monitor critical states of the hub. +""" + +def info() -> dict: + """ + Gets status information from the subsystem that supervises the hub. + + This returns a dictionary of the form: + + ``` + { + # Checks if the peak current is too high. + 'peek_current_too_high': False, + + # Checks if the current is too high. + 'continous_current_too_high': False, + + # The current value in mA. + 'continuous_current': 60, + + # Checks if the hub temperature is too high. + 'temperature_too_high': False + } + ``` + ### Returns + - Supervision status information. + """ + pass + +def callback(self, function: Callable[[int], None]) -> None: + """ + Sets the callback function that is called when an over-current event occurs. + + The function must accept one argument, which indicates the current in mA that triggered the callback. + + ### Parameters + - `function` - Callable function that takes one argument. Choose None to disable the callback. + """ + pass \ No newline at end of file diff --git a/iqrobot.py b/iqrobot.py new file mode 100644 index 0000000..7a456c5 --- /dev/null +++ b/iqrobot.py @@ -0,0 +1,47 @@ +# LEGO type:standard slot:6 autostart + +from spike import PrimeHub, Motor, MotorPair, ColorSensor +from spike.control import wait_for_seconds + +HELLO = "HELLO IQ" + +''' +Wir nutzen "Duck typing", dh wir schreiben hinter jede Variabel mit ':' die Klasse, zB `leftMotor: Motor` +damit man dann später auch wieder Code Completion hat bei Nutzung der Variablen +''' +class IQRobot: + + def __init__(self, hub: PrimeHub, leftMotorPort: str, rightMotorPort: str, colorSensorPort: str): + self.hub: PrimeHub = hub + self.leftMotor: Motor = Motor(leftMotorPort) + self.rightMotor: Motor = Motor(rightMotorPort) + self.movementMotors: MotorPair = MotorPair(leftMotorPort, rightMotorPort) + self.colorSensor: ColorSensor = ColorSensor(colorSensorPort) + + + def show(self, image: str): + ''' + Zeige Bild auf LED Matrix des Spikes + image: Bildname wie zB 'HAPPY' + ''' + self.hub.light_matrix.show_image(image) + + + def driveForward(self, seconds: float): + # Fahre die übergebene Anzahl seconds gerade aus + self.movementMotors.start() + wait_for_seconds(seconds) + self.movementMotors.stop() + + def getColorIntensity(self): + # Ermittele Farbintensität über den Farbsensor + (red, green, blue, colorIntensity) = self.colorSensor.get_rgb_intensity() + return colorIntensity + + + + + +print("successfully loaded the Backsteinclub code :)") + + diff --git a/main.py b/main.py new file mode 100644 index 0000000..9fa64d0 --- /dev/null +++ b/main.py @@ -0,0 +1,93 @@ +# LEGO type:standard slot:5 autostart + +import os, sys + +from spike import PrimeHub, LightMatrix, Button, StatusLight, ForceSensor, MotionSensor, Speaker, ColorSensor, App, DistanceSensor, Motor, MotorPair +from spike.control import wait_for_seconds, wait_until, Timer +from hub import battery +from math import * + +############## Allgemein: Prüfe Batteriezustand ############################### +if battery.voltage() < 8000: #set threshold for battery level + print("Spannung der Batterie zu niedrig: " + str(battery.voltage()) + " \n" + + "--------------------------------------- \n " + + "#### UNBEDINGT ROBOTER AUFLADEN !!! #### \n" + + "---------------------------------------- \n") +else: + print("Spannung der Batterie " + str(battery.voltage()) + "\n") +################################################################################ + +############################## NICHT ÄNDERN ############################### +def importFile(slotid=0, precompiled=False, module_name='importFile'): + print("##### START # IMPORTING CODE FROM SLOT "+str(slotid)+" ##############") + import os, sys + suffix = ".py" + if precompiled: + suffix = ".mpy" + with open("/projects/.slots","rt") as f: + slots = eval(str(f.read())) + print(slots) + print(os.listdir("/projects/"+str(slots[slotid]["id"]))) + with open("/projects/"+str(slots[slotid]["id"])+"/__init__"+suffix,"rb") as f: + print("trying to read import program") + program = f.read() + print(program) + try: + os.remove("/"+module_name+suffix) + except: + pass + with open("/"+module_name+suffix,"w+") as f: + print("trying to write import program") + f.write(program) + if (module_name in sys.modules): + del sys.modules[module_name] + #exec("from " + module_name + " import *") + print("##### END # IMPORTING CODE FROM SLOT "+str(slotid)+" ##############") +##################################################################################### + + +################ Importiere Code aus andere Dateien ################################# + +# Importiere Code aus der Datei "iqrobot.py" +# Dateiname und Modulname sollten gleich sein, dann kann man Code Completion nutzen +importFile(slotid=6, precompiled=True, module_name="iqrobot") +import iqrobot as iq +print(iq.HELLO) + +# Importiere Go Robot Code +#importFile(slotid=3, precompiled=True, module_name="gorobot") +#import gorobot as gr +#gr.exampleFour() +#gr.db.gyroRotation(90, 25, 35, 25) + + +################### Hauptcode #################################### +''' +Code zum Lösen einer Aufgabe, kann oben importierten Code nutzen +Es können auch pro Aufgabe eigene Funktionen geschrieben werden +Wichtig ist, dass die PORTS der Sensoren überall gleich sind +und auch `hub` als Instanz von PrimeHub +dh auch an die Funktionen im importierten Code übergeben werde +''' + +# Definiere an welchen Ports die Sensoren angeschlossen sind +COLOR_SENSOR_PORT = 'E' +LEFT_MOTOR_PORT = 'A' +RIGHT_MOTOR_PORT = 'B' + +# Initialisieren des Hubs, der Aktoren und Sensoren +hub = PrimeHub() + +# Initialisiere Robot Klasse mit unseren Funktionen +iqRobot: iq.IQRobot = iq.IQRobot(hub, LEFT_MOTOR_PORT, RIGHT_MOTOR_PORT, COLOR_SENSOR_PORT) + +# Führe Funktionen aus unser Robot Klasse aus: +iqRobot.show('HAPPY') +iqRobot.driveForward(2.0) +colorIntensity = iqRobot.getColorIntensity() +print("Farbintensität: " + str(colorIntensity)) + + + + + diff --git a/spike/__init__.py b/spike/__init__.py new file mode 100644 index 0000000..8c0922e --- /dev/null +++ b/spike/__init__.py @@ -0,0 +1,1839 @@ +""" +SPIKE Prime Python Classes +""" +class App: + def __init__(self): + pass + def play_sound(self, name, volume=100): + """ + Plays a sound from the device (tablet or computer). + + The program will not continue until the sound has finished playing. + + If no sound is found with the given name is found, nothing will happen. + + Parameters + ------------- + name : The name of the sound to play. + + Type : string (text) + + Values : Alert, Applause1, Applause2, Applause3, Baa, Bang1, Bang2, BasketballBounce, BigBoing, Bird, Bite, BoatHorn1, BoatHorn2, Bonk, BoomCloud, BoopBingBop, BowlingStrike, Burp1, Burp2, Burp3, CarAccelerate1, CarAccelerating2, CarHorn, CarIdle, CarReverse, CarSkid1, CarSkid2, CarVroom, CatAngry, CatHappy, CatHiss, CatMeow1, CatMeow2, CatMeow3, CatPurring, CatWhining, Chatter, Chirp, Clang, ClockTicking, ClownHonk1, ClownHonk2, ClownHonk3, Coin, Collect, Connect, Crank, CrazyLaugh, Croak, CrowdGasp, Crunch, Cuckoo, CymbalCrash, Disconnect, DogBark1, DogBark2, DogBark3, DogWhining1, DogWhining2, Doorbell1, Doorbell2, Doorbell3, DoorClosing, DoorCreek1, DoorCreek2, DoorHandle, DoorKnock, DoorSlam1, DoorSlam2, DrumRoll, DunDunDunnn, EmotionalPiano, Fart1, Fart2, Fart3, Footsteps, Gallop, GlassBreaking, Glug, GoalCheer, Gong, Growl, Grunt, HammerHit, HeadShake, HighWhoosh, Jump, JungleFrogs, Laser1, Laser2, Laser3, LaughingBaby1, LaughingBaby2, LaughingBoy, LaughingCrowd1, LaughingCrowd2, LaughingGirl, LaughingMale, Lose, LowBoing, LowSqueak, LowWhoosh, MagicSpell, MaleJump1, MaleJump2, Moo, OceanWave, Oops, OrchestraTuning, PartyBlower, Pew, PingPongHit, PlaneFlyingBy, PlaneMotorRunning, PlaneStarting, Pluck, PoliceSiren1, PoliceSiren2, PoliceSiren3, Punch, Rain, Ricochet, Rimshot, RingTone, Rip, Robot1, Robot2, Robot3, RocketExplosionRumble, Rooster, ScramblingFeet, Screech, Seagulls, ServiceAnnouncement, SewingMachine, ShipBell, SirenWhistle, Skid, SlideWhistle1, SlideWhistle2, SneakerSqueak, Snoring, Snort, SpaceAmbience, SpaceFlyby, SpaceNoise, Splash, SportWhistle1, SportWhistle2, SqueakyToy, SquishPop, SuctionCup, Tada, TelephoneRing2, TelephoneRing, Teleport2, Teleport3, Teleport, TennisHit, ThunderStorm, TolietFlush, ToyHonk, ToyZing, Traffic, TrainBreaks, TrainHorn1, TrainHorn2, TrainHorn3, TrainOnTracks, TrainSignal1, TrainSignal2, TrainStart, TrainWhistle, Triumph, TropicalBirds, Wand, WaterDrop, WhistleThump, Whiz1, Whiz2, WindowBreaks, Win, Wobble, WoodTap, Zip + + Default : no default value + + volume : The volume at which the sound will be played. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % + + Default : 100% + + Errors + ------------ + TypeError : name is not a string or volume is not an integer. + + RuntimeError : The SPIKE App has been disconnected from the Hub. + """ + pass + def start_sound(self, name, volume): + """ + Starts playing a sound from your device (tablet or computer). + The program will not wait for the sound to finish playing before proceeding to the next command. + If no sound with the given name is found, nothing will happen. + + Parameters + ------------- + name : The name of the sound to play. + + Type : string (text) + + Values : Alert, Applause1, Applause2, Applause3, Baa, Bang1, Bang2, BasketballBounce, BigBoing, Bird, Bite, BoatHorn1, BoatHorn2, Bonk, BoomCloud, BoopBingBop, BowlingStrike, Burp1, Burp2, Burp3, CarAccelerate1, CarAccelerating2, CarHorn, CarIdle, CarReverse, CarSkid1, CarSkid2, CarVroom, CatAngry, CatHappy, CatHiss, CatMeow1, CatMeow2, CatMeow3, CatPurring, CatWhining, Chatter, Chirp, Clang, ClockTicking, ClownHonk1, ClownHonk2, ClownHonk3, Coin, Collect, Connect, Crank, CrazyLaugh, Croak, CrowdGasp, Crunch, Cuckoo, CymbalCrash, Disconnect, DogBark1, DogBark2, DogBark3, DogWhining1, DogWhining2, Doorbell1, Doorbell2, Doorbell3, DoorClosing, DoorCreek1, DoorCreek2, DoorHandle, DoorKnock, DoorSlam1, DoorSlam2, DrumRoll, DunDunDunnn, EmotionalPiano, Fart1, Fart2, Fart3, Footsteps, Gallop, GlassBreaking, Glug, GoalCheer, Gong, Growl, Grunt, HammerHit, HeadShake, HighWhoosh, Jump, JungleFrogs, Laser1, Laser2, Laser3, LaughingBaby1, LaughingBaby2, LaughingBoy, LaughingCrowd1, LaughingCrowd2, LaughingGirl, LaughingMale, Lose, LowBoing, LowSqueak, LowWhoosh, MagicSpell, MaleJump1, MaleJump2, Moo, OceanWave, Oops, OrchestraTuning, PartyBlower, Pew, PingPongHit, PlaingFlyingBy, PlaneMotorRunning, PlaneStarting, Pluck, PoliceSiren1, PoliceSiren2, PoliceSiren3, Punch, Rain, Ricochet, Rimshot, RingTone, Rip, Robot1, Robot2, Robot3, RocketExplosionRumble, Rooster, ScramblingFeet, Screech, Seagulls, ServiceAnnouncement, SewingMachine, ShipBell, SirenWhistle, Skid, SlideWhistle1, SlideWhistle2, SneakerSqueak, Snoring, Snort, SpaceAmbience, SpaceFlyby, SpaceNoise, Splash, SportWhistle1, SportWhistle2, SqueakyToy, SquishPop, SuctionCup, Tada, TelephoneRing2, TelephoneRing, Teleport2, Teleport3, Teleport, TennisHit, ThunderStorm, TolietFlush, ToyHonk, ToyZing, Traffic, TrainBreaks, TrainHorn1, TrainHorn2, TrainHorn3, TrainOnTracks, TrainSignal1, TrainSignal2, TrainStart, TrainWhistle, Triumph, TropicalBirds, Wand, WaterDrop, WhistleThump, Whiz1, Whiz2, WindowBreaks, Win, Wobble, WoodTap, Zip + + Default : no default value + + volume : The volume at which the sound will be played. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % + + Default : 100% + + Errors + ------------ + TypeError : name is not a string or volume is not an integer. + + RuntimeError : The SPIKE App has been disconnected from the Hub. + """ + pass + +class DistanceSensor: + def __init__(self, port): + """ + Allows access to the connected distance sensor. + Parameters + ------------- + port : The port label the sensor is connected to + + Type : string (text) + + Values : 'A', 'B', 'C', 'D', and 'E' + + Default : no default value + """ + pass + def light_up_all(self, brightness=100): + """ + Lights up all of the lights on the Distance Sensor with the specified brightness. + + Parameters + --------- + brightness : The specified brightness of all the lights. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % (0 is off and 100 is full brightness.) + + Default : 100 % + + Errors + ---------- + TypeError : brightness is not an integer. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def light_up(self, right_top=100, left_top=100, right_bottom=100, left_bottom=100): + """ + Sets the brightness of the individual lights on the Distance Sensor. + + Parameters + ------------- + right_top : The brightness of the light above the right part of the Distance Sensor. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% (0 is off and 100 is full brightness.) + + Default : 100 + + left_top : The brightness of the light above the left part of the Distance Sensor. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% (0 is off and 100 is full brightness.) + + Default : 100 + + right_bottom : The brightness of the light below the right part of the Distance Sensor. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% (0 is off and 100 is full brightness.) + + Default : 100 + + left_bottom : The brightness of the light below the left part of the Distance Sensor. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% (0 is off and 100 is full brightness.) + + Default : 100 + + Errors + --------------- + TypeError : right_top, left_top, right_bottom or left_bottom is not a number. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_distance_cm(self, short_range=False) -> float: + """ + Retrieves the measured distance in centimeters. + + Parameters + ---------- + short_range : Whether to use or not the short range mode. The short range mode increases accuracy but it can only detect nearby objects. + + Type : boolean + + Values : True or False + + Default : False + + Returns + ---------------- + The measured distance, or "none" if the distance cannot be measured. + + Type : float (decimal number) + + Values : 0 to 200 cm + + Errors + ------------ + TypeError : short_range is not a boolean. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_distance_inches(self, short_range=False) -> float: + """ + Gets the measured distance in inches. + + Parameters + ---------- + short_range : Whether or not to use short range mode. Short range mode increases accuracy but it can only detect nearby objects. + + Type : boolean + + Values : True or False + + Default : False + + Returns + ------------------ + The measured distance, or "none" if the distance cannot be measured. + + Type : float (decimal number) + + Values : any value between 0 and 79 + + Errors + ------------- + TypeError : short_range is not a boolean. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + + def get_distance_percentage(self, short_range=False) -> int: + """ + Retrieves the measured distance in percent. + + Parameters + --------- + short_range : Whether or not to use short range mode. Short range mode increases accuracy but it can only detect nearby objects. + + Type : boolean + + Values : True or False + + Default : False + + Returns + ---------- + The measured distance, or "none" if the distance cannot be measured. + + Type : integer (positive or negative whole number, including 0) + + Values : any value between 0 and 100 + + Errors + ---------- + TypeError : short_range is not a boolean. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def wait_for_distance_farther_than(self, distance, unit='cm', short_range=False): + """ + Waits until the measured distance is greater than distance. + + Parameters + ----------- + distance : The target distance to detect, from the sensor to an object. + + Type : float (decimal number) + + Values : any value + + Default : no default value + + unit : Unit of measurement of the distance. + + Type : string (text) + + Values : 'cm','in','%' + + Default : cm + + short_range : Whether or not to use short range mode. Short range mode increases accuracy but it can only detect nearby objects. + + Type : boolean + + Values : True or False + + Default : False + + Errors + ---------- + TypeError : distance is not a number or unit is not a string or short_range is not a boolean. + + ValueError : unit is not one of the allowed values. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def wait_for_distance_closer_than(self, distance, unit='cm', short_range=False): + """ + Waits until the measured distance is less than distance. + + Parameters + -------------- + distance : The target distance to detect, from the sensor to an object. + + Type : float (decimal number) + + Values : any value + + Default : no default value + + unit : Unit of measurement of the distance. + + Type : string (text) + + Values : 'cm','in','%' + + Default : cm + + short_range : Whether or not to use short range mode. Short range mode increases accuracy but it can only detect nearby objects. + + Type : boolean + + Values : True or False + + Default : False + + Errors + ------------ + TypeError : distance is not a number or unit is not a string or short_range is not a boolean. + + ValueError : unit is not one of the allowed values. short_range is not a boolean. + + RuntimeError: The sensor has been disconnected from the Port. + """ + pass + +class ForceSensor: + def __init__(self, port): + """ + Allows access to the connected force sensor. + Parameters + ------------- + port : The port label the sensor is connected to + + Type : string (text) + + Values : 'A', 'B', 'C', 'D', and 'E' + + Default : no default value + """ + pass + def is_pressed(self) -> bool: + """ + Tests whether the button on the sensor is pressed. + + Returns + ---------- + True if the button is pressed. + + Type : boolean + + Values : True or False + + Errors + ----------- + RuntimeError : The Force Sensor has been disconnected from the port. + """ + pass + def get_force_newton(self) -> float: + """ + Retrieves the measured force, in newtons. + + Returns + ----------- + The measured force in newtons. + + Type : float (decimal number) + + Values : between 0 and 10 + + Errors + ------------ + RuntimeError : The Force Sensor has been disconnected from the port. + """ + pass + def get_force_percentage(self) -> int: + """ + Retrieves the measured force as a percentage of the maximum force. + + Returns + ------------ + The measured force, in percentage. + + Type : integer (positive or negative whole number, including 0) + + Values : between 0 - 100%. + + Errors + ----------- + RuntimeError : The Force Sensor has been disconnected from the port. + """ + pass + def wait_until_pressed(self): + """ + Waits until the Force Sensor is pressed. + Errors + ---------- + RuntimeError : The sensor has been disconnected from the port. + """ + pass + def wait_until_released(self): + """ + Waits until the Force Sensor is released. + Errors + --------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + +class LightMatrix: + def __init__(self): + """ + Controls the light matrix on the Spike Hub + """ + pass + def show_image(self, image, brightness=100): + """ + Shows an image on the Light Matrix. + + Parameters + ----------- + image : Name of the image. + + Type : string (text) + + Values : ANGRY, ARROW_E, ARROW_N, ARROW_NE, ARROW_NW, ARROW_S, ARROW_SE, ARROW_SW, ARROW_W, ASLEEP, BUTTERFLY, CHESSBOARD, CLOCK1, CLOCK10, CLOCK11, CLOCK12, CLOCK2, CLOCK3, CLOCK4, CLOCK5, CLOCK6, CLOCK7, CLOCK8, CLOCK9, CONFUSED, COW, DIAMOND, DIAMOND_SMALL, DUCK, FABULOUS, GHOST, GIRAFFE, GO_RIGHT, GO_LEFT, GO_IP, GO_DOWN, HAPPY, HEART, HEART_SMALL, HOUSE, MEH, MUSIC_CROTCHET, MUSIC_QUAVER, MUSIC_QUAVERS, NO, PACMAN, PITCHFORK, RABBIT, ROLLERSKATE, SAD, SILLY, SKULL, SMILE, SNAKE, SQUARE, SQUARE_SMALL, STICKFIGURE, SURPRISED, SWORD, TARGET, TORTOISE, TRIANGLE, TRIANGLE_LEFT, TSHIRT, UMBRELLA, XMAS, YES + + Default : no default value + + brightness : Brightness of the image + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% + + Default : 100 + + Errors + ------------------- + TypeError : image is not a string or brightness is not an integer. + + ValueError : image is not one of the allowed values. + """ + pass + def set_pixel(self, x, y, brightness=100): + """ + Sets the brightness of one pixel (one of the 25 LED) on the Light Matrix. + + Parameters + ----------- + x : Pixel position, counting from the left. + + Type : integer (positive or negative whole number, including 0) + + Values : 1 to 5 + + Default : no default value + + y : Pixel position, counting from the top. + + Type : integer (positive or negative whole number, including 0) + + Values : 1 to 5 + + Default : no default value + + brightness : Brightness of the pixel + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% + + Default : 100 + + Errors + -------------- + TypeError : x, y or brightness is not an integer. + + ValueError : x, y is not within the allowed range of 0-4. + """ + pass + def write(self, text): + """ + Writes text on the Light Matrix, one letter at a time, scrolling from right to left. + Your program will not continue until all of the letters have been shown. + + Parameters + --------- + text : Text to write. + + Type : string (text) + + Values : any text + + Default : no default value + """ + pass + def off(self): + """ + Turns off all the pixels on the Light Matrix. + """ + pass + + +class MotionSensor: + def __init__(self): + """ + Senses angle and motion changes and it built into the Hub. + """ + pass + def reset_yaw_angle(self): + """ + Sets the yaw angle to 0. + """ + pass + def get_yaw_angle(self) -> int: + """ + Retrieves the yaw angle of the Hub. + + "Yaw" is the rotation around the front-back (vertical) axis. "Pitch" the is rotation around the left-right (transverse) axis. "Roll" the is rotation around the front-back (longitudinal) axis. + + Returns + ------- + The yaw angle, specified in degrees. + + Type : Integer (Positive or negative whole number, including 0) + + Values : -180 to 180 BUG: in 1.2 the values are -179 to 179 + """ + pass + def get_orientation(self) -> str: + """ + Retrieves the current orientation of the Hub. + Returns + ------- + The Hub's current orientation. + + Type : string (text) + + Values : 'front','back','up','down','leftside','rightside' + """ + pass + def get_gesture(self) -> str: + """ + Retrieves the most recently-detected gesture. + Returns + --------- + The gesture. + + Type : string (text) + + Values : 'shaken','tapped','doubletapped','falling' + """ + pass + def get_roll_angle(self) -> int: + """ + Retrieves the roll angle of the Hub. + "Roll" is the rotation around the front-back (longitudinal) axis. "Yaw" is the rotation around the front-back (vertical) axis. "Pitch" is the rotation around the left-right (transverse) axis. + Returns + ----------- + The roll angle, specified in degrees. + + Type : Integer (Positive or negative whole number, including 0) + + Values : -180 to 180 BUG: currently returns -179 to 179 + """ + pass + def get_pitch_angle(self) -> int: + """ + Retrieves the pitch angle of the Hub. + "Pitch" is the rotation around the left-right (transverse) axis. "Roll" is the rotation around the front-back (longitudinal) axis. "Yaw" is the rotation around the front-back (vertical) axis. + Returns + ----------- + The pitch angle, specified in degrees. + Type : Integer (Positive or negative whole number, including 0) + Values : -180 to 180 BUG: only reads -90 to 90 + """ + pass + def was_gesture(self, gesture) -> bool: + """ + Tests whether a gesture has occurred since the last time was_gesture() was used or since the beginning of the program (for the first use). + Parameters + ------------ + gesture : The name of the gesture. + + Type : string (text) + + Values : 'shaken','tapped','doubletapped','falling','None' + + Default : no default value + + Errors + ------------ + TypeError : gesture is not a string. + + ValueError : gesture is not one of the allowed values. + + Returns + ---------- + True if gesture has occurred since the last time was_gesture() was called, otherwise False. + + Type : boolean + + Values : True or False + """ + pass + def wait_for_new_gesture(self) -> str: + """ + Waits until a new gesture happens. + Returns + -------------- + The new gesture. + Type : string (text) + Values : 'shaken','tapped','doubletapped','falling' + """ + pass + def wait_for_new_orientation(self) -> str: + """ + Waits until the orientation of the Hub changes. + The first time this method is called, it will immediately return the current value. After that, calling this method will block the program until the Hub's orientation has changed since the previous time this method was called. + Returns + ---------- + The Hub's new orientation. + Type : string (text) + Values : 'front', 'back', 'up', 'down', 'left side', 'right side' + """ + pass + + +class Motor: + def __init__(self, port): + """ + Controls a single motor + Parameters + ------------- + port : The port label the motor is connected to. + + Type : string (text) + + Values : 'A', 'B', 'C', 'D', and 'E' + + Default : no default value + """ + pass + def run_to_position(self, degrees, direction='shortest path', speed=None): + """ + Runs the motor to an absolute position. + The sign of the speed will be ignored (absolute value) and the motor will always travel in the direction specified by direction parameter. If speed is greater than 100, it will be limited to 100. + + Parameters + ------------ + degrees : The target position. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 359 + + Default : no default value + + direction : The direction to use to reach the target position. + + Type : string (text) + + Values : shortest path' could run in either direction depending on the shortest distance to the target. - 'clockwise' will make the motor run clockwise until it reaches the target position. - 'counterclockwise' will make the motor run counterclockwise until it reaches the target position. + + Default : no default value + + speed : The motor's speed. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% + + Default : if no value is specified, it will use the default speed set by set_default_speed(). + + Errors + ----------------- + TypeError : degrees or speed is not an integer or direction is not a string. + + ValueError : direction is not one of the allowed values or degrees is not within the range of 0-359 (both inclusive). + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def run_to_degrees_counted(self, degrees, speed=None): + """ + Runs the motor to until degrees counted is equal to the value specified by the degrees parameter. + The sign of the speed will be ignored and the motor will always travel in the direction required to reach degrees. If speed is greater than 100, it will be limited to 100. + + Parameters + ----------- + degrees : The target degrees counted. + + Type : integer (positive or negative whole number, including 0) + + Values : any number + + Default : no default value + + speed : The desired speed.. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% (positive values only) + + Default : if no value is specified, it will use the default speed set by set_default_speed(). + + Errors + ----------- + TypeError : degrees or speed is not an integer. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def run_for_degrees(self, degrees, speed=None): + """ + Runs the motor for a given number of degrees. + + Parameters + ------------- + degrees : The number of degrees the motor should run. + + Type : integer (positive or negative whole number, including 0) + + Values : any number + + Default : no default value + + speed : The motor's speed + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100% + + Default : if no value is specified, it will use the default speed set by set_default_speed(). + + Errors + ---------- + TypeError : degrees or speed is not an integer. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def run_for_rotations(self, rotations, speed=None): + """ + Runs the motor for a specified number of rotations. + + Parameters + ------------- + rotations : The number of rotations the motor should run. + + Type : float (decimal number) + + Values : any number + + Default : no default value + + speed : The motor's speed + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100% + + Default : if no value is specified, it will use the default speed set by set_default_speed(). + + Errors + ------------- + TypeError : rotations is not a number or speed is not an integer. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def run_for_seconds(self, seconds, speed=None): + """ + Runs the motor for a specified number of seconds. + + Parameters + ----------- + seconds : The number of seconds for which the motor should run. + + Type : float (decimal number) + + Values : any number + + Default : no default value + + speed : The motor's speed. + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100% + + Default : if no value is specified, it will use the default speed set by set_default_speed(). + + Errors + ---------- + TypeError : seconds is not a number or speed is not an integer. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def start(self, speed=None): + """ + Starts running the motor at a specified speed. + The motor will keep moving at this speed until you give it another motor command, or when your program ends. + + Parameters + ---------- + speed : The motor's speed. + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100% + + Default : if no value is specified, it will use the default speed set by set_default_speed(). + + Errors + -------- + TypeError : speed is not an integer. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def stop(self): + """ + Stops the motor. What the motor does after it stops depends on the action set in set_stop_action(). The default value of set_stop_action() is coast. + + Errors + ---------- + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def start_at_power(self, power): + """ + Starts rotating the motor at a specified power level. + The motor will keep moving at this power level until you give it another motor command, or when your program ends. + + Parameters + --------- + power : Power of the motor. + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100% + + Default : no default value + + Errors + --------- + TypeError : power is not an integer. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def get_speed(self) -> int: + """ + Retrieves the speed of the motor. + + Returns + ---------- + The current speed of the motor + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100% + + Errors + ------------ + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def get_position(self) -> int: + """ + Retrieves the position of the motor. This is the clockwise angle between the moving marker and the zero-point marker on the motor. + + Returns + ---------- + The position of the motor + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 359 degrees + + Errors + ------------ + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def get_degrees_counted(self) -> int: + """ + Retrieves the degrees counted by the motor. + + Returns + ----------- + The number of degrees counted. + + Type : integer (positive or negative whole number, including 0) + + Values : any number + + Errors + ---------- + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def get_default_speed(self) -> int: + """ + Retrieves the current default motor speed. + + Returns + --------- + The default motor's speed. + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100%. + + Errors + ---------- + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def was_interrupted(self) -> bool: + """ + Tests whether the motor was interrupted. + + Returns + ----------- + True if the motor was interrupted since the last time was_interrupted() was called, otherwise False. + + Type : boolean + + Values : True or False + + Errors + ----------- + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def was_stalled(self) -> bool: + """ + Tests whether the motor was stalled. + + Returns + ----------- + True if the motor was stalled since the last time was_stalled() was called, otherwise False. + + Type : boolean + + Values : True or False + + Errors + ----------- + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def set_degrees_counted(self, degrees_counted): + """ + Sets the number of degrees counted to a desired value. + + Parameters + ---------- + degrees_counted : The value to which the number of degrees counted should be set. + + Type : integer (positive or negative whole number, including 0) + + Values : any number + + Default : no default value + + Errors + ---------- + TypeError : degrees_counted is not an integer. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def set_default_speed(self, default_speed): + """ + Sets the default motor speed. This speed will be used when you omit the speed argument in one of the other methods, such as run_for_degrees. + Setting the default speed does not affect any motors that are currently running. + It will only have an effect when another motor method is called after this method. + If the value of default_speed is outside of the allowed range, the default speed will be set to -100 or 100 depending on whether the value was negative or positive. + + Parameters + ----------- + default_speed : The default speed value. + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100%. + + Default : no default value + + Errors + ------------ + TypeError : default_speed is not an integer. + """ + pass + + def set_stop_action(self, action): + """ + Sets the default behavior when a motor stops. + + Parameters + ------------- + action : The desired motor behavior when the motor stops. + + Type : string (text) + + Values : 'coast','brake','hold' + + Default : coast + + Errors + ------------ + TypeError : action is not a string. + + ValueError : action is not one of the allowed values. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + def set_stall_detection(self, stop_when_stalled): + """ + Turns stall detection on or off. + Stall detection senses when a motor has been blocked and can't move. If stall detection has been enabled and a motor is blocked, the motor will be powered off after two seconds and the current motor command will be interrupted. If stall detection has been disabled, the motor will keep trying to run and programs will "get stuck" until the motor is no longer blocked. + Stall detection is enabled by default. + + Parameters + ----------- + stop_when_stalled : Choose True to enable stall detection or False to disable it. + + Type : boolean + + Values : True or False + + Default : True + + Errors + ----------- + TypeError : stop_when_stalled is not a boolean. + + RuntimeError : The motor has been disconnected from the Port. + """ + pass + +class MotorPair: + def __init__(self, port1, port2): + """ + Binds two motors together to use as a pair. + Parameters + ---------- + port1 : Port of the first motor + + Type : string (text) + + Values : 'A', 'B', 'C', 'D', and 'E' + + Default : no default value + + port2 : Port of the second motor + + Type : string (text) + + Values : 'A', 'B', 'C', 'D', and 'E' + + Default : no default value + """ + pass + + def move(self, amount, unit='cm', steering=0, speed=None): + """ + Start the 2 motors simultaneously to move a Driving Base. + steering=0 makes the Driving Base go straight. Negative numbers make the Driving Base turn left. Positive numbers make the Driving Base turn right. + The program will not continue until amount is reached. + If the value of steering is equal to -100 or 100, the Driving Base will perform a rotation on itself (tank move) with the default speed on each motor. + If the value of steering is outside of the allowed range, the value will be set to -100 or 100 depending whether the value is positive or negative. + If speed is outside of the allowed range, the value will be set to -100 or 100 depending whether the value is positive or negative. + If the speed is negative, then the Driving Base will move backward instead of forward. Likewise, if amount is negative, the Driving Base will move backward instead of forward. If both the speed and the amount are negative, then the Driving Base will move forward. + When unit is 'cm' or 'in', the amount of the unit parameter is the horizontal distance that the Driving Base will travel before stopping. The relationship between motor rotations and distance traveled can be adjusted by calling set_motor_rotation(). + When 'unit' is 'rotations' or 'degrees', the amount parameter value specifies how much the motor axle will turn before stopping. + When unit is 'seconds', the amount parameter value specifies the amount of time the motors will run before stopping. + + Parameters + ------------- + amount : The quantity to move in relation to the specified unit of measurement. + + Type : float (decimal numbers) + + Values : any value + + Default : no default value + + unit : The units of measurement of the amount parameter + + Type : string (text) + + Values : 'cm','in','rotations','degrees','seconds' + + Default : cm + + steering : The direction and the quantity to steer the Driving Base. + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : 0 + + speed : The motor speed. + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : the speed set by set_default_speed() + + Errors + -------------- + TypeError : amount is not a number, or steering or speed is not an integer, or unit is not a string. + + ValueError : unit is not one of the allowed values. + + RuntimeError : One or both of the motors has been disconnected or the motors could not be paired. + """ + pass + def start(self, steering=0, speed=None): + """ + Start the 2 motors simultaneously, to will move a Driving Base. + steering=0 makes the Driving Base go straight. Negative numbers make the Driving Base turn left. Positive numbers make the Driving Base turn right. + The program flow is not interrupted. This is most likely interrupted by a sensor input and a condition. + If the value of steering is equal to -100 or 100, the Driving Base will perform a rotation on itself (tank move) with the default speed on each motor. + If the value of steering is outside of the allowed range, the value will be set to -100 or 100 depending on whether the value is positive or negative. + If speed is outside of the allowed range, the value will be set to -100 or 100 depending whether the value is positive or negative. + If the speed is negative, then the Driving Base will move backward instead of forward. Likewise, if amount is negative, the Driving Base will move backward instead of forward. If both the speed and the amount are negative, then the Driving Base will move forward. + + Parameters + ------------ + steering : The direction and the quantity to steer the Driving Base. + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : 0 + + speed : The speed at which the Driving Base will move while performing a curve. + + Type : integer (positive or negative whole number, including 0) + + Values : -100% to 100% + + Default : if no value is specified, it will use the default speed set by set_default_speed(). + + Errors + ----------- + TypeError : Steering or speed is not an integer. + + RuntimeError : One or both of the motors has been disconnected or the motors could not be paired. + """ + pass + def stop(self): + """ + Stops the 2 motors simultaneously, which will stop a Driving Base. + The motors will either actively hold their current position or coast freely depending on the option selected by set_stop_action(). + Errors + -------------- + RuntimeError : One or both of the motors has been disconnected or the motors could not be paired. + """ + pass + def move_tank(self, amount, unit='cm', left_speed=None, right_speed=None): + """ + Moves the Driving Base using differential (tank) steering. + The speed of each motor can be controlled independently for differential (tank) drive Driving Bases. + When unit is 'cm' or 'in', the amount of the unit parameter is the horizontal distance that the Driving Base will travel before stopping. The relationship between motor rotations and distance traveled can be adjusted by calling set_motor_rotation(). + When 'unit' is 'rotations' or 'degrees', the amount parameter value specifies how much the motor axle will turn before stopping. + When unit is 'seconds', the amount parameter value specifies the amount of time the motors will run before stopping. + If left_speed or right_speed is outside of the allowed range, the value will be set to -100 or 100 depending whether the value is positive or negative. + If one of the speed is negative (left_speed or right_speed), then the motor with that negative speed will run backward instead of forward. If the value of the amount parameter is negative, both motors will rotate backward instead of forward. If both the speed values (left_speed or right_speed) are negative and the value of the amount parameter is negative, then the both motors will rotate forward. + The program will not continue until amount is reached. + + Parameters + ----------------- + amount : The quantity to move in relation to the specified unit of measurement. + + Type : float (decimal number) + + Values : any value + + Default : no default value + + unit : The units of measurement of the amount parameter + + Type : string (text) + + Values : 'cm','in','rotations','degrees','seconds' + + Default : cm + + left_speed : The speed of the left motor + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : the speed set by set_default_speed() + + right_speed : The speed of the right motor + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : the speed set by set_default_speed() + + Errors + -------------- + TypeError : amount, left_speed or right_speed is not a number or unit is not a string. + + ValueError : unit is not one of the allowed values. + + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + def start_tank(self, left_speed, right_speed): + """ + Starts moving the Driving Base using differential (tank) steering. + The speed of each motor can be controlled independently for differential (tank) drive Driving Bases. + If left_speed or right_speed is outside of the allowed range, the value will be set to -100 or 100 depending whether the value is positive or negative. + If a speed is negative, then the motors will move backward instead of forward. + The program flow is not interrupted. This is most likely interrupted by a sensor input and a condition. + + Parameters + ---------- + left_speed : The speed of the left motor. + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : no default value + + right_speed : The speed of the right motor. + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : no default value + + Errors + ------- + TypeError : left_speed or right_speed is not an integer. + + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + + def start_at_power(self, power, steering=0): + """ + Starts moving the Driving Base without speed control. + The motors can also be driven without speed control. This is useful when using your own control algorithm (e.g., a proportional line follower). + If steering is outside of the allowed range, the value will be set to -100 or 100 depending whether the value is positive or negative. + If power is outside of the allowed range, the value will be set to -100 or 100 depending whether the value is positive or negative. + If the power is negative, then Driving Base will move backward instead of forward. + The program flow is not interrupted. This can most likely interrupted by a sensor input and a condition. + + Parameters + -------------- + power : The amount of power to send to the motors. + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 % + + Default : 100 + + steering : The steering direction (-100 to 100). 0 makes the Driving Base go straight. Negative numbers make the Driving Base turn left. Positive numbers make the Driving Base turn right. + + Type : Integer + + Values : -100 to 100 + + Default : 0 + + Errors + ---------- + TypeError : steering or power is not an integer. + + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + def start_tank_at_power(self, left_power, right_power): + """ + Starts moving the Driving Base using differential (tank) steering without speed control. + The motors can also be driven without speed control. This is useful when using your own control algorithm (e.g., a proportional line follower). + If left_power or right_power is outside of the allowed range, the value will be rounded to -100 or 100 depending on whether the value is positive or negative. + If a power is negative, then the corresponding motor will move backward instead of forward. + The program flow is not interrupted. This can most likely interrupted by a sensor input and a condition. + + Parameters + =========== + left_power : The power of the left motor + + Type : Integer + + Values : -100 to 100 + + Default : no default value + + right_power : The power of the right motor + + Type : Integer + + Values : -100 to 100 + + Default : no default value + + Errors + ------------ + TypeError : left_power or right_power is not an integer. + + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + def get_default_speed(self) -> int: + """ + Retrieves the default motor speed. + + Returns + ----------- + The default motor speed. + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 % + + Errors + ------------ + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + def set_motor_rotation(self, amount, unit='cm'): + """ + Sets the ratio of one motor rotation to the distance traveled. + If there are no gears used between the motors and the wheels of the Driving Base, then amount is the circumference of one wheel. + Calling this method does not affect the Driving Base if it is already currently running. It will only have an effect the next time one of the move or start methods is used. + + Parameters + ----------- + amount : The distance the Driving Base moves when both motors move one rotation each. + + Type : float (decimal number) + + Values : any value + + Default : 17.6cm (large wheel) + + unit : The units of measurement of the amount parameter. + + Type : string (text) + + Values : 'cm','in' + + Default : cm + + Errors + ------------ + TypeError : amount is not a number or unit is not a string. + + ValueError : unit is not one of the allowed values. + + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + def set_default_speed(self, speed): + """ + Sets the default motor speed. + If speed is outside of the allowed range, the value will be set to -100 or 100 depending on whether the value is positive or negative. + Setting the speed will not have any effect until one of the move or start methods is called, even if the Driving Base is already moving. + + Parameters + -------- + speed : The default motor speed + + Type : integer (positive or negative whole number, including 0) + + Values : -100 to 100 + + Default : 100 + + Errors + ---------- + TypeError : speed is not a number. + + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + def set_stop_action(self, action): + """ + Sets the motor action that will be used when the Driving Base stops. + If action is 'brake' the motors will stop quickly but will be allowed to turn freely. + If action is 'hold', the motors will actively hold their current position and cannot be turned manually. + If action is set to 'coast', the motors will stop slowly and will be able to be turned freely. + Setting the stop action does not take immediate effect on the motors. The setting will be saved and used whenever stop() is called or when one of the move methods has completed without being interrupted. + + Parameters + ----------- + action : The desired action of the motors when the Driving Base stops. + + Type : string (text) + + Values : 'brake','hold','coast' + + Default : 'coast' + + Errors + ----------- + TypeError : action is not a string. + + ValueError : action is not one of the allowed values. + + RuntimeError : One or both of the Ports do not have a motor connected or the motors could not be paired. + """ + pass + +class Speaker: + def __init__(self): + """ + Controls this SpikeHub speaker + """ + pass + + def beep(self, note=60, seconds=0.2): + """ + Plays a beep on the Hub. + Your program will not continue until seconds have passed. + Parameters + --------- + note : The MIDI note number. + + Type : float (decimal number) + + Values : 44 to 123 (60 is middle C note) + + Default : 60 (middle C note) + + seconds : The duration of the beep in seconds. + + Type : float (decimal number) + + Values : any values + + Default : 0.2 seconds + + Errors + --------- + TypeError : note is not an integer or seconds is not a number. + + ValueError : note is not within the allowed range of 44-123. + """ + pass + def start_beep(self, note=60): + """ + Starts playing a beep. + The beep will play indefinitely until stop() or another beep method is called. + + Parameters + ----------- + note : The MIDI note number. + + Type : float (decimal number) + + Values : 44 to 123 (60 is middle C note) + + Default : 60 (middle C note) + + Errors + ------------ + TypeError : note is not an integer. + + ValueError : note is not within the allowed range of 44-123 + """ + pass + def stop(self): + """ + Stops any sound that is playing. + """ + pass + def get_volume(self) -> int: + """ + Retrieves the value of the speaker volume. + This only retrieves the volume for the Hub and not the programming app. + + Returns + -------------- + The current volume. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% + """ + pass + def set_volume(self, volume): + """ + Sets the speaker volume. + If the assigned volume is out of range, the nearest volume (0 or 100) will be used instead. This only sets the volume for the Hub and not the programming app. + + Parameters + ----------- + volume : The new volume percentage. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100% + + Default : 100% + + Errors + ------------ + TypeError : volume is not an integer. + """ + pass + +class StatusLight: + def __init__(self): + """ + Controls the Status light on the PrimeHub + """ + pass + def on(self, color='white'): + """ + Sets the color of the light. + + Parameters + -------- + color : Illuminates the Brick Status Light on the Hub in the specified color + + Type : string (text) + + Values : azure,black,'blue','cyan','green','orange','pink','red','violet','yellow','white' + + Default : 'white' + + Errors + ------- + TypeError : color is not a string. + + ValueError : color is not one of the allowed values. + """ + pass + def off(self): + """ + Turns the status light off + """ + pass + +class Button: + def __init__(self, location): + """ + Accesses the PrimeHub buttons + """ + pass + def wait_until_pressed(self): + """ + Waits until the button is pressed. + """ + pass + def wait_until_released(self): + """ + Waits until the button is released. + """ + pass + def was_pressed(self) -> bool: + """ + Tests to see whether the button has been pressed since the last time this method called. + Once this method returns True, the button must be released and pressed again before this method will return True again. + Returns + ------------- + If the button was pressed, otherwise + Type : boolean + Values : True or False + """ + pass + def is_pressed(self) -> bool: + """ + Tests whether the button is pressed. + Returns + ---------- + True if the button is pressed, otherwise False + + Type : boolean + + Values : True or False + """ + pass + +class ColorSensor: + def __init__(self, port): + """ + Controls the color sensor. + Parameters + ------------- + port : The port label the sensor is connected to. + + Type : string (text) + + Values : 'A', 'B', 'C', 'D', and 'E' + + Default : no default value + """ + pass + def get_color(self) -> str: + """ + Retrieves the detected color of a surface. + + Returns + ----------- + Name of the color. + + Type : string (text) + + Values : 'black','violet','blue','cyan','green','yellow','red','white',None + + Errors + ----------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_ambient_light(self) -> int: + """ + Retrieves the intensity of the ambient light. + This causes the Color Sensor to change modes, which can affect your program in unexpected ways. For example, when the Color Sensor is in ambient light mode, it cannot read colors. + + Returns + ------------- + The ambient light intensity. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % + + Errors + -------------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_reflected_light(self) -> int: + """ + Retrieves the intensity of the reflected light. + + Returns + --------- + The reflected light intensity. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % + + Errors + ------------ + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_rgb_intensity(self) -> tuple: + """ + Retrieves the red, green, blue, and overall color intensity. + + Returns + ---------- + Type : tuple of int + + Values : Red, green, blue, and overall intensity (0-1024) + + Errors + ----------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_red(self) -> int: + """ + Retrieves the red color intensity. + + Returns + -------- + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 1024 + + Errors + ---------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_green(self) -> int: + """ + Retrieves the green color intensity. + + Returns + ----------- + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 1024 + + Errors + ----------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def get_blue(self) -> int: + """ + Retrieves the blue color intensity. + + Returns + ----------- + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 1024 + + Errors + ----------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def wait_until_color(self, color): + """ + Waits until the Color Sensor detects the specified color. + + Parameters + ----------- + color : The name of the color + + Type : string (text) + + Values : 'black','violet','blue','cyan','green','yellow','red','white',None + + Default : no default value + + Errors + ------------ + TypeError : color is not a string or None. + + ValueError : color is not one of the allowed values. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def wait_for_new_color(self): + """ + Waits until the Color Sensor detects a new color. + The first time this method is called, it returns immediately the detected color. After that, it waits until the Color Sensor detects a color that is different from the color that was detected the last time this method was used. + + Returns + ----------- + The name of the new color + + Type : string (text) + + Values : 'black','violet','blue','cyan','green','yellow','red','white',None + + Errors + ---------- + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def light_up_all(self, brightness=100): + """ + Lights up all of the lights on the Color Sensor with a specified brightness. + This causes the Color Sensor to change modes, which can affect your program in unexpected ways. For example, when the Color Sensor is in light up mode, it cannot read colors. + + Parameters + --------- + brightness : The desired brightness of the lights on the Color Sensor. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % (0 is off and 100 is full brightness.) + + Default : 100 % + + Errors + ---------- + TypeError : brightness is not an integer. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + def light_up(self, light_1=100, light_2=100, light_3=100): + """ + Sets the brightness of the individual lights on the Color Sensor. + This causes the Color Sensor to change modes, which can affect your program in unexpected ways. For example, when the Color Sensor is in light up mode, it cannot read colors. + + Parameters + ------------- + light_1 : The desired brightness of light 1. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % (0 is off and 100 is full brightness.) + + Default : 100 % + + light_2 : The desired brightness of light 2. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % (0 is off and 100 is full brightness.) + + Default : 100 % + + light_3 : The desired brightness of light 3. + + Type : integer (positive or negative whole number, including 0) + + Values : 0 to 100 % (0 is off and 100 is full brightness.) + + Default : 100 % + + Errors + -------- + TypeError : light_1, light_2, or light_3 is not an integer. + + RuntimeError : The sensor has been disconnected from the Port. + """ + pass + +class PrimeHub: + speaker = Speaker() + motion_sensor = MotionSensor() + left_button = Button("left") + right_button = Button("right") + light_matrix = LightMatrix() + status_light = StatusLight() + PORT_A = 'A' + PORT_B = 'B' + PORT_C = 'C' + PORT_D = 'D' + PORT_E = 'E' + PORT_F = 'F' + + def __init__(self): + """ + The PrimeHub is divided into six components, each with a number of functions linked to it. To be able to use the Hub, you must initialize it. + """ + pass \ No newline at end of file diff --git a/spike/control.py b/spike/control.py new file mode 100644 index 0000000..6d98e86 --- /dev/null +++ b/spike/control.py @@ -0,0 +1,103 @@ +def wait_for_seconds(seconds): + """ + Waits for a specified number of seconds before continuing the program. + + Parameters + -------------- + seconds : The time to wait in seconds. + + Type : float (decimal value) + + Values : any value + + Default : no default value + + Errors + ---------------- + TypeError : seconds is not a number. + + ValueError : seconds is not at least 0. + """ + pass + +def wait_until(get_value_function, operator_function, target_value=True): + """ + Waits until the condition is True before continuing with the program. + + Parameters + -------------- + get_value_function + + Type : callable function + + Values : A function that returns the current value to be compared to the target value. + + Default : no default value + + operator_function + + Type : callable function + + Values : A function that compares two arguments. The first argument will be the result of get_value_function() and the second argument will be target_value. The function will compare these two values and return the result. + + Default : no default value + + target_value + + Type : any type + + Values : Any object that can be compared by operator_function. + + Default : no default value + + Errors + ---------------- + TypeError : get_value_function or operator_function is not callable or operator_function does not compare two arguments. + """ + pass + +def greater_than(a, b): + """ + Tests whether value a is greater than value b. + This is the same as a > b. + + Parameters + --------- + a : Any object that can be compared to b. + + Type : any type + + Values : any value + + Default : no default value + + b : Any object that can be compared to a. + + Type : any type + + Values : any value + + Default : no default value + + Returns + --------- + Type : boolean + + Values : True if a > b, otherwise False. + """ + pass + +class Timer: + def __init__(self): + pass + + def reset(self): + """ + Sets the Timer to "0." + """ + pass + def now(self): + """ + Retrieves the "right now" time of the Timer + """ + pass diff --git a/vscode-lego-extension-precompile.png b/vscode-lego-extension-precompile.png new file mode 100644 index 0000000..feedd35 Binary files /dev/null and b/vscode-lego-extension-precompile.png differ diff --git a/vscode-lego-extension-settings.png b/vscode-lego-extension-settings.png new file mode 100644 index 0000000..a280ca6 Binary files /dev/null and b/vscode-lego-extension-settings.png differ