Skip to content

Commit e3f8479

Browse files
committed
Added external_samples/spark_mini.py that wraps the wpilib.SparkMini class.
Changed component class names to be consistent with the external_samples python files. Updated generated json files. Added function addInstanceComponentBlocks to mrc_call_python_function.ts to generate component function blocks. Updated function getBlocks in blocks_components.ts to use addInstanceComponentBlocks.
1 parent 1357155 commit e3f8479

File tree

15 files changed

+786
-425
lines changed

15 files changed

+786
-425
lines changed

external_samples/spark_mini.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""This is the spark_mini module.
16+
17+
This component wraps the RobotPy SparkMini, providing support for the REV
18+
Robotics SPARKMini Motor Controller with PWM control.
19+
"""
20+
21+
__author__ = "[email protected] (Liz Looney)"
22+
23+
from component import Component, PortType, InvalidPortException
24+
import wpilib
25+
import wpimath
26+
import wpiutil
27+
28+
class SparkMiniComponent(Component):
29+
def __init__(self, ports : list[tuple[PortType, int]]):
30+
portType, port = ports[0]
31+
if portType != PortType.SMART_MOTOR_PORT:
32+
raise InvalidPortException
33+
self.spark_mini = wpilib.SparkMini(port)
34+
35+
# Component methods
36+
37+
def get_manufacturer(self) -> str:
38+
return "REV Robotics"
39+
40+
def get_name(self) -> str:
41+
return "SPARKMini Motor Controller"
42+
43+
def get_part_number(self) -> str:
44+
return "REV-31-1230"
45+
46+
def get_url(self) -> str:
47+
return "https://www.revrobotics.com/rev-31-1230"
48+
49+
def get_version(self) -> tuple[int, int, int]:
50+
return (1, 0, 0)
51+
52+
def stop(self) -> None:
53+
# send stop command to motor
54+
pass
55+
56+
def reset(self) -> None:
57+
pass
58+
59+
def get_connection_port_type(self) -> list[PortType]:
60+
return [PortType.SMART_MOTOR_PORT]
61+
62+
def periodic(self) -> None:
63+
pass
64+
65+
# Component specific methods
66+
67+
# Methods from wpilib.PWMMotorController
68+
69+
def add_follower(self, follower: wpilib.PWMMotorController) -> None:
70+
'''Make the given PWM motor controller follow the output of this one.\n\n:param follower: The motor controller follower.'''
71+
self.spark_mini.addFollower(follower)
72+
73+
def disable(self) -> None:
74+
self.spark_mini.disable()
75+
76+
def enable_deadband_elimination(self, eliminateDeadband: bool) -> None:
77+
'''Optionally eliminate the deadband from a motor controller.\n\n:param eliminateDeadband: If true, set the motor curve on the motor\n controller to eliminate the deadband in the middle\n of the range. Otherwise, keep the full range\n without modifying any values.'''
78+
self.spark_mini.enableDeadbandElimination(eliminateDeadband)
79+
80+
def get(self) -> float:
81+
'''Get the recently set value of the PWM. This value is affected by the\ninversion property. If you want the value that is sent directly to the\nMotorController, use PWM::GetSpeed() instead.\n\n:returns: The most recently set value for the PWM between -1.0 and 1.0.'''
82+
return self.spark_mini.get()
83+
84+
def get_channel(self) -> int:
85+
return self.spark_mini.getChannel()
86+
87+
def get_description(self) -> str:
88+
return self.spark_mini.getDescription()
89+
90+
def get_inverted(self) -> bool:
91+
return self.spark_mini.getInverted()
92+
93+
def get_voltage(self) -> wpimath.units.volts:
94+
'''Gets the voltage output of the motor controller, nominally between -12 V\nand 12 V.\n\n:returns: The voltage of the motor controller, nominally between -12 V and 12\n V.'''
95+
return self.spark_mini.getVoltage()
96+
97+
def set(self, value: float) -> None:
98+
'''Set the PWM value.\n\nThe PWM value is set using a range of -1.0 to 1.0, appropriately scaling\nthe value for the FPGA.\n\n:param value: The speed value between -1.0 and 1.0 to set.'''
99+
self.spark_mini.set(value)
100+
101+
def set_inverted(self, isInverted: bool) -> None:
102+
self.spark_mini.setInverted(isInverted)
103+
104+
def set_voltage(self, output: wpimath.units.volts) -> None:
105+
'''Sets the voltage output of the PWMMotorController. Compensates for\nthe current bus voltage to ensure that the desired voltage is output even\nif the battery voltage is below 12V - highly useful when the voltage\noutputs are "meaningful" (e.g. they come from a feedforward calculation).\n\nNOTE: This function *must* be called regularly in order for voltage\ncompensation to work properly - unlike the ordinary set function, it is not\n"set it and forget it."\n\n:param output: The voltage to output.'''
106+
self.spark_mini.setVoltage(output)
107+
108+
def stop_motor(self) -> None:
109+
self.spark_mini.stopMotor()
110+
111+
# Methods from wpilib.MotorSafety
112+
113+
def check(self) -> None:
114+
'''Check if this motor has exceeded its timeout.\n\nThis method is called periodically to determine if this motor has exceeded\nits timeout value. If it has, the stop method is called, and the motor is\nshut down until its value is updated again.'''
115+
self.spark_mini.check(follower)
116+
117+
# TODO(lizlooney): Decide whether we should expose checkMotors. It seems
118+
# like it isn't intended to be called by users.
119+
def check_motors() -> None:
120+
'''Check the motors to see if any have timed out.\n\nThis static method is called periodically to poll all the motors and stop\nany that have timed out.'''
121+
wpilib.SparkMini.checkMotors()
122+
123+
def feed(self) -> None:
124+
'''Feed the motor safety object.\n\nResets the timer on this object that is used to do the timeouts.'''
125+
self.spark_mini.feed()
126+
127+
def get_expiration(self) -> wpimath.units.seconds:
128+
'''Retrieve the timeout value for the corresponding motor safety object.\n\n:returns: the timeout value.'''
129+
return self.spark_mini.getExpiration()
130+
131+
def is_alive(self) -> bool:
132+
'''Determine if the motor is still operating or has timed out.\n\n:returns: true if the motor is still operating normally and hasn't timed out.'''
133+
return self.spark_mini.isAlive()
134+
135+
def is_safety_enabled(self) -> bool:
136+
'''Return the state of the motor safety enabled flag.\n\nReturn if the motor safety is currently enabled for this device.\n\n:returns: True if motor safety is enforced for this device.'''
137+
return self.spark_mini.isSafetyEnabled()
138+
139+
def set_expiration(self, expirationTime: wpimath.units.seconds) -> None:
140+
'''Set the expiration time for the corresponding motor safety object.\n\n:param expirationTime: The timeout value.'''
141+
self.spark_mini.setExpiration(expirationTime)
142+
143+
def set_safety_enabled(self, enabled: bool) -> None:
144+
'''Enable/disable motor safety for this device.\n\nTurn on and off the motor safety option for this PWM object.\n\n:param enabled: True if motor safety is enforced for this object.'''
145+
self.spark_mini.setSafetyEnabled(enabled)
146+
147+
# Methods from wpiutil.Sendable
148+
149+
def init_sendable(self, builder: wpiutil.SendableBuilder) -> None:
150+
'''Initializes this Sendable object.\n\n:param builder: sendable builder'''
151+
self.spark_mini.initSendable(builder)

external_samples/sparkfun_led_stick.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def get_manufacturer(self) -> str:
3030
return "SparkFun"
3131

3232
def get_name(self) -> str:
33-
return "SparkFun Qwiic LED Strip"
33+
return "SparkFun Qwiic LED Stick"
3434

3535
def get_part_number(self) -> str:
3636
return "COM-18354"

src/blocks/mrc_call_python_function.ts

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import { Order } from 'blockly/python';
2525

2626
import { ClassMethodDefExtraState } from './mrc_class_method_def'
2727
import { getAllowedTypesForSetCheck, getOutputCheck } from './utils/python';
28-
import { FunctionData } from './utils/python_json_types';
28+
import { FunctionData, findSuperFunctionData } from './utils/python_json_types';
2929
import * as value from './utils/value';
3030
import * as variable from './utils/variable';
3131
import { Editor } from '../editor/editor';
@@ -34,6 +34,8 @@ import { createFieldDropdown } from '../fields/FieldDropdown';
3434
import { createFieldNonEditableText } from '../fields/FieldNonEditableText';
3535
import { MRC_STYLE_FUNCTIONS } from '../themes/styles'
3636
import * as toolboxItems from '../toolbox/items';
37+
import { getClassData } from './utils/external_samples_data';
38+
import * as commonStorage from '../storage/common_storage';
3739

3840

3941
// A block to call a python function.
@@ -217,6 +219,68 @@ function createInstanceMethodBlock(
217219
return block;
218220
}
219221

222+
export function addInstanceComponentBlocks(
223+
componentType: string,
224+
componentName: string,
225+
contents: toolboxItems.ContentsType[]) {
226+
227+
const classData = getClassData(componentType);
228+
const functions = classData.instanceMethods;
229+
230+
const componentClassData = getClassData('component.Component');
231+
const componentFunctions = componentClassData.instanceMethods;
232+
233+
for (const functionData of functions) {
234+
// Skip the functions that are also defined in componentFunctions.
235+
if (findSuperFunctionData(functionData, componentFunctions)) {
236+
continue;
237+
}
238+
const block = createInstanceComponentBlock(componentName, functionData);
239+
contents.push(block);
240+
}
241+
}
242+
243+
function createInstanceComponentBlock(
244+
componentName: string, functionData: FunctionData): toolboxItems.Block {
245+
const extraState: CallPythonFunctionExtraState = {
246+
functionKind: FunctionKind.INSTANCE_COMPONENT,
247+
returnType: functionData.returnType,
248+
args: [],
249+
tooltip: functionData.tooltip,
250+
importModule: '',
251+
componentClassName: functionData.declaringClassName,
252+
componentName: componentName,
253+
};
254+
const fields: {[key: string]: any} = {};
255+
fields[FIELD_COMPONENT_NAME] = componentName;
256+
fields[FIELD_FUNCTION_NAME] = functionData.functionName;
257+
const inputs: {[key: string]: any} = {};
258+
// For INSTANCE_COMPONENT functions, the 0 argument is 'self', but
259+
// self is represented by the FIELD_COMPONENT_NAME field.
260+
// We don't include the arg or input for self.
261+
for (let i = 1; i < functionData.args.length; i++) {
262+
const argData = functionData.args[i];
263+
let argName = argData.name;
264+
extraState.args.push({
265+
'name': argName,
266+
'type': argData.type,
267+
});
268+
// Check if we should plug a variable getter block into the argument input socket.
269+
const input = value.valueForFunctionArgInput(argData.type, argData.defaultValue);
270+
if (input) {
271+
// Because we skipped the self argument, use i - 1 when filling the inputs array.
272+
inputs['ARG' + (i - 1)] = input;
273+
}
274+
}
275+
let block = new toolboxItems.Block(BLOCK_NAME, extraState, fields, Object.keys(inputs).length ? inputs : null);
276+
if (functionData.returnType && functionData.returnType != 'None') {
277+
const varName = variable.varNameForType(functionData.returnType);
278+
if (varName) {
279+
block = variable.createVariableSetterBlock(varName, block);
280+
}
281+
}
282+
return block;
283+
}
220284

221285
//..............................................................................
222286

@@ -612,7 +676,18 @@ export const pythonFromBlock = function(
612676
const functionName = callPythonFunctionBlock.mrcActualFunctionName
613677
? callPythonFunctionBlock.mrcActualFunctionName
614678
: block.getFieldValue(FIELD_FUNCTION_NAME);
615-
code = 'self.' + componentName + '.' + functionName;
679+
// Generate the correct code depending on the module type.
680+
switch (generator.getModuleType()) {
681+
case commonStorage.MODULE_TYPE_PROJECT:
682+
code = 'self.';
683+
break;
684+
case commonStorage.MODULE_TYPE_MECHANISM:
685+
case commonStorage.MODULE_TYPE_OPMODE:
686+
default:
687+
code = 'self.robot.';
688+
break;
689+
}
690+
code += componentName + '.' + functionName;
616691
break;
617692
}
618693
default:

src/blocks/utils/external_samples_data.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,16 @@
1919
* @author [email protected] (Liz Looney)
2020
*/
2121

22-
import { PythonData } from './python_json_types';
22+
import { PythonData, ClassData } from './python_json_types';
2323
import generatedExternalSamplesData from './generated/external_samples_data.json';
2424

2525
export const externalSamplesData = generatedExternalSamplesData as PythonData;
26+
27+
export function getClassData(className: string): ClassData | null {
28+
for (const classData of externalSamplesData.classes) {
29+
if (classData.className === className) {
30+
return classData;
31+
}
32+
}
33+
return null;
34+
}

0 commit comments

Comments
 (0)