diff --git a/build.gradle b/build.gradle index a6f9cbe868..d2ecfb9781 100644 --- a/build.gradle +++ b/build.gradle @@ -27,6 +27,12 @@ allprojects { subprojects { apply plugin: 'eclipse' apply plugin: 'idea' + apply plugin: 'checkstyle' + + checkstyle { + toolVersion = "6.18" + configFile = new File(rootDir, "styleguide/checkstyle.xml") + } ext.armBuild = true diff --git a/styleguide/checkstyle.xml b/styleguide/checkstyle.xml new file mode 100644 index 0000000000..66461b781f --- /dev/null +++ b/styleguide/checkstyle.xml @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/styleguide/intellij-java-google-style.xml b/styleguide/intellij-java-google-style.xml new file mode 100644 index 0000000000..fb1adddde0 --- /dev/null +++ b/styleguide/intellij-java-google-style.xml @@ -0,0 +1,475 @@ + + + + + diff --git a/styleguide/suppressions.xml b/styleguide/suppressions.xml new file mode 100644 index 0000000000..b969deece0 --- /dev/null +++ b/styleguide/suppressions.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/wpilibj/athena.gradle b/wpilibj/athena.gradle index 90a1d45c91..ed63278644 100644 --- a/wpilibj/athena.gradle +++ b/wpilibj/athena.gradle @@ -107,7 +107,7 @@ task wpilibjSources(type: Jar, dependsOn: classes) { } def ntSourcesDependency = - project.dependencies.create('edu.wpi.first.wpilib.networktables.java:NetworkTables:3.0.0-SNAPSHOT:sources@jar') + project.dependencies.create('edu.wpi.first.wpilib.networktables.java:NetworkTables:3.0.0-SNAPSHOT:sources@jar') def ntSourcesConfig = project.configurations.detachedConfiguration(ntSourcesDependency) ntSourcesDependency.setTransitive(false) def ntSources = ntSourcesConfig.singleFile diff --git a/wpilibj/build.gradle b/wpilibj/build.gradle index fa92da9aab..b899bd16cd 100644 --- a/wpilibj/build.gradle +++ b/wpilibj/build.gradle @@ -12,6 +12,6 @@ dependencies { apply from: 'athena.gradle' -if (project.hasProperty('makeSim')){ - apply from: 'simulation.gradle' +if (project.hasProperty('makeSim')) { + apply from: 'simulation.gradle' } diff --git a/wpilibj/src/athena/cpp/nivision/gen_java.py b/wpilibj/src/athena/cpp/nivision/gen_java.py index 151dc4e61c..f598ae3b6e 100644 --- a/wpilibj/src/athena/cpp/nivision/gen_java.py +++ b/wpilibj/src/athena/cpp/nivision/gen_java.py @@ -1,8 +1,9 @@ from __future__ import print_function + import codecs -import sys import os -import re +import sys + try: import configparser except ImportError: @@ -12,31 +13,33 @@ from nivision_parse import * # base, cast-out-pre, cast-out-post, cast-in-pre, cast-in-post java_accessor_map = { - "B": ("", "", "", "", ""), - "C": ("Char", "", "", "", ""), - "S": ("Short", "", "", "", ""), - "I": ("Int", "", "", "", ""), - "J": ("Long", "", "", "", ""), - "F": ("Float", "", "", "", ""), - "D": ("Double", "", "", "", ""), - "Z": ("Boolean", "", "", "", ""), - "X": ("", "(short)(", " & 0xff)", "(byte)(", " & 0xff)"), - "Y": ("Short", "(int)(", " & 0xffff)", "(short)(", " & 0xffff)"), - } + "B": ("", "", "", "", ""), + "C": ("Char", "", "", "", ""), + "S": ("Short", "", "", "", ""), + "I": ("Int", "", "", "", ""), + "J": ("Long", "", "", "", ""), + "F": ("Float", "", "", "", ""), + "D": ("Double", "", "", "", ""), + "Z": ("Boolean", "", "", "", ""), + "X": ("", "(short)(", " & 0xff)", "(byte)(", " & 0xff)"), + "Y": ("Short", "(int)(", " & 0xffff)", "(short)(", " & 0xffff)"), +} java_size_map = { - "B": 1, - "C": 2, - "S": 2, - "I": 4, - "J": 8, - "F": 4, - "D": 8, - "Z": 1, - } + "B": 1, + "C": 2, + "S": 2, + "I": 4, + "J": 8, + "F": 4, + "D": 8, + "Z": 1, +} + class JavaType: - def __init__(self, j_type, jn_type, jni_type, jni_sig, is_enum=False, is_struct=False, is_opaque=False, string_array=False, array_size=None): + def __init__(self, j_type, jn_type, jni_type, jni_sig, is_enum=False, is_struct=False, + is_opaque=False, string_array=False, array_size=None): self.j_type = j_type self.jn_type = jn_type self.jni_type = jni_type @@ -56,52 +59,57 @@ class JavaType: def __repr__(self): return "JavaType(%s, %s, %s, %s, is_enum=%s, is_struct=%s, is_opaque=%s, string_array=%s, array_size=%s)" % ( - self.j_type, self.jn_type, self.jni_type, self.jni_sig, - self.is_enum, self.is_struct, - self.is_opaque, self.string_array, self.array_size) + self.j_type, self.jn_type, self.jni_type, self.jni_sig, + self.is_enum, self.is_struct, + self.is_opaque, self.string_array, self.array_size) + java_types_map = { - ("void", None): JavaType("void", "void", "void", None), - ("env", None): JavaType("", "", "JNIEnv*", None), - ("cls", None): JavaType("", "", "jclass", None), - ("int", None): JavaType("int", "int", "jint", "I"), - ("char", None): JavaType("byte", "byte", "jbyte", "B"), - ("wchar_t", None): JavaType("char", "char", "jchar", "C"), - ("unsigned char", None): JavaType("short", "short", "jshort", "X"), - ("short", None): JavaType("short", "short", "jshort", "S"), - ("unsigned short", None): JavaType("int", "int", "jint", "Y"), - ("unsigned", None): JavaType("int", "int", "jint", "I"), - ("unsigned int", None): JavaType("int", "int", "jint", "I"), - ("uInt32", None): JavaType("int", "int", "jint", "I"), - ("IMAQdxSession", None): JavaType("int", "int", "jint", "I"), - ("bool32", None): JavaType("int", "int", "jint", "I"), - ("long", None): JavaType("long", "long", "jlong", "J"), - ("unsigned long", None): JavaType("long", "long", "jlong", "J"), - ("__int64", None): JavaType("long", "long", "jlong", "J"), - ("long long", None): JavaType("long", "long", "jlong", "J"), - ("unsigned __int64", None): JavaType("long", "long", "jlong", "J"), - ("__uint64", None): JavaType("long", "long", "jlong", "J"), - ("unsigned long long", None): JavaType("long", "long", "jlong", "J"), - ("float", None): JavaType("float", "float", "jfloat", "F"), - ("double", None): JavaType("double", "double", "jdouble", "D"), - ("long double", None): JavaType("double", "double", "jdouble", "D"), - ("unsigned char*", None): JavaType("String", "String", "jstring", "Ljava/lang/String;"), - ("char*", None): JavaType("String", "String", "jstring", "Ljava/lang/String;"), - ("void*", None): JavaType("RawData", "long", "jlong", "J", is_opaque=True), - #("size_t", None): JavaType("long", "long", "jlong", "J"), - ("String255", None): JavaType("String", "String", "jstring", "Ljava/lang/String;", string_array=True, array_size="256"), - ("String255", ""): JavaType("String[]", "String[]", "jstringArray", "[Ljava/lang/String;", string_array=True, array_size="256"), - ("char*", ""): JavaType("String[]", "String[]", "jstringArray", "[Ljava/lang/String;"), - ("char", ""): JavaType("String", "String", "jstring", "Ljava/lang/String;", string_array=True, array_size=""), - ("unsigned char", ""): JavaType("byte[]", "byte[]", "jbyteArray", "[B"), - ("short", ""): JavaType("short[]", "short[]", "jshortArray", "[S"), - ("int", ""): JavaType("int[]", "int[]", "jintArray", "[I"), - ("unsigned int", ""): JavaType("int[]", "int[]", "jintArray", "[I"), - ("uInt32", ""): JavaType("int[]", "int[]", "jintArray", "[I"), - ("long", ""): JavaType("long[]", "long[]", "jlongArray", "[J"), - ("float", ""): JavaType("float[]", "float[]", "jfloatArray", "[F"), - ("double", ""): JavaType("double[]", "double[]", "jdoubleArray", "[D"), - } + ("void", None): JavaType("void", "void", "void", None), + ("env", None): JavaType("", "", "JNIEnv*", None), + ("cls", None): JavaType("", "", "jclass", None), + ("int", None): JavaType("int", "int", "jint", "I"), + ("char", None): JavaType("byte", "byte", "jbyte", "B"), + ("wchar_t", None): JavaType("char", "char", "jchar", "C"), + ("unsigned char", None): JavaType("short", "short", "jshort", "X"), + ("short", None): JavaType("short", "short", "jshort", "S"), + ("unsigned short", None): JavaType("int", "int", "jint", "Y"), + ("unsigned", None): JavaType("int", "int", "jint", "I"), + ("unsigned int", None): JavaType("int", "int", "jint", "I"), + ("uInt32", None): JavaType("int", "int", "jint", "I"), + ("IMAQdxSession", None): JavaType("int", "int", "jint", "I"), + ("bool32", None): JavaType("int", "int", "jint", "I"), + ("long", None): JavaType("long", "long", "jlong", "J"), + ("unsigned long", None): JavaType("long", "long", "jlong", "J"), + ("__int64", None): JavaType("long", "long", "jlong", "J"), + ("long long", None): JavaType("long", "long", "jlong", "J"), + ("unsigned __int64", None): JavaType("long", "long", "jlong", "J"), + ("__uint64", None): JavaType("long", "long", "jlong", "J"), + ("unsigned long long", None): JavaType("long", "long", "jlong", "J"), + ("float", None): JavaType("float", "float", "jfloat", "F"), + ("double", None): JavaType("double", "double", "jdouble", "D"), + ("long double", None): JavaType("double", "double", "jdouble", "D"), + ("unsigned char*", None): JavaType("String", "String", "jstring", "Ljava/lang/String;"), + ("char*", None): JavaType("String", "String", "jstring", "Ljava/lang/String;"), + ("void*", None): JavaType("RawData", "long", "jlong", "J", is_opaque=True), + # ("size_t", None): JavaType("long", "long", "jlong", "J"), + ("String255", None): JavaType("String", "String", "jstring", "Ljava/lang/String;", + string_array=True, array_size="256"), + ("String255", ""): JavaType("String[]", "String[]", "jstringArray", "[Ljava/lang/String;", + string_array=True, array_size="256"), + ("char*", ""): JavaType("String[]", "String[]", "jstringArray", "[Ljava/lang/String;"), + ("char", ""): JavaType("String", "String", "jstring", "Ljava/lang/String;", string_array=True, + array_size=""), + ("unsigned char", ""): JavaType("byte[]", "byte[]", "jbyteArray", "[B"), + ("short", ""): JavaType("short[]", "short[]", "jshortArray", "[S"), + ("int", ""): JavaType("int[]", "int[]", "jintArray", "[I"), + ("unsigned int", ""): JavaType("int[]", "int[]", "jintArray", "[I"), + ("uInt32", ""): JavaType("int[]", "int[]", "jintArray", "[I"), + ("long", ""): JavaType("long[]", "long[]", "jlongArray", "[J"), + ("float", ""): JavaType("float[]", "float[]", "jfloatArray", "[F"), + ("double", ""): JavaType("double[]", "double[]", "jdoubleArray", "[D"), +} + def c_to_jtype(name, arr): jtype = java_types_map.get((name, arr), None) @@ -112,7 +120,7 @@ def c_to_jtype(name, arr): if arr is not None and arr != "": jtype = c_to_jtype(name, "").copy() jtype.array_size = arr - java_types_map[(name, arr)] = jtype # cache + java_types_map[(name, arr)] = jtype # cache return jtype # Opaque structures @@ -121,8 +129,8 @@ def c_to_jtype(name, arr): jtype = JavaType(name, "long", "jlong", "J", is_opaque=True) else: # FIXME - jtype = JavaType(name+"[]", "long[]", "jlongArray", "[J", is_opaque=True) - java_types_map[(name, arr)] = jtype # cache + jtype = JavaType(name + "[]", "long[]", "jlongArray", "[J", is_opaque=True) + java_types_map[(name, arr)] = jtype # cache return jtype # Enums @@ -131,8 +139,8 @@ def c_to_jtype(name, arr): jtype = JavaType(name, "int", "jint", "I", is_enum=True) else: # FIXME - jtype = JavaType(name+"[]", "int[]", "jintArray", "[I", is_enum=True) - java_types_map[(name, arr)] = jtype # cache + jtype = JavaType(name + "[]", "int[]", "jintArray", "[I", is_enum=True) + java_types_map[(name, arr)] = jtype # cache return jtype # handle pointers as void* (FIXME) @@ -146,10 +154,11 @@ def c_to_jtype(name, arr): jtype = JavaType(name, "long", "jlong", "J", is_struct=True) else: # FIXME - jtype = JavaType(name+"[]", "long[]", "jlongArray", "[J", is_struct=True) + jtype = JavaType(name + "[]", "long[]", "jlongArray", "[J", is_struct=True) java_types_map[(name, arr)] = jtype return jtype + class JavaEmitData: def __init__(self): self.construct = [] @@ -161,22 +170,23 @@ class JavaEmitData: self.toArg = "" def addConstruct(self, s): - self.construct.extend(s.split('\n')[1 if s[0]=='\n' else 0:]) + self.construct.extend(s.split('\n')[1 if s[0] == '\n' else 0:]) def addBackingRead(self, s): - self.backingRead.extend(s.split('\n')[1 if s[0]=='\n' else 0:]) + self.backingRead.extend(s.split('\n')[1 if s[0] == '\n' else 0:]) def addRead(self, s): - self.read.extend(s.split('\n')[1 if s[0]=='\n' else 0:]) + self.read.extend(s.split('\n')[1 if s[0] == '\n' else 0:]) def addWriteBuf(self, s): self.writeBufs.append(s) def addWrite(self, s): - self.write.extend(s.split('\n')[1 if s[0]=='\n' else 0:]) + self.write.extend(s.split('\n')[1 if s[0] == '\n' else 0:]) def addBackingWrite(self, s): - self.backingWrite.extend(s.split('\n')[1 if s[0]=='\n' else 0:]) + self.backingWrite.extend(s.split('\n')[1 if s[0] == '\n' else 0:]) + class JavaEmitArrayData(JavaEmitData): def __init__(self): @@ -185,6 +195,7 @@ class JavaEmitArrayData(JavaEmitData): self.addBackingRead("int {size_fname} = {backing}.get{jaccessor}({size_foffset});") self.addBackingWrite("{backing}.put{jaccessor}({size_foffset}, {fname}.length);") + # sized array of null-terminated strings strzArrayEmitSized = JavaEmitArrayData() strzArrayEmitSized.addBackingRead("long {fname}_addr = getPointer({backing}, {foffset});") @@ -435,8 +446,10 @@ structEmit.toArg = "{fname}.getAddress()" # java type jtypeEmit = JavaEmitData() -jtypeEmit.addBackingRead("{fname} = {jaccessor_cast_out_pre}{backing}.get{jaccessor}({foffset}){jaccessor_cast_out_post};") -jtypeEmit.addBackingWrite("{backing}.put{jaccessor}({foffset}, {jaccessor_cast_in_pre}{fname}{jaccessor_cast_in_post});") +jtypeEmit.addBackingRead( + "{fname} = {jaccessor_cast_out_pre}{backing}.get{jaccessor}({foffset}){jaccessor_cast_out_post};") +jtypeEmit.addBackingWrite( + "{backing}.put{jaccessor}({foffset}, {jaccessor_cast_in_pre}{fname}{jaccessor_cast_in_post});") # string - array of characters strSizedEmit = JavaEmitData() @@ -493,9 +506,11 @@ if ({fname} != null) {{ {fname}_buf = ByteBuffer.allocateDirect({fname}_bytes.length+1); putBytes({fname}_buf, {fname}_bytes, 0, {fname}_bytes.length).put({fname}_bytes.length, (byte)0); }}""") -strzEmit.addBackingWrite("putPointer({backing}, {foffset}, {fname} == null ? 0 : getByteBufferAddress({fname}_buf));") +strzEmit.addBackingWrite( + "putPointer({backing}, {foffset}, {fname} == null ? 0 : getByteBufferAddress({fname}_buf));") strzEmit.toArg = "{fname} == null ? 0 : getByteBufferAddress({fname}_buf)" + class JavaStructEmitHelper: def __init__(self, emit, name, fields, sized_members=None): self.emit = emit @@ -503,19 +518,21 @@ class JavaStructEmitHelper: self.fields = fields self.exclude_members = set(self.config_get("exclude_members", "").split(',')) - self.exclude_members |= set(x.split(':')[0] for x in self.config_get("uniontype", "").split(',')) + self.exclude_members |= set( + x.split(':')[0] for x in self.config_get("uniontype", "").split(',')) self.union_members = {} for v in self.config_get("uniontype", "").split(','): if not v: continue vl = v.split(':') - self.union_members[vl[0]] = (vl[1], [tuple(y.strip() for y in x.split('=')) for x in vl[2:]]) + self.union_members[vl[0]] = ( + vl[1], [tuple(y.strip() for y in x.split('=')) for x in vl[2:]]) if sized_members is not None: self.sized_members = sized_members else: self.sized_members = dict(tuple(y.strip() for y in x.split(':')) for x in - self.config_get("arraysize", "").split(',') if x) + self.config_get("arraysize", "").split(',') if x) self.size_members = dict((x, None) for x in self.sized_members.values()) # get type of each sized member @@ -532,7 +549,8 @@ class JavaStructEmitHelper: def config_struct_get(self, option): return self.emit.config_struct.get(self.name, option) - def get_field_java_code(self, fname, ftype, arr, foffset, jfielddefs_private, backing="backing"): + def get_field_java_code(self, fname, ftype, arr, foffset, jfielddefs_private, + backing="backing"): """Returns dict of fielddef, init, read, write, type """ if ftype.startswith("const"): @@ -546,9 +564,9 @@ class JavaStructEmitHelper: size_jtype = c_to_jtype(self.size_members[size_fname], None) size_foffset = self.config_struct_get(size_fname) else: - size_fname="" - size_jtype=None - size_foffset=None + size_fname = "" + size_jtype = None + size_foffset = None is_pointer = False if ftype[-1] == '*' and ftype[:-1] in opaque_structs: @@ -658,7 +676,7 @@ for (int i=0, off={foffset}; i<%s; i++, off += {struct_sz}) ftype=jtype.j_type, ftype_one=jtype.j_type[:-2], foffset=foffset, - size_fname=fname+"_"+size_fname, + size_fname=fname + "_" + size_fname, size_foffset=size_foffset, pointer_sz=self.emit.config_struct.get("_platform_", "pointer"), struct_sz=struct_sz, @@ -705,10 +723,10 @@ for (int i=0, off={foffset}; i<%s; i++, off += {struct_sz}) # standard struct fields for fname, ftype, arr, comment in self.fields: if fname in self.size_members or fname in self.exclude_members: - continue # don't emit + continue # don't emit if ":" in fname: - continue # TODO: bit field + continue # TODO: bit field foffset = self.config_struct_get(fname) field = self.get_field_java_code(fname, ftype, arr, foffset, jfielddefs_private) @@ -756,7 +774,8 @@ for (int i=0, off={foffset}; i<%s; i++, off += {struct_sz}) # find the rest of the info from the union fields ftype, arr, comment = ufieldmap[fname] - field = self.get_field_java_code(fname, ftype, arr, foffset, jfielddefs_union_private) + field = self.get_field_java_code(fname, ftype, arr, foffset, + jfielddefs_union_private) fielddef = field["fielddef"] read = field["backing_read"] @@ -832,15 +851,15 @@ for (int i=0, off={foffset}; i<%s; i++, off += {struct_sz}) return {size}; }} }}""" - return "".join([p1,p2,p3]).format( - name=self.name, - jfielddefs="\n ".join(jfielddefs), - jread="\n ".join(jread), - jwrite="\n ".join(jwrite), - jconstruct="\n ".join(jconstruct), - jcargs=", ".join(jcargs), - jcinit="\n ".join(jcinit), - size=self.config_struct_get("_SIZE_")) + return "".join([p1, p2, p3]).format( + name=self.name, + jfielddefs="\n ".join(jfielddefs), + jread="\n ".join(jread), + jwrite="\n ".join(jwrite), + jconstruct="\n ".join(jconstruct), + jcargs=", ".join(jcargs), + jcinit="\n ".join(jcinit), + size=self.config_struct_get("_SIZE_")) class JavaEmitter: @@ -1278,7 +1297,9 @@ static const char* getErrorText(int err) {{ {errs} default: return "Unknown error"; }} -}}""".format(errs="\n ".join('case %s: return "%s";' % (x, self.errors[x]) for x in sorted(self.errors))), file=self.outc) +}}""".format(errs="\n ".join( + 'case %s: return "%s";' % (x, self.errors[x]) for x in sorted(self.errors))), + file=self.outc) def config_get(self, section, option, fallback): try: @@ -1357,7 +1378,7 @@ static const char* getErrorText(int err) {{ name = name[5:] code = " public static final {type} {name} = {value};" \ - .format(type=type, name=name, value=clean) + .format(type=type, name=name, value=clean) if after_struct: define_after_struct.append((name, code)) return @@ -1428,7 +1449,9 @@ static const char* getErrorText(int err) {{ private {name}(int value) {{ this.value = value; }} - public static {name} fromValue(int val) {{""".format(name=name, values="\n ".join(valuestrs)), file=self.out) + public static {name} fromValue(int val) {{""".format(name=name, + values="\n ".join(valuestrs)), + file=self.out) if need_search: print(""" for ({name} v : values()) {{ if (v.value == val) @@ -1503,7 +1526,8 @@ static const char* getErrorText(int err) {{ dxEnumerateVideoModesResult rv = new dxEnumerateVideoModesResult(rv_buf, videoModeArray_buf); return rv; }} - private static native void _IMAQdxEnumerateVideoModes(int id, long videoModeArray, long count, long currentMode);""".format(struct_sz=self.config_struct.get("IMAQdxEnumItem", "_SIZE_")), file=self.out) + private static native void _IMAQdxEnumerateVideoModes(int id, long videoModeArray, long count, long currentMode);""".format( + struct_sz=self.config_struct.get("IMAQdxEnumItem", "_SIZE_")), file=self.out) print(""" JNIEXPORT void JNICALL Java_{package}_{classname}__1IMAQdxEnumerateVideoModes(JNIEnv* env, jclass , jint id, jlong videoModeArray, jlong count, jlong currentMode) {{ @@ -1519,7 +1543,8 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1IMAQdxEnumerateVideoModes(JN int buffer_size = buffer.capacity(); return _IMAQdxGetImageData(id, buffer_addr, buffer_size, mode.getValue(), desiredBufferNumber); }} - private static native int _IMAQdxGetImageData(int id, long buffer, int bufferSize, int mode, int desiredBufferNumber);""".format(), file=self.out) + private static native int _IMAQdxGetImageData(int id, long buffer, int bufferSize, int mode, int desiredBufferNumber);""".format(), + file=self.out) print(""" JNIEXPORT jint JNICALL Java_{package}_{classname}__1IMAQdxGetImageData(JNIEnv* env, jclass , jint id, jlong buffer, jint bufferSize, jint mode, jint desiredBufferNumber) {{ @@ -1543,7 +1568,8 @@ JNIEXPORT jint JNICALL Java_{package}_{classname}__1IMAQdxGetImageData(JNIEnv* e putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, (byte)0); _imaqReadFile(image.getAddress(), getByteBufferAddress(fileName_buf), 0, 0); }} - private static native void _imaqReadFile(long image, long fileName, long colorTable, long numColors);""".format(), file=self.out) + private static native void _imaqReadFile(long image, long fileName, long colorTable, long numColors);""".format(), + file=self.out) print(""" JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jclass , jlong image, jlong fileName, jlong colorTable, jlong numColors) {{ @@ -1592,16 +1618,19 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc rettype = c_to_jtype(restype, None) # TODO: defaults - #defaults = dict((y.strip() for y in x.split(':')) for x in + # defaults = dict((y.strip() for y in x.split(':')) for x in # self.config_get(name, "defaults", "").split(',') if x) sized_params = dict(tuple(y.strip() for y in x.split(':')) for x in - self.config_get(name, "arraysize", "").split(',') if x) + self.config_get(name, "arraysize", "").split(',') if x) size_params = set(sized_params.values()) - inparams = [x.strip() for x in self.config_get(name, "inparams", "").split(',') if x.strip()] - outparams = [x.strip() for x in self.config_get(name, "outparams", "").split(',') if x.strip()] - nullokparams = [x.strip() for x in self.config_get(name, "nullok", "").split(',') if x.strip()] + inparams = [x.strip() for x in self.config_get(name, "inparams", "").split(',') if + x.strip()] + outparams = [x.strip() for x in self.config_get(name, "outparams", "").split(',') if + x.strip()] + nullokparams = [x.strip() for x in self.config_get(name, "nullok", "").split(',') if + x.strip()] # guess additional output parameters for pname, ptype, arr in params: if (pname not in inparams @@ -1616,7 +1645,7 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc retarraysize = self.config_get(name, "retarraysize", "").strip() if retarraysize: size_params.add(retarraysize) - #rettype = c_to_jtype(restype, "") + # rettype = c_to_jtype(restype, "") if retarraysize not in outparams: outparams.append(retarraysize) @@ -1644,7 +1673,7 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc jfielddefs_private = [] for fname, ftype, arr, comment in helper.fields: - #print(fname, ftype, arr) + # print(fname, ftype, arr) is_outparam = (fname in outparams) is_nullok = (fname in nullokparams) and not is_outparam @@ -1653,7 +1682,8 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc ftype = ftype[:-1] elif arr is None: raise ValueError("outparam %s is not a pointer or array", fname) - field = helper.get_field_java_code(fname, ftype, arr, 0, jfielddefs_private, backing="%s_buf" % fname) + field = helper.get_field_java_code(fname, ftype, arr, 0, jfielddefs_private, + backing="%s_buf" % fname) paramtypes[fname] = (ftype, arr, field["type"]) if is_outparam: jn_funcargs.append((fname, jtype_ptr)) @@ -1685,7 +1715,9 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc if arr: raise NotImplementedError("sized array") else: - jinit.append("{size_jtype} {size_fname} = {fname}.length;".format(size_jtype=field["size_jtype"].j_type, size_fname=field["size_fname"], fname=fname)) + jinit.append("{size_jtype} {size_fname} = {fname}.length;".format( + size_jtype=field["size_jtype"].j_type, size_fname=field["size_fname"], + fname=fname)) jinit.extend("%s = null;" % x for x in write_bufs) jinit.extend(write) jn_passedargs[fname] = to_arg @@ -1703,9 +1735,13 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc jn_passedargs[fname] = fname elif jtype.jni_sig == "Ljava/lang/String;": if jtype.string_array: - jinit.append("ByteBuffer {fname}_buf = ByteBuffer.allocateDirect({array_size}).order(ByteOrder.nativeOrder());".format(fname=fname, array_size=256)) + jinit.append( + "ByteBuffer {fname}_buf = ByteBuffer.allocateDirect({array_size}).order(ByteOrder.nativeOrder());".format( + fname=fname, array_size=256)) jinit.extend(field["backing_write"]) - jn_passedargs[fname] = "{fname} == null ? 0 : getByteBufferAddress({fname}_buf)".format(fname=fname) + jn_passedargs[ + fname] = "{fname} == null ? 0 : getByteBufferAddress({fname}_buf)".format( + fname=fname) else: jinit.extend("%s = null;" % x for x in write_bufs) jinit.extend(write) @@ -1716,7 +1752,7 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc jrettype = rettype.j_type outstruct_name = None - #print(name, jrettype, outparams, retarraysize, retsize) + # print(name, jrettype, outparams, retarraysize, retsize) if outparams or retarraysize or retsize: # create a return structure outstruct_fields = [] @@ -1738,7 +1774,9 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc outstruct_name = name[4:] + "Result" # create a return buffer (TODO: optimize size) - jinit.append("ByteBuffer rv_buf = ByteBuffer.allocateDirect(%s).order(ByteOrder.nativeOrder());" % "+".join(outstruct_size)) + jinit.append( + "ByteBuffer rv_buf = ByteBuffer.allocateDirect(%s).order(ByteOrder.nativeOrder());" % "+".join( + outstruct_size)) jinit.append("long rv_addr = getByteBufferAddress(rv_buf);") jconstruct_args = [("rv_buf", "ByteBuffer")] @@ -1760,17 +1798,20 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc jfielddefs_private = [] off = 0 for fname, ftype, arr, comment in helper.fields: - field = helper.get_field_java_code(fname, ftype, arr, off, jfielddefs_private, backing="rv_buf") + field = helper.get_field_java_code(fname, ftype, arr, off, jfielddefs_private, + backing="rv_buf") if fname == retarraysize: - jconstruct.append(field["fielddef"].replace("public ", "").replace(fname, "array_%s" % fname)) - jconstruct.extend(x.replace(fname, "array_%s" % fname) for x in field["backing_read"]) + jconstruct.append( + field["fielddef"].replace("public ", "").replace(fname, "array_%s" % fname)) + jconstruct.extend( + x.replace(fname, "array_%s" % fname) for x in field["backing_read"]) jn_passedargs[fname] = "rv_addr+%d" % off off += 8 continue jfielddefs.append(field["fielddef"]) if fname == "array": - #jconstruct.extend(field["backing_read"]) + # jconstruct.extend(field["backing_read"]) jconstruct.extend(field["read"]) elif fname != "val": jn_passedargs[fname] = "rv_addr+%d" % off @@ -1788,24 +1829,29 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc jfini.extend(jconstruct) jretc = "return %s;" % outparams[0] jrettype = paramtypes[outparams[0]][2].j_type - #rettype = paramtypes[outparams[0]][2] + # rettype = paramtypes[outparams[0]][2] elif len(outparams) == 1 and retsize: jfini.extend(x.replace("public ", "") for x in jfielddefs) jfini.extend(jconstruct) - jfini.append("val = new {type}(jn_rv, {owned}, {size});".format(type=rettype.j_type, owned="true" if retowned else "false", size=retsize)) + jfini.append("val = new {type}(jn_rv, {owned}, {size});".format(type=rettype.j_type, + owned="true" if retowned else "false", + size=retsize)) jretc = "return val;" else: defined.add(outstruct_name) - jfini.append("{struct_name} rv = new {struct_name}({args});".format(struct_name=outstruct_name, args=", ".join(x[0] for x in jconstruct_args))) + jfini.append("{struct_name} rv = new {struct_name}({args});".format( + struct_name=outstruct_name, args=", ".join(x[0] for x in jconstruct_args))) if retsize: - jfini.append("rv.val = new {type}(jn_rv, {owned}, rv.{size});".format(type=rettype.j_type, owned="true" if retowned else "false", size=retsize)) + jfini.append("rv.val = new {type}(jn_rv, {owned}, rv.{size});".format( + type=rettype.j_type, owned="true" if retowned else "false", size=retsize)) elif not retarraysize and functype != "STDFUNC": - jfini.append("rv.val = new {type}(jn_rv, {owned});".format(type=rettype.j_type, owned="true" if retowned else "false")) + jfini.append("rv.val = new {type}(jn_rv, {owned});".format(type=rettype.j_type, + owned="true" if retowned else "false")) jrettype = outstruct_name if retarraysize: rettype = c_to_jtype(outstruct_name, None) - #else: + # else: # rettype = java_types_map[("void", None)] print(""" @@ -1814,9 +1860,9 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc private {struct_name}({jconstruct_args}) {{ {jconstruct} }}""".format(struct_name=outstruct_name, - jfielddefs="\n ".join(jfielddefs), - jconstruct_args=", ".join("%s %s" % (x[1], x[0]) for x in jconstruct_args), - jconstruct="\n ".join(jconstruct)), + jfielddefs="\n ".join(jfielddefs), + jconstruct_args=", ".join("%s %s" % (x[1], x[0]) for x in jconstruct_args), + jconstruct="\n ".join(jconstruct)), file=self.out) if retarraysize: print(""" @@ -1834,15 +1880,16 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc if rettype.is_enum: jretc = "return {type}.fromValue(jn_rv);".format(type=rettype.j_type) elif rettype.is_struct or rettype.is_opaque: - jretc = "return new {type}(jn_rv, {owned});".format(type=rettype.j_type, owned="true" if retowned else "false") + jretc = "return new {type}(jn_rv, {owned});".format(type=rettype.j_type, + owned="true" if retowned else "false") else: jretc = "return jn_rv;" # # Java function # - #assert name.startswith("imaq") - #name = name[4].lower() + name[5:] + # assert name.startswith("imaq") + # name = name[4].lower() + name[5:] print(""" public static {rettype} {name}({args}) {{ @@ -1855,17 +1902,19 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc init="\n ".join(jinit), fini="\n ".join(jfini), rv="%s jn_rv = " % rettype.jn_type if rettype.jn_type != "void" else "", - retcode="\n "+jretc if jretc else "", - passedargs=", ".join(jn_passedargs[x[0]] if x[0] in jn_passedargs else "UNKNOWN" for x in jn_funcargs)), - file=self.out) + retcode="\n " + jretc if jretc else "", + passedargs=", ".join( + jn_passedargs[x[0]] if x[0] in jn_passedargs else "UNKNOWN" for x in + jn_funcargs)), + file=self.out) # # Native Java function # print(""" private static native {rettype} _{name}({args});""".format( - rettype=rettype.jn_type, name=name, - args=", ".join("%s %s" % (x[1].jn_type, x[0]) for x in jn_funcargs)), - file=self.out) + rettype=rettype.jn_type, name=name, + args=", ".join("%s %s" % (x[1].jn_type, x[0]) for x in jn_funcargs)), + file=self.out) # # C function @@ -1897,8 +1946,8 @@ JNIEXPORT void JNICALL Java_{package}_{classname}__1imaqReadFile(JNIEnv* env, jc cargs.append("(%s)%s" % (ptype, pname)) callcfunc = "{restype} rv = {name}({args});".format(name=name, - restype=restype, - args=", ".join(cargs)) + restype=restype, + args=", ".join(cargs)) print(""" JNIEXPORT {rettype} JNICALL Java_{package}_{classname}__1{name}({args}) @@ -1930,6 +1979,7 @@ JNIEXPORT {rettype} JNICALL Java_{package}_{classname}__1{name}({args}) def union(self, name, fields): self.unions[name] = fields + def generate(srcdir, outdir, inputs): emit = None @@ -1940,7 +1990,7 @@ def generate(srcdir, outdir, inputs): config = configparser.ConfigParser() config.read(configpath) block_comment_exclude = set(x.strip() for x in - config.get("Block Comment", "exclude").splitlines()) + config.get("Block Comment", "exclude").splitlines()) library_funcs = set() with open(funcs_path) as ff: @@ -1965,17 +2015,18 @@ def generate(srcdir, outdir, inputs): emit.finish() + if __name__ == "__main__": - if len(sys.argv) < 5 or ((len(sys.argv)-1) % 4) != 0: + if len(sys.argv) < 5 or ((len(sys.argv) - 1) % 4) != 0: print("Usage: gen_wrap.py ...") exit(0) inputs = [] for i in range(1, len(sys.argv), 4): fname = sys.argv[i] - config_struct_name = sys.argv[i+1] - configname = sys.argv[i+2] - funcs_name = sys.argv[i+3] + config_struct_name = sys.argv[i + 1] + configname = sys.argv[i + 2] + funcs_name = sys.argv[i + 3] inputs.append((fname, config_struct_name, configname, funcs_name)) generate("", "", inputs) diff --git a/wpilibj/src/athena/cpp/nivision/gen_struct_sizer.py b/wpilibj/src/athena/cpp/nivision/gen_struct_sizer.py index 0e64fb3d8b..d449729f00 100644 --- a/wpilibj/src/athena/cpp/nivision/gen_struct_sizer.py +++ b/wpilibj/src/athena/cpp/nivision/gen_struct_sizer.py @@ -1,7 +1,8 @@ from __future__ import print_function -import sys + import os -import re +import sys + try: import configparser except ImportError: @@ -9,6 +10,7 @@ except ImportError: from nivision_parse import * + class StructSizerEmitter: def __init__(self, out, config, hname): self.out = out @@ -70,12 +72,15 @@ int main() return print('asm("#STRUCT_SIZER [{name}]\\n");'.format(name=name), file=self.out) - print('asm("#STRUCT_SIZER _SIZE_=%0\\n" : : "n"((int)sizeof({name})));'.format(name=name), file=self.out) + print('asm("#STRUCT_SIZER _SIZE_=%0\\n" : : "n"((int)sizeof({name})));'.format(name=name), + file=self.out) for fname, ftype, arr, comment in fields: if ':' in fname: - continue # can't handle bitfields - print('asm("#STRUCT_SIZER {field}=%0\\n" : : "n"((int)offsetof({name}, {field})));'.format(name=name, field=fname), file=self.out) + continue # can't handle bitfields + print( + 'asm("#STRUCT_SIZER {field}=%0\\n" : : "n"((int)offsetof({name}, {field})));'.format( + name=name, field=fname), file=self.out) def struct(self, name, fields): self.structunion("Structure", name, fields) @@ -83,12 +88,13 @@ int main() def union(self, name, fields): self.structunion("Union", name, fields) + def generate(srcdir, configpath=None, hpath=None): # read config file config = configparser.ConfigParser() config.read(configpath) block_comment_exclude = set(x.strip() for x in - config.get("Block Comment", "exclude").splitlines()) + config.get("Block Comment", "exclude").splitlines()) # open input file inf = open(hpath) @@ -103,6 +109,7 @@ def generate(srcdir, configpath=None, hpath=None): parse_file(emit, inf, block_comment_exclude) emit.finish() + if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: gen_struct_sizer.py ") diff --git a/wpilibj/src/athena/cpp/nivision/get_struct_size.py b/wpilibj/src/athena/cpp/nivision/get_struct_size.py index 004d9b08c0..3df06fc5a7 100644 --- a/wpilibj/src/athena/cpp/nivision/get_struct_size.py +++ b/wpilibj/src/athena/cpp/nivision/get_struct_size.py @@ -1,6 +1,8 @@ from __future__ import print_function + import sys + def main(): for line in sys.stdin: line = line.strip() @@ -10,5 +12,6 @@ def main(): line = line.replace("#", "") print(line) + if __name__ == "__main__": main() diff --git a/wpilibj/src/athena/cpp/nivision/nivision_parse.py b/wpilibj/src/athena/cpp/nivision/nivision_parse.py index 8e303b997c..52ffca5be3 100644 --- a/wpilibj/src/athena/cpp/nivision/nivision_parse.py +++ b/wpilibj/src/athena/cpp/nivision/nivision_parse.py @@ -1,8 +1,10 @@ from __future__ import print_function + import re import traceback -__all__ = ["define_after_struct", "defined", "forward_structs", "opaque_structs", "enums", "structs", "prescan_file", "parse_file", "number_re", "constant_re"] +__all__ = ["define_after_struct", "defined", "forward_structs", "opaque_structs", "enums", + "structs", "prescan_file", "parse_file", "number_re", "constant_re"] # parser regular expressions number_re = re.compile(r'-?[0-9]+') @@ -12,9 +14,12 @@ enum_re = re.compile(r'^typedef\s+enum\s+(?P[A-Za-z0-9]+)_enum\s*{') enum_value_re = re.compile(r'^\s*(?P[A-Za-z0-9_]+)\s*(=\s*(?P-?[0-9A-Fx]+))?\s*,?') struct_re = re.compile(r'^typedef\s+struct\s+(?P[A-Za-z0-9]+)_struct\s*{') union_re = re.compile(r'^typedef\s+union\s+(?P[A-Za-z0-9]+)_union\s*{') -func_pointer_re = re.compile(r'\s*(?P[A-Za-z0-9_*]+)\s*\(\s*[A-Za-z0-9_]*\s*[*]\s*(?P[A-Za-z0-9_]+)\s*\)\s*\((?P[^)]*)\)') -static_const_re = re.compile(r'^static\s+const\s+(?P[A-Za-z0-9_]+)\s+(?P[A-Za-z0-9_]+)\s*=\s*(?P[^;]+);') -function_re = re.compile(r'^((IMAQ|NI)_FUNC\s+)?(?P(const\s+)?[A-Za-z0-9_*]+)\s+((IMAQ_STDCALL|NI_FUNC[C]?)\s+)?(?P[A-Za-z0-9_]+)\s*\((?P[^)]*)\);') +func_pointer_re = re.compile( + r'\s*(?P[A-Za-z0-9_*]+)\s*\(\s*[A-Za-z0-9_]*\s*[*]\s*(?P[A-Za-z0-9_]+)\s*\)\s*\((?P[^)]*)\)') +static_const_re = re.compile( + r'^static\s+const\s+(?P[A-Za-z0-9_]+)\s+(?P[A-Za-z0-9_]+)\s*=\s*(?P[^;]+);') +function_re = re.compile( + r'^((IMAQ|NI)_FUNC\s+)?(?P(const\s+)?[A-Za-z0-9_*]+)\s+((IMAQ_STDCALL|NI_FUNC[C]?)\s+)?(?P[A-Za-z0-9_]+)\s*\((?P[^)]*)\);') # defines deferred until after structures define_after_struct = [] @@ -24,6 +29,7 @@ opaque_structs = set() enums = set() structs = set() + def parse_cdecl(decl): decl = " ".join(decl.split()) ctype, sep, name = decl.rpartition(' ') @@ -35,6 +41,7 @@ def parse_cdecl(decl): arr = None return name, ctype, arr + def split_comment(line): if line.startswith('/*'): return "", "" @@ -43,6 +50,7 @@ def split_comment(line): comment = parts[1].strip() if len(parts) > 1 else None return code, comment + def prescan_file(f): for line in f: code, comment = split_comment(line) @@ -66,6 +74,7 @@ def prescan_file(f): opaque_structs.update(forward_structs - structs) + def parse_file(emit, f, block_comment_exclude): in_block_comment = False cur_block = "" @@ -77,7 +86,7 @@ def parse_file(emit, f, block_comment_exclude): code, comment = split_comment(line) if not code and not comment: continue - #print(comment) + # print(comment) # in block comment if in_block_comment: @@ -87,7 +96,8 @@ def parse_file(emit, f, block_comment_exclude): try: emit.block_comment(cur_block) except Exception as e: - print("%d: exception in block_comment():\n%s" % (lineno+1, traceback.format_exc())) + print("%d: exception in block_comment():\n%s" % ( + lineno + 1, traceback.format_exc())) in_block_comment = False # emit "after struct" constants in Globals if cur_block == "Globals": @@ -95,7 +105,8 @@ def parse_file(emit, f, block_comment_exclude): try: emit.text(dtext) except Exception as e: - print("%d: exception in text():\n%s" % (lineno+1, traceback.format_exc())) + print("%d: exception in text():\n%s" % ( + lineno + 1, traceback.format_exc())) defined.add(dname) continue if not code and comment is not None: @@ -110,7 +121,7 @@ def parse_file(emit, f, block_comment_exclude): try: emit.enum(*in_enum) except Exception as e: - print("%d: exception in enum():\n%s" % (lineno+1, traceback.format_exc())) + print("%d: exception in enum():\n%s" % (lineno + 1, traceback.format_exc())) in_enum = None continue m = enum_value_re.match(code) @@ -126,13 +137,15 @@ def parse_file(emit, f, block_comment_exclude): try: emit.struct(*in_struct) except Exception as e: - print("%d: exception in struct(\"%s\"):\n%s" % (lineno+1, in_struct[0], traceback.format_exc())) + print("%d: exception in struct(\"%s\"):\n%s" % ( + lineno + 1, in_struct[0], traceback.format_exc())) in_struct = None if in_union is not None: try: emit.union(*in_union) except Exception as e: - print("%d: exception in union(\"%s\"):\n%s" % (lineno+1, in_union[0], traceback.format_exc())) + print("%d: exception in union(\"%s\"):\n%s" % ( + lineno + 1, in_union[0], traceback.format_exc())) in_union = None continue name, ctype, arr = parse_cdecl(code[:-1]) @@ -153,7 +166,7 @@ def parse_file(emit, f, block_comment_exclude): try: emit.define(m.group('name'), m.group('value').strip(), comment) except Exception as e: - print("%d: exception in define():\n%s" % (lineno+1, traceback.format_exc())) + print("%d: exception in define():\n%s" % (lineno + 1, traceback.format_exc())) continue # typedef enum { @@ -179,11 +192,13 @@ def parse_file(emit, f, block_comment_exclude): # typedef function? m = func_pointer_re.match(code[8:-1]) if m is not None: - params = [parse_cdecl(param.strip()) for param in m.group('params').strip().split(',') if param.strip()] + params = [parse_cdecl(param.strip()) for param in + m.group('params').strip().split(',') if param.strip()] try: emit.typedef_function(m.group('name'), m.group('restype'), params) except Exception as e: - print("%d: exception in typedef_function():\n%s" % (lineno+1, traceback.format_exc())) + print("%d: exception in typedef_function():\n%s" % ( + lineno + 1, traceback.format_exc())) continue if '(' in code: print("Invalid typedef: %s" % code) @@ -194,11 +209,13 @@ def parse_file(emit, f, block_comment_exclude): # function m = function_re.match(code) if m is not None: - params = [parse_cdecl(param.strip()) for param in m.group('params').strip().split(',') if param.strip()] + params = [parse_cdecl(param.strip()) for param in m.group('params').strip().split(',') + if param.strip()] try: emit.function(m.group('name'), m.group('restype'), params) except Exception as e: - print("%d: exception in function(\"%s\"):\n%s" % (lineno+1, m.group('name'), traceback.format_exc())) + print("%d: exception in function(\"%s\"):\n%s" % ( + lineno + 1, m.group('name'), traceback.format_exc())) continue # static const @@ -210,7 +227,7 @@ def parse_file(emit, f, block_comment_exclude): try: emit.static_const(m.group('name'), m.group('type'), value) except Exception as e: - print("%d: exception in static_const():\n%s" % (lineno+1, traceback.format_exc())) + print("%d: exception in static_const():\n%s" % (lineno + 1, traceback.format_exc())) continue if not code or code[0] == '#': @@ -222,5 +239,4 @@ def parse_file(emit, f, block_comment_exclude): if code == 'extern "C" {' or code == "}": continue - print("%d: Unrecognized: %s" % (lineno+1, code)) - + print("%d: Unrecognized: %s" % (lineno + 1, code)) diff --git a/wpilibj/src/athena/java/com/ni/vision/NIVision.java b/wpilibj/src/athena/java/com/ni/vision/NIVision.java index d2f0b623b1..6188eebb6b 100644 --- a/wpilibj/src/athena/java/com/ni/vision/NIVision.java +++ b/wpilibj/src/athena/java/com/ni/vision/NIVision.java @@ -5,12 +5,14 @@ package com.ni.vision; -import java.lang.reflect.*; import java.io.UnsupportedEncodingException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; +@SuppressWarnings("all") public class NIVision { private NIVision() {} diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_I2C.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_I2C.java index eb9a4ff9b8..183c6f095c 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_I2C.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_I2C.java @@ -7,8 +7,8 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; import java.nio.ByteBuffer; +import java.nio.ByteOrder; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; @@ -19,9 +19,11 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** + * ADXL345 I2C Accelerometer. * * @author dtjones */ +@SuppressWarnings("TypeName") public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindowSendable { private static final byte kAddress = 0x1D; @@ -29,26 +31,34 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow private static final byte kDataFormatRegister = 0x31; private static final byte kDataRegister = 0x32; private static final double kGsPerLSB = 0.00390625; - private static final byte kPowerCtl_Link = 0x20, kPowerCtl_AutoSleep = 0x10, - kPowerCtl_Measure = 0x08, kPowerCtl_Sleep = 0x04; - private static final byte kDataFormat_SelfTest = (byte) 0x80, kDataFormat_SPI = 0x40, - kDataFormat_IntInvert = 0x20, kDataFormat_FullRes = 0x08, kDataFormat_Justify = 0x04; + private static final byte kPowerCtl_Link = 0x20; + private static final byte kPowerCtl_AutoSleep = 0x10; + private static final byte kPowerCtl_Measure = 0x08; + private static final byte kPowerCtl_Sleep = 0x04; - public static enum Axes { + private static final byte kDataFormat_SelfTest = (byte) 0x80; + private static final byte kDataFormat_SPI = 0x40; + private static final byte kDataFormat_IntInvert = 0x20; + private static final byte kDataFormat_FullRes = 0x08; + private static final byte kDataFormat_Justify = 0x04; + + public enum Axes { kX((byte) 0x00), kY((byte) 0x02), kZ((byte) 0x04); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final byte value; - private Axes(byte value) { + Axes(byte value) { this.value = value; } } + @SuppressWarnings("MemberName") public static class AllAxes { public double XAxis; @@ -60,8 +70,8 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow /** * Constructs the ADXL345 Accelerometer with I2C address 0x1D. - *$ - * @param port The I2C port the accelerometer is attached to + * + * @param port The I2C port the accelerometer is attached to * @param range The range (+ or -) that the accelerometer will measure. */ public ADXL345_I2C(I2C.Port port, Range range) { @@ -70,10 +80,10 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow /** * Constructs the ADXL345 Accelerometer over I2C. - *$ - * @param port The I2C port the accelerometer is attached to - * @param range The range (+ or -) that the accelerometer will measure. - * @param the I2C address of the accelerometer (0x1D or 0x53) + * + * @param port The I2C port the accelerometer is attached to + * @param range The range (+ or -) that the accelerometer will measure. + * @param deviceAddress I2C address of the accelerometer (0x1D or 0x53) */ public ADXL345_I2C(I2C.Port port, Range range, int deviceAddress) { m_i2c = new I2C(port, deviceAddress); @@ -87,10 +97,10 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow LiveWindow.addSensor("ADXL345_I2C", port.getValue(), this); } - /** {inheritdoc} */ + @Override public void setRange(Range range) { - byte value = 0; + final byte value; switch (range) { case k2G: @@ -105,25 +115,24 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow case k16G: value = 3; break; + default: + throw new IllegalArgumentException(range + " unsupported range type"); } // Specify the data format to read m_i2c.write(kDataFormatRegister, kDataFormat_FullRes | value); } - /** {@inheritDoc} */ @Override public double getX() { return getAcceleration(Axes.kX); } - /** {@inheritDoc} */ @Override public double getY() { return getAcceleration(Axes.kY); } - /** {@inheritDoc} */ @Override public double getZ() { return getAcceleration(Axes.kZ); @@ -147,8 +156,7 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow /** * Get the acceleration of all axes in Gs. * - * @return An object containing the acceleration measured on each axis of the - * ADXL345 in Gs. + * @return An object containing the acceleration measured on each axis of the ADXL345 in Gs. */ public AllAxes getAccelerations() { AllAxes data = new AllAxes(); @@ -163,19 +171,20 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow return data; } + @Override public String getSmartDashboardType() { return "3AxisAccelerometer"; } private ITable m_table; - /** {@inheritDoc} */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** {@inheritDoc} */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("X", getX()); @@ -184,12 +193,16 @@ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindow } } - /** {@inheritDoc} */ + @Override public ITable getTable() { return m_table; } - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_SPI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_SPI.java index f019a01362..6d0ba88c9a 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_SPI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL345_SPI.java @@ -7,8 +7,8 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; import java.nio.ByteBuffer; +import java.nio.ByteOrder; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; @@ -19,10 +19,12 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** + * ADXL345 SPI Accelerometer. * * @author dtjones * @author mwills */ +@SuppressWarnings({"TypeName"}) public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindowSendable { private static final int kPowerCtlRegister = 0x2D; private static final int kDataFormatRegister = 0x31; @@ -43,21 +45,23 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow private static final int kDataFormat_FullRes = 0x08; private static final int kDataFormat_Justify = 0x04; - public static enum Axes { + public enum Axes { kX((byte) 0x00), kY((byte) 0x02), kZ((byte) 0x04); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final byte value; - private Axes(byte value) { + Axes(byte value) { this.value = value; } } + @SuppressWarnings("MemberName") public static class AllAxes { public double XAxis; @@ -70,7 +74,7 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow /** * Constructor. * - * @param port The SPI port that the accelerometer is connected to + * @param port The SPI port that the accelerometer is connected to * @param range The range (+ or -) that the accelerometer will measure. */ public ADXL345_SPI(SPI.Port port, Range range) { @@ -84,7 +88,7 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow } /** - * Set SPI bus parameters, bring device out of sleep and set format + * Set SPI bus parameters, bring device out of sleep and set format. * * @param range The range (+ or -) that the accelerometer will measure. */ @@ -106,10 +110,9 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow UsageReporting.report(tResourceType.kResourceType_ADXL345, tInstances.kADXL345_SPI); } - /** {inheritdoc} */ @Override public void setRange(Range range) { - byte value = 0; + final byte value; switch (range) { case k2G: @@ -124,26 +127,25 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow case k16G: value = 3; break; + default: + throw new IllegalArgumentException(range + " unsupported"); } // Specify the data format to read - byte[] commands = new byte[] {kDataFormatRegister, (byte) (kDataFormat_FullRes | value)}; + byte[] commands = new byte[]{kDataFormatRegister, (byte) (kDataFormat_FullRes | value)}; m_spi.write(commands, commands.length); } - /** {@inheritDoc} */ @Override public double getX() { return getAcceleration(Axes.kX); } - /** {@inheritDoc} */ @Override public double getY() { return getAcceleration(Axes.kY); } - /** {@inheritDoc} */ @Override public double getZ() { return getAcceleration(Axes.kZ); @@ -157,7 +159,8 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow */ public double getAcceleration(ADXL345_SPI.Axes axis) { ByteBuffer transferBuffer = ByteBuffer.allocateDirect(3); - transferBuffer.put(0, (byte) ((kAddress_Read | kAddress_MultiByte | kDataRegister) + axis.value)); + transferBuffer.put(0, + (byte) ((kAddress_Read | kAddress_MultiByte | kDataRegister) + axis.value)); m_spi.transaction(transferBuffer, transferBuffer, 3); // Sensor is little endian transferBuffer.order(ByteOrder.LITTLE_ENDIAN); @@ -168,8 +171,7 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow /** * Get the acceleration of all axes in Gs. * - * @return An object containing the acceleration measured on each axis of the - * ADXL345 in Gs. + * @return An object containing the acceleration measured on each axis of the ADXL345 in Gs. */ public ADXL345_SPI.AllAxes getAccelerations() { ADXL345_SPI.AllAxes data = new ADXL345_SPI.AllAxes(); @@ -188,19 +190,20 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow return data; } + @Override public String getSmartDashboardType() { return "3AxisAccelerometer"; } private ITable m_table; - /** {@inheritDoc} */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** {@inheritDoc} */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("X", getX()); @@ -209,12 +212,16 @@ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindow } } - /** {@inheritDoc} */ + @Override public ITable getTable() { return m_table; } - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL362.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL362.java index 8df8f6dbf3..913a3cc6cf 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL362.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXL362.java @@ -7,10 +7,9 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; import java.nio.ByteBuffer; +import java.nio.ByteOrder; -import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.interfaces.Accelerometer; @@ -21,7 +20,7 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * ADXL362 SPI Accelerometer. * - * This class allows access to an Analog Devices ADXL362 3-axis accelerometer. + *

This class allows access to an Analog Devices ADXL362 3-axis accelerometer. */ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSendable { private static final byte kRegWrite = 0x0A; @@ -41,21 +40,23 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend private static final byte kPowerCtl_AutoSleep = 0x04; private static final byte kPowerCtl_Measure = 0x02; - public static enum Axes { + public enum Axes { kX((byte) 0x00), kY((byte) 0x02), kZ((byte) 0x04); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final byte value; - private Axes(byte value) { + Axes(byte value) { this.value = value; } } + @SuppressWarnings("MemberName") public static class AllAxes { public double XAxis; @@ -78,7 +79,7 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend /** * Constructor. * - * @param port The SPI port that the accelerometer is connected to + * @param port The SPI port that the accelerometer is connected to * @param range The range (+ or -) that the accelerometer will measure. */ public ADXL362(SPI.Port port, Range range) { @@ -94,7 +95,7 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend transferBuffer.put(0, kRegRead); transferBuffer.put(1, kPartIdRegister); m_spi.transaction(transferBuffer, transferBuffer, 3); - if (transferBuffer.get(2) != (byte)0xF2) { + if (transferBuffer.get(2) != (byte) 0xF2) { m_spi.free(); m_spi = null; DriverStation.reportError("could not find ADXL362 on SPI port " + port.getValue(), false); @@ -117,45 +118,46 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend m_spi.free(); } - /** {inheritdoc} */ @Override public void setRange(Range range) { - byte value = 0; + final byte value; switch (range) { case k2G: value = kFilterCtl_Range2G; - m_gsPerLSB = 0.001; + m_gsPerLSB = 0.001; break; case k4G: value = kFilterCtl_Range4G; - m_gsPerLSB = 0.002; + m_gsPerLSB = 0.002; break; case k8G: case k16G: // 16G not supported; treat as 8G value = kFilterCtl_Range8G; - m_gsPerLSB = 0.004; + m_gsPerLSB = 0.004; break; + default: + throw new IllegalArgumentException(range + " unsupported"); + } // Specify the data format to read - byte[] commands = new byte[] {kRegWrite, kFilterCtlRegister, (byte) (kFilterCtl_ODR_100Hz | value)}; + byte[] commands = new byte[]{kRegWrite, kFilterCtlRegister, (byte) (kFilterCtl_ODR_100Hz + | value)}; m_spi.write(commands, commands.length); } - /** {@inheritDoc} */ + @Override public double getX() { return getAcceleration(Axes.kX); } - /** {@inheritDoc} */ @Override public double getY() { return getAcceleration(Axes.kY); } - /** {@inheritDoc} */ @Override public double getZ() { return getAcceleration(Axes.kZ); @@ -168,8 +170,9 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend * @return Acceleration of the ADXL362 in Gs. */ public double getAcceleration(ADXL362.Axes axis) { - if (m_spi == null) + if (m_spi == null) { return 0.0; + } ByteBuffer transferBuffer = ByteBuffer.allocateDirect(4); transferBuffer.put(0, kRegRead); transferBuffer.put(1, (byte) (kDataRegister + axis.value)); @@ -183,8 +186,7 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend /** * Get the acceleration of all axes in Gs. * - * @return An object containing the acceleration measured on each axis of the - * ADXL362 in Gs. + * @return An object containing the acceleration measured on each axis of the ADXL362 in Gs. */ public ADXL362.AllAxes getAccelerations() { ADXL362.AllAxes data = new ADXL362.AllAxes(); @@ -204,19 +206,20 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend return data; } + @Override public String getSmartDashboardType() { return "3AxisAccelerometer"; } private ITable m_table; - /** {@inheritDoc} */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** {@inheritDoc} */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("X", getX()); @@ -225,12 +228,16 @@ public class ADXL362 extends SensorBase implements Accelerometer, LiveWindowSend } } - /** {@inheritDoc} */ + @Override public ITable getTable() { return m_table; } - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java index 4f05874541..e7b8318d10 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java @@ -7,28 +7,25 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; import java.nio.ByteBuffer; +import java.nio.ByteOrder; -import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.interfaces.Gyro; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; -import edu.wpi.first.wpilibj.tables.ITable; /** - * Use a rate gyro to return the robots heading relative to a starting position. - * The Gyro class tracks the robots heading based on the starting position. As - * the robot rotates the new heading is computed by integrating the rate of - * rotation returned by the sensor. When the class is instantiated, it does a - * short calibration routine where it samples the gyro while at rest to - * determine the default offset. This is subtracted from each sample to - * determine the heading. + * Use a rate gyro to return the robots heading relative to a starting position. The Gyro class + * tracks the robots heading based on the starting position. As the robot rotates the new heading is + * computed by integrating the rate of rotation returned by the sensor. When the class is + * instantiated, it does a short calibration routine where it samples the gyro while at rest to + * determine the default offset. This is subtracted from each sample to determine the heading. * - * This class is for the digital ADXRS450 gyro sensor that connects via SPI. + *

This class is for the digital ADXRS450 gyro sensor that connects via SPI. */ +@SuppressWarnings({"TypeName", "AbbreviationAsWordInName"}) public class ADXRS450_Gyro extends GyroBase implements Gyro, PIDSource, LiveWindowSendable { private static final double kSamplePeriod = 0.001; private static final double kCalibrationSampleTime = 5.0; @@ -70,7 +67,8 @@ public class ADXRS450_Gyro extends GyroBase implements Gyro, PIDSource, LiveWind if ((readRegister(kPIDRegister) & 0xff00) != 0x5200) { m_spi.free(); m_spi = null; - DriverStation.reportError("could not find ADXRS450 gyro on SPI port " + port.getValue(), false); + DriverStation.reportError("could not find ADXRS450 gyro on SPI port " + port.getValue(), + false); return; } @@ -83,12 +81,11 @@ public class ADXRS450_Gyro extends GyroBase implements Gyro, PIDSource, LiveWind LiveWindow.addSensor("ADXRS450_Gyro", port.getValue(), this); } - /** - * {@inheritDoc} - */ @Override public void calibrate() { - if (m_spi == null) return; + if (m_spi == null) { + return; + } Timer.delay(0.1); @@ -97,15 +94,15 @@ public class ADXRS450_Gyro extends GyroBase implements Gyro, PIDSource, LiveWind Timer.delay(kCalibrationSampleTime); - m_spi.setAccumulatorCenter((int)m_spi.getAccumulatorAverage()); + m_spi.setAccumulatorCenter((int) m_spi.getAccumulatorAverage()); m_spi.resetAccumulator(); } - private boolean calcParity(int v) { + private boolean calcParity(int value) { boolean parity = false; - while (v != 0) { + while (value != 0) { parity = !parity; - v = v & (v - 1); + value = value & (value - 1); } return parity; } @@ -130,9 +127,7 @@ public class ADXRS450_Gyro extends GyroBase implements Gyro, PIDSource, LiveWind return (buf.getInt(0) >> 5) & 0xffff; } - /** - * {@inheritDoc} - */ + @Override public void reset() { m_spi.resetAccumulator(); } @@ -148,19 +143,19 @@ public class ADXRS450_Gyro extends GyroBase implements Gyro, PIDSource, LiveWind } } - /** - * {@inheritDoc} - */ + @Override public double getAngle() { - if (m_spi == null) return 0.0; + if (m_spi == null) { + return 0.0; + } return m_spi.getAccumulatorValue() * kDegreePerSecondPerLSB * kSamplePeriod; } - /** - * {@inheritDoc} - */ + @Override public double getRate() { - if (m_spi == null) return 0.0; + if (m_spi == null) { + return 0.0; + } return m_spi.getAccumulatorLastValue() * kDegreePerSecondPerLSB; } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AccumulatorResult.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AccumulatorResult.java index a6ff5b5b31..70e1b055fb 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AccumulatorResult.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AccumulatorResult.java @@ -8,18 +8,20 @@ package edu.wpi.first.wpilibj; /** - * Structure for holding the values stored in an accumulator - *$ + * Structure for holding the values stored in an accumulator. + * * @author brad */ public class AccumulatorResult { /** - * The total value accumulated + * The total value accumulated. */ + @SuppressWarnings("MemberName") public long value; /** - * The number of sample vaule was accumulated over + * The number of sample vaule was accumulated over. */ + @SuppressWarnings("MemberName") public long count; } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java index f7e0072c8f..e360eed490 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java @@ -15,10 +15,9 @@ import edu.wpi.first.wpilibj.tables.ITable; /** - * Handle operation of an analog accelerometer. The accelerometer reads - * acceleration directly through the sensor. Many sensors have multiple axis and - * can be treated as multiple devices. Each is calibrated by finding the center - * value over a period of time. + * Handle operation of an analog accelerometer. The accelerometer reads acceleration directly + * through the sensor. Many sensors have multiple axis and can be treated as multiple devices. Each + * is calibrated by finding the center value over a period of time. */ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWindowSendable { @@ -29,7 +28,7 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement; /** - * Common initialization + * Common initialization. */ private void initAccelerometer() { UsageReporting.report(tResourceType.kResourceType_Accelerometer, m_analogChannel.getChannel()); @@ -39,10 +38,9 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi /** * Create a new instance of an accelerometer. * - * The constructor allocates desired analog channel. - *$ - * @param channel The channel number for the analog input the accelerometer is - * connected to + *

The constructor allocates desired analog channel. + * + * @param channel The channel number for the analog input the accelerometer is connected to */ public AnalogAccelerometer(final int channel) { m_allocatedChannel = true; @@ -51,18 +49,18 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi } /** - * Create a new instance of Accelerometer from an existing AnalogChannel. Make - * a new instance of accelerometer given an AnalogChannel. This is - * particularly useful if the port is going to be read as an analog channel as - * well as through the Accelerometer class. - *$ - * @param channel The existing AnalogInput object for the analog input the - * accelerometer is connected to + * Create a new instance of Accelerometer from an existing AnalogChannel. Make a new instance of + * accelerometer given an AnalogChannel. This is particularly useful if the port is going to be + * read as an analog channel as well as through the Accelerometer class. + * + * @param channel The existing AnalogInput object for the analog input the accelerometer is + * connected to */ public AnalogAccelerometer(AnalogInput channel) { m_allocatedChannel = false; - if (channel == null) + if (channel == null) { throw new NullPointerException("Analog Channel given was null"); + } m_analogChannel = channel; initAccelerometer(); } @@ -70,6 +68,7 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi /** * Delete the analog components used for the accelerometer. */ + @Override public void free() { if (m_analogChannel != null && m_allocatedChannel) { m_analogChannel.free(); @@ -80,7 +79,7 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi /** * Return the acceleration in Gs. * - * The acceleration is returned units of Gs. + *

The acceleration is returned units of Gs. * * @return The current acceleration of the sensor in Gs. */ @@ -91,9 +90,8 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi /** * Set the accelerometer sensitivity. * - * This sets the sensitivity of the accelerometer used for calculating the - * acceleration. The sensitivity varies by accelerometer model. There are - * constants defined for various models. + *

This sets the sensitivity of the accelerometer used for calculating the acceleration. The + * sensitivity varies by accelerometer model. There are constants defined for various models. * * @param sensitivity The sensitivity of accelerometer in Volts per G. */ @@ -104,8 +102,8 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi /** * Set the voltage that corresponds to 0 G. * - * The zero G voltage varies by accelerometer model. There are constants - * defined for various models. + *

The zero G voltage varies by accelerometer model. There are constants defined for various + * models. * * @param zero The zero G voltage. */ @@ -113,16 +111,12 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi m_zeroGVoltage = zero; } - /** - * {@inheritDoc} - */ + @Override public void setPIDSourceType(PIDSourceType pidSource) { m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_pidSource; } @@ -132,10 +126,12 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi * * @return The current acceleration in Gs. */ + @Override public double pidGet() { return getAcceleration(); } + @Override public String getSmartDashboardType() { return "Accelerometer"; } @@ -145,24 +141,18 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi */ private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", getAcceleration()); @@ -170,14 +160,16 @@ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWi } /** - * Analog Channels don't have to do anything special when entering the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when entering the LiveWindow. {@inheritDoc} */ - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } /** - * Analog Channels don't have to do anything special when exiting the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when exiting the LiveWindow. {@inheritDoc} */ - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogGyro.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogGyro.java index c2d541072d..e643a55d9b 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogGyro.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogGyro.java @@ -12,39 +12,35 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.interfaces.Gyro; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; -import edu.wpi.first.wpilibj.tables.ITable; /** - * Use a rate gyro to return the robots heading relative to a starting position. - * The Gyro class tracks the robots heading based on the starting position. As - * the robot rotates the new heading is computed by integrating the rate of - * rotation returned by the sensor. When the class is instantiated, it does a - * short calibration routine where it samples the gyro while at rest to - * determine the default offset. This is subtracted from each sample to - * determine the heading. + * Use a rate gyro to return the robots heading relative to a starting position. The Gyro class + * tracks the robots heading based on the starting position. As the robot rotates the new heading is + * computed by integrating the rate of rotation returned by the sensor. When the class is + * instantiated, it does a short calibration routine where it samples the gyro while at rest to + * determine the default offset. This is subtracted from each sample to determine the heading. * - * This class is for gyro sensors that connect to an analog input. + *

This class is for gyro sensors that connect to an analog input. */ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowSendable { - static final int kOversampleBits = 10; - static final int kAverageBits = 0; - static final double kSamplesPerSecond = 50.0; - static final double kCalibrationSampleTime = 5.0; - static final double kDefaultVoltsPerDegreePerSecond = 0.007; + private static final int kOversampleBits = 10; + private static final int kAverageBits = 0; + private static final double kSamplesPerSecond = 50.0; + private static final double kCalibrationSampleTime = 5.0; + private static final double kDefaultVoltsPerDegreePerSecond = 0.007; protected AnalogInput m_analog; - double m_voltsPerDegreePerSecond; - double m_offset; - int m_center; - boolean m_channelAllocated = false; - AccumulatorResult result; - private PIDSourceType m_pidSource; + private double m_voltsPerDegreePerSecond; + private double m_offset; + private int m_center; + private boolean m_channelAllocated = false; + private AccumulatorResult m_result; /** * Initialize the gyro. Calibration is handled by calibrate(). */ public void initGyro() { - result = new AccumulatorResult(); + m_result = new AccumulatorResult(); m_voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; m_analog.setAverageBits(kAverageBits); @@ -61,20 +57,18 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS LiveWindow.addSensor("AnalogGyro", m_analog.getChannel(), this); } - /** - * {@inheritDoc} - */ + @Override public void calibrate() { m_analog.initAccumulator(); m_analog.resetAccumulator(); Timer.delay(kCalibrationSampleTime); - m_analog.getAccumulatorOutput(result); + m_analog.getAccumulatorOutput(m_result); - m_center = (int) ((double) result.value / (double) result.count + .5); + m_center = (int) ((double) m_result.value / (double) m_result.count + .5); - m_offset = ((double) result.value / (double) result.count) - m_center; + m_offset = ((double) m_result.value / (double) m_result.count) - m_center; m_analog.setAccumulatorCenter(m_center); m_analog.resetAccumulator(); @@ -83,8 +77,8 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS /** * Gyro constructor using the channel number * - * @param channel The analog channel the gyro is connected to. Gyros can only - * be used on on-board channels 0-1. + * @param channel The analog channel the gyro is connected to. Gyros can only be used on on-board + * channels 0-1. */ public AnalogGyro(int channel) { this(new AnalogInput(channel)); @@ -92,11 +86,11 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } /** - * Gyro constructor with a precreated analog channel object. Use this - * constructor when the analog channel needs to be shared. + * Gyro constructor with a precreated analog channel object. Use this constructor when the analog + * channel needs to be shared. * - * @param channel The AnalogInput object that the gyro is connected to. Gyros - * can only be used on on-board channels 0-1. + * @param channel The AnalogInput object that the gyro is connected to. Gyros can only be used on + * on-board channels 0-1. */ public AnalogGyro(AnalogInput channel) { m_analog = channel; @@ -108,12 +102,13 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } /** - * Gyro constructor using the channel number along with parameters for - * presetting the center and offset values. Bypasses calibration. - * @param channel The analog channel the gyro is connected to. Gyros can only - * be used on on-board channels 0-1. - * @param center Preset uncalibrated value to use as the accumulator center value. - * @param offset Preset uncalibrated value to use as the gyro offset. + * Gyro constructor using the channel number along with parameters for presetting the center and + * offset values. Bypasses calibration. + * + * @param channel The analog channel the gyro is connected to. Gyros can only be used on on-board + * channels 0-1. + * @param center Preset uncalibrated value to use as the accumulator center value. + * @param offset Preset uncalibrated value to use as the gyro offset. */ public AnalogGyro(int channel, int center, double offset) { this(new AnalogInput(channel), center, offset); @@ -121,13 +116,13 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } /** - * Gyro constructor with a precreated analog channel object along with - * parameters for presetting the center and offset values. Bypasses - * calibration. - * @param channel The analog channel the gyro is connected to. Gyros can only - * be used on on-board channels 0-1. - * @param center Preset uncalibrated value to use as the accumulator center value. - * @param offset Preset uncalibrated value to use as the gyro offset. + * Gyro constructor with a precreated analog channel object along with parameters for presetting + * the center and offset values. Bypasses calibration. + * + * @param channel The analog channel the gyro is connected to. Gyros can only be used on on-board + * channels 0-1. + * @param center Preset uncalibrated value to use as the accumulator center value. + * @param offset Preset uncalibrated value to use as the gyro offset. */ public AnalogGyro(AnalogInput channel, int center, double offset) { m_analog = channel; @@ -142,9 +137,7 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS m_analog.resetAccumulator(); } - /** - * {@inheritDoc} - */ + @Override public void reset() { if (m_analog != null) { m_analog.resetAccumulator(); @@ -162,16 +155,14 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS m_analog = null; } - /** - * {@inheritDoc} - */ + @Override public synchronized double getAngle() { if (m_analog == null) { return 0.0; } else { - m_analog.getAccumulatorOutput(result); + m_analog.getAccumulatorOutput(m_result); - long value = result.value - (long) (result.count * m_offset); + long value = m_result.value - (long) (m_result.count * m_offset); double scaledValue = value * 1e-9 * m_analog.getLSBWeight() * (1 << m_analog.getAverageBits()) @@ -181,9 +172,7 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } } - /** - * {@inheritDoc} - */ + @Override public double getRate() { if (m_analog == null) { return 0.0; @@ -194,8 +183,7 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } /** - * Return the gyro offset value set during calibration to - * use as a future preset + * Return the gyro offset value set during calibration to use as a future preset. * * @return the current offset value */ @@ -204,8 +192,7 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } /** - * Return the gyro center value set during calibration to - * use as a future preset + * Return the gyro center value set during calibration to use as a future preset. * * @return the current center value */ @@ -214,10 +201,9 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } /** - * Set the gyro sensitivity. This takes the number of volts/degree/second - * sensitivity of the gyro and uses it in subsequent calculations to allow the - * code to work with multiple gyros. This value is typically found in the gyro - * datasheet. + * Set the gyro sensitivity. This takes the number of volts/degree/second sensitivity of the gyro + * and uses it in subsequent calculations to allow the code to work with multiple gyros. This + * value is typically found in the gyro datasheet. * * @param voltsPerDegreePerSecond The sensitivity in Volts/degree/second. */ @@ -226,10 +212,9 @@ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowS } /** - * Set the size of the neutral zone. Any voltage from the gyro less than this - * amount from the center is considered stationary. Setting a deadband will - * decrease the amount of drift when the gyro isn't rotating, but will make it - * less accurate. + * Set the size of the neutral zone. Any voltage from the gyro less than this amount from the + * center is considered stationary. Setting a deadband will decrease the amount of drift when the + * gyro isn't rotating, but will make it less accurate. * * @param volts The size of the deadband in volts */ diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogInput.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogInput.java index 7765b327f8..b943bf5e26 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogInput.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogInput.java @@ -7,12 +7,8 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.nio.LongBuffer; import java.nio.ByteBuffer; - -// import com.sun.jna.Pointer; +import java.nio.ByteOrder; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; @@ -26,17 +22,14 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Analog channel class. * - * Each analog channel is read from hardware as a 12-bit number representing 0V - * to 5V. + *

Each analog channel is read from hardware as a 12-bit number representing 0V to 5V. * - * Connected to each analog channel is an averaging and oversampling engine. - * This engine accumulates the specified ( by setAverageBits() and - * setOversampleBits() ) number of samples before returning a new value. This is - * not a sliding window average. The only difference between the oversampled - * samples and the averaged samples is that the oversampled samples are simply - * accumulated effectively increasing the resolution, while the averaged samples - * are divided by the number of samples to retain the resolution, but get more - * stable values. + *

Connected to each analog channel is an averaging and oversampling engine. This engine + * accumulates the specified ( by setAverageBits() and setOversampleBits() ) number of samples + * before returning a new value. This is not a sliding window average. The only difference between + * the oversampled samples and the averaged samples is that the oversampled samples are simply + * accumulated effectively increasing the resolution, while the averaged samples are divided by the + * number of samples to retain the resolution, but get more stable values. */ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSendable { @@ -51,8 +44,7 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Construct an analog channel. * - * @param channel The channel number to represent. 0-3 are on-board 4-7 are on - * the MXP port. + * @param channel The channel number to represent. 0-3 are on-board 4-7 are on the MXP port. */ public AnalogInput(final int channel) { m_channel = channel; @@ -63,12 +55,12 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } try { channels.allocate(channel); - } catch (CheckedAllocationException e) { + } catch (CheckedAllocationException ex) { throw new AllocationException("Analog input channel " + m_channel + " is already allocated"); } - long port_pointer = AnalogJNI.getPort((byte) channel); - m_port = AnalogJNI.initializeAnalogInputPort(port_pointer); + final long portPointer = AnalogJNI.getPort((byte) channel); + m_port = AnalogJNI.initializeAnalogInputPort(portPointer); LiveWindow.addSensor("AnalogInput", channel, this); UsageReporting.report(tResourceType.kResourceType_AnalogChannel, channel); @@ -86,10 +78,9 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Get a sample straight from this channel. The sample is a 12-bit value - * representing the 0V to 5V range of the A/D converter. The units are in A/D - * converter codes. Use GetVoltage() to get the analog value in calibrated - * units. + * Get a sample straight from this channel. The sample is a 12-bit value representing the 0V to 5V + * range of the A/D converter. The units are in A/D converter codes. Use GetVoltage() to get the + * analog value in calibrated units. * * @return A sample straight from this channel. */ @@ -98,13 +89,12 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Get a sample from the output of the oversample and average engine for this - * channel. The sample is 12-bit + the bits configured in SetOversampleBits(). - * The value configured in setAverageBits() will cause this value to be - * averaged 2^bits number of samples. This is not a sliding window. The sample - * will not change until 2^(OversampleBits + AverageBits) samples have been - * acquired from this channel. Use getAverageVoltage() to get the analog value - * in calibrated units. + * Get a sample from the output of the oversample and average engine for this channel. The sample + * is 12-bit + the bits configured in SetOversampleBits(). The value configured in + * setAverageBits() will cause this value to be averaged 2^bits number of samples. This is not a + * sliding window. The sample will not change until 2^(OversampleBits + AverageBits) samples have + * been acquired from this channel. Use getAverageVoltage() to get the analog value in calibrated + * units. * * @return A sample from the oversample and average engine for this channel. */ @@ -113,9 +103,8 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Get a scaled sample straight from this channel. The value is scaled to - * units of Volts using the calibrated scaling data from getLSBWeight() and - * getOffset(). + * Get a scaled sample straight from this channel. The value is scaled to units of Volts using the + * calibrated scaling data from getLSBWeight() and getOffset(). * * @return A scaled sample straight from this channel. */ @@ -124,26 +113,23 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Get a scaled sample from the output of the oversample and average engine - * for this channel. The value is scaled to units of Volts using the - * calibrated scaling data from getLSBWeight() and getOffset(). Using - * oversampling will cause this value to be higher resolution, but it will - * update more slowly. Using averaging will cause this value to be more - * stable, but it will update more slowly. + * Get a scaled sample from the output of the oversample and average engine for this channel. The + * value is scaled to units of Volts using the calibrated scaling data from getLSBWeight() and + * getOffset(). Using oversampling will cause this value to be higher resolution, but it will + * update more slowly. Using averaging will cause this value to be more stable, but it will update + * more slowly. * - * @return A scaled sample from the output of the oversample and average - * engine for this channel. + * @return A scaled sample from the output of the oversample and average engine for this channel. */ public double getAverageVoltage() { return AnalogJNI.getAnalogAverageVoltage(m_port); } /** - * Get the factory scaling least significant bit weight constant. The least - * significant bit weight constant for the channel that was calibrated in - * manufacturing and stored in an eeprom. + * Get the factory scaling least significant bit weight constant. The least significant bit weight + * constant for the channel that was calibrated in manufacturing and stored in an eeprom. * - * Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) + *

Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) * * @return Least significant bit weight. */ @@ -152,10 +138,10 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Get the factory scaling offset constant. The offset constant for the - * channel that was calibrated in manufacturing and stored in an eeprom. + * Get the factory scaling offset constant. The offset constant for the channel that was + * calibrated in manufacturing and stored in an eeprom. * - * Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) + *

Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) * * @return Offset constant. */ @@ -173,9 +159,8 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Set the number of averaging bits. This sets the number of averaging bits. - * The actual number of averaged samples is 2^bits. The averaging is done - * automatically in the FPGA. + * Set the number of averaging bits. This sets the number of averaging bits. The actual number of + * averaged samples is 2^bits. The averaging is done automatically in the FPGA. * * @param bits The number of averaging bits. */ @@ -184,9 +169,8 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Get the number of averaging bits. This gets the number of averaging bits - * from the FPGA. The actual number of averaged samples is 2^bits. The - * averaging is done automatically in the FPGA. + * Get the number of averaging bits. This gets the number of averaging bits from the FPGA. The + * actual number of averaged samples is 2^bits. The averaging is done automatically in the FPGA. * * @return The number of averaging bits. */ @@ -195,9 +179,8 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Set the number of oversample bits. This sets the number of oversample bits. - * The actual number of oversampled values is 2^bits. The oversampling is done - * automatically in the FPGA. + * Set the number of oversample bits. This sets the number of oversample bits. The actual number + * of oversampled values is 2^bits. The oversampling is done automatically in the FPGA. * * @param bits The number of oversample bits. */ @@ -206,9 +189,9 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend } /** - * Get the number of oversample bits. This gets the number of oversample bits - * from the FPGA. The actual number of oversampled values is 2^bits. The - * oversampling is done automatically in the FPGA. + * Get the number of oversample bits. This gets the number of oversample bits from the FPGA. The + * actual number of oversampled values is 2^bits. The oversampling is done automatically in the + * FPGA. * * @return The number of oversample bits. */ @@ -231,10 +214,9 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Set an initial value for the accumulator. * - * This will be added to all values returned to the user. + *

This will be added to all values returned to the user. * - * @param initialValue The value that the accumulator should start from when - * reset. + * @param initialValue The value that the accumulator should start from when reset. */ public void setAccumulatorInitialValue(long initialValue) { m_accumulatorOffset = initialValue; @@ -258,13 +240,13 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Set the center value of the accumulator. * - * The center value is subtracted from each A/D value before it is added to - * the accumulator. This is used for the center value of devices like gyros - * and accelerometers to take the device offset into account when integrating. + *

The center value is subtracted from each A/D value before it is added to the accumulator. + * This is used for the center value of devices like gyros and accelerometers to take the device + * offset into account when integrating. * - * This center value is based on the output of the oversampled and averaged - * source the accumulator channel. Because of this, any non-zero oversample - * bits will affect the size of the value for this field. + *

This center value is based on the output of the oversampled and averaged source the + * accumulator channel. Because of this, any non-zero oversample bits will affect the size of the + * value for this field. */ public void setAccumulatorCenter(int center) { AnalogJNI.setAccumulatorCenter(m_port, center); @@ -272,7 +254,7 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Set the accumulator's deadband. - *$ + * * @param deadband The deadband size in ADC codes (12-bit value) */ public void setAccumulatorDeadband(int deadband) { @@ -282,8 +264,8 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Read the accumulated value. * - * Read the value that has been accumulating. The accumulator is attached - * after the oversample and average engine. + *

Read the value that has been accumulating. The accumulator is attached after the oversample + * and average engine. * * @return The 64-bit value accumulated since the last Reset(). */ @@ -294,8 +276,7 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Read the number of accumulated values. * - * Read the count of the accumulated values since the accumulator was last - * Reset(). + *

Read the count of the accumulated values since the accumulator was last Reset(). * * @return The number of times samples from the channel were accumulated. */ @@ -306,8 +287,8 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Read the accumulated value and the number of accumulated values atomically. * - * This function reads the value and count from the FPGA atomically. This can - * be used for averaging. + *

This function reads the value and count from the FPGA atomically. This can be used for + * averaging. * * @param result AccumulatorResult object to store the results in. */ @@ -316,7 +297,8 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend throw new IllegalArgumentException("Null parameter `result'"); } if (!isAccumulatorChannel()) { - throw new IllegalArgumentException("Channel " + m_channel + " is not an accumulator channel."); + throw new IllegalArgumentException( + "Channel " + m_channel + " is not an accumulator channel."); } ByteBuffer value = ByteBuffer.allocateDirect(8); // set the byte order @@ -346,10 +328,9 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Set the sample rate per channel. * - * This is a global setting for all channels. The maximum rate is 500kS/s - * divided by the number of channels in use. This is 62500 samples/s per - * channel if all 8 channels are used. - *$ + *

This is a global setting for all channels. The maximum rate is 500kS/s divided by the number + * of channels in use. This is 62500 samples/s per channel if all 8 channels are used. + * * @param samplesPerSecond The number of samples per second. */ public static void setGlobalSampleRate(final double samplesPerSecond) { @@ -359,8 +340,7 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Get the current sample rate. * - * This assumes one entry in the scan list. This is a global setting for all - * channels. + *

This assumes one entry in the scan list. This is a global setting for all channels. * * @return Sample rate. */ @@ -368,25 +348,22 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend return AnalogJNI.getAnalogSampleRate(); } - /** - * {@inheritDoc} - */ + @Override public void setPIDSourceType(PIDSourceType pidSource) { m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_pidSource; } /** - * Get the average voltage for use with PIDController + * Get the average voltage for use with PIDController. * * @return the average voltage */ + @Override public double pidGet() { return getAverageVoltage(); } @@ -394,45 +371,42 @@ public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSend /** * Live Window code, only does anything if live window is activated. */ + @Override public String getSmartDashboardType() { return "Analog Input"; } private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", getAverageVoltage()); } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } /** - * Analog Channels don't have to do anything special when entering the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when entering the LiveWindow. {@inheritDoc} */ - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } /** - * Analog Channels don't have to do anything special when exiting the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when exiting the LiveWindow. {@inheritDoc} */ - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogOutput.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogOutput.java index 0c9767040a..101daace9f 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogOutput.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogOutput.java @@ -38,12 +38,12 @@ public class AnalogOutput extends SensorBase implements LiveWindowSendable { } try { channels.allocate(channel); - } catch (CheckedAllocationException e) { + } catch (CheckedAllocationException ex) { throw new AllocationException("Analog output channel " + m_channel + " is already allocated"); } - long port_pointer = AnalogJNI.getPort((byte) channel); - m_port = AnalogJNI.initializeAnalogOutputPort(port_pointer); + final long portPointer = AnalogJNI.getPort((byte) channel); + m_port = AnalogJNI.initializeAnalogOutputPort(portPointer); LiveWindow.addSensor("AnalogOutput", channel, this); UsageReporting.report(tResourceType.kResourceType_AnalogOutput, channel); @@ -70,45 +70,42 @@ public class AnalogOutput extends SensorBase implements LiveWindowSendable { /* * Live Window code, only does anything if live window is activated. */ + @Override public String getSmartDashboardType() { return "Analog Output"; } private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", getVoltage()); } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } /** - * Analog Channels don't have to do anything special when entering the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when entering the LiveWindow. {@inheritDoc} */ - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } /** - * Analog Channels don't have to do anything special when exiting the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when exiting the LiveWindow. {@inheritDoc} */ - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java index b4dfdbe01f..5e896623a8 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java @@ -7,104 +7,85 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteBuffer; -import java.nio.IntBuffer; - -import edu.wpi.first.wpilibj.hal.HALUtil; -import edu.wpi.first.wpilibj.hal.PowerJNI; import edu.wpi.first.wpilibj.interfaces.Potentiometer; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class for reading analog potentiometers. Analog potentiometers read in an - * analog voltage that corresponds to a position. The position is in whichever - * units you choose, by way of the scaling and offset constants passed to the - * constructor. + * Class for reading analog potentiometers. Analog potentiometers read in an analog voltage that + * corresponds to a position. The position is in whichever units you choose, by way of the scaling + * and offset constants passed to the constructor. * * @author Alex Henning * @author Colby Skeggs (rail voltage) */ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { - private double m_fullRange, m_offset; - private AnalogInput m_analog_input; - private boolean m_init_analog_input; + private double m_fullRange; + private double m_offset; + private AnalogInput m_analogInput; + private boolean m_initAnalogInput; protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement; /** * Common initialization code called by all constructors. - *$ - * @param input The {@link AnalogInput} this potentiometer is plugged into. - * @param fullRange The scaling to multiply the voltage by to get a meaningful - * unit. - * @param offset The offset to add to the scaled value for controlling the - * zero value + * + * @param input The {@link AnalogInput} this potentiometer is plugged into. + * @param fullRange The scaling to multiply the voltage by to get a meaningful unit. + * @param offset The offset to add to the scaled value for controlling the zero value */ private void initPot(final AnalogInput input, double fullRange, double offset) { - this.m_fullRange = fullRange; - this.m_offset = offset; - m_analog_input = input; + m_fullRange = fullRange; + m_offset = offset; + m_analogInput = input; } /** * AnalogPotentiometer constructor. * - * Use the fullRange and offset values so that the output produces meaningful - * values. I.E: you have a 270 degree potentiometer and you want the output to - * be degrees with the halfway point as 0 degrees. The fullRange value is - * 270.0(degrees) and the offset is -135.0 since the halfway point after - * scaling is 135 degrees. - *$ - * This will calculate the result from the fullRange times the fraction of the - * supply voltage, plus the offset. + *

Use the fullRange and offset values so that the output produces meaningful values. I.E: you + * have a 270 degree potentiometer and you want the output to be degrees with the halfway point as + * 0 degrees. The fullRange value is 270.0(degrees) and the offset is -135.0 since the halfway + * point after scaling is 135 degrees. This will calculate the result from the fullRange times + * the fraction of the supply voltage, plus the offset. * - * @param channel The analog channel this potentiometer is plugged into. - * @param fullRange The scaling to multiply the fraction by to get a - * meaningful unit. - * @param offset The offset to add to the scaled value for controlling the - * zero value + * @param channel The analog channel this potentiometer is plugged into. + * @param fullRange The scaling to multiply the fraction by to get a meaningful unit. + * @param offset The offset to add to the scaled value for controlling the zero value */ public AnalogPotentiometer(final int channel, double fullRange, double offset) { AnalogInput input = new AnalogInput(channel); - m_init_analog_input = true; + m_initAnalogInput = true; initPot(input, fullRange, offset); } /** * AnalogPotentiometer constructor. * - * Use the fullRange and offset values so that the output produces meaningful - * values. I.E: you have a 270 degree potentiometer and you want the output to - * be degrees with the halfway point as 0 degrees. The fullRange value is - * 270.0(degrees) and the offset is -135.0 since the halfway point after - * scaling is 135 degrees. - *$ - * This will calculate the result from the fullRange times the fraction of the - * supply voltage, plus the offset. + *

Use the fullRange and offset values so that the output produces meaningful values. I.E: you + * have a 270 degree potentiometer and you want the output to be degrees with the halfway point as + * 0 degrees. The fullRange value is 270.0(degrees) and the offset is -135.0 since the halfway + * point after scaling is 135 degrees. This will calculate the result from the fullRange times + * the fraction of the supply voltage, plus the offset. * - * @param input The {@link AnalogInput} this potentiometer is plugged into. - * @param fullRange The scaling to multiply the fraction by to get a - * meaningful unit. - * @param offset The offset to add to the scaled value for controlling the - * zero value + * @param input The {@link AnalogInput} this potentiometer is plugged into. + * @param fullRange The scaling to multiply the fraction by to get a meaningful unit. + * @param offset The offset to add to the scaled value for controlling the zero value */ public AnalogPotentiometer(final AnalogInput input, double fullRange, double offset) { - m_init_analog_input = false; + m_initAnalogInput = false; initPot(input, fullRange, offset); } /** * AnalogPotentiometer constructor. * - * Use the fullRange and offset values so that the output produces meaningful - * values. I.E: you have a 270 degree potentiometer and you want the output to - * be degrees with the halfway point as 0 degrees. The fullRange value is - * 270.0(degrees) and the offset is -135.0 since the halfway point after - * scaling is 135 degrees. + *

Use the fullRange and offset values so that the output produces meaningful values. I.E: you + * have a 270 degree potentiometer and you want the output to be degrees with the halfway point as + * 0 degrees. The fullRange value is 270.0(degrees) and the offset is -135.0 since the halfway + * point after scaling is 135 degrees. * * @param channel The analog channel this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful - * unit. + * @param scale The scaling to multiply the voltage by to get a meaningful unit. */ public AnalogPotentiometer(final int channel, double scale) { this(channel, scale, 0); @@ -113,15 +94,13 @@ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { /** * AnalogPotentiometer constructor. * - * Use the fullRange and offset values so that the output produces meaningful - * values. I.E: you have a 270 degree potentiometer and you want the output to - * be degrees with the halfway point as 0 degrees. The fullRange value is - * 270.0(degrees) and the offset is -135.0 since the halfway point after - * scaling is 135 degrees. + *

Use the fullRange and offset values so that the output produces meaningful values. I.E: you + * have a 270 degree potentiometer and you want the output to be degrees with the halfway point as + * 0 degrees. The fullRange value is 270.0(degrees) and the offset is -135.0 since the halfway + * point after scaling is 135 degrees. * * @param input The {@link AnalogInput} this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful - * unit. + * @param scale The scaling to multiply the voltage by to get a meaningful unit. */ public AnalogPotentiometer(final AnalogInput input, double scale) { this(input, scale, 0); @@ -150,13 +129,12 @@ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { * * @return The current position of the potentiometer. */ + @Override public double get() { - return (m_analog_input.getVoltage() / ControllerPower.getVoltage5V()) * m_fullRange + m_offset; + return (m_analogInput.getVoltage() / ControllerPower.getVoltage5V()) * m_fullRange + m_offset; } - /** - * {@inheritDoc} - */ + @Override public void setPIDSourceType(PIDSourceType pidSource) { if (!pidSource.equals(PIDSourceType.kDisplacement)) { throw new IllegalArgumentException("Only displacement PID is allowed for potentiometers."); @@ -164,9 +142,7 @@ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_pidSource; } @@ -176,6 +152,7 @@ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { * * @return The current reading. */ + @Override public double pidGet() { return get(); } @@ -184,53 +161,53 @@ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { /** * Live Window code, only does anything if live window is activated. */ + @Override public String getSmartDashboardType() { return "Analog Input"; } private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", get()); } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } + /** + * Frees this resource. + */ public void free() { - if (m_init_analog_input) { - m_analog_input.free(); - m_analog_input = null; - m_init_analog_input = false; + if (m_initAnalogInput) { + m_analogInput.free(); + m_analogInput = null; + m_initAnalogInput = false; } } /** - * Analog Channels don't have to do anything special when entering the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when entering the LiveWindow. {@inheritDoc} */ - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } /** - * Analog Channels don't have to do anything special when exiting the - * LiveWindow. {@inheritDoc} + * Analog Channels don't have to do anything special when exiting the LiveWindow. {@inheritDoc} */ - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTrigger.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTrigger.java index 37c3e64d33..11fab0a64a 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTrigger.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTrigger.java @@ -7,32 +7,31 @@ package edu.wpi.first.wpilibj; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + import edu.wpi.first.wpilibj.AnalogTriggerOutput.AnalogTriggerType; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.hal.AnalogJNI; import edu.wpi.first.wpilibj.util.BoundaryException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; - // import com.sun.jna.Pointer; /** - * Class for creating and configuring Analog Triggers + * Class for creating and configuring Analog Triggers. * * @author dtjones */ public class AnalogTrigger { /** - * Exceptions dealing with improper operation of the Analog trigger + * Exceptions dealing with improper operation of the Analog trigger. */ public class AnalogTriggerException extends RuntimeException { /** - * Create a new exception with the given message + * Create a new exception with the given message. * * @param message the message to pass with the exception */ @@ -43,7 +42,7 @@ public class AnalogTrigger { } /** - * Where the analog trigger is attached + * Where the analog trigger is attached. */ protected long m_port; protected int m_index; @@ -54,12 +53,12 @@ public class AnalogTrigger { * @param channel the port to use for the analog trigger */ protected void initTrigger(final int channel) { - long port_pointer = AnalogJNI.getPort((byte) channel); + final long portPointer = AnalogJNI.getPort((byte) channel); ByteBuffer index = ByteBuffer.allocateDirect(4); index.order(ByteOrder.LITTLE_ENDIAN); m_port = - AnalogJNI.initializeAnalogTrigger(port_pointer, index.asIntBuffer()); + AnalogJNI.initializeAnalogTrigger(portPointer, index.asIntBuffer()); m_index = index.asIntBuffer().get(0); UsageReporting.report(tResourceType.kResourceType_AnalogTrigger, channel); @@ -68,17 +67,16 @@ public class AnalogTrigger { /** * Constructor for an analog trigger given a channel number. * - * @param channel the port to use for the analog trigger 0-3 are on-board, 4-7 - * are on the MXP port + * @param channel the port to use for the analog trigger 0-3 are on-board, 4-7 are on the MXP + * port */ public AnalogTrigger(final int channel) { initTrigger(channel); } /** - * Construct an analog trigger given an analog channel. This should be used in - * the case of sharing an analog channel between the trigger and an analog - * input object. + * Construct an analog trigger given an analog channel. This should be used in the case of sharing + * an analog channel between the trigger and an analog input object. * * @param channel the AnalogInput to use for the analog trigger */ @@ -90,7 +88,7 @@ public class AnalogTrigger { } /** - * Release the resources used by this object + * Release the resources used by this object. */ public void free() { AnalogJNI.cleanAnalogTrigger(m_port); @@ -98,9 +96,8 @@ public class AnalogTrigger { } /** - * Set the upper and lower limits of the analog trigger. The limits are given - * in ADC codes. If oversampling is used, the units must be scaled - * appropriately. + * Set the upper and lower limits of the analog trigger. The limits are given in ADC codes. If + * oversampling is used, the units must be scaled appropriately. * * @param lower the lower raw limit * @param upper the upper raw limit @@ -113,8 +110,8 @@ public class AnalogTrigger { } /** - * Set the upper and lower limits of the analog trigger. The limits are given - * as floating point voltage values. + * Set the upper and lower limits of the analog trigger. The limits are given as floating point + * voltage values. * * @param lower the lower voltage limit * @param upper the upper voltage limit @@ -127,9 +124,8 @@ public class AnalogTrigger { } /** - * Configure the analog trigger to use the averaged vs. raw values. If the - * value is true, then the averaged value is selected for the analog trigger, - * otherwise the immediate value is used. + * Configure the analog trigger to use the averaged vs. raw values. If the value is true, then the + * averaged value is selected for the analog trigger, otherwise the immediate value is used. * * @param useAveragedValue true to use an averaged value, false otherwise */ @@ -138,10 +134,9 @@ public class AnalogTrigger { } /** - * Configure the analog trigger to use a filtered value. The analog trigger - * will operate with a 3 point average rejection filter. This is designed to - * help with 360 degree pot applications for the period where the pot crosses - * through zero. + * Configure the analog trigger to use a filtered value. The analog trigger will operate with a 3 + * point average rejection filter. This is designed to help with 360 degree pot applications for + * the period where the pot crosses through zero. * * @param useFilteredValue true to use a filterd value, false otherwise */ @@ -150,8 +145,8 @@ public class AnalogTrigger { } /** - * Return the index of the analog trigger. This is the FPGA index of this - * analog trigger instance. + * Return the index of the analog trigger. This is the FPGA index of this analog trigger + * instance. * * @return The index of the analog trigger. */ @@ -160,8 +155,8 @@ public class AnalogTrigger { } /** - * Return the InWindow output of the analog trigger. True if the analog input - * is between the upper and lower limits. + * Return the InWindow output of the analog trigger. True if the analog input is between the upper + * and lower limits. * * @return The InWindow output of the analog trigger. */ @@ -170,9 +165,8 @@ public class AnalogTrigger { } /** - * Return the TriggerState output of the analog trigger. True if above upper - * limit. False if below lower limit. If in Hysteresis, maintain previous - * state. + * Return the TriggerState output of the analog trigger. True if above upper limit. False if below + * lower limit. If in Hysteresis, maintain previous state. * * @return The TriggerState output of the analog trigger. */ @@ -181,9 +175,8 @@ public class AnalogTrigger { } /** - * Creates an AnalogTriggerOutput object. Gets an output object that can be - * used for routing. Caller is responsible for deleting the - * AnalogTriggerOutput object. + * Creates an AnalogTriggerOutput object. Gets an output object that can be used for routing. + * Caller is responsible for deleting the AnalogTriggerOutput object. * * @param type An enum of the type of output object to create. * @return A pointer to a new AnalogTriggerOutput object. diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java index a006c089cf..84dcca66da 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java @@ -11,47 +11,41 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tReso import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.hal.AnalogJNI; -import java.nio.IntBuffer; - /** - * Class to represent a specific output from an analog trigger. This class is - * used to get the current output value and also as a DigitalSource to provide - * routing of an output to digital subsystems on the FPGA such as Counter, - * Encoder, and Interrupt. + * Class to represent a specific output from an analog trigger. This class is used to get the + * current output value and also as a DigitalSource to provide routing of an output to digital + * subsystems on the FPGA such as Counter, Encoder, and Interrupt. * - * The TriggerState output indicates the primary output value of the trigger. If - * the analog signal is less than the lower limit, the output is false. If the - * analog value is greater than the upper limit, then the output is true. If the - * analog value is in between, then the trigger output state maintains its most - * recent value. + *

The TriggerState output indicates the primary output value of the trigger. If the analog + * signal is less than the lower limit, the output is false. If the analog value is greater than the + * upper limit, then the output is true. If the analog value is in between, then the trigger output + * state maintains its most recent value. * - * The InWindow output indicates whether or not the analog signal is inside the - * range defined by the limits. + *

The InWindow output indicates whether or not the analog signal is inside the range defined by + * the limits. * - * The RisingPulse and FallingPulse outputs detect an instantaneous transition - * from above the upper limit to below the lower limit, and vise versa. These - * pulses represent a rollover condition of a sensor and can be routed to an up - * / down couter or to interrupts. Because the outputs generate a pulse, they - * cannot be read directly. To help ensure that a rollover condition is not - * missed, there is an average rejection filter available that operates on the - * upper 8 bits of a 12 bit number and selects the nearest outlyer of 3 samples. - * This will reject a sample that is (due to averaging or sampling) errantly - * between the two limits. This filter will fail if more than one sample in a - * row is errantly in between the two limits. You may see this problem if - * attempting to use this feature with a mechanical rollover sensor, such as a - * 360 degree no-stop potentiometer without signal conditioning, because the - * rollover transition is not sharp / clean enough. Using the averaging engine - * may help with this, but rotational speeds of the sensor will then be limited. + *

The RisingPulse and FallingPulse outputs detect an instantaneous transition from above the + * upper limit to below the lower limit, and vise versa. These pulses represent a rollover condition + * of a sensor and can be routed to an up / down couter or to interrupts. Because the outputs + * generate a pulse, they cannot be read directly. To help ensure that a rollover condition is not + * missed, there is an average rejection filter available that operates on the upper 8 bits of a 12 + * bit number and selects the nearest outlyer of 3 samples. This will reject a sample that is (due + * to averaging or sampling) errantly between the two limits. This filter will fail if more than one + * sample in a row is errantly in between the two limits. You may see this problem if attempting to + * use this feature with a mechanical rollover sensor, such as a 360 degree no-stop potentiometer + * without signal conditioning, because the rollover transition is not sharp / clean enough. Using + * the averaging engine may help with this, but rotational speeds of the sensor will then be + * limited. */ public class AnalogTriggerOutput extends DigitalSource { /** - * Exceptions dealing with improper operation of the Analog trigger output + * Exceptions dealing with improper operation of the Analog trigger output. */ public class AnalogTriggerOutputException extends RuntimeException { /** - * Create a new exception with the given message + * Create a new exception with the given message. * * @param message the message to pass with the exception */ @@ -65,26 +59,26 @@ public class AnalogTriggerOutput extends DigitalSource { private final AnalogTriggerType m_outputType; /** - * Create an object that represents one of the four outputs from an analog - * trigger. + * Create an object that represents one of the four outputs from an analog trigger. * - * Because this class derives from DigitalSource, it can be passed into - * routing functions for Counter, Encoder, etc. + *

Because this class derives from DigitalSource, it can be passed into routing functions for + * Counter, Encoder, etc. * - * @param trigger The trigger for which this is an output. - * @param outputType An enum that specifies the output on the trigger to - * represent. + * @param trigger The trigger for which this is an output. + * @param outputType An enum that specifies the output on the trigger to represent. */ public AnalogTriggerOutput(AnalogTrigger trigger, final AnalogTriggerType outputType) { - if (trigger == null) + if (trigger == null) { throw new NullPointerException("Analog Trigger given was null"); - if (outputType == null) + } + if (outputType == null) { throw new NullPointerException("Analog Trigger Type given was null"); + } m_trigger = trigger; m_outputType = outputType; UsageReporting.report(tResourceType.kResourceType_AnalogTriggerOutput, trigger.getIndex(), - outputType.value); + outputType.m_value); } @Override @@ -98,12 +92,12 @@ public class AnalogTriggerOutput extends DigitalSource { * @return The state of the analog trigger output. */ public boolean get() { - return AnalogJNI.getAnalogTriggerOutput(m_trigger.m_port, m_outputType.value); + return AnalogJNI.getAnalogTriggerOutput(m_trigger.m_port, m_outputType.m_value); } @Override public int getChannelForRouting() { - return (m_trigger.m_index << 2) + m_outputType.value; + return (m_trigger.m_index << 2) + m_outputType.m_value; } @Override @@ -117,19 +111,19 @@ public class AnalogTriggerOutput extends DigitalSource { } /** - * Defines the state in which the AnalogTrigger triggers - *$ + * Defines the state in which the AnalogTrigger triggers. + * * @author jonathanleitschuh */ public enum AnalogTriggerType { - kInWindow(AnalogJNI.AnalogTriggerType.kInWindow), kState(AnalogJNI.AnalogTriggerType.kState), kRisingPulse( - AnalogJNI.AnalogTriggerType.kRisingPulse), kFallingPulse( - AnalogJNI.AnalogTriggerType.kFallingPulse); + kInWindow(AnalogJNI.AnalogTriggerType.kInWindow), kState(AnalogJNI.AnalogTriggerType.kState), + kRisingPulse(AnalogJNI.AnalogTriggerType.kRisingPulse), + kFallingPulse(AnalogJNI.AnalogTriggerType.kFallingPulse); - private final int value; + private final int m_value; - private AnalogTriggerType(int value) { - this.value = value; + AnalogTriggerType(int value) { + m_value = value; } } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java index b00778e329..64bf9738ba 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java @@ -7,10 +7,10 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.interfaces.Accelerometer; -import edu.wpi.first.wpilibj.hal.AccelerometerJNI; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; +import edu.wpi.first.wpilibj.hal.AccelerometerJNI; +import edu.wpi.first.wpilibj.interfaces.Accelerometer; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; @@ -18,12 +18,12 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * Built-in accelerometer. * - * This class allows access to the RoboRIO's internal accelerometer. + *

This class allows access to the RoboRIO's internal accelerometer. */ public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { /** * Constructor. - *$ + * * @param range The range the accelerometer will measure */ public BuiltInAccelerometer(Range range) { @@ -40,7 +40,6 @@ public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { this(Range.k8G); } - /** {inheritdoc} */ @Override public void setRange(Range range) { AccelerometerJNI.setAccelerometerActive(false); @@ -56,13 +55,17 @@ public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { AccelerometerJNI.setAccelerometerRange(2); break; case k16G: - throw new RuntimeException("16G range not supported (use k2G, k4G, or k8G)"); + default: + throw new IllegalArgumentException(range + " range not supported (use k2G, k4G, or k8G)"); + } AccelerometerJNI.setAccelerometerActive(true); } /** + * The acceleration in the X axis. + * * @return The acceleration of the RoboRIO along the X axis in g-forces */ @Override @@ -71,6 +74,8 @@ public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { } /** + * The acceleration in the Y axis. + * * @return The acceleration of the RoboRIO along the Y axis in g-forces */ @Override @@ -79,6 +84,8 @@ public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { } /** + * The acceleration in the Z axis. + * * @return The acceleration of the RoboRIO along the Z axis in g-forces */ @Override @@ -86,19 +93,20 @@ public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { return AccelerometerJNI.getAccelerometerZ(); } + @Override public String getSmartDashboardType() { return "3AxisAccelerometer"; } private ITable m_table; - /** {@inheritDoc} */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** {@inheritDoc} */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("X", getX()); @@ -107,12 +115,16 @@ public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { } } - /** {@inheritDoc} */ + @Override public ITable getTable() { return m_table; } - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } - public void stopLiveWindowMode() {} -}; + @Override + public void stopLiveWindowMode() { + } +} diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANJaguar.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANJaguar.java index cabcaba6fe..7dab0d8974 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANJaguar.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANJaguar.java @@ -19,7 +19,7 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Texas Instruments Jaguar Speed Controller as a CAN device. - *$ + * * @author Thomas Clark */ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { @@ -39,33 +39,33 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // Control Mode tags private static class EncoderTag { - }; + } /** - * Sets an encoder as the speed reference only.
- * Passed as the "tag" when setting the control mode. + * Sets an encoder as the speed reference only.
Passed as the "tag" when setting the control + * mode. */ - public final static EncoderTag kEncoder = new EncoderTag(); + public static final EncoderTag kEncoder = new EncoderTag(); private static class QuadEncoderTag { - }; + } /** - * Sets a quadrature encoder as the position and speed reference.
- * Passed as the "tag" when setting the control mode. + * Sets a quadrature encoder as the position and speed reference.
Passed as the "tag" when + * setting the control mode. */ - public final static QuadEncoderTag kQuadEncoder = new QuadEncoderTag(); + public static final QuadEncoderTag kQuadEncoder = new QuadEncoderTag(); private static class PotentiometerTag { - }; + } /** - * Sets a potentiometer as the position reference only.
- * Passed as the "tag" when setting the control mode. + * Sets a potentiometer as the position reference only.
Passed as the "tag" when setting the + * control mode. */ - public final static PotentiometerTag kPotentiometer = new PotentiometerTag(); + public static final PotentiometerTag kPotentiometer = new PotentiometerTag(); - private boolean isInverted = false; + private boolean m_isInverted = false; /** * Mode determines how the Jaguar is controlled, used internally. @@ -75,12 +75,12 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { @Override public boolean isPID() { - return this == Current || this == Speed || this == Position; + return this == Current || this == Speed || this == Position; } @Override public int getValue() { - return ordinal(); + return ordinal(); } } @@ -91,7 +91,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { public static final int kGateDriverFault = 8; /** - * Limit switch masks + * Limit switch masks. */ public static final int kForwardLimit = 1; public static final int kReverseLimit = 2; @@ -100,18 +100,24 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * Determines how the Jaguar behaves when sending a zero signal. */ public enum NeutralMode { - /** Use the NeutralMode that is set by the jumper wire on the CAN device */ + /** + * Use the NeutralMode that is set by the jumper wire on the CAN device. + */ Jumper((byte) 0), - /** Stop the motor's rotation by applying a force. */ + /** + * Stop the motor's rotation by applying a force. + */ Brake((byte) 1), /** - * Do not attempt to stop the motor. Instead allow it to coast to a stop - * without applying resistance. + * Do not attempt to stop the motor. Instead allow it to coast to a stop without applying + * resistance. */ Coast((byte) 2); - public byte value; + @SuppressWarnings("MemberName") + public final byte value; + @SuppressWarnings("JavadocMethod") public static NeutralMode valueOf(byte value) { for (NeutralMode mode : values()) { if (mode.value == value) { @@ -122,36 +128,36 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { return null; } - private NeutralMode(byte value) { + NeutralMode(byte value) { this.value = value; } } /** - * Determines which sensor to use for position reference. Limit switches will - * always be used to limit the rotation. This can not be disabled. + * Determines which sensor to use for position reference. Limit switches will always be used to + * limit the rotation. This can not be disabled. */ public enum LimitMode { /** - * Disables the soft position limits and only uses the limit switches to - * limit rotation. - *$ + * Disables the soft position limits and only uses the limit switches to limit rotation. + * * @see CANJaguar#getForwardLimitOK() * @see CANJaguar#getReverseLimitOK() */ SwitchInputsOnly((byte) 0), /** - * Enables the soft position limits on the Jaguar. These will be used in - * addition to the limit switches. This does not disable the behavior of the - * limit switch input. - *$ + * Enables the soft position limits on the Jaguar. These will be used in addition to the limit + * switches. This does not disable the behavior of the limit switch input. + * * @see CANJaguar#configSoftPositionLimits(double, double) */ SoftPositionLimits((byte) 1); - public byte value; + @SuppressWarnings("MemberName") + public final byte value; + @SuppressWarnings("JavadocMethod") public static LimitMode valueOf(byte value) { for (LimitMode mode : values()) { if (mode.value == value) { @@ -162,15 +168,14 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { return null; } - private LimitMode(byte value) { + LimitMode(byte value) { this.value = value; } } /** - * Constructor for the CANJaguar device.
- * By default the device is configured in Percent mode. The control mode can - * be changed by calling one of the control modes listed below. + * Constructor for the CANJaguar device.
By default the device is configured in Percent mode. + * The control mode can be changed by calling one of the control modes listed below. * * @param deviceNumber The address of the Jaguar on the CAN bus. * @see CANJaguar#setCurrentMode(double, double, double) @@ -222,7 +227,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { getMessage(CANJNI.CAN_MSGID_API_FIRMVER, CANJNI.CAN_MSGID_FULL_M, data); m_firmwareVersion = unpackINT32(data); receivedFirmwareVersion = true; - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { + // no-op } } @@ -242,7 +248,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { try { getMessage(CANJNI.LM_API_HWVER, CANJNI.CAN_MSGID_FULL_M, data); m_hardwareVersion = data[0]; - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Not all Jaguar firmware reports a hardware version. m_hardwareVersion = 0; } @@ -259,7 +265,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { + m_deviceNumber + " firmware " + m_firmwareVersion - + " is not FIRST approved (must be at least version 108 of the FIRST approved firmware)", + + " is not FIRST approved (must be at least version 108 of the FIRST approved" + + " firmware)", false); } return; @@ -267,8 +274,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Cancel periodic messages to the Jaguar, effectively disabling it. No other - * methods should be called after this is called. + * Cancel periodic messages to the Jaguar, effectively disabling it. No other methods should be + * called after this is called. */ public void free() { allocated.free(m_deviceNumber - 1); @@ -309,6 +316,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** + * The CAN ID. + * * @return The CAN ID passed in the constructor */ int getDeviceNumber() { @@ -318,13 +327,10 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Get the recently set outputValue set point. * - * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus mode, the outputValue is from -1.0 to 1.0 (same as PWM - * Jaguar).
- * In voltage mode, the outputValue is in volts.
- * In current mode, the outputValue is in amps.
- * In speed mode, the outputValue is in rotations/minute.
- * In position mode, the outputValue is in rotations.
+ *

The scale and the units depend on the mode the Jaguar is in.
In percentVbus mode, the + * outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
In voltage mode, the outputValue is + * in volts.
In current mode, the outputValue is in amps.
In speed mode, the outputValue + * is in rotations/minute.
In position mode, the outputValue is in rotations.
* * @return The most recently set outputValue set point. */ @@ -344,8 +350,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Get the difference between the setpoint and goal in closed loop modes. * - * Outside of position and velocity modes the return value of getError() has - * relatively little meaning. + *

Outside of position and velocity modes the return value of getError() has relatively little + * meaning. * * @return The difference between the setpoint and the current position. */ @@ -357,17 +363,14 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Sets the output set-point value. * - * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus Mode, the outputValue is from -1.0 to 1.0 (same as PWM - * Jaguar).
- * In voltage Mode, the outputValue is in volts.
- * In current Mode, the outputValue is in amps.
- * In speed mode, the outputValue is in rotations/minute.
- * In position Mode, the outputValue is in rotations. + *

The scale and the units depend on the mode the Jaguar is in.
In percentVbus Mode, the + * outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
In voltage Mode, the outputValue is + * in volts.
In current Mode, the outputValue is in amps.
In speed mode, the outputValue + * is in rotations/minute.
In position Mode, the outputValue is in rotations. * * @param outputValue The set-point to sent to the motor controller. - * @param syncGroup The update group to add this set() to, pending - * UpdateSyncGroup(). If 0, update immediately. + * @param syncGroup The update group to add this set() to, pending UpdateSyncGroup(). If 0, + * update immediately. */ @Override public void set(double outputValue, byte syncGroup) { @@ -375,8 +378,9 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { byte[] data = new byte[8]; byte dataSize; - if (m_safetyHelper != null) + if (m_safetyHelper != null) { m_safetyHelper.feed(); + } if (m_stopped) { enableControl(); @@ -387,12 +391,12 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { switch (m_controlMode) { case PercentVbus: messageID = CANJNI.LM_API_VOLT_T_SET; - dataSize = packPercentage(data, isInverted ? -outputValue : outputValue); + dataSize = packPercentage(data, m_isInverted ? -outputValue : outputValue); break; case Speed: messageID = CANJNI.LM_API_SPD_T_SET; - dataSize = packFXP16_16(data, isInverted ? -outputValue : outputValue); + dataSize = packFXP16_16(data, m_isInverted ? -outputValue : outputValue); break; case Position: @@ -408,7 +412,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { case Voltage: messageID = CANJNI.LM_API_VCOMP_T_SET; - dataSize = packFXP8_8(data, isInverted ? -outputValue : outputValue); + dataSize = packFXP8_8(data, m_isInverted ? -outputValue : outputValue); break; default: @@ -430,13 +434,10 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Sets the output set-point value. * - * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus mode, the outputValue is from -1.0 to 1.0 (same as PWM - * Jaguar).
- * In voltage mode, the outputValue is in volts.
- * In current mode, the outputValue is in amps.
- * In speed mode, the outputValue is in rotations/minute.
- * In position mode, the outputValue is in rotations. + *

The scale and the units depend on the mode the Jaguar is in.
In percentVbus mode, the + * outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
In voltage mode, the outputValue is + * in volts.
In current mode, the outputValue is in amps.
In speed mode, the outputValue + * is in rotations/minute.
In position mode, the outputValue is in rotations. * * @param value The set-point to sent to the motor controller. */ @@ -460,31 +461,29 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Inverts the direction of rotation of the motor Only works in percentVbus, - * Speed, and Voltage mode - *$ + * Inverts the direction of rotation of the motor Only works in percentVbus, Speed, and Voltage + * mode. + * * @param isInverted The state of inversion true is inverted */ @Override public void setInverted(boolean isInverted) { - this.isInverted = isInverted; + m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. * * @return isInverted The state of inversion, true is inverted. - * */ @Override public boolean getInverted() { - return this.isInverted; + return m_isInverted; } /** - * Check all unverified params and make sure they're equal to their local - * cached versions. If a value isn't available, it gets requested. If a value - * doesn't match up, it gets set again. + * Check all unverified params and make sure they're equal to their local cached versions. If a + * value isn't available, it gets requested. If a value doesn't match up, it gets set again. */ protected void verify() { byte[] data = new byte[8]; @@ -512,7 +511,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { m_maxOutputVoltageVerified = false; m_faultTimeVerified = false; - if (m_controlMode == JaguarControlMode.PercentVbus || m_controlMode == JaguarControlMode.Voltage) { + if (m_controlMode == JaguarControlMode.PercentVbus + || m_controlMode == JaguarControlMode.Voltage) { m_voltageRampRateVerified = false; } else { m_pVerified = false; @@ -528,7 +528,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // Remove any old values from netcomms. Otherwise, parameters // are incorrectly marked as verified based on stale messages. int[] messages = - new int[] {CANJNI.LM_API_SPD_REF, CANJNI.LM_API_POS_REF, CANJNI.LM_API_SPD_PC, + new int[]{CANJNI.LM_API_SPD_REF, CANJNI.LM_API_POS_REF, CANJNI.LM_API_SPD_PC, CANJNI.LM_API_POS_PC, CANJNI.LM_API_ICTRL_PC, CANJNI.LM_API_SPD_IC, CANJNI.LM_API_POS_IC, CANJNI.LM_API_ICTRL_IC, CANJNI.LM_API_SPD_DC, CANJNI.LM_API_POS_DC, CANJNI.LM_API_ICTRL_DC, CANJNI.LM_API_CFG_ENC_LINES, @@ -541,11 +541,12 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { for (int message : messages) { try { getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { + // no-op } } } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { requestMessage(CANJNI.LM_API_STATUS_POWER); } @@ -562,7 +563,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // Enable control again to resend the control mode enableControl(); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_STATUS_CMODE); } @@ -580,7 +581,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again setSpeedReference(m_speedReference); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_SPD_REF); } @@ -598,7 +599,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again setPositionReference(m_positionReference); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_POS_REF); } @@ -627,15 +628,15 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { try { getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - double p = unpackFXP16_16(data); + double punpacked = unpackFXP16_16(data); - if (FXP16_EQ(m_p, p)) { + if (FXP16_EQ(m_p, punpacked)) { m_pVerified = true; } else { // It's wrong - set it again setP(m_p); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(message); } @@ -664,15 +665,15 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { try { getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - double i = unpackFXP16_16(data); + double iunpacked = unpackFXP16_16(data); - if (FXP16_EQ(m_i, i)) { + if (FXP16_EQ(m_i, iunpacked)) { m_iVerified = true; } else { // It's wrong - set it again setI(m_i); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(message); } @@ -701,15 +702,15 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { try { getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - double d = unpackFXP16_16(data); + double dunpacked = unpackFXP16_16(data); - if (FXP16_EQ(m_d, d)) { + if (FXP16_EQ(m_d, dunpacked)) { m_dVerified = true; } else { // It's wrong - set it again setD(m_d); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(message); } @@ -727,7 +728,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again configNeutralMode(m_neutralMode); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_BRAKE_COAST); } @@ -745,7 +746,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again configEncoderCodesPerRev(m_encoderCodesPerRev); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_ENC_LINES); } @@ -763,7 +764,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again configPotentiometerTurns(m_potentiometerTurns); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_POT_TURNS); } @@ -781,7 +782,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again configLimitMode(m_limitMode); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_LIMIT_MODE); } @@ -799,7 +800,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again configForwardLimit(m_forwardLimit); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_LIMIT_FWD); } @@ -817,7 +818,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again configReverseLimit(m_reverseLimit); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_LIMIT_REV); } @@ -839,7 +840,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { configMaxOutputVoltage(m_maxOutputVoltage); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_MAX_VOUT); } @@ -859,7 +860,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { setVoltageRampRate(m_voltageRampRate); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_VOLT_SET_RAMP); } @@ -877,7 +878,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { setVoltageRampRate(m_voltageRampRate); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_VCOMP_COMP_RAMP); } @@ -895,7 +896,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // It's wrong - set it again configFaultTime(m_faultTime); } - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { // Verification is needed but not available - request it again. requestMessage(CANJNI.LM_API_CFG_FAULT_TIME); } @@ -941,12 +942,12 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Set the reference source device for speed controller mode. * - * Choose encoder as the source of speed feedback when in speed control mode. + *

Choose encoder as the source of speed feedback when in speed control mode. * * @param reference Specify a speed reference. */ private void setSpeedReference(int reference) { - sendMessage(CANJNI.LM_API_SPD_REF, new byte[] {(byte) reference}, 1); + sendMessage(CANJNI.LM_API_SPD_REF, new byte[]{(byte) reference}, 1); m_speedReference = reference; m_speedRefVerified = false; @@ -955,13 +956,13 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Set the reference source device for position controller mode. * - * Choose between using and encoder and using a potentiometer as the source of - * position feedback when in position control mode. + *

Choose between using and encoder and using a potentiometer as the source of position + * feedback when in position control mode. * * @param reference Specify a position reference. */ private void setPositionReference(int reference) { - sendMessage(CANJNI.LM_API_POS_REF, new byte[] {(byte) reference}, 1); + sendMessage(CANJNI.LM_API_POS_REF, new byte[]{(byte) reference}, 1); m_positionReference = reference; m_posRefVerified = false; @@ -972,6 +973,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * * @param p The proportional gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setP(double p) { byte[] data = new byte[8]; byte dataSize = packFXP16_16(data, p); @@ -1003,6 +1005,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * * @param i The integral gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setI(double i) { byte[] data = new byte[8]; byte dataSize = packFXP16_16(data, i); @@ -1034,6 +1037,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * * @param d The derivative gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setD(double d) { byte[] data = new byte[8]; byte dataSize = packFXP16_16(data, d); @@ -1067,6 +1071,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setPID(double p, double i, double d) { setP(p); setI(i); @@ -1079,7 +1084,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * @return The proportional gain. */ public double getP() { - if (m_controlMode.equals(JaguarControlMode.PercentVbus) || m_controlMode.equals(JaguarControlMode.Voltage)) { + if (m_controlMode.equals(JaguarControlMode.PercentVbus) || m_controlMode.equals( + JaguarControlMode.Voltage)) { throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); } return m_p; @@ -1091,7 +1097,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * @return The integral gain. */ public double getI() { - if (m_controlMode.equals(JaguarControlMode.PercentVbus) || m_controlMode.equals(JaguarControlMode.Voltage)) { + if (m_controlMode.equals(JaguarControlMode.PercentVbus) || m_controlMode.equals( + JaguarControlMode.Voltage)) { throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); } return m_i; @@ -1103,7 +1110,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * @return The derivative gain. */ public double getD() { - if (m_controlMode.equals(JaguarControlMode.PercentVbus) || m_controlMode.equals(JaguarControlMode.Voltage)) { + if (m_controlMode.equals(JaguarControlMode.PercentVbus) || m_controlMode.equals( + JaguarControlMode.Voltage)) { throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); } return m_d; @@ -1112,12 +1120,12 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Enable the closed loop controller. * - * Start actually controlling the output based on the feedback. If starting a - * position controller with an encoder reference, use the - * encoderInitialPosition parameter to initialize the encoder state. + *

Start actually controlling the output based on the feedback. If starting a position + * controller with an encoder reference, use the encoderInitialPosition parameter to initialize + * the encoder state. * - * @param encoderInitialPosition Encoder position to set if position with - * encoder reference. Ignored otherwise. + * @param encoderInitialPosition Encoder position to set if position with encoder reference. + * Ignored otherwise. */ public void enableControl(double encoderInitialPosition) { switch (m_controlMode) { @@ -1142,6 +1150,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { case Voltage: sendMessage(CANJNI.LM_API_VCOMP_T_EN, new byte[0], 0); break; + default: + break; } m_controlEnabled = true; @@ -1150,8 +1160,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Enable the closed loop controller. * - * Start actually controlling the output based on the feedback. This is the - * same as calling + *

Start actually controlling the output based on the feedback. This is the same as calling * CANJaguar.enableControl(double encoderInitialPosition) with * encoderInitialPosition set to 0.0 */ @@ -1171,7 +1180,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Disable the closed loop controller. * - * Stop driving the output based on the feedback. + *

Stop driving the output based on the feedback. */ public void disableControl() { // Disable all control modes. @@ -1192,9 +1201,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage as a percentage of the bus voltage - * without any position or speed feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or + * Enable controlling the motor voltage as a percentage of the bus voltage without any position or + * speed feedback.
After calling this you must call {@link CANJaguar#enableControl()} or * {@link CANJaguar#enableControl(double)} to enable the device. */ public void setPercentMode() { @@ -1204,12 +1212,11 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage as a percentage of the bus voltage, - * and enable speed sensing from a non-quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor voltage as a percentage of the bus voltage, and enable speed + * sensing from a non-quadrature encoder.
After calling this you must call {@link + * CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. * - * @param tag The constant {@link CANJaguar#kEncoder} + * @param tag The constant {@link CANJaguar#kEncoder} * @param codesPerRev The counts per revolution on the encoder */ public void setPercentMode(EncoderTag tag, int codesPerRev) { @@ -1220,12 +1227,11 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage as a percentage of the bus voltage, - * and enable position and speed sensing from a quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor voltage as a percentage of the bus voltage, and enable position + * and speed sensing from a quadrature encoder.
After calling this you must call {@link + * CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. * - * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param tag The constant {@link CANJaguar#kQuadEncoder} * @param codesPerRev The counts per revolution on the encoder */ public void setPercentMode(QuadEncoderTag tag, int codesPerRev) { @@ -1236,10 +1242,9 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage as a percentage of the bus voltage, - * and enable position sensing from a potentiometer and no speed feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor voltage as a percentage of the bus voltage, and enable position + * sensing from a potentiometer and no speed feedback.
After calling this you must call {@link + * CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. * * @param tag The constant {@link CANJaguar#kPotentiometer} */ @@ -1251,14 +1256,15 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor current with a PID loop.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor current with a PID loop.
After calling this you must call + * {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the + * device. * * @param p The proportional gain of the Jaguar's PID controller. * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setCurrentMode(double p, double i, double d) { changeControlMode(JaguarControlMode.Current); setPositionReference(CANJNI.LM_REF_NONE); @@ -1267,16 +1273,16 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor current with a PID loop, and enable speed - * sensing from a non-quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor current with a PID loop, and enable speed sensing from a + * non-quadrature encoder.
After calling this you must call {@link CANJaguar#enableControl()} + * or {@link CANJaguar#enableControl(double)} to enable the device. * * @param tag The constant {@link CANJaguar#kEncoder} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setCurrentMode(EncoderTag tag, int codesPerRev, double p, double i, double d) { changeControlMode(JaguarControlMode.Current); setPositionReference(CANJNI.LM_REF_NONE); @@ -1286,16 +1292,16 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor current with a PID loop, and enable speed and - * position sensing from a quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor current with a PID loop, and enable speed and position sensing + * from a quadrature encoder.
After calling this you must call {@link + * CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. * * @param tag The constant {@link CANJaguar#kQuadEncoder} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setCurrentMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) { changeControlMode(JaguarControlMode.Current); setPositionReference(CANJNI.LM_REF_ENCODER); @@ -1305,16 +1311,16 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor current with a PID loop, and enable position - * sensing from a potentiometer.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor current with a PID loop, and enable position sensing from a + * potentiometer.
After calling this you must call {@link CANJaguar#enableControl()} or {@link + * CANJaguar#enableControl(double)} to enable the device. * * @param tag The constant {@link CANJaguar#kPotentiometer} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setCurrentMode(PotentiometerTag tag, double p, double i, double d) { changeControlMode(JaguarControlMode.Current); setPositionReference(CANJNI.LM_REF_POT); @@ -1324,17 +1330,17 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the speed with a feedback loop from a non-quadrature - * encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the speed with a feedback loop from a non-quadrature encoder.
After + * calling this you must call {@link CANJaguar#enableControl()} or {@link + * CANJaguar#enableControl(double)} to enable the device. * - * @param tag The constant {@link CANJaguar#kEncoder} + * @param tag The constant {@link CANJaguar#kEncoder} * @param codesPerRev The counts per revolution on the encoder - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setSpeedMode(EncoderTag tag, int codesPerRev, double p, double i, double d) { changeControlMode(JaguarControlMode.Speed); setPositionReference(CANJNI.LM_REF_NONE); @@ -1344,17 +1350,17 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the speed with a feedback loop from a quadrature - * encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the speed with a feedback loop from a quadrature encoder.
After calling + * this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} + * to enable the device. * - * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param tag The constant {@link CANJaguar#kQuadEncoder} * @param codesPerRev The counts per revolution on the encoder - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setSpeedMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) { changeControlMode(JaguarControlMode.Speed); setPositionReference(CANJNI.LM_REF_ENCODER); @@ -1364,17 +1370,17 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the position with a feedback loop using an encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the position with a feedback loop using an encoder.
After calling this + * you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to + * enable the device. * - * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param tag The constant {@link CANJaguar#kQuadEncoder} * @param codesPerRev The counts per revolution on the encoder - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - * + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setPositionMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) { changeControlMode(JaguarControlMode.Position); setPositionReference(CANJNI.LM_REF_ENCODER); @@ -1383,15 +1389,16 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the position with a feedback loop using a potentiometer.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the position with a feedback loop using a potentiometer.
After calling + * this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} + * to enable the device. * * @param tag The constant {@link CANJaguar#kPotentiometer} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. */ + @SuppressWarnings("ParameterName") public void setPositionMode(PotentiometerTag tag, double p, double i, double d) { changeControlMode(JaguarControlMode.Position); setPositionReference(CANJNI.LM_REF_POT); @@ -1400,10 +1407,9 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage without any position or speed - * feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor voltage without any position or speed feedback.
After calling + * this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} + * to enable the device. */ public void setVoltageMode() { changeControlMode(JaguarControlMode.Voltage); @@ -1412,12 +1418,11 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage with speed feedback from a - * non-quadrature encoder and no position feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or + * Enable controlling the motor voltage with speed feedback from a non-quadrature encoder and no + * position feedback.
After calling this you must call {@link CANJaguar#enableControl()} or * {@link CANJaguar#enableControl(double)} to enable the device. * - * @param tag The constant {@link CANJaguar#kEncoder} + * @param tag The constant {@link CANJaguar#kEncoder} * @param codesPerRev The counts per revolution on the encoder */ public void setVoltageMode(EncoderTag tag, int codesPerRev) { @@ -1428,12 +1433,11 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage with position and speed feedback from - * a quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or - * {@link CANJaguar#enableControl(double)} to enable the device. + * Enable controlling the motor voltage with position and speed feedback from a quadrature + * encoder.
After calling this you must call {@link CANJaguar#enableControl()} or {@link + * CANJaguar#enableControl(double)} to enable the device. * - * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param tag The constant {@link CANJaguar#kQuadEncoder} * @param codesPerRev The counts per revolution on the encoder */ public void setVoltageMode(QuadEncoderTag tag, int codesPerRev) { @@ -1444,8 +1448,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enable controlling the motor voltage with position feedback from a - * potentiometer and no speed feedback. + * Enable controlling the motor voltage with position feedback from a potentiometer and no speed + * feedback. * * @param tag The constant {@link CANJaguar#kPotentiometer} */ @@ -1457,16 +1461,14 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Used internally. In order to set the control mode see the methods listed - * below. + * Used internally. In order to set the control mode see the methods listed below. * - * Change the control mode of this Jaguar object. + *

Change the control mode of this Jaguar object. * - * After changing modes, configure any PID constants or other settings needed - * and then EnableControl() to actually change the mode on the Jaguar. + *

After changing modes, configure any PID constants or other settings needed and then + * EnableControl() to actually change the mode on the Jaguar. * * @param controlMode The new mode. - * * @see CANJaguar#setCurrentMode(double, double, double) * @see CANJaguar#setCurrentMode(PotentiometerTag, double, double, double) * @see CANJaguar#setCurrentMode(EncoderTag, int, double, double, double) @@ -1496,7 +1498,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Get the active control mode from the Jaguar. * - * Ask the Jagaur what mode it is in. + *

Ask the Jagaur what mode it is in. * * @return JaguarControlMode that the Jag is in. */ @@ -1505,7 +1507,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } public void setControlMode(int mode) { - changeControlMode(JaguarControlMode.values()[mode]); + changeControlMode(JaguarControlMode.values()[mode]); } /** @@ -1555,8 +1557,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Get the position of the encoder or potentiometer. * - * @return The position of the motor in rotations based on the configured - * feedback. + * @return The position of the motor in rotations based on the configured feedback. * @see CANJaguar#configPotentiometerTurns(int) * @see CANJaguar#configEncoderCodesPerRev(int) */ @@ -1617,12 +1618,10 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * set the maximum voltage change rate. * - * When in PercentVbus or Voltage output mode, the rate at which the voltage - * changes can be limited to reduce current spikes. set this to 0.0 to disable - * rate limiting. + *

When in PercentVbus or Voltage output mode, the rate at which the voltage changes can be + * limited to reduce current spikes. set this to 0.0 to disable rate limiting. * - * @param rampRate The maximum rate of voltage change in Percent Voltage mode - * in V/s. + * @param rampRate The maximum rate of voltage change in Percent Voltage mode in V/s. */ public void setVoltageRampRate(double rampRate) { byte[] data = new byte[8]; @@ -1665,16 +1664,14 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Configure what the controller does to the H-Bridge when neutral (not - * driving the output). + * Configure what the controller does to the H-Bridge when neutral (not driving the output). * - * This allows you to override the jumper configuration for brake or coast. + *

This allows you to override the jumper configuration for brake or coast. * - * @param mode Select to use the jumper setting or to override it to coast or - * brake. + * @param mode Select to use the jumper setting or to override it to coast or brake. */ public void configNeutralMode(NeutralMode mode) { - sendMessage(CANJNI.LM_API_CFG_BRAKE_COAST, new byte[] {mode.value}, 1); + sendMessage(CANJNI.LM_API_CFG_BRAKE_COAST, new byte[]{mode.value}, 1); m_neutralMode = mode; m_neutralModeVerified = false; @@ -1698,8 +1695,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Configure the number of turns on the potentiometer. * - * There is no special support for continuous turn potentiometers. Only - * integer numbers of turns are supported. + *

There is no special support for continuous turn potentiometers. Only integer numbers of + * turns are supported. * * @param turns The number of turns of the potentiometer */ @@ -1716,15 +1713,14 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Configure Soft Position Limits when in Position Controller mode.
* - * When controlling position, you can add additional limits on top of the - * limit switch inputs that are based on the position feedback. If the - * position limit is reached or the switch is opened, that direction will be - * disabled. + *

When controlling position, you can add additional limits on top of the limit switch inputs + * that are based on the position feedback. If the position limit is reached or the switch is + * opened, that direction will be disabled. * - * @param forwardLimitPosition The position that, if exceeded, will disable - * the forward direction. - * @param reverseLimitPosition The position that, if exceeded, will disable - * the reverse direction. + * @param forwardLimitPosition The position that, if exceeded, will disable the forward + * direction. + * @param reverseLimitPosition The position that, if exceeded, will disable the reverse + * direction. */ public void configSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) { configLimitMode(LimitMode.SoftPositionLimits); @@ -1735,7 +1731,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Disable Soft Position Limits if previously enabled.
* - * Soft Position Limits are disabled by default. + *

Soft Position Limits are disabled by default. */ public void disableSoftPositionLimits() { configLimitMode(LimitMode.SwitchInputsOnly); @@ -1744,26 +1740,25 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Set the limit mode for position control mode.
* - * Use {@link #configSoftPositionLimits(double, double)} or - * {@link #disableSoftPositionLimits()} to set this automatically. - *$ - * @param mode The {@link LimitMode} to use to limit the rotation of the - * device. + *

Use {@link #configSoftPositionLimits(double, double)} or {@link + * #disableSoftPositionLimits()} to set this automatically. + * + * @param mode The {@link LimitMode} to use to limit the rotation of the device. * @see LimitMode#SwitchInputsOnly * @see LimitMode#SoftPositionLimits */ public void configLimitMode(LimitMode mode) { - sendMessage(CANJNI.LM_API_CFG_LIMIT_MODE, new byte[] {mode.value}, 1); + sendMessage(CANJNI.LM_API_CFG_LIMIT_MODE, new byte[]{mode.value}, 1); } /** * Set the position that, if exceeded, will disable the forward direction. * - * Use {@link #configSoftPositionLimits(double, double)} to set this and the - * {@link LimitMode} automatically. - *$ - * @param forwardLimitPosition The position that, if exceeded, will disable - * the forward direction. + *

Use {@link #configSoftPositionLimits(double, double)} to set this and the {@link LimitMode} + * automatically. + * + * @param forwardLimitPosition The position that, if exceeded, will disable the forward + * direction. */ public void configForwardLimit(double forwardLimitPosition) { byte[] data = new byte[8]; @@ -1779,11 +1774,11 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Set the position that, if exceeded, will disable the reverse direction. * - * Use {@link #configSoftPositionLimits(double, double)} to set this and the - * {@link LimitMode} automatically. - *$ - * @param reverseLimitPosition The position that, if exceeded, will disable - * the reverse direction. + *

Use {@link #configSoftPositionLimits(double, double)} to set this and the {@link LimitMode} + * automatically. + * + * @param reverseLimitPosition The position that, if exceeded, will disable the reverse + * direction. */ public void configReverseLimit(double reverseLimitPosition) { byte[] data = new byte[8]; @@ -1799,8 +1794,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Configure the maximum voltage that the Jaguar will ever output. * - * This can be used to limit the maximum output voltage in all modes so that - * motors which cannot withstand full bus voltage can be used safely. + *

This can be used to limit the maximum output voltage in all modes so that motors which + * cannot withstand full bus voltage can be used safely. * * @param voltage The maximum voltage output by the Jaguar. */ @@ -1815,21 +1810,21 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Configure how long the Jaguar waits in the case of a fault before resuming - * operation. + * Configure how long the Jaguar waits in the case of a fault before resuming operation. * - * Faults include over temerature, over current, and bus under voltage. The - * default is 3.0 seconds, but can be reduced to as low as 0.5 seconds. + *

Faults include over temerature, over current, and bus under voltage. The default is 3.0 + * seconds, but can be reduced to as low as 0.5 seconds. * * @param faultTime The time to wait before resuming operation, in seconds. */ public void configFaultTime(float faultTime) { byte[] data = new byte[8]; - if (faultTime < 0.5f) + if (faultTime < 0.5f) { faultTime = 0.5f; - else if (faultTime > 3.0f) + } else if (faultTime > 3.0f) { faultTime = 3.0f; + } int dataSize = packINT16(data, (short) (faultTime * 1000.0)); sendMessage(CANJNI.LM_API_CFG_FAULT_TIME, data, dataSize); @@ -1845,25 +1840,31 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { JaguarControlMode m_controlMode; int m_speedReference = CANJNI.LM_REF_NONE; int m_positionReference = CANJNI.LM_REF_NONE; + @SuppressWarnings("MemberName") double m_p = 0.0; + @SuppressWarnings("MemberName") double m_i = 0.0; + @SuppressWarnings("MemberName") double m_d = 0.0; NeutralMode m_neutralMode = NeutralMode.Jumper; short m_encoderCodesPerRev = 0; short m_potentiometerTurns = 0; - LimitMode m_limitMode = LimitMode.SwitchInputsOnly; + final LimitMode m_limitMode = LimitMode.SwitchInputsOnly; double m_forwardLimit = 0.0; double m_reverseLimit = 0.0; double m_maxOutputVoltage = kApproxBusVoltage; - double m_voltageRampRate = 0.0; + final double m_voltageRampRate = 0.0; float m_faultTime = 0.0f; // Which parameters have been verified since they were last set? boolean m_controlModeVerified = true; boolean m_speedRefVerified = true; boolean m_posRefVerified = true; + @SuppressWarnings("MemberName") boolean m_pVerified = true; + @SuppressWarnings("MemberName") boolean m_iVerified = true; + @SuppressWarnings("MemberName") boolean m_dVerified = true; boolean m_neutralModeVerified = true; boolean m_encoderCodesPerRevVerified = true; @@ -1943,24 +1944,22 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Send a message to the Jaguar. * - * @param messageID The messageID to be used on the CAN bus (device number is - * added internally) - * @param data The up to 8 bytes of data to be sent with the message - * @param dataSize Specify how much of the data in "data" to send - * @param period If positive, tell Network Communications to send the message - * every "period" milliseconds. + * @param messageID The messageID to be used on the CAN bus (device number is added internally) + * @param data The up to 8 bytes of data to be sent with the message + * @param dataSize Specify how much of the data in "data" to send + * @param period If positive, tell Network Communications to send the message every "period" + * milliseconds. */ protected void sendMessage(int messageID, byte[] data, int dataSize, int period) { sendMessageHelper(messageID | m_deviceNumber, data, dataSize, period); } /** - * Send a message to the Jaguar, non-periodically + * Send a message to the Jaguar, non-periodically. * - * @param messageID The messageID to be used on the CAN bus (device number is - * added internally) - * @param data The up to 8 bytes of data to be sent with the message - * @param dataSize Specify how much of the data in "data" to send + * @param messageID The messageID to be used on the CAN bus (device number is added internally) + * @param data The up to 8 bytes of data to be sent with the message + * @param dataSize Specify how much of the data in "data" to send */ protected void sendMessage(int messageID, byte[] data, int dataSize) { sendMessage(messageID, data, dataSize, CANJNI.CAN_SEND_PERIOD_NO_REPEAT); @@ -1970,8 +1969,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { * Request a message from the Jaguar, but don't wait for it to arrive. * * @param messageID The message to request - * @param period If positive, tell Network Communications to request the - * message every "period" milliseconds. + * @param period If positive, tell Network Communications to request the message every "period" + * milliseconds. */ protected void requestMessage(int messageID, int period) { sendMessageHelper(messageID | m_deviceNumber, null, 0, period); @@ -1989,12 +1988,10 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { /** * Get a previously requested message. * - * Jaguar always generates a message with the same message ID when replying. - * - * @param messageID The messageID to read from the CAN bus (device number is - * added internally) - * @param data The up to 8 bytes of data that was received with the message + *

Jaguar always generates a message with the same message ID when replying. * + * @param messageID The messageID to read from the CAN bus (device number is added internally) + * @param data The up to 8 bytes of data that was received with the message * @throws CANMessageNotFoundException if there's not new message available */ protected void getMessage(int messageID, int messageMask, byte[] data) @@ -2021,7 +2018,7 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /** - * Enables periodic status updates from the Jaguar + * Enables periodic status updates from the Jaguar. */ protected void setupPeriodicStatus() { byte[] data = new byte[8]; @@ -2030,19 +2027,19 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { // Message 0 returns bus voltage, output voltage, output current, and // temperature. final byte[] kMessage0Data = - new byte[] {CANJNI.LM_PSTAT_VOLTBUS_B0, CANJNI.LM_PSTAT_VOLTBUS_B1, + new byte[]{CANJNI.LM_PSTAT_VOLTBUS_B0, CANJNI.LM_PSTAT_VOLTBUS_B1, CANJNI.LM_PSTAT_VOLTOUT_B0, CANJNI.LM_PSTAT_VOLTOUT_B1, CANJNI.LM_PSTAT_CURRENT_B0, CANJNI.LM_PSTAT_CURRENT_B1, CANJNI.LM_PSTAT_TEMP_B0, CANJNI.LM_PSTAT_TEMP_B1}; // Message 1 returns position and speed final byte[] kMessage1Data = - new byte[] {CANJNI.LM_PSTAT_POS_B0, CANJNI.LM_PSTAT_POS_B1, CANJNI.LM_PSTAT_POS_B2, + new byte[]{CANJNI.LM_PSTAT_POS_B0, CANJNI.LM_PSTAT_POS_B1, CANJNI.LM_PSTAT_POS_B2, CANJNI.LM_PSTAT_POS_B3, CANJNI.LM_PSTAT_SPD_B0, CANJNI.LM_PSTAT_SPD_B1, CANJNI.LM_PSTAT_SPD_B2, CANJNI.LM_PSTAT_SPD_B3}; // Message 2 returns limits and faults final byte[] kMessage2Data = - new byte[] {CANJNI.LM_PSTAT_LIMIT_CLR, CANJNI.LM_PSTAT_FAULT, CANJNI.LM_PSTAT_END, + new byte[]{CANJNI.LM_PSTAT_LIMIT_CLR, CANJNI.LM_PSTAT_FAULT, CANJNI.LM_PSTAT_END, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,}; dataSize = packINT16(data, (short) (kSendMessagePeriod)); @@ -2061,31 +2058,32 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { */ protected void updatePeriodicStatus() { byte[] data = new byte[8]; - int dataSize; // Check if a new bus voltage/output voltage/current/temperature message // has arrived and unpack the values into the cached member variables try { getMessage(CANJNI.LM_API_PSTAT_DATA_S0, CANJNI.CAN_MSGID_FULL_M, data); - m_busVoltage = unpackFXP8_8(new byte[] {data[0], data[1]}); - m_outputVoltage = unpackPercentage(new byte[] {data[2], data[3]}) * m_busVoltage; - m_outputCurrent = unpackFXP8_8(new byte[] {data[4], data[5]}); - m_temperature = unpackFXP8_8(new byte[] {data[6], data[7]}); + m_busVoltage = unpackFXP8_8(new byte[]{data[0], data[1]}); + m_outputVoltage = unpackPercentage(new byte[]{data[2], data[3]}) * m_busVoltage; + m_outputCurrent = unpackFXP8_8(new byte[]{data[4], data[5]}); + m_temperature = unpackFXP8_8(new byte[]{data[6], data[7]}); m_receivedStatusMessage0 = true; - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { + // no-op } // Check if a new position/speed message has arrived and do the same try { getMessage(CANJNI.LM_API_PSTAT_DATA_S1, CANJNI.CAN_MSGID_FULL_M, data); - m_position = unpackFXP16_16(new byte[] {data[0], data[1], data[2], data[3]}); - m_speed = unpackFXP16_16(new byte[] {data[4], data[5], data[6], data[7]}); + m_position = unpackFXP16_16(new byte[]{data[0], data[1], data[2], data[3]}); + m_speed = unpackFXP16_16(new byte[]{data[4], data[5], data[6], data[7]}); m_receivedStatusMessage1 = true; - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { + // no-op } // Check if a new limits/faults message has arrived and do the same @@ -2095,7 +2093,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { m_faults = data[1]; m_receivedStatusMessage2 = true; - } catch (CANMessageNotFoundException e) { + } catch (CANMessageNotFoundException ex) { + // no-op } } @@ -2113,100 +2112,106 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { } /* we are on ARM-LE now, not Freescale so no need to swap */ - private final static void swap16(int x, byte[] buffer) { + @SuppressWarnings("ParameterName") + private static void swap16(int x, byte[] buffer) { buffer[0] = (byte) (x & 0xff); buffer[1] = (byte) ((x >> 8) & 0xff); } - private final static void swap32(int x, byte[] buffer) { + @SuppressWarnings("ParameterName") + private static void swap32(int x, byte[] buffer) { buffer[0] = (byte) (x & 0xff); buffer[1] = (byte) ((x >> 8) & 0xff); buffer[2] = (byte) ((x >> 16) & 0xff); buffer[3] = (byte) ((x >> 24) & 0xff); } - private static final byte packPercentage(byte[] buffer, double value) { - if (value < -1.0) + private static byte packPercentage(byte[] buffer, double value) { + if (value < -1.0) { value = -1.0; - if (value > 1.0) + } + if (value > 1.0) { value = 1.0; + } short intValue = (short) (value * 32767.0); swap16(intValue, buffer); return 2; } - private static final byte packFXP8_8(byte[] buffer, double value) { + private static byte packFXP8_8(byte[] buffer, double value) { short intValue = (short) (value * 256.0); swap16(intValue, buffer); return 2; } - private static final byte packFXP16_16(byte[] buffer, double value) { + private static byte packFXP16_16(byte[] buffer, double value) { int intValue = (int) (value * 65536.0); swap32(intValue, buffer); return 4; } - private static final byte packINT16(byte[] buffer, short value) { + private static byte packINT16(byte[] buffer, short value) { swap16(value, buffer); return 2; } - private static final byte packINT32(byte[] buffer, int value) { + private static byte packINT32(byte[] buffer, int value) { swap32(value, buffer); return 4; } /** - * Unpack 16-bit data from a buffer in little-endian byte order - *$ + * Unpack 16-bit data from a buffer in little-endian byte order. + * * @param buffer The buffer to unpack from * @param offset The offset into he buffer to unpack * @return The data that was unpacked */ - private static final short unpack16(byte[] buffer, int offset) { + private static short unpack16(byte[] buffer, int offset) { return (short) ((buffer[offset] & 0xFF) | (short) ((buffer[offset + 1] << 8)) & 0xFF00); } /** - * Unpack 32-bit data from a buffer in little-endian byte order - *$ + * Unpack 32-bit data from a buffer in little-endian byte order. + * * @param buffer The buffer to unpack from * @param offset The offset into he buffer to unpack * @return The data that was unpacked */ - private static final int unpack32(byte[] buffer, int offset) { + private static int unpack32(byte[] buffer, int offset) { return (buffer[offset] & 0xFF) | ((buffer[offset + 1] << 8) & 0xFF00) | ((buffer[offset + 2] << 16) & 0xFF0000) | ((buffer[offset + 3] << 24) & 0xFF000000); } - private static final double unpackPercentage(byte[] buffer) { + private static double unpackPercentage(byte[] buffer) { return unpack16(buffer, 0) / 32767.0; } - private static final double unpackFXP8_8(byte[] buffer) { + private static double unpackFXP8_8(byte[] buffer) { return unpack16(buffer, 0) / 256.0; } - private static final double unpackFXP16_16(byte[] buffer) { + private static double unpackFXP16_16(byte[] buffer) { return unpack32(buffer, 0) / 65536.0; } - private static final short unpackINT16(byte[] buffer) { + private static short unpackINT16(byte[] buffer) { return unpack16(buffer, 0); } - private static final int unpackINT32(byte[] buffer) { + private static int unpackINT32(byte[] buffer) { return unpack32(buffer, 0); } /* Compare floats for equality as fixed point numbers */ - public boolean FXP8_EQ(double a, double b) { + @SuppressWarnings({"ParameterName", "MethodName", "SummaryJavadoc"}) + public static boolean FXP8_EQ(double a, double b) { return (int) (a * 256.0) == (int) (b * 256.0); } /* Compare floats for equality as fixed point numbers */ - public boolean FXP16_EQ(double a, double b) { + @SuppressWarnings({"ParameterName", "MethodName", "SummaryJavadoc"}) + public static boolean FXP16_EQ(double a, double b) { return (int) (a * 65536.0) == (int) (b * 65536.0); } @@ -2260,50 +2265,38 @@ public class CANJaguar implements MotorSafety, PIDOutput, CANSpeedController { */ private ITable m_table = null; - private ITableListener m_table_listener = null; + private ITableListener m_tableListener = null; - /** - * {@inheritDoc} - */ @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { CANSpeedController.super.updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ @Override public void startLiveWindowMode() { set(0); // Stop for safety - m_table_listener = createTableListener(); - m_table.addTableListener(m_table_listener, true); + m_tableListener = createTableListener(); + m_table.addTableListener(m_tableListener, true); } - /** - * {@inheritDoc} - */ + @Override public void stopLiveWindowMode() { set(0); // Stop for safety // TODO: See if this is still broken - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANSpeedController.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANSpeedController.java index 75d48c55a1..f448cab16c 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANSpeedController.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANSpeedController.java @@ -13,28 +13,27 @@ import edu.wpi.first.wpilibj.tables.ITableListener; public interface CANSpeedController extends SpeedController, PIDInterface, LiveWindowSendable { /** - * Mode determines how the motor is controlled, used internally. This is meant - * to be subclassed by enums - * (see {@link CANTalon.TalonControlMode CANTalon.TalonControlMode}). + * Mode determines how the motor is controlled, used internally. This is meant to be subclassed by + * enums (see {@link CANTalon.TalonControlMode CANTalon.TalonControlMode}). * - * - * Note that the Jaguar does not support follower mode. + *

Note that the Jaguar does not support follower mode. */ - public interface ControlMode { - /** - * Gets the name of this control mode. Since this interface should only be - * subclassed by enumerations, this will be overridden by the builtin - * name() method. - */ - public String name(); - /** - * Checks if this control mode is PID-compatible. - */ - public boolean isPID(); - /** - * Gets the integer value of this control mode. - */ - public int getValue(); + interface ControlMode { + /** + * Gets the name of this control mode. Since this interface should only be subclassed by + * enumerations, this will be overridden by the builtin name() method. + */ + String name(); + + /** + * Checks if this control mode is PID-compatible. + */ + boolean isPID(); + + /** + * Gets the integer value of this control mode. + */ + int getValue(); } /** @@ -42,42 +41,46 @@ public interface CANSpeedController extends SpeedController, PIDInterface, LiveW * * @return the current control mode */ - public ControlMode getControlMode(); + ControlMode getControlMode(); /** * Sets the control mode of this speed controller. * * @param mode the the new mode */ - public void setControlMode(int mode); + void setControlMode(int mode); /** * Set the proportional PID constant. */ - public void setP(double p); + @SuppressWarnings("ParameterName") + void setP(double p); /** * Set the integral PID constant. */ - public void setI(double i); + @SuppressWarnings("ParameterName") + void setI(double i); /** * Set the derivative PID constant. */ - public void setD(double d); + @SuppressWarnings("ParameterName") + void setD(double d); /** * Set the feed-forward PID constant. This method is optional to implement. */ - public default void setF(double f) { + @SuppressWarnings("ParameterName") + default void setF(double f) { } /** - * Gets the feed-forward PID constant. This method is optional to implement. - * If a subclass does not implement this, it will always return zero. + * Gets the feed-forward PID constant. This method is optional to implement. If a subclass does + * not implement this, it will always return zero. */ - public default double getF() { - return 0.0; + default double getF() { + return 0.0; } /** @@ -85,55 +88,53 @@ public interface CANSpeedController extends SpeedController, PIDInterface, LiveW * * @return the input voltage to the controller (in Volts). */ - public double getBusVoltage(); + double getBusVoltage(); /** * Get the current output voltage. * * @return the output voltage to the motor in volts. */ - public double getOutputVoltage(); + double getOutputVoltage(); /** * Get the current being applied to the motor. * * @return the current motor current (in Amperes). */ - public double getOutputCurrent(); + double getOutputCurrent(); /** * Get the current temperature of the controller. * * @return the current temperature of the controller, in degrees Celsius. */ - public double getTemperature(); + double getTemperature(); /** * Return the current position of whatever the current selected sensor is. * - * See specific implementations for more information on selecting feedback - * sensors. + *

See specific implementations for more information on selecting feedback sensors. * * @return the current sensor position. */ - public double getPosition(); + double getPosition(); /** * Return the current velocity of whatever the current selected sensor is. * - * See specific implementations for more information on selecting feedback - * sensors. + *

See specific implementations for more information on selecting feedback sensors. * * @return the current sensor velocity. */ - public double getSpeed(); + double getSpeed(); /** * Set the maximum rate of change of the output voltage. * * @param rampRate the maximum rate of change of the votlage, in Volts / sec. */ - public void setVoltageRampRate(double rampRate); + void setVoltageRampRate(double rampRate); /** * All CAN Speed Controllers have the same SmartDashboard type: "CANSpeedController". @@ -141,56 +142,71 @@ public interface CANSpeedController extends SpeedController, PIDInterface, LiveW String SMART_DASHBOARD_TYPE = "CANSpeedController"; @Override - public default void updateTable() { - ITable table = getTable(); - if(table != null) { - table.putString("~TYPE~", SMART_DASHBOARD_TYPE); - table.putString("Type", getClass().getSimpleName()); // "CANTalon", "CANJaguar" - table.putNumber("Mode", getControlMode().getValue()); - if (getControlMode().isPID()) { - // CANJaguar throws an exception if you try to get its PID constants - // when it's not in a PID-compatible mode - table.putNumber("p", getP()); - table.putNumber("i", getI()); - table.putNumber("d", getD()); - table.putNumber("f", getF()); - } - table.putBoolean("Enabled", isEnabled()); - table.putNumber("Value", get()); + default void updateTable() { + ITable table = getTable(); + if (table != null) { + table.putString("~TYPE~", SMART_DASHBOARD_TYPE); + table.putString("Type", getClass().getSimpleName()); // "CANTalon", "CANJaguar" + table.putNumber("Mode", getControlMode().getValue()); + if (getControlMode().isPID()) { + // CANJaguar throws an exception if you try to get its PID constants + // when it's not in a PID-compatible mode + table.putNumber("p", getP()); + table.putNumber("i", getI()); + table.putNumber("d", getD()); + table.putNumber("f", getF()); } + table.putBoolean("Enabled", isEnabled()); + table.putNumber("Value", get()); + } } @Override - public default String getSmartDashboardType() { - return SMART_DASHBOARD_TYPE; + default String getSmartDashboardType() { + return SMART_DASHBOARD_TYPE; } /** - * Creates an ITableListener for the LiveWindow table for this CAN speed - * controller. + * Creates an ITableListener for the LiveWindow table for this CAN speed controller. */ - public default ITableListener createTableListener() { - return (table, key, value, isNew) -> { - switch(key) { - case "Enabled": - if ((Boolean) value) { - enable(); - } else { - disable(); - } - break; - case "Value": set((Double) value); break; - case "Mode": setControlMode(((Double) value).intValue()); break; + default ITableListener createTableListener() { + return (table, key, value, isNew) -> { + switch (key) { + case "Enabled": + if ((Boolean) value) { + enable(); + } else { + disable(); } - if(getControlMode().isPID()) { - switch(key) { - case "p": setP((Double) value); break; - case "i": setI((Double) value); break; - case "d": setD((Double) value); break; - case "f": setF((Double) value); break; - } - } - }; + break; + case "Value": + set((Double) value); + break; + case "Mode": + setControlMode(((Double) value).intValue()); + break; + default: + break; + } + if (getControlMode().isPID()) { + switch (key) { + case "p": + setP((Double) value); + break; + case "i": + setI((Double) value); + break; + case "d": + setD((Double) value); + break; + case "f": + setF((Double) value); + break; + default: + break; + } + } + }; } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANTalon.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANTalon.java index b60de8676d..547b928e2e 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANTalon.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CANTalon.java @@ -7,38 +7,41 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.hal.CanTalonJNI; -import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; +import edu.wpi.first.wpilibj.communication.UsageReporting; +import edu.wpi.first.wpilibj.hal.CanTalonJNI; +import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -import edu.wpi.first.wpilibj.livewindow.LiveWindow; public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedController { private MotorSafetyHelper m_safetyHelper; - private boolean isInverted = false; + private boolean m_isInverted = false; protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement; /** - * Number of adc engineering units per 0 to 3.3V sweep. - * This is necessary for scaling Analog Position in rotations/RPM. + * Number of adc engineering units per 0 to 3.3V sweep. This is necessary for scaling Analog + * Position in rotations/RPM. */ - private final int kNativeAdcUnitsPerRotation = 1024; + private static final int kNativeAdcUnitsPerRotation = 1024; /** - * Number of pulse width engineering units per full rotation. - * This is necessary for scaling Pulse Width Decoded Position in rotations/RPM. + * Number of pulse width engineering units per full rotation. This is necessary for scaling Pulse + * Width Decoded Position in rotations/RPM. */ - private final double kNativePwdUnitsPerRotation = 4096.0; + private static final double kNativePwdUnitsPerRotation = 4096.0; /** - * Number of minutes per 100ms unit. Useful for scaling velocities - * measured by Talon's 100ms timebase to rotations per minute. + * Number of minutes per 100ms unit. Useful for scaling velocities measured by Talon's 100ms + * timebase to rotations per minute. */ - private final double kMinutesPer100msUnit = 1.0/600.0; + private static final double kMinutesPer100msUnit = 1.0 / 600.0; public enum TalonControlMode implements CANSpeedController.ControlMode { - PercentVbus(0), Position(1), Speed(2), Current(3), Voltage(4), Follower(5), MotionProfile(6), Disabled(15); + PercentVbus(0), Position(1), Speed(2), Current(3), Voltage(4), Follower(5), MotionProfile(6), + Disabled(15); + @SuppressWarnings("MemberName") public final int value; + @SuppressWarnings("JavadocMethod") public static TalonControlMode valueOf(int value) { for (TalonControlMode mode : values()) { if (mode.value == value) { @@ -49,25 +52,29 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return null; } - private TalonControlMode(int value) { + TalonControlMode(int value) { this.value = value; } @Override public boolean isPID() { - return this == Current || this == Speed || this == Position; + return this == Current || this == Speed || this == Position; } @Override public int getValue() { - return value; + return value; } } - public enum FeedbackDevice { - QuadEncoder(0), AnalogPot(2), AnalogEncoder(3), EncRising(4), EncFalling(5), CtreMagEncoder_Relative(6), CtreMagEncoder_Absolute(7), PulseWidth(8); + public enum FeedbackDevice { + QuadEncoder(0), AnalogPot(2), AnalogEncoder(3), EncRising(4), EncFalling(5), + CtreMagEncoder_Relative(6), CtreMagEncoder_Absolute(7), PulseWidth(8); + + @SuppressWarnings("MemberName") public int value; + @SuppressWarnings("JavadocMethod") public static FeedbackDevice valueOf(int value) { for (FeedbackDevice mode : values()) { if (mode.value == value) { @@ -78,16 +85,21 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return null; } - private FeedbackDevice(int value) { + FeedbackDevice(int value) { this.value = value; } } + /** * Depending on the sensor type, Talon can determine if sensor is plugged in ot not. */ public enum FeedbackDeviceStatus { FeedbackStatusUnknown(0), FeedbackStatusPresent(1), FeedbackStatusNotPresent(2); + + @SuppressWarnings("MemberName") public int value; + + @SuppressWarnings("JavadocMethod") public static FeedbackDeviceStatus valueOf(int value) { for (FeedbackDeviceStatus mode : values()) { if (mode.value == value) { @@ -96,15 +108,22 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } return null; } - private FeedbackDeviceStatus(int value) { + + FeedbackDeviceStatus(int value) { this.value = value; } } - /** enumerated types for frame rate ms */ + + /** + * Enumerated types for frame rate ms. + */ public enum StatusFrameRate { General(0), Feedback(1), QuadEncoder(2), AnalogTempVbat(3), PulseWidth(4); + + @SuppressWarnings("MemberName") public int value; + @SuppressWarnings("JavadocMethod") public static StatusFrameRate valueOf(int value) { for (StatusFrameRate mode : values()) { if (mode.value == value) { @@ -114,51 +133,43 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return null; } - private StatusFrameRate(int value) { + StatusFrameRate(int value) { this.value = value; } } + /** - * Enumerated types for Motion Control Set Values. - * When in Motion Profile control mode, these constants are paseed - * into set() to manipulate the motion profile executer. - * When changing modes, be sure to read the value back using getMotionProfileStatus() - * to ensure changes in output take effect before performing buffering actions. - * Disable will signal Talon to put motor output into neutral drive. - * Talon will stop processing motion profile points. This means the buffer is - * effectively disconnected from the executer, allowing the robot to gracefully - * clear and push new traj points. isUnderrun will get cleared. - * The active trajectory is also cleared. - * Enable will signal Talon to pop a trajectory point from it's buffer and process it. - * If the active trajectory is empty, Talon will shift in the next point. - * If the active traj is empty, and so is the buffer, the motor drive is neutral and - * isUnderrun is set. When active traj times out, and buffer has at least one point, - * Talon shifts in next one, and isUnderrun is cleared. When active traj times out, - * and buffer is empty, Talon keeps processing active traj and sets IsUnderrun. - * Hold will signal Talon keep processing the active trajectory indefinitely. - * If the active traj is cleared, Talon will neutral motor drive. Otherwise - * Talon will keep processing the active traj but it will not shift in - * points from the buffer. This means the buffer is effectively disconnected - * from the executer, allowing the robot to gracefully clear and push - * new traj points. - * isUnderrun is set if active traj is empty, otherwise it is cleared. - * isLast signal is also cleared. + * Enumerated types for Motion Control Set Values. When in Motion Profile control mode, these + * constants are paseed into set() to manipulate the motion profile executer. When changing modes, + * be sure to read the value back using getMotionProfileStatus() to ensure changes in output take + * effect before performing buffering actions. Disable will signal Talon to put motor output into + * neutral drive. Talon will stop processing motion profile points. This means the buffer is + * effectively disconnected from the executer, allowing the robot to gracefully clear and push new + * traj points. isUnderrun will get cleared. The active trajectory is also cleared. Enable will + * signal Talon to pop a trajectory point from it's buffer and process it. If the active + * trajectory is empty, Talon will shift in the next point. If the active traj is empty, and so is + * the buffer, the motor drive is neutral and isUnderrun is set. When active traj times out, and + * buffer has at least one point, Talon shifts in next one, and isUnderrun is cleared. When + * active traj times out, and buffer is empty, Talon keeps processing active traj and sets + * IsUnderrun. Hold will signal Talon keep processing the active trajectory indefinitely. If the + * active traj is cleared, Talon will neutral motor drive. Otherwise Talon will keep processing + * the active traj but it will not shift in points from the buffer. This means the buffer is + * effectively disconnected from the executer, allowing the robot to gracefully clear and push new + * traj points. isUnderrun is set if active traj is empty, otherwise it is cleared. isLast signal + * is also cleared. * - * Typical workflow: - * set(Disable), - * Confirm Disable takes effect, - * clear buffer and push buffer points, - * set(Enable) when enough points have been pushed to ensure no underruns, - * wait for MP to finish or decide abort, - * If MP finished gracefully set(Hold) to hold position servo and disconnect buffer, - * If MP is being aborted set(Disable) to neutral the motor and disconnect buffer, - * Confirm mode takes effect, - * clear buffer and push buffer points, and rinse-repeat. + *

Typical workflow: set(Disable), Confirm Disable takes effect, clear buffer and push buffer + * points, set(Enable) when enough points have been pushed to ensure no underruns, wait for MP to + * finish or decide abort, If MP finished gracefully set(Hold) to hold position servo and + * disconnect buffer, If MP is being aborted set(Disable) to neutral the motor and disconnect + * buffer, Confirm mode takes effect, clear buffer and push buffer points, and rinse-repeat. */ public enum SetValueMotionProfile { Disable(0), Enable(1), Hold(2); + @SuppressWarnings("MemberName") public int value; + @SuppressWarnings("JavadocMethod") public static SetValueMotionProfile valueOf(int value) { for (SetValueMotionProfile mode : values()) { if (mode.value == value) { @@ -168,74 +179,70 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return null; } - private SetValueMotionProfile(int value) { + SetValueMotionProfile(int value) { this.value = value; } } + /** - * Motion Profile Trajectory Point - * This is simply a data transer object. + * Motion Profile Trajectory Point This is simply a data transer object. */ + @SuppressWarnings("MemberName") public static class TrajectoryPoint { public double position; //!< The position to servo to. public double velocity; //!< The velocity to feed-forward. /** - * Time in milliseconds to process this point. - * Value should be between 1ms and 255ms. If value is zero - * then Talon will default to 1ms. If value exceeds 255ms API will cap it. + * Time in milliseconds to process this point. Value should be between 1ms and 255ms. If value + * is zero then Talon will default to 1ms. If value exceeds 255ms API will cap it. */ public int timeDurMs; /** - * Which slot to get PIDF gains. - * PID is used for position servo. - * F is used as the Kv constant for velocity feed-forward. - * Typically this is hardcoded to the a particular slot, but you are free - * gain schedule if need be. + * Which slot to get PIDF gains. PID is used for position servo. F is used as the Kv constant + * for velocity feed-forward. Typically this is hardcoded to the a particular slot, but you are + * free gain schedule if need be. */ public int profileSlotSelect; /** - * Set to true to only perform the velocity feed-forward and not perform - * position servo. This is useful when learning how the position servo - * changes the motor response. The same could be accomplish by clearing the - * PID gains, however this is synchronous the streaming, and doesn't require restoing - * gains when finished. + * Set to true to only perform the velocity feed-forward and not perform position servo. This is + * useful when learning how the position servo changes the motor response. The same could be + * accomplish by clearing the PID gains, however this is synchronous the streaming, and doesn't + * require restoing gains when finished. * - * Additionaly setting this basically gives you direct control of the motor output - * since motor output = targetVelocity X Kv, where Kv is our Fgain. - * This means you can also scheduling straight-throttle curves without relying on - * a sensor. + *

Additionaly setting this basically gives you direct control of the motor output since + * motor output = targetVelocity X Kv, where Kv is our Fgain. This means you can also scheduling + * straight-throttle curves without relying on a sensor. */ public boolean velocityOnly; /** - * Set to true to signal Talon that this is the final point, so do not - * attempt to pop another trajectory point from out of the Talon buffer. - * Instead continue processing this way point. Typically the velocity - * member variable should be zero so that the motor doesn't spin indefinitely. + * Set to true to signal Talon that this is the final point, so do not attempt to pop another + * trajectory point from out of the Talon buffer. Instead continue processing this way point. + * Typically the velocity member variable should be zero so that the motor doesn't spin + * indefinitely. */ public boolean isLastPoint; - /** - * Set to true to signal Talon to zero the selected sensor. - * When generating MPs, one simple method is to make the first target position zero, - * and the final target position the target distance from the current position. - * Then when you fire the MP, the current position gets set to zero. - * If this is the intent, you can set zeroPos on the first trajectory point. + /** + * Set to true to signal Talon to zero the selected sensor. When generating MPs, one simple + * method is to make the first target position zero, and the final target position the target + * distance from the current position. Then when you fire the MP, the current position gets set + * to zero. If this is the intent, you can set zeroPos on the first trajectory point. * - * Otherwise you can leave this false for all points, and offset the positions - * of all trajectory points so they are correct. + *

Otherwise you can leave this false for all points, and offset the positions of all + * trajectory points so they are correct. */ public boolean zeroPos; } + /** - * Motion Profile Status - * This is simply a data transer object. + * Motion Profile Status This is simply a data transer object. */ + @SuppressWarnings("MemberName") public static class MotionProfileStatus { /** * The available empty slots in the trajectory buffer. * - * The robot API holds a "top buffer" of trajectory points, so your applicaion - * can dump several points at once. The API will then stream them into the Talon's - * low-level buffer, allowing the Talon to act on them. + *

The robot API holds a "top buffer" of trajectory points, so your applicaion can dump + * several points at once. The API will then stream them into the Talon's low-level buffer, + * allowing the Talon to act on them. */ public int topBufferRem; /** @@ -247,21 +254,20 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont */ public int btmBufferCnt; /** - * Set if isUnderrun ever gets set. - * Only is cleared by clearMotionProfileHasUnderrun() to ensure + * Set if isUnderrun ever gets set. Only is cleared by clearMotionProfileHasUnderrun() to ensure * robot logic can react or instrument it. + * * @see clearMotionProfileHasUnderrun() */ public boolean hasUnderrun; /** - * This is set if Talon needs to shift a point from its buffer into - * the active trajectory point however the buffer is empty. This gets cleared - * automatically when is resolved. + * This is set if Talon needs to shift a point from its buffer into the active trajectory point + * however the buffer is empty. This gets cleared automatically when is resolved. */ public boolean isUnderrun; /** - * True if the active trajectory point has not empty, false otherwise. - * The members in activePoint are only valid if this signal is set. + * True if the active trajectory point has not empty, false otherwise. The members in + * activePoint are only valid if this signal is set. */ public boolean activePointValid; /** @@ -269,9 +275,9 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont */ public TrajectoryPoint activePoint = new TrajectoryPoint(); /** - * The current output mode of the motion profile executer (disabled, enabled, or hold). - * When changing the set() value in MP mode, it's important to check this signal to - * confirm the change takes effect before interacting with the top buffer. + * The current output mode of the motion profile executer (disabled, enabled, or hold). When + * changing the set() value in MP mode, it's important to check this signal to confirm the + * change takes effect before interacting with the top buffer. */ public SetValueMotionProfile outputEnable; } @@ -282,35 +288,36 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont private double m_minimumInput; private double m_maximumInput; - int m_deviceNumber; - boolean m_controlEnabled; - boolean m_stopped = false; - int m_profile; + private int m_deviceNumber; + private boolean m_controlEnabled; + private boolean m_stopped = false; + private int m_profile; double m_setPoint; /** - * Encoder CPR, counts per rotations, also called codes per revoluion. - * Default value of zero means the API behaves as it did during the 2015 season, each position - * unit is a single pulse and there are four pulses per count (4X). - * Caller can use configEncoderCodesPerRev to set the quadrature encoder CPR. + * Encoder CPR, counts per rotations, also called codes per revoluion. Default value of zero means + * the API behaves as it did during the 2015 season, each position unit is a single pulse and + * there are four pulses per count (4X). Caller can use configEncoderCodesPerRev to set the + * quadrature encoder CPR. */ int m_codesPerRev; /** - * Number of turns per rotation. For example, a 10-turn pot spins ten full rotations from - * a wiper voltage of zero to 3.3 volts. Therefore knowing the - * number of turns a full voltage sweep represents is necessary for calculating rotations - * and velocity. - * A default value of zero means the API behaves as it did during the 2015 season, there are 1024 - * position units from zero to 3.3V. + * Number of turns per rotation. For example, a 10-turn pot spins ten full rotations from a wiper + * voltage of zero to 3.3 volts. Therefore knowing the number of turns a full voltage sweep + * represents is necessary for calculating rotations and velocity. A default value of zero means + * the API behaves as it did during the 2015 season, there are 1024 position units from zero to + * 3.3V. */ int m_numPotTurns; /** - * Although the Talon handles feedback selection, caching the feedback selection is helpful at the API level - * for scaling into rotations and RPM. + * Although the Talon handles feedback selection, caching the feedback selection is helpful at the + * API level for scaling into rotations and RPM. */ FeedbackDevice m_feedbackDevice; + /** * Constructor for the CANTalon device. + * * @param deviceNumber The CAN ID of the Talon SRX */ public CANTalon(int deviceNumber) { @@ -327,11 +334,13 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont applyControlMode(TalonControlMode.PercentVbus); LiveWindow.addActuator("CANTalon", m_deviceNumber, this); } + /** * Constructor for the CANTalon device. - * @param deviceNumber The CAN ID of the Talon SRX - * @param controlPeriodMs The period in ms to send the CAN control frame. - * Period is bounded to [1ms,95ms]. + * + * @param deviceNumber The CAN ID of the Talon SRX + * @param controlPeriodMs The period in ms to send the CAN control frame. Period is bounded to + * [1ms,95ms]. */ public CANTalon(int deviceNumber, int controlPeriodMs) { m_deviceNumber = deviceNumber; @@ -348,15 +357,17 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont applyControlMode(TalonControlMode.PercentVbus); LiveWindow.addActuator("CANTalon", m_deviceNumber, this); } + /** * Constructor for the CANTalon device. - * @param deviceNumber The CAN ID of the Talon SRX - * @param controlPeriodMs The period in ms to send the CAN control frame. - * Period is bounded to [1ms,95ms]. - * @param enablePeriodMs The period in ms to send the enable control frame. - * Period is bounded to [1ms,95ms]. This typically is not - * required to specify, however this could be used to minimize the - * time between robot-enable and talon-motor-drive. + * + * @param deviceNumber The CAN ID of the Talon SRX + * @param controlPeriodMs The period in ms to send the CAN control frame. Period is bounded to + * [1ms,95ms]. + * @param enablePeriodMs The period in ms to send the enable control frame. Period is bounded to + * [1ms,95ms]. This typically is not required to specify, however this + * could be used to minimize the time between robot-enable and + * talon-motor-drive. */ public CANTalon(int deviceNumber, int controlPeriodMs, int enablePeriodMs) { m_deviceNumber = deviceNumber; @@ -382,16 +393,12 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } } - /** - * {@inheritDoc} - */ + @Override public void setPIDSourceType(PIDSourceType pidSource) { m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_pidSource; } @@ -401,6 +408,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return getPosition(); } + @SuppressWarnings("JavadocMethod") public void delete() { disable(); if (m_handle != 0) { @@ -409,22 +417,32 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } } + /** + * Sets the output of the Talon. + * + * @param outputValue See set(). + * @param thisValueDoesNotDoAnything corresponds to syncGroup from Jaguar; not relevant here. + */ + @Override + public void set(double outputValue, byte thisValueDoesNotDoAnything) { + set(outputValue); + } + /** * Sets the appropriate output on the talon, depending on the mode. * - * In PercentVbus, the output is between -1.0 and 1.0, with 0.0 as stopped. In - * Follower mode, the output is the integer device ID of the talon to - * duplicate. In Voltage mode, outputValue is in volts. In Current mode, - * outputValue is in amperes. In Speed mode, outputValue is in position change - * / 10ms. In Position mode, outputValue is in encoder ticks or an analog - * value, depending on the sensor. + *

In PercentVbus, the output is between -1.0 and 1.0, with 0.0 as stopped. In Follower mode, + * the output is the integer device ID of the talon to duplicate. In Voltage mode, outputValue is + * in volts. In Current mode, outputValue is in amperes. In Speed mode, outputValue is in position + * change / 10ms. In Position mode, outputValue is in encoder ticks or an analog value, depending + * on the sensor. * * @param outputValue The setpoint value, as described above. */ public void set(double outputValue) { /* feed safety helper since caller just updated our output */ m_safetyHelper.feed(); - if(m_stopped) { + if (m_stopped) { enableControl(); m_stopped = false; } @@ -432,25 +450,27 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont m_setPoint = outputValue; /* cache set point for getSetpoint() */ switch (m_controlMode) { case PercentVbus: - CanTalonJNI.Set(m_handle, isInverted ? -outputValue : outputValue); + CanTalonJNI.Set(m_handle, m_isInverted ? -outputValue : outputValue); break; case Follower: CanTalonJNI.SetDemand(m_handle, (int) outputValue); break; case Voltage: // Voltage is an 8.8 fixed point number. - int volts = (int) ((isInverted ? -outputValue : outputValue) * 256); + int volts = (int) ((m_isInverted ? -outputValue : outputValue) * 256); CanTalonJNI.SetDemand(m_handle, volts); break; case Speed: - CanTalonJNI.SetDemand(m_handle, ScaleVelocityToNativeUnits(m_feedbackDevice,(isInverted ? -outputValue : outputValue))); + CanTalonJNI.SetDemand(m_handle, scaleVelocityToNativeUnits(m_feedbackDevice, + (m_isInverted ? -outputValue : outputValue))); break; case Position: - CanTalonJNI.SetDemand(m_handle, ScaleRotationsToNativeUnits(m_feedbackDevice,outputValue)); + CanTalonJNI.SetDemand(m_handle, scaleRotationsToNativeUnits(m_feedbackDevice, + outputValue)); break; case Current: - double milliamperes = (isInverted ? -outputValue : outputValue) * 1000.0; /* mA*/ - CanTalonJNI.SetDemand(m_handle, (int)milliamperes); + double milliamperes = (m_isInverted ? -outputValue : outputValue) * 1000.0; /* mA*/ + CanTalonJNI.SetDemand(m_handle, (int) milliamperes); break; case MotionProfile: CanTalonJNI.SetDemand(m_handle, (int) outputValue); @@ -463,45 +483,31 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Inverts the direction of the motor's rotation. Only works in PercentVbus - * mode. + * Inverts the direction of the motor's rotation. Only works in PercentVbus mode. * * @param isInverted The state of inversion, true is inverted. */ @Override public void setInverted(boolean isInverted) { - this.isInverted = isInverted; + m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. * * @return isInverted The state of inversion, true is inverted. - * */ @Override public boolean getInverted() { - return this.isInverted; - } - - /** - * Sets the output of the Talon. - * - * @param outputValue See set(). - * @param thisValueDoesNotDoAnything corresponds to syncGroup from Jaguar; not - * relevant here. - */ - @Override - public void set(double outputValue, byte thisValueDoesNotDoAnything) { - set(outputValue); + return m_isInverted; } /** * Resets the accumulated integral error and disables the controller. * - * The only difference between this and {@link PIDController#reset} is that - * the PIDController also resets the previous error for the D term, but the - * difference should have minimal effect as it will only last one cycle. + *

The only difference between this and {@link PIDController#reset} is that the PIDController + * also resets the previous error for the D term, but the difference should have minimal effect as + * it will only last one cycle. */ public void reset() { disable(); @@ -535,12 +541,10 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Flips the sign (multiplies by negative one) the sensor values going into - * the talon. + * Flips the sign (multiplies by negative one) the sensor values going into the talon. * - * This only affects position and velocity closed loop control. Allows for - * situations where you may have a sensor flipped and going in the wrong - * direction. + *

This only affects position and velocity closed loop control. Allows for situations where you + * may have a sensor flipped and going in the wrong direction. * * @param flip True if sensor input should be flipped; False if not. */ @@ -549,8 +553,8 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Flips the sign (multiplies by negative one) the throttle values going into - * the motor on the talon in closed loop modes. + * Flips the sign (multiplies by negative one) the throttle values going into the motor on the + * talon in closed loop modes. * * @param flip True if motor output should be flipped; False if not. */ @@ -561,9 +565,9 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /** * Gets the current status of the Talon (usually a sensor value). * - * In Current mode: returns output current. In Speed mode: returns current - * speed. In Position mode: returns current sensor position. In PercentVbus - * and Follower modes: returns current applied throttle. + *

In Current mode: returns output current. In Speed mode: returns current speed. In Position + * mode: returns current sensor position. In PercentVbus and Follower modes: returns current + * applied throttle. * * @return The current sensor value of the Talon. */ @@ -574,9 +578,10 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont case Current: return getOutputCurrent(); case Speed: - return ScaleNativeUnitsToRpm(m_feedbackDevice,CanTalonJNI.GetSensorVelocity(m_handle)); + return scaleNativeUnitsToRpm(m_feedbackDevice, CanTalonJNI.GetSensorVelocity(m_handle)); case Position: - return ScaleNativeUnitsToRotations(m_feedbackDevice,CanTalonJNI.GetSensorPosition(m_handle)); + return scaleNativeUnitsToRotations(m_feedbackDevice, CanTalonJNI.GetSensorPosition( + m_handle)); case PercentVbus: default: return (double) CanTalonJNI.GetAppliedThrottle(m_handle) / 1023.0; @@ -584,8 +589,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Get the current encoder position, regardless of whether it is the current - * feedback device. + * Get the current encoder position, regardless of whether it is the current feedback device. * * @return The current position of the encoder. */ @@ -598,29 +602,34 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Get the current encoder velocity, regardless of whether it is the current - * feedback device. + * Get the current encoder velocity, regardless of whether it is the current feedback device. * * @return The current speed of the encoder. */ public int getEncVelocity() { return CanTalonJNI.GetEncVel(m_handle); } + public int getPulseWidthPosition() { return CanTalonJNI.GetPulseWidthPosition(m_handle); } + public void setPulseWidthPosition(int newPosition) { setParameter(CanTalonJNI.param_t.ePwdPosition, newPosition); } + public int getPulseWidthVelocity() { return CanTalonJNI.GetPulseWidthVelocity(m_handle); } + public int getPulseWidthRiseToFallUs() { return CanTalonJNI.GetPulseWidthRiseToFallUs(m_handle); } + public int getPulseWidthRiseToRiseUs() { return CanTalonJNI.GetPulseWidthRiseToRiseUs(m_handle); } + /** * @param feedbackDevice which feedback sensor to check it if is connected. * @return status of caller's specified sensor type. @@ -628,7 +637,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont public FeedbackDeviceStatus isSensorPresent(FeedbackDevice feedbackDevice) { FeedbackDeviceStatus retval = FeedbackDeviceStatus.FeedbackStatusUnknown; /* detecting sensor health depends on which sensor caller cares about */ - switch(feedbackDevice){ + switch (feedbackDevice) { case QuadEncoder: case AnalogPot: case AnalogEncoder: @@ -641,17 +650,20 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont case CtreMagEncoder_Relative: case CtreMagEncoder_Absolute: /* all of these require pulse width signal to be present. */ - if( CanTalonJNI.IsPulseWidthSensorPresent(m_handle) == 0 ){ + if (CanTalonJNI.IsPulseWidthSensorPresent(m_handle) == 0) { /* Talon not getting a signal */ retval = FeedbackDeviceStatus.FeedbackStatusNotPresent; - }else{ + } else { /* getting good signal */ retval = FeedbackDeviceStatus.FeedbackStatusPresent; } break; + default: + break; } return retval; } + /** * Get the number of of rising edges seen on the index pin. * @@ -682,25 +694,25 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return CanTalonJNI.GetQuadIdxpin(m_handle); } - public void setAnalogPosition(int newPosition){ - setParameter(CanTalonJNI.param_t.eAinPosition, (double)newPosition); + public void setAnalogPosition(int newPosition) { + setParameter(CanTalonJNI.param_t.eAinPosition, (double) newPosition); } + /** - * Get the current analog in position, regardless of whether it is the current - * feedback device. + * Get the current analog in position, regardless of whether it is the current feedback device. * - * @return The 24bit analog position. The bottom ten bits is the ADC (0 - - * 1023) on the analog pin of the Talon. The upper 14 bits tracks the - * overflows and underflows (continuous sensor). + *

The bottom ten bits is the ADC (0 - 1023) on the analog pin of the Talon. The upper 14 bits + * tracks the overflows and underflows (continuous sensor). + * + * @return The 24bit analog position. */ public int getAnalogInPosition() { return CanTalonJNI.GetAnalogInWithOv(m_handle); } /** - * Get the current analog in position, regardless of whether it is the current - * feedback device. - *$ + * Get the current analog in position, regardless of whether it is the current feedback device. + * * @return The ADC (0 - 1023) on analog pin of the Talon. */ public int getAnalogInRaw() { @@ -708,8 +720,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Get the current encoder velocity, regardless of whether it is the current - * feedback device. + * Get the current encoder velocity, regardless of whether it is the current feedback device. * * @return The current speed of the analog in device. */ @@ -726,34 +737,36 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /* retrieve the closed loop error in native units */ return CanTalonJNI.GetCloseLoopErr(m_handle); } + /** * Set the allowable closed loop error. - * @param allowableCloseLoopError allowable closed loop error for selected profile. - * mA for Curent closed loop. - * Talon Native Units for position and velocity. + * + * @param allowableCloseLoopError allowable closed loop error for selected profile. mA for Curent + * closed loop. Talon Native Units for position and velocity. */ - public void setAllowableClosedLoopErr(int allowableCloseLoopError) - { - if(m_profile == 0){ - setParameter(CanTalonJNI.param_t.eProfileParamSlot0_AllowableClosedLoopErr, (double)allowableCloseLoopError); - }else{ - setParameter(CanTalonJNI.param_t.eProfileParamSlot1_AllowableClosedLoopErr, (double)allowableCloseLoopError); + public void setAllowableClosedLoopErr(int allowableCloseLoopError) { + if (m_profile == 0) { + setParameter(CanTalonJNI.param_t.eProfileParamSlot0_AllowableClosedLoopErr, (double) + allowableCloseLoopError); + } else { + setParameter(CanTalonJNI.param_t.eProfileParamSlot1_AllowableClosedLoopErr, (double) + allowableCloseLoopError); } } // Returns true if limit switch is closed. false if open. public boolean isFwdLimitSwitchClosed() { - return (CanTalonJNI.GetLimitSwitchClosedFor(m_handle) == 0) ? true : false; + return (CanTalonJNI.GetLimitSwitchClosedFor(m_handle) == 0); } // Returns true if limit switch is closed. false if open. public boolean isRevLimitSwitchClosed() { - return (CanTalonJNI.GetLimitSwitchClosedRev(m_handle) == 0) ? true : false; + return (CanTalonJNI.GetLimitSwitchClosedRev(m_handle) == 0); } // Returns true if break is enabled during neutral. false if coast. public boolean getBrakeEnableDuringNeutral() { - return (CanTalonJNI.GetBrakeIsEnabled(m_handle) == 0) ? false : true; + return CanTalonJNI.GetBrakeIsEnabled(m_handle) != 0; } /** @@ -769,6 +782,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont this is only for instrumentation and is not necessary for Talon functionality. */ setParameter(CanTalonJNI.param_t.eNumberEncoderCPR, m_codesPerRev); } + /** * Configure the number of turns on the potentiometer. * @@ -782,6 +796,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont this is only for instrumentation and is not necessary for Talon functionality. */ setParameter(CanTalonJNI.param_t.eNumberPotTurns, m_numPotTurns); } + /** * Returns temperature of Talon, in degrees Celsius. */ @@ -811,63 +826,60 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * TODO documentation (see CANJaguar.java) + * When using analog sensors, 0 units corresponds to 0V, 1023 units corresponds to 3.3V When using + * an analog encoder (wrapping around 1023 to 0 is possible) the units are still 3.3V per 1023 + * units. When using quadrature, each unit is a quadrature edge (4X) mode. * - * @return The position of the sensor currently providing feedback. When using - * analog sensors, 0 units corresponds to 0V, 1023 units corresponds - * to 3.3V When using an analog encoder (wrapping around 1023 to 0 is - * possible) the units are still 3.3V per 1023 units. When using - * quadrature, each unit is a quadrature edge (4X) mode. + * @return The position of the sensor currently providing feedback. */ public double getPosition() { - return ScaleNativeUnitsToRotations(m_feedbackDevice,CanTalonJNI.GetSensorPosition(m_handle)); + return scaleNativeUnitsToRotations(m_feedbackDevice, CanTalonJNI.GetSensorPosition(m_handle)); } public void setPosition(double pos) { - int nativePos = ScaleRotationsToNativeUnits(m_feedbackDevice,pos); + int nativePos = scaleRotationsToNativeUnits(m_feedbackDevice, pos); CanTalonJNI.SetSensorPosition(m_handle, nativePos); } /** - * TODO documentation (see CANJaguar.java) + * The speed units will be in the sensor's native ticks per 100ms. + * + *

For analog sensors, 3.3V corresponds to 1023 units. So a speed of 200 equates to ~0.645 dV + * per 100ms or 6.451 dV per second. If this is an analog encoder, that likely means 1.9548 + * rotations per sec. For quadrature encoders, each unit corresponds a quadrature edge (4X). So a + * 250 count encoder will produce 1000 edge events per rotation. An example speed of 200 would + * then equate to 20% of a rotation per 100ms, or 10 rotations per second. * * @return The speed of the sensor currently providing feedback. - * - * The speed units will be in the sensor's native ticks per 100ms. - * - * For analog sensors, 3.3V corresponds to 1023 units. So a speed of - * 200 equates to ~0.645 dV per 100ms or 6.451 dV per second. If this - * is an analog encoder, that likely means 1.9548 rotations per sec. - * For quadrature encoders, each unit corresponds a quadrature edge - * (4X). So a 250 count encoder will produce 1000 edge events per - * rotation. An example speed of 200 would then equate to 20% of a - * rotation per 100ms, or 10 rotations per second. */ public double getSpeed() { - return ScaleNativeUnitsToRpm(m_feedbackDevice,CanTalonJNI.GetSensorVelocity(m_handle)); + return scaleNativeUnitsToRpm(m_feedbackDevice, CanTalonJNI.GetSensorVelocity(m_handle)); } public TalonControlMode getControlMode() { return m_controlMode; } + @SuppressWarnings("JavadocMethod") public void setControlMode(int mode) { TalonControlMode tcm = TalonControlMode.valueOf(mode); - if(tcm != null) + if (tcm != null) { changeControlMode(tcm); + } } /** - * Fixup the m_controlMode so set() serializes the correct demand value. Also - * fills the modeSelecet in the control frame to disabled. - *$ + * Fixup the m_controlMode so set() serializes the correct demand value. Also fills the + * modeSelecet in the control frame to disabled. + * * @param controlMode Control mode to ultimately enter once user calls set(). * @see #set */ private void applyControlMode(TalonControlMode controlMode) { m_controlMode = controlMode; - if (controlMode == TalonControlMode.Disabled) + if (controlMode == TalonControlMode.Disabled) { m_controlEnabled = false; + } // Disable until set() is called. CanTalonJNI.SetModeSelect(m_handle, TalonControlMode.Disabled.value); @@ -875,6 +887,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont controlMode.value); } + @SuppressWarnings("JavadocMethod") public void changeControlMode(TalonControlMode controlMode) { if (m_controlMode == controlMode) { /* we already are in this mode, don't perform disable workaround */ @@ -883,6 +896,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } } + @SuppressWarnings("JavadocMethod") public void setFeedbackDevice(FeedbackDevice device) { /* save the selection so that future setters/getters know which scalars to apply */ m_feedbackDevice = device; @@ -925,10 +939,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont // } // Update the information that we have. - if (m_profile == 0) + if (m_profile == 0) { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot0_P.value); - else + } else { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot1_P.value); + } // Briefly wait for new values from the Talon. Timer.delay(kDelayForSolicitedSignals); @@ -936,6 +951,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return CanTalonJNI.GetPgain(m_handle, m_profile); } + @SuppressWarnings("JavadocMethod") public double getI() { // if(!(m_controlMode.equals(ControlMode.Position) || // m_controlMode.equals(ControlMode.Speed))) { @@ -944,10 +960,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont // } // Update the information that we have. - if (m_profile == 0) + if (m_profile == 0) { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot0_I.value); - else + } else { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot1_I.value); + } // Briefly wait for new values from the Talon. Timer.delay(kDelayForSolicitedSignals); @@ -955,6 +972,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return CanTalonJNI.GetIgain(m_handle, m_profile); } + @SuppressWarnings("JavadocMethod") public double getD() { // if(!(m_controlMode.equals(ControlMode.Position) || // m_controlMode.equals(ControlMode.Speed))) { @@ -963,10 +981,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont // } // Update the information that we have. - if (m_profile == 0) + if (m_profile == 0) { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot0_D.value); - else + } else { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot1_D.value); + } // Briefly wait for new values from the Talon. Timer.delay(kDelayForSolicitedSignals); @@ -974,6 +993,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return CanTalonJNI.GetDgain(m_handle, m_profile); } + @SuppressWarnings("JavadocMethod") public double getF() { // if(!(m_controlMode.equals(ControlMode.Position) || // m_controlMode.equals(ControlMode.Speed))) { @@ -982,10 +1002,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont // } // Update the information that we have. - if (m_profile == 0) + if (m_profile == 0) { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot0_F.value); - else + } else { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot1_F.value); + } // Briefly wait for new values from the Talon. Timer.delay(kDelayForSolicitedSignals); @@ -993,6 +1014,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return CanTalonJNI.GetFgain(m_handle, m_profile); } + @SuppressWarnings("JavadocMethod") public double getIZone() { // if(!(m_controlMode.equals(ControlMode.Position) || // m_controlMode.equals(ControlMode.Speed))) { @@ -1001,10 +1023,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont // } // Update the information that we have. - if (m_profile == 0) + if (m_profile == 0) { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot0_IZone.value); - else + } else { CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot1_IZone.value); + } // Briefly wait for new values from the Talon. Timer.delay(kDelayForSolicitedSignals); @@ -1015,8 +1038,8 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /** * Get the closed loop ramp rate for the current profile. * - * Limits the rate at which the throttle will change. Only affects position - * and speed closed loop modes. + *

Limits the rate at which the throttle will change. Only affects position and speed closed + * loop modes. * * @return rampRate Maximum change in voltage, in volts / sec. * @see #setProfile For selecting a certain profile. @@ -1029,10 +1052,13 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont // } // Update the information that we have. - if (m_profile == 0) - CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot0_CloseLoopRampRate.value); - else - CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot1_CloseLoopRampRate.value); + if (m_profile == 0) { + CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot0_CloseLoopRampRate + .value); + } else { + CanTalonJNI.RequestParam(m_handle, CanTalonJNI.param_t.eProfileParamSlot1_CloseLoopRampRate + .value); + } // Briefly wait for new values from the Talon. Timer.delay(kDelayForSolicitedSignals); @@ -1042,8 +1068,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** + * Firmware version running on the Talon. + * * @return The version of the firmware running on the Talon */ + @SuppressWarnings("MethodName") public long GetFirmwareVersion() { // Update the information that we have. @@ -1055,6 +1084,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont return CanTalonJNI.GetParamResponseInt32(m_handle, CanTalonJNI.param_t.eFirmVers.value); } + @SuppressWarnings({"MethodName", "JavadocMethod"}) public long GetIaccum() { // Update the information that we have. @@ -1072,6 +1102,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont * @param p Proportional constant for the currently selected PID profile. * @see #setProfile For selecting a certain profile. */ + @SuppressWarnings("ParameterName") public void setP(double p) { CanTalonJNI.SetPgain(m_handle, m_profile, p); } @@ -1082,6 +1113,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont * @param i Integration constant for the currently selected PID profile. * @see #setProfile For selecting a certain profile. */ + @SuppressWarnings("ParameterName") public void setI(double i) { CanTalonJNI.SetIgain(m_handle, m_profile, i); } @@ -1092,6 +1124,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont * @param d Derivative constant for the currently selected PID profile. * @see #setProfile For selecting a certain profile. */ + @SuppressWarnings("ParameterName") public void setD(double d) { CanTalonJNI.SetDgain(m_handle, m_profile, d); } @@ -1102,6 +1135,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont * @param f Feedforward constant for the currently selected PID profile. * @see #setProfile For selecting a certain profile. */ + @SuppressWarnings("ParameterName") public void setF(double f) { CanTalonJNI.SetFgain(m_handle, m_profile, f); } @@ -1109,10 +1143,9 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /** * Set the integration zone of the current Closed Loop profile. * - * Whenever the error is larger than the izone value, the accumulated - * integration error is cleared so that high errors aren't racked up when at - * high errors. An izone value of 0 means no difference from a standard PIDF - * loop. + *

Whenever the error is larger than the izone value, the accumulated integration error is + * cleared so that high errors aren't racked up when at high errors. An izone value of 0 means no + * difference from a standard PIDF loop. * * @param izone Width of the integration zone. * @see #setProfile For selecting a certain profile. @@ -1124,8 +1157,8 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /** * Set the closed loop ramp rate for the current profile. * - * Limits the rate at which the throttle will change. Only affects position - * and speed closed loop modes. + *

Limits the rate at which the throttle will change. Only affects position and speed closed + * loop modes. * * @param rampRate Maximum change in voltage, in volts / sec. * @see #setProfile For selecting a certain profile. @@ -1139,7 +1172,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /** * Set the voltage ramp rate for the current profile. * - * Limits the rate at which the throttle will change. Affects all modes. + *

Limits the rate at which the throttle will change. Affects all modes. * * @param rampRate Maximum change in voltage, in volts / sec. */ @@ -1152,9 +1185,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont public void setVoltageCompensationRampRate(double rampRate) { CanTalonJNI.SetVoltageCompensationRate(m_handle, rampRate / 1000); } + /** * Clear the accumulator for I gain. */ + @SuppressWarnings("MethodName") public void ClearIaccum() { CanTalonJNI.SetParam(m_handle, CanTalonJNI.param_t.ePidIaccum.value, 0); } @@ -1162,23 +1197,24 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /** * Sets control values for closed loop control. * - * @param p Proportional constant. - * @param i Integration constant. - * @param d Differential constant. - * @param f Feedforward constant. - * @param izone Integration zone -- prevents accumulation of integration error - * with large errors. Setting this to zero will ignore any izone stuff. - * @param closeLoopRampRate Closed loop ramp rate. Maximum change in voltage, - * in volts / sec. - * @param profile which profile to set the pid constants for. You can have two - * profiles, with values of 0 or 1, allowing you to keep a second set - * of values on hand in the talon. In order to switch profiles without - * recalling setPID, you must call setProfile(). + * @param p Proportional constant. + * @param i Integration constant. + * @param d Differential constant. + * @param f Feedforward constant. + * @param izone Integration zone -- prevents accumulation of integration error with + * large errors. Setting this to zero will ignore any izone stuff. + * @param closeLoopRampRate Closed loop ramp rate. Maximum change in voltage, in volts / sec. + * @param profile which profile to set the pid constants for. You can have two profiles, + * with values of 0 or 1, allowing you to keep a second set of values on + * hand in the talon. In order to switch profiles without recalling + * setPID, you must call setProfile(). */ + @SuppressWarnings("ParameterName") public void setPID(double p, double i, double d, double f, int izone, double closeLoopRampRate, - int profile) { - if (profile != 0 && profile != 1) + int profile) { + if (profile != 0 && profile != 1) { throw new IllegalArgumentException("Talon PID profile must be 0 or 1."); + } m_profile = profile; setProfile(profile); setP(p); @@ -1189,6 +1225,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont setCloseLoopRampRate(closeLoopRampRate); } + @SuppressWarnings("ParameterName") public void setPID(double p, double i, double d) { setPID(p, i, d, 0, 0, 0, m_profile); } @@ -1201,12 +1238,13 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Select which closed loop profile to use, and uses whatever PIDF gains and - * the such that are already there. + * Select which closed loop profile to use, and uses whatever PIDF gains and the such that are + * already there. */ public void setProfile(int profile) { - if (profile != 0 && profile != 1) + if (profile != 0 && profile != 1) { throw new IllegalArgumentException("Talon PID profile must be 0 or 1."); + } m_profile = profile; CanTalonJNI.SetProfileSlotSelect(m_handle, m_profile); } @@ -1237,7 +1275,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } public void setForwardSoftLimit(double forwardLimit) { - int nativeLimitPos = ScaleRotationsToNativeUnits(m_feedbackDevice,forwardLimit); + int nativeLimitPos = scaleRotationsToNativeUnits(m_feedbackDevice, forwardLimit); CanTalonJNI.SetForwardSoftLimit(m_handle, nativeLimitPos); } @@ -1250,11 +1288,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } public boolean isForwardSoftLimitEnabled() { - return (CanTalonJNI.GetForwardSoftEnable(m_handle) == 0) ? false : true; + return CanTalonJNI.GetForwardSoftEnable(m_handle) != 0; } public void setReverseSoftLimit(double reverseLimit) { - int nativeLimitPos = ScaleRotationsToNativeUnits(m_feedbackDevice,reverseLimit); + int nativeLimitPos = scaleRotationsToNativeUnits(m_feedbackDevice, reverseLimit); CanTalonJNI.SetReverseSoftLimit(m_handle, nativeLimitPos); } @@ -1267,13 +1305,14 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } public boolean isReverseSoftLimitEnabled() { - return (CanTalonJNI.GetReverseSoftEnable(m_handle) == 0) ? false : true; + return CanTalonJNI.GetReverseSoftEnable(m_handle) != 0; } + /** * Configure the maximum voltage that the Jaguar will ever output. * - * This can be used to limit the maximum output voltage in all modes so that - * motors which cannot withstand full bus voltage can be used safely. + *

This can be used to limit the maximum output voltage in all modes so that motors which + * cannot withstand full bus voltage can be used safely. * * @param voltage The maximum voltage output by the Jaguar. */ @@ -1282,44 +1321,53 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont configPeakOutputVoltage(voltage, -voltage); } - public void configPeakOutputVoltage(double forwardVoltage,double reverseVoltage) { + @SuppressWarnings("JavadocMethod") + public void configPeakOutputVoltage(double forwardVoltage, double reverseVoltage) { /* bounds checking */ - if(forwardVoltage > 12) + if (forwardVoltage > 12) { forwardVoltage = 12; - else if(forwardVoltage < 0) + } else if (forwardVoltage < 0) { forwardVoltage = 0; - if(reverseVoltage > 0) + } + if (reverseVoltage > 0) { reverseVoltage = 0; - else if(reverseVoltage < -12) + } else if (reverseVoltage < -12) { reverseVoltage = -12; + } /* config calls */ - setParameter(CanTalonJNI.param_t.ePeakPosOutput,1023*forwardVoltage/12.0); - setParameter(CanTalonJNI.param_t.ePeakNegOutput,1023*reverseVoltage/12.0); + setParameter(CanTalonJNI.param_t.ePeakPosOutput, 1023 * forwardVoltage / 12.0); + setParameter(CanTalonJNI.param_t.ePeakNegOutput, 1023 * reverseVoltage / 12.0); } - public void configNominalOutputVoltage(double forwardVoltage,double reverseVoltage) { + + @SuppressWarnings("JavadocMethod") + public void configNominalOutputVoltage(double forwardVoltage, double reverseVoltage) { /* bounds checking */ - if(forwardVoltage > 12) + if (forwardVoltage > 12) { forwardVoltage = 12; - else if(forwardVoltage < 0) + } else if (forwardVoltage < 0) { forwardVoltage = 0; - if(reverseVoltage > 0) + } + if (reverseVoltage > 0) { reverseVoltage = 0; - else if(reverseVoltage < -12) + } else if (reverseVoltage < -12) { reverseVoltage = -12; + } /* config calls */ - setParameter(CanTalonJNI.param_t.eNominalPosOutput,1023*forwardVoltage/12.0); - setParameter(CanTalonJNI.param_t.eNominalNegOutput,1023*reverseVoltage/12.0); + setParameter(CanTalonJNI.param_t.eNominalPosOutput, 1023 * forwardVoltage / 12.0); + setParameter(CanTalonJNI.param_t.eNominalNegOutput, 1023 * reverseVoltage / 12.0); } + /** - * General set frame. Since the parameter is a general integral type, this can - * be used for testing future features. + * General set frame. Since the parameter is a general integral type, this can be used for + * testing future features. */ - public void setParameter(CanTalonJNI.param_t paramEnum, double value){ - CanTalonJNI.SetParam(m_handle,paramEnum.value,value); + public void setParameter(CanTalonJNI.param_t paramEnum, double value) { + CanTalonJNI.SetParam(m_handle, paramEnum.value, value); } + /** - * General get frame. Since the parameter is a general integral type, this can - * be used for testing future features. + * General get frame. Since the parameter is a general integral type, this can be used for + * testing future features. */ public double getParameter(CanTalonJNI.param_t paramEnum) { /* transmit a request for this param */ @@ -1329,6 +1377,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /* poll out latest response value */ return CanTalonJNI.GetParamResponse(m_handle, paramEnum.value); } + public void clearStickyFaults() { CanTalonJNI.ClearStickyFaults(m_handle); } @@ -1339,33 +1388,35 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont } /** - * Configure the fwd limit switch to be normally open or normally closed. - * Talon will disable momentarilly if the Talon's current setting is - * dissimilar to the caller's requested setting. + * Configure the fwd limit switch to be normally open or normally closed. Talon will disable + * momentarilly if the Talon's current setting is dissimilar to the caller's requested setting. * - * Since Talon saves setting to flash this should only affect a given Talon - * initially during robot install. + *

Since Talon saves setting to flash this should only affect a given Talon initially during + * robot install. * * @param normallyOpen true for normally open. false for normally closed. */ + @SuppressWarnings("MethodName") public void ConfigFwdLimitSwitchNormallyOpen(boolean normallyOpen) { - CanTalonJNI.SetParam(m_handle, CanTalonJNI.param_t.eOnBoot_LimitSwitch_Forward_NormallyClosed.value, - normallyOpen ? 0 : 1); + CanTalonJNI.SetParam(m_handle, CanTalonJNI.param_t.eOnBoot_LimitSwitch_Forward_NormallyClosed + .value, + normallyOpen ? 0 : 1); } /** - * Configure the rev limit switch to be normally open or normally closed. - * Talon will disable momentarilly if the Talon's current setting is - * dissimilar to the caller's requested setting. + * Configure the rev limit switch to be normally open or normally closed. Talon will disable + * momentarilly if the Talon's current setting is dissimilar to the caller's requested setting. * - * Since Talon saves setting to flash this should only affect a given Talon - * initially during robot install. + *

Since Talon saves setting to flash this should only affect a given Talon initially during + * robot install. * * @param normallyOpen true for normally open. false for normally closed. */ + @SuppressWarnings("MethodName") public void ConfigRevLimitSwitchNormallyOpen(boolean normallyOpen) { - CanTalonJNI.SetParam(m_handle, CanTalonJNI.param_t.eOnBoot_LimitSwitch_Reverse_NormallyClosed.value, - normallyOpen ? 0 : 1); + CanTalonJNI.SetParam(m_handle, CanTalonJNI.param_t.eOnBoot_LimitSwitch_Reverse_NormallyClosed + .value, + normallyOpen ? 0 : 1); } public void enableBrakeMode(boolean brake) { @@ -1423,23 +1474,26 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont public int getStickyFaultRevSoftLim() { return CanTalonJNI.GetStckyFault_RevSoftLim(m_handle); } + /** - * @return Number of native units per rotation if scaling info is available. - * Zero if scaling information is not available. + * Number of native units per rotation if scaling info is available. Zero if scaling information + * is not available. + * + * @return Number of native units per rotation. */ - double GetNativeUnitsPerRotationScalar(FeedbackDevice devToLookup) - { + private double getNativeUnitsPerRotationScalar(FeedbackDevice devToLookup) { double retval = 0; boolean scalingAvail = false; - switch(devToLookup){ - case QuadEncoder: - { /* When caller wants to lookup Quadrature, the QEI may be in 1x if the selected feedback is edge counter. + switch (devToLookup) { + case QuadEncoder: { + /* When caller wants to lookup Quadrature, the QEI may be in 1x if the selected feedback + * is edge counter. * Additionally if the quadrature source is the CTRE Mag encoder, then the CPR is known. * This is nice in that the calling app does not require knowing the CPR at all. * So do both checks here. */ int qeiPulsePerCount = 4; /* default to 4x */ - switch(m_feedbackDevice){ + switch (m_feedbackDevice) { case CtreMagEncoder_Relative: case CtreMagEncoder_Absolute: /* we assume the quadrature signal comes from the MagEnc, @@ -1454,239 +1508,257 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont case QuadEncoder: /* Talon's QEI is 4x */ default: /* pulse width and everything else, assume its regular quad use. */ break; - } - if(scalingAvail){ - /* already deduced the scalar above, we're done. */ - }else{ - /* we couldn't deduce the scalar just based on the selection */ - if(0 == m_codesPerRev){ - /* caller has never set the CPR. Most likely caller - is just using engineering units so fall to the - bottom of this func.*/ - }else{ - /* Talon expects PPR units */ - retval = 4 * m_codesPerRev; - scalingAvail = true; + } + if (scalingAvail) { + /* already deduced the scalar above, we're done. */ + } else { + /* we couldn't deduce the scalar just based on the selection */ + if (0 == m_codesPerRev) { + /* + * caller has never set the CPR. Most likely caller is just using engineering units so + * fall to the bottom of this func. + */ + } else { + /* Talon expects PPR units */ + retval = 4 * m_codesPerRev; + scalingAvail = true; + } } } - } break; - case EncRising: - case EncFalling: - if(0 == m_codesPerRev){ - /* caller has never set the CPR. Most likely caller - is just using engineering units so fall to the - bottom of this func.*/ - }else{ - /* Talon expects PPR units */ - retval = 1 * m_codesPerRev; + break; + case EncRising: + case EncFalling: + if (0 == m_codesPerRev) { + /* + * caller has never set the CPR. Most likely caller + * is just using engineering units so fall to the + * bottom of this func. + */ + } else { + /* Talon expects PPR units */ + retval = 1 * m_codesPerRev; + scalingAvail = true; + } + break; + case AnalogPot: + case AnalogEncoder: + if (0 == m_numPotTurns) { + /* + * caller has never set the CPR. Most likely caller + * is just using engineering units so fall to the + * bottom of this func. + */ + } else { + retval = (double) kNativeAdcUnitsPerRotation / m_numPotTurns; + scalingAvail = true; + } + break; + case CtreMagEncoder_Relative: + case CtreMagEncoder_Absolute: + case PulseWidth: + retval = kNativePwdUnitsPerRotation; scalingAvail = true; - } - break; - case AnalogPot: - case AnalogEncoder: - if(0 == m_numPotTurns){ - /* caller has never set the CPR. Most likely caller - is just using engineering units so fall to the - bottom of this func.*/ - }else { - retval = (double)kNativeAdcUnitsPerRotation / m_numPotTurns; - scalingAvail = true; - } - break; - case CtreMagEncoder_Relative: - case CtreMagEncoder_Absolute: - case PulseWidth: - retval = kNativePwdUnitsPerRotation; - scalingAvail = true; - break; + break; + default: + break; } /* if scaling info is not available give caller zero */ - if(false == scalingAvail) + if (false == scalingAvail) { return 0; + } return retval; } + /** - * @param fullRotations double precision value representing number of rotations of selected feedback sensor. - * If user has never called the config routine for the selected sensor, then the caller - * is likely passing rotations in engineering units already, in which case it is returned - * as is. - * @see configPotentiometerTurns - * @see configEncoderCodesPerRev + * @param fullRotations double precision value representing number of rotations of selected + * feedback sensor. If user has never called the config routine for the + * selected sensor, then the caller is likely passing rotations in + * engineering units already, in which case it is returned as is. * @return fullRotations in native engineering units of the Talon SRX firmware. + * @see configPotentiometerTurns + * @see configEncoderCodesPerRev */ - int ScaleRotationsToNativeUnits(FeedbackDevice devToLookup, double fullRotations) - { + private int scaleRotationsToNativeUnits(FeedbackDevice devToLookup, double fullRotations) { /* first assume we don't have config info, prep the default return */ - int retval = (int)fullRotations; + int retval = (int) fullRotations; /* retrieve scaling info */ - double scalar = GetNativeUnitsPerRotationScalar(devToLookup); + double scalar = getNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ - if(scalar > 0) - retval = (int)(fullRotations*scalar); + if (scalar > 0) { + retval = (int) (fullRotations * scalar); + } return retval; } + /** - * @param rpm double precision value representing number of rotations per minute of selected feedback sensor. - * If user has never called the config routine for the selected sensor, then the caller - * is likely passing rotations in engineering units already, in which case it is returned - * as is. - * @see configPotentiometerTurns - * @see configEncoderCodesPerRev + * @param rpm double precision value representing number of rotations per minute of selected + * feedback sensor. If user has never called the config routine for the selected + * sensor, then the caller is likely passing rotations in engineering units already, in + * which case it is returned as is. * @return sensor velocity in native engineering units of the Talon SRX firmware. + * @see configPotentiometerTurns + * @see configEncoderCodesPerRev */ - int ScaleVelocityToNativeUnits(FeedbackDevice devToLookup, double rpm) - { + private int scaleVelocityToNativeUnits(FeedbackDevice devToLookup, double rpm) { /* first assume we don't have config info, prep the default return */ - int retval = (int)rpm; + int retval = (int) rpm; /* retrieve scaling info */ - double scalar = GetNativeUnitsPerRotationScalar(devToLookup); + double scalar = getNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ - if(scalar > 0) - retval = (int)(rpm * kMinutesPer100msUnit * scalar); + if (scalar > 0) { + retval = (int) (rpm * kMinutesPer100msUnit * scalar); + } return retval; } + /** - * @param nativePos integral position of the feedback sensor in native Talon SRX units. - * If user has never called the config routine for the selected sensor, then the return - * will be in TALON SRX units as well to match the behavior in the 2015 season. - * @see configPotentiometerTurns - * @see configEncoderCodesPerRev + * @param nativePos integral position of the feedback sensor in native Talon SRX units. If user + * has never called the config routine for the selected sensor, then the return + * will be in TALON SRX units as well to match the behavior in the 2015 season. * @return double precision number of rotations, unless config was never performed. + * @see configPotentiometerTurns + * @see configEncoderCodesPerRev */ - double ScaleNativeUnitsToRotations(FeedbackDevice devToLookup, int nativePos) - { + private double scaleNativeUnitsToRotations(FeedbackDevice devToLookup, int nativePos) { /* first assume we don't have config info, prep the default return */ - double retval = (double)nativePos; + double retval = (double) nativePos; /* retrieve scaling info */ - double scalar = GetNativeUnitsPerRotationScalar(devToLookup); + double scalar = getNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ - if(scalar > 0) - retval = ((double)nativePos) / scalar; + if (scalar > 0) { + retval = ((double) nativePos) / scalar; + } return retval; } + /** - * @param nativeVel integral velocity of the feedback sensor in native Talon SRX units. - * If user has never called the config routine for the selected sensor, then the return - * will be in TALON SRX units as well to match the behavior in the 2015 season. - * @see configPotentiometerTurns - * @see configEncoderCodesPerRev + * @param nativeVel integral velocity of the feedback sensor in native Talon SRX units. If user + * has never called the config routine for the selected sensor, then the return + * will be in TALON SRX units as well to match the behavior in the 2015 season. * @return double precision of sensor velocity in RPM, unless config was never performed. + * @see configPotentiometerTurns + * @see configEncoderCodesPerRev */ - double ScaleNativeUnitsToRpm(FeedbackDevice devToLookup, long nativeVel) - { + private double scaleNativeUnitsToRpm(FeedbackDevice devToLookup, long nativeVel) { /* first assume we don't have config info, prep the default return */ - double retval = (double)nativeVel; + double retval = (double) nativeVel; /* retrieve scaling info */ - double scalar = GetNativeUnitsPerRotationScalar(devToLookup); + double scalar = getNativeUnitsPerRotationScalar(devToLookup); /* apply scalar if its available */ - if(scalar > 0) - retval = (double)(nativeVel) / (scalar*kMinutesPer100msUnit); + if (scalar > 0) { + retval = (double) (nativeVel) / (scalar * kMinutesPer100msUnit); + } return retval; } + /** - * Enables Talon SRX to automatically zero the Sensor Position whenever an - * edge is detected on the index signal. - * @param enable boolean input, pass true to enable feature or false to disable. - * @param risingEdge boolean input, pass true to clear the position on rising edge, - * pass false to clear the position on falling edge. + * Enables Talon SRX to automatically zero the Sensor Position whenever an edge is detected on the + * index signal. + * + * @param enable boolean input, pass true to enable feature or false to disable. + * @param risingEdge boolean input, pass true to clear the position on rising edge, pass false to + * clear the position on falling edge. */ public void enableZeroSensorPositionOnIndex(boolean enable, boolean risingEdge) { - if(enable){ + if (enable) { /* enable the feature, update the edge polarity first to ensure it is correct before the feature is enabled. */ - setParameter(CanTalonJNI.param_t.eQuadIdxPolarity,risingEdge ? 1 : 0); - setParameter(CanTalonJNI.param_t.eClearPositionOnIdx,1); - }else{ + setParameter(CanTalonJNI.param_t.eQuadIdxPolarity, risingEdge ? 1 : 0); + setParameter(CanTalonJNI.param_t.eClearPositionOnIdx, 1); + } else { /* disable the feature first, then update the edge polarity. */ - setParameter(CanTalonJNI.param_t.eClearPositionOnIdx,0); - setParameter(CanTalonJNI.param_t.eQuadIdxPolarity,risingEdge ? 1 : 0); + setParameter(CanTalonJNI.param_t.eClearPositionOnIdx, 0); + setParameter(CanTalonJNI.param_t.eQuadIdxPolarity, risingEdge ? 1 : 0); } } + /** - * Calling application can opt to speed up the handshaking between the robot API and the Talon to increase the - * download rate of the Talon's Motion Profile. Ideally the period should be no more than half the period - * of a trajectory point. + * Calling application can opt to speed up the handshaking between the robot API and the Talon to + * increase the download rate of the Talon's Motion Profile. Ideally the period should be no more + * than half the period of a trajectory point. */ public void changeMotionControlFramePeriod(int periodMs) { CanTalonJNI.ChangeMotionControlFramePeriod(m_handle, periodMs); } /** - * Clear the buffered motion profile in both Talon RAM (bottom), and in the API (top). - * Be sure to check getMotionProfileStatus() to know when the buffer is actually cleared. + * Clear the buffered motion profile in both Talon RAM (bottom), and in the API (top). Be sure to + * check getMotionProfileStatus() to know when the buffer is actually cleared. */ public void clearMotionProfileTrajectories() { CanTalonJNI.ClearMotionProfileTrajectories(m_handle); } + /** - * Retrieve just the buffer count for the api-level (top) buffer. - * This routine performs no CAN or data structure lookups, so its fast and ideal - * if caller needs to quickly poll the progress of trajectory points being emptied - * into Talon's RAM. Otherwise just use GetMotionProfileStatus. + * Retrieve just the buffer count for the api-level (top) buffer. This routine performs no CAN or + * data structure lookups, so its fast and ideal if caller needs to quickly poll the progress of + * trajectory points being emptied into Talon's RAM. Otherwise just use GetMotionProfileStatus. + * * @return number of trajectory points in the top buffer. */ public int getMotionProfileTopLevelBufferCount() { return CanTalonJNI.GetMotionProfileTopLevelBufferCount(m_handle); } + /** - * Push another trajectory point into the top level buffer (which is emptied into - * the Talon's bottom buffer as room allows). - * @param targPos servo position in native Talon units (sensor units). - * @param targVel velocity to feed-forward in native Talon units (sensor units per 100ms). - * @param profileSlotSelect which slot to pull PIDF gains from. Currently supports 0 or 1. - * @param timeDurMs time in milliseconds of how long to apply this point. - * @param velOnly set to nonzero to signal Talon that only the feed-foward velocity should be - * used, i.e. do not perform PID on position. This is equivalent to setting - * PID gains to zero, but much more efficient and synchronized to MP. - * @param isLastPoint set to nonzero to signal Talon to keep processing this trajectory point, - * instead of jumping to the next one when timeDurMs expires. Otherwise - * MP executer will eventuall see an empty buffer after the last point expires, - * causing it to assert the IsUnderRun flag. However this may be desired - * if calling application nevers wants to terminate the MP. - * @param zeroPos set to nonzero to signal Talon to "zero" the selected position sensor before executing - * this trajectory point. Typically the first point should have this set only thus allowing - * the remainder of the MP positions to be relative to zero. - * @return CTR_OKAY if trajectory point push ok. CTR_BufferFull if buffer is full due to kMotionProfileTopBufferCapacity. + * Push another trajectory point into the top level buffer (which is emptied into the Talon's + * bottom buffer as room allows). + * + *

Will return CTR_OKAY if trajectory point push ok. CTR_BufferFull if buffer is full due to + * kMotionProfileTopBufferCapacity. + * + * @param trajPt {@link TrajectoryPoint} + * @return CTR_OKAY or CTR_BufferFull. */ public boolean pushMotionProfileTrajectory(TrajectoryPoint trajPt) { /* check if there is room */ - if(isMotionProfileTopLevelBufferFull()) + if (isMotionProfileTopLevelBufferFull()) { return false; + } /* convert position and velocity to native units */ - int targPos = ScaleRotationsToNativeUnits(m_feedbackDevice, trajPt.position); - int targVel = ScaleVelocityToNativeUnits(m_feedbackDevice, trajPt.velocity); + int targPos = scaleRotationsToNativeUnits(m_feedbackDevice, trajPt.position); + int targVel = scaleVelocityToNativeUnits(m_feedbackDevice, trajPt.velocity); /* bounds check signals that require it */ int profileSlotSelect = (trajPt.profileSlotSelect > 0) ? 1 : 0; int timeDurMs = trajPt.timeDurMs; /* cap time to [0ms, 255ms], 0 and 1 are both interpreted as 1ms. */ - if(timeDurMs > 255) + if (timeDurMs > 255) { timeDurMs = 255; - if(timeDurMs < 0) + } + if (timeDurMs < 0) { timeDurMs = 0; + } /* send it to the top level buffer */ - CanTalonJNI.PushMotionProfileTrajectory(m_handle, targPos, targVel, profileSlotSelect, timeDurMs, trajPt.velocityOnly ? 1 : 0, trajPt.isLastPoint ? 1 : 0, trajPt.zeroPos ? 1 : 0); + CanTalonJNI.PushMotionProfileTrajectory(m_handle, targPos, targVel, profileSlotSelect, + timeDurMs, trajPt.velocityOnly ? 1 : 0, trajPt.isLastPoint ? 1 : 0, trajPt.zeroPos ? 1 : 0); return true; } + /** * @return true if api-level (top) buffer is full. */ public boolean isMotionProfileTopLevelBufferFull() { return CanTalonJNI.IsMotionProfileTopLevelBufferFull(m_handle); } + /** - * This must be called periodically to funnel the trajectory points from the API's top level buffer to - * the Talon's bottom level buffer. Recommendation is to call this twice as fast as the executation rate of the motion profile. - * So if MP is running with 20ms trajectory points, try calling this routine every 10ms. All motion profile functions are thread-safe - * through the use of a mutex, so there is no harm in having the caller utilize threading. + * This must be called periodically to funnel the trajectory points from the API's top level + * buffer to the Talon's bottom level buffer. Recommendation is to call this twice as fast as the + * executation rate of the motion profile. So if MP is running with 20ms trajectory points, try + * calling this routine every 10ms. All motion profile functions are thread-safe through the use + * of a mutex, so there is no harm in having the caller utilize threading. */ public void processMotionProfileBuffer() { CanTalonJNI.ProcessMotionProfileBuffer(m_handle); } + /** - * Retrieve all Motion Profile status information. - * Since this all comes from one CAN frame, its ideal to have one routine to retrieve the frame once and decode everything. - * @param [out] motionProfileStatus contains all progress information on the currently running MP. Caller should - * must instantiate the motionProfileStatus object first then pass into this routine to be filled. + * Retrieve all Motion Profile status information. Since this all comes from one CAN frame, its + * ideal to have one routine to retrieve the frame once and decode everything. + * + * @param motionProfileStatus [out] contains all progress information on the currently running MP. + * Caller should must instantiate the motionProfileStatus object first + * then pass into this routine to be filled. */ public void getMotionProfileStatus(MotionProfileStatus motionProfileStatus) { CanTalonJNI.GetMotionProfileStatus(m_handle, this, motionProfileStatus); @@ -1695,35 +1767,44 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont /** * Internal method to set the contents. */ - protected void setMotionProfileStatusFromJNI(MotionProfileStatus motionProfileStatus, int flags, int profileSlotSelect, int targPos, int targVel, int topBufferRem, int topBufferCnt, int btmBufferCnt, int outputEnable) { + protected void setMotionProfileStatusFromJNI(MotionProfileStatus motionProfileStatus, + int flags, int profileSlotSelect, int targPos, + int targVel, int topBufferRem, int topBufferCnt, + int btmBufferCnt, int outputEnable) { motionProfileStatus.topBufferRem = topBufferRem; motionProfileStatus.topBufferCnt = topBufferCnt; motionProfileStatus.btmBufferCnt = btmBufferCnt; - motionProfileStatus.hasUnderrun = ((flags & CanTalonJNI.kMotionProfileFlag_HasUnderrun)>0) ? true :false; - motionProfileStatus.isUnderrun = ((flags & CanTalonJNI.kMotionProfileFlag_IsUnderrun)>0) ? true :false; - motionProfileStatus.activePointValid = ((flags & CanTalonJNI.kMotionProfileFlag_ActTraj_IsValid)>0) ? true :false; - motionProfileStatus.activePoint.isLastPoint = ((flags & CanTalonJNI.kMotionProfileFlag_ActTraj_IsLast)>0) ? true :false; - motionProfileStatus.activePoint.velocityOnly = ((flags & CanTalonJNI.kMotionProfileFlag_ActTraj_VelOnly)>0) ? true :false; - motionProfileStatus.activePoint.position = ScaleNativeUnitsToRotations(m_feedbackDevice, targPos); - motionProfileStatus.activePoint.velocity = ScaleNativeUnitsToRpm(m_feedbackDevice, targVel); + motionProfileStatus.hasUnderrun = ((flags & CanTalonJNI.kMotionProfileFlag_HasUnderrun) > 0); + motionProfileStatus.isUnderrun = ((flags & CanTalonJNI.kMotionProfileFlag_IsUnderrun) > 0); + motionProfileStatus.activePointValid = + ((flags & CanTalonJNI.kMotionProfileFlag_ActTraj_IsValid) > 0); + motionProfileStatus.activePoint.isLastPoint = + ((flags & CanTalonJNI.kMotionProfileFlag_ActTraj_IsLast) > 0); + motionProfileStatus.activePoint.velocityOnly = + ((flags & CanTalonJNI.kMotionProfileFlag_ActTraj_VelOnly) > 0); + motionProfileStatus.activePoint.position = + scaleNativeUnitsToRotations(m_feedbackDevice, targPos); + motionProfileStatus.activePoint.velocity = scaleNativeUnitsToRpm(m_feedbackDevice, targVel); motionProfileStatus.activePoint.profileSlotSelect = profileSlotSelect; motionProfileStatus.outputEnable = SetValueMotionProfile.valueOf(outputEnable); - motionProfileStatus.activePoint.zeroPos = false; // this signal is only used sending pts to Talon - motionProfileStatus.activePoint.timeDurMs = 0; // this signal is only used sending pts to Talon + motionProfileStatus.activePoint.zeroPos = false; // this signal is only used sending pts to + // Talon + motionProfileStatus.activePoint.timeDurMs = 0; // this signal is only used sending pts to } /** - * Clear the hasUnderrun flag in Talon's Motion Profile Executer when MPE is ready for another point, - * but the low level buffer is empty. + * Clear the hasUnderrun flag in Talon's Motion Profile Executer when MPE is ready for another + * point, but the low level buffer is empty. * - * Once the Motion Profile Executer sets the hasUnderrun flag, it stays set until - * Robot Application clears it with this routine, which ensures Robot Application - * gets a chance to instrument or react. Caller could also check the isUnderrun flag - * which automatically clears when fault condition is removed. + *

Once the Motion Profile Executer sets the hasUnderrun flag, it stays set until Robot + * Application clears it with this routine, which ensures Robot Application gets a chance to + * instrument or react. Caller could also check the isUnderrun flag which automatically clears + * when fault condition is removed. */ public void clearMotionProfileHasUnderrun() { setParameter(CanTalonJNI.param_t.eMotionProfileHasUnderrunErr, 0); } + @Override public void setExpiration(double timeout) { m_safetyHelper.setExpiration(timeout); @@ -1759,51 +1840,36 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, CANSpeedCont */ private ITable m_table = null; - private ITableListener m_table_listener = null; + private ITableListener m_tableListener = null; - /** - * {@inheritDoc} - */ @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ @Override public void updateTable() { CANSpeedController.super.updateTable(); } - /** - * {@inheritDoc} - */ @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ @Override public void startLiveWindowMode() { set(0); // Stop for safety - m_table_listener = createTableListener(); - m_table.addTableListener(m_table_listener, true); + m_tableListener = createTableListener(); + m_table.addTableListener(m_tableListener, true); } - /** - * {@inheritDoc} - */ @Override public void stopLiveWindowMode() { set(0); // Stop for safety // TODO: See if this is still broken - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CameraServer.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CameraServer.java index 4af3a2f5ed..2ba171fe43 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CameraServer.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CameraServer.java @@ -7,29 +7,21 @@ package edu.wpi.first.wpilibj; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicBoolean; - import com.ni.vision.NIVision; import com.ni.vision.NIVision.Image; import com.ni.vision.NIVision.RawData; import com.ni.vision.VisionException; -import edu.wpi.first.wpilibj.DriverStation; -import edu.wpi.first.wpilibj.Timer; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.Deque; + import edu.wpi.first.wpilibj.vision.USBCamera; // replicates CameraServer.cpp in java lib @@ -46,6 +38,7 @@ public class CameraServer { private static final int kMaxImageSize = 200000; private static CameraServer server; + @SuppressWarnings("JavadocMethod") public static CameraServer getInstance() { if (server == null) { server = new CameraServer(); @@ -53,7 +46,6 @@ public class CameraServer { return server; } - private Thread serverThread; private int m_quality; private boolean m_autoCaptureStarted; private boolean m_hwClient = true; @@ -61,16 +53,20 @@ public class CameraServer { private CameraData m_imageData; private Deque m_imageDataPool; - private class CameraData { - RawData data; - int start; + @SuppressWarnings("JavadocMethod") + private final class CameraData { + @SuppressWarnings("MemberName") + private final RawData data; + @SuppressWarnings("MemberName") + private final int start; - public CameraData(RawData d, int s) { - data = d; - start = s; + CameraData(RawData data, int start) { + this.data = data; + this.start = start; } } + @SuppressWarnings("JavadocMethod") private CameraServer() { m_quality = 50; m_camera = null; @@ -79,14 +75,14 @@ public class CameraServer { for (int i = 0; i < 3; i++) { m_imageDataPool.addLast(ByteBuffer.allocateDirect(kMaxImageSize)); } - serverThread = new Thread(new Runnable() { + final Thread serverThread = new Thread(new Runnable() { public void run() { try { serve(); - } catch (IOException e) { - // do stuff here - } catch (InterruptedException e) { + } catch (IOException ex) { // do stuff here + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } } }); @@ -94,11 +90,13 @@ public class CameraServer { serverThread.start(); } + @SuppressWarnings("JavadocMethod") private synchronized void setImageData(RawData data, int start) { if (m_imageData != null && m_imageData.data != null) { m_imageData.data.free(); - if (m_imageData.data.getBuffer() != null) + if (m_imageData.data.getBuffer() != null) { m_imageDataPool.addLast(m_imageData.data.getBuffer()); + } m_imageData = null; } m_imageData = new CameraData(data, start); @@ -106,12 +104,11 @@ public class CameraServer { } /** - * Manually change the image that is served by the MJPEG stream. This can be - * called to pass custom annotated images to the dashboard. Note that, for - * 640x480 video, this method could take between 40 and 50 milliseconds to - * complete. + * Manually change the image that is served by the MJPEG stream. This can be called to pass custom + * annotated images to the dashboard. Note that, for 640x480 video, this method could take between + * 40 and 50 milliseconds to complete. * - * This shouldn't be called if {@link #startAutomaticCapture} is called. + *

This shouldn't be called if {@link #startAutomaticCapture} is called. * * @param image The IMAQ image to show on the dashboard */ @@ -134,25 +131,26 @@ public class CameraServer { int index = 0; if (hwClient) { while (index < buffer.limit() - 1) { - if ((buffer.get(index) & 0xff) == 0xFF && (buffer.get(index + 1) & 0xff) == 0xD8) + if ((buffer.get(index) & 0xff) == 0xFF && (buffer.get(index + 1) & 0xff) == 0xD8) { break; + } index++; } } if (buffer.limit() - index - 1 <= 2) { - throw new VisionException("data size of flattened image is less than 2. Try another camera! "); + throw new VisionException("data size of flattened image is less than 2. Try another " + + "camera!"); } setImageData(data, index); } /** - * Start automatically capturing images to send to the dashboard. You should - * call this method to just see a camera feed on the dashboard without doing - * any vision processing on the roboRIO. {@link #setImage} shouldn't be called - * after this is called. This overload calles - * {@link #startAutomaticCapture(String)} with the default camera name + * Start automatically capturing images to send to the dashboard. You should call this method to + * just see a camera feed on the dashboard without doing any vision processing on the roboRIO. + * {@link #setImage} shouldn't be called after this is called. This overload calles {@link + * #startAutomaticCapture(String)} with the default camera name */ public void startAutomaticCapture() { startAutomaticCapture(USBCamera.kDefaultCameraName); @@ -161,9 +159,8 @@ public class CameraServer { /** * Start automatically capturing images to send to the dashboard. * - * You should call this method to just see a camera feed on the dashboard - * without doing any vision processing on the roboRIO. {@link #setImage} - * shouldn't be called after this is called. + *

You should call this method to just see a camera feed on the dashboard without doing any + * vision processing on the roboRIO. {@link #setImage} shouldn't be called after this is called. * * @param cameraName The name of the camera interface (e.g. "cam1") */ @@ -178,9 +175,11 @@ public class CameraServer { } } + @SuppressWarnings("JavadocMethod") public synchronized void startAutomaticCapture(USBCamera camera) { - if (m_autoCaptureStarted) + if (m_autoCaptureStarted) { return; + } m_autoCaptureStarted = true; m_camera = camera; @@ -232,25 +231,23 @@ public class CameraServer { } - /** - * check if auto capture is started - * + * Check if auto capture is started. */ public synchronized boolean isAutoCaptureStarted() { return m_autoCaptureStarted; } /** - * Sets the size of the image to use. Use the public kSize constants to set - * the correct mode, or set it directory on a camera and call the appropriate - * autoCapture method - *$ + * Sets the size of the image to use. Use the public kSize constants to set the correct mode, or + * set it directory on a camera and call the appropriate autoCapture method. + * * @param size The size to use */ public synchronized void setSize(int size) { - if (m_camera == null) + if (m_camera == null) { return; + } switch (size) { case kSize640x480: m_camera.setSize(640, 480); @@ -261,11 +258,13 @@ public class CameraServer { case kSize160x120: m_camera.setSize(160, 120); break; + default: + throw new IllegalArgumentException("Unsupported size: " + size); } } /** - * Set the quality of the compressed image sent to the dashboard + * Set the quality of the compressed image sent to the dashboard. * * @param quality The quality of the JPEG image, from 0 to 100 */ @@ -274,7 +273,7 @@ public class CameraServer { } /** - * Get the quality of the compressed image sent to the dashboard + * Get the quality of the compressed image sent to the dashboard. * * @return The quality, from 0 to 100 */ @@ -285,10 +284,10 @@ public class CameraServer { /** * Run the M-JPEG server. * - * This function listens for a connection from the dashboard in a background - * thread, then sends back the M-JPEG stream. + *

This function listens for a connection from the dashboard in a background thread, then + * sends back the M-JPEG stream. * - * @throws IOException if the Socket connection fails + * @throws IOException if the Socket connection fails * @throws InterruptedException if the sleep is interrupted */ protected void serve() throws IOException, InterruptedException { @@ -300,10 +299,10 @@ public class CameraServer { while (true) { try { - Socket s = socket.accept(); + Socket socket1 = socket.accept(); - DataInputStream is = new DataInputStream(s.getInputStream()); - DataOutputStream os = new DataOutputStream(s.getOutputStream()); + DataInputStream is = new DataInputStream(socket1.getInputStream()); + DataOutputStream os = new DataOutputStream(socket1.getOutputStream()); int fps = is.readInt(); int compression = is.readInt(); @@ -311,35 +310,38 @@ public class CameraServer { if (compression != kHardwareCompression) { DriverStation.reportError("Choose \"USB Camera HW\" on the dashboard", false); - s.close(); + socket1.close(); continue; } // Wait for the camera synchronized (this) { System.out.println("Camera not yet ready, awaiting image"); - if (m_camera == null) + if (m_camera == null) { wait(); + } m_hwClient = compression == kHardwareCompression; - if (!m_hwClient) + if (!m_hwClient) { setQuality(100 - compression); - else if (m_camera != null) + } else if (m_camera != null) { m_camera.setFPS(fps); + } setSize(size); } long period = (long) (1000 / (1.0 * fps)); while (true) { long t0 = System.currentTimeMillis(); - CameraData imageData = null; + final CameraData imageData; synchronized (this) { wait(); imageData = m_imageData; m_imageData = null; } - if (imageData == null) + if (imageData == null) { continue; + } // Set the buffer position to the start of the data, // and then create a new wrapper for the data at // exactly that position diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Compressor.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Compressor.java index 5148d19ab1..d3099a52c2 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Compressor.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Compressor.java @@ -7,41 +7,38 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.SensorBase; import edu.wpi.first.wpilibj.hal.CompressorJNI; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class for operating the PCM (Pneumatics compressor module) The PCM - * automatically will run in close-loop mode by default whenever a Solenoid - * object is created. For most cases the Compressor object does not need to be - * instantiated or used in a robot program. - *$ - * This class is only required in cases where more detailed status or to - * enable/disable closed loop control. Note: you cannot operate the compressor - * directly from this class as doing so would circumvent the safety provided in - * using the pressure switch and closed loop control. You can only turn off - * closed loop control, thereby stopping the compressor from operating. + * Class for operating the PCM (Pneumatics compressor module) The PCM automatically will run in + * close-loop mode by default whenever a Solenoid object is created. For most cases the Compressor + * object does not need to be instantiated or used in a robot program. This class is only required + * in cases where more detailed status or to enable/disable closed loop control. Note: you cannot + * operate the compressor directly from this class as doing so would circumvent the safety provided + * in using the pressure switch and closed loop control. You can only turn off closed loop control, + * thereby stopping the compressor from operating. */ public class Compressor extends SensorBase implements LiveWindowSendable { private long m_pcm; /** - * Create an instance of the Compressor - *$ - * @param pcmId The PCM CAN device ID. Most robots that use PCM will have a - * single module. Use this for supporting a second module other than - * the default. + * Create an instance of the Compressor. + * + *

Most robots that use PCM will have a single module. Use this for supporting a second module + * other than the default. + * + * @param pcmId The PCM CAN device ID. */ public Compressor(int pcmId) { initCompressor(pcmId); } /** - * Create an instance of the Compressor Makes a new instance of the compressor - * using the default PCM ID (0). Additional modules can be supported by making - * a new instance and specifying the CAN ID + * Create an instance of the Compressor Makes a new instance of the compressor using the default + * PCM ID (0). Additional modules can be supported by making a new instance and specifying the CAN + * ID. */ public Compressor() { initCompressor(getDefaultSolenoidModule()); @@ -54,28 +51,26 @@ public class Compressor extends SensorBase implements LiveWindowSendable { } /** - * Start the compressor running in closed loop control mode Use the method in - * cases where you would like to manually stop and start the compressor for - * applications such as conserving battery or making sure that the compressor - * motor doesn't start during critical operations. + * Start the compressor running in closed loop control mode Use the method in cases where you + * would like to manually stop and start the compressor for applications such as conserving + * battery or making sure that the compressor motor doesn't start during critical operations. */ public void start() { setClosedLoopControl(true); } /** - * Stop the compressor from running in closed loop control mode. Use the - * method in cases where you would like to manually stop and start the - * compressor for applications such as conserving battery or making sure that - * the compressor motor doesn't start during critical operations. + * Stop the compressor from running in closed loop control mode. Use the method in cases where you + * would like to manually stop and start the compressor for applications such as conserving + * battery or making sure that the compressor motor doesn't start during critical operations. */ public void stop() { setClosedLoopControl(false); } /** - * Get the enabled status of the compressor - *$ + * Get the enabled status of the compressor. + * * @return true if the compressor is on */ public boolean enabled() { @@ -83,18 +78,17 @@ public class Compressor extends SensorBase implements LiveWindowSendable { } /** - * Get the current pressure switch value - *$ - * @return true if the pressure is low by reading the pressure switch that is - * plugged into the PCM + * Get the current pressure switch value. + * + * @return true if the pressure is low by reading the pressure switch that is plugged into the PCM */ public boolean getPressureSwitchValue() { return CompressorJNI.getPressureSwitch(m_pcm); } /** - * Get the current being used by the compressor - *$ + * Get the current being used by the compressor. + * * @return current consumed in amps for the compressor motor */ public float getCompressorCurrent() { @@ -102,68 +96,73 @@ public class Compressor extends SensorBase implements LiveWindowSendable { } /** - * Set the PCM in closed loop control mode - *$ - * @param on If true sets the compressor to be in closed loop control mode - * otherwise normal operation of the compressor is disabled. + * Set the PCM in closed loop control mode. + * + * @param on If true sets the compressor to be in closed loop control mode otherwise normal + * operation of the compressor is disabled. */ public void setClosedLoopControl(boolean on) { CompressorJNI.setClosedLoopControl(m_pcm, on); } /** - * Gets the current operating mode of the PCM - *$ - * @return true if compressor is operating on closed-loop mode, otherwise - * return false. + * Gets the current operating mode of the PCM. + * + * @return true if compressor is operating on closed-loop mode, otherwise return false. */ public boolean getClosedLoopControl() { return CompressorJNI.getClosedLoopControl(m_pcm); } /** - * @return true if PCM is in fault state : Compressor Drive is disabled due to - * compressor current being too high. + * If PCM is in fault state : Compressor Drive is disabled due to compressor current being too + * high. + * + * @return true if PCM is in fault state. */ public boolean getCompressorCurrentTooHighFault() { return CompressorJNI.getCompressorCurrentTooHighFault(m_pcm); } /** - * @return true if PCM sticky fault is set : Compressor Drive is disabled due - * to compressor current being too high. + * If PCM sticky fault is set : Compressor Drive is disabled due to compressor current being too + * high. + * + * @return true if PCM sticky fault is set. */ public boolean getCompressorCurrentTooHighStickyFault() { return CompressorJNI.getCompressorCurrentTooHighStickyFault(m_pcm); } /** - * @return true if PCM sticky fault is set : Compressor output appears to be - * shorted. + * @return true if PCM sticky fault is set : Compressor output appears to be shorted. */ public boolean getCompressorShortedStickyFault() { return CompressorJNI.getCompressorShortedStickyFault(m_pcm); } /** - * @return true if PCM is in fault state : Compressor output appears to be - * shorted. + * @return true if PCM is in fault state : Compressor output appears to be shorted. */ public boolean getCompressorShortedFault() { return CompressorJNI.getCompressorShortedFault(m_pcm); } /** - * @return true if PCM sticky fault is set : Compressor does not appear to be - * wired, i.e. compressor is not drawing enough current. + * If PCM sticky fault is set : Compressor does not appear to be wired, i.e. compressor is not + * drawing enough current. + * + * @return true if PCM sticky fault is set. */ public boolean getCompressorNotConnectedStickyFault() { return CompressorJNI.getCompressorNotConnectedStickyFault(m_pcm); } /** - * @return true if PCM is in fault state : Compressor does not appear to be - * wired, i.e. compressor is not drawing enough current. + * If PCM is in fault state : Compressor does not appear to be wired, i.e. compressor is not + * drawing enough current. + * + * @return true if PCM is in fault state. */ public boolean getCompressorNotConnectedFault() { return CompressorJNI.getCompressorNotConnectedFault(m_pcm); @@ -172,22 +171,23 @@ public class Compressor extends SensorBase implements LiveWindowSendable { /** * Clear ALL sticky faults inside PCM that Compressor is wired to. * - * If a sticky fault is set, then it will be persistently cleared. Compressor - * drive maybe momentarily disable while flags are being cleared. Care should - * be taken to not call this too frequently, otherwise normal compressor - * functionality may be prevented. + *

If a sticky fault is set, then it will be persistently cleared. Compressor drive maybe + * momentarily disable while flags are being cleared. Care should be taken to not call this too + * frequently, otherwise normal compressor functionality may be prevented. * - * If no sticky faults are set then this call will have no effect. + *

If no sticky faults are set then this call will have no effect. */ public void clearAllPCMStickyFaults() { CompressorJNI.clearAllPCMStickyFaults(m_pcm); } @Override - public void startLiveWindowMode() {} + public void startLiveWindowMode() { + } @Override - public void stopLiveWindowMode() {} + public void stopLiveWindowMode() { + } @Override public String getSmartDashboardType() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ControllerPower.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ControllerPower.java index f829c194a2..f550b3cd25 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ControllerPower.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/ControllerPower.java @@ -11,8 +11,8 @@ import edu.wpi.first.wpilibj.hal.PowerJNI; public class ControllerPower { /** - * Get the input voltage to the robot controller - *$ + * Get the input voltage to the robot controller. + * * @return The controller input voltage value in Volts */ public static double getInputVoltage() { @@ -20,8 +20,8 @@ public class ControllerPower { } /** - * Get the input current to the robot controller - *$ + * Get the input current to the robot controller. + * * @return The controller input current value in Amps */ public static double getInputCurrent() { @@ -29,8 +29,8 @@ public class ControllerPower { } /** - * Get the voltage of the 3.3V rail - *$ + * Get the voltage of the 3.3V rail. + * * @return The controller 3.3V rail voltage value in Volts */ public static double getVoltage3V3() { @@ -38,8 +38,8 @@ public class ControllerPower { } /** - * Get the current output of the 3.3V rail - *$ + * Get the current output of the 3.3V rail. + * * @return The controller 3.3V rail output current value in Volts */ public static double getCurrent3V3() { @@ -47,10 +47,9 @@ public class ControllerPower { } /** - * Get the enabled state of the 3.3V rail. The rail may be disabled due to a - * controller brownout, a short circuit on the rail, or controller - * over-voltage - *$ + * Get the enabled state of the 3.3V rail. The rail may be disabled due to a controller brownout, + * a short circuit on the rail, or controller over-voltage. + * * @return The controller 3.3V rail enabled value */ public static boolean getEnabled3V3() { @@ -58,9 +57,8 @@ public class ControllerPower { } /** - * Get the count of the total current faults on the 3.3V rail since the - * controller has booted - *$ + * Get the count of the total current faults on the 3.3V rail since the controller has booted. + * * @return The number of faults */ public static int getFaultCount3V3() { @@ -68,8 +66,8 @@ public class ControllerPower { } /** - * Get the voltage of the 5V rail - *$ + * Get the voltage of the 5V rail. + * * @return The controller 5V rail voltage value in Volts */ public static double getVoltage5V() { @@ -77,8 +75,8 @@ public class ControllerPower { } /** - * Get the current output of the 5V rail - *$ + * Get the current output of the 5V rail. + * * @return The controller 5V rail output current value in Amps */ public static double getCurrent5V() { @@ -86,10 +84,9 @@ public class ControllerPower { } /** - * Get the enabled state of the 5V rail. The rail may be disabled due to a - * controller brownout, a short circuit on the rail, or controller - * over-voltage - *$ + * Get the enabled state of the 5V rail. The rail may be disabled due to a controller brownout, a + * short circuit on the rail, or controller over-voltage. + * * @return The controller 5V rail enabled value */ public static boolean getEnabled5V() { @@ -97,9 +94,8 @@ public class ControllerPower { } /** - * Get the count of the total current faults on the 5V rail since the - * controller has booted - *$ + * Get the count of the total current faults on the 5V rail since the controller has booted. + * * @return The number of faults */ public static int getFaultCount5V() { @@ -107,8 +103,8 @@ public class ControllerPower { } /** - * Get the voltage of the 6V rail - *$ + * Get the voltage of the 6V rail. + * * @return The controller 6V rail voltage value in Volts */ public static double getVoltage6V() { @@ -116,8 +112,8 @@ public class ControllerPower { } /** - * Get the current output of the 6V rail - *$ + * Get the current output of the 6V rail. + * * @return The controller 6V rail output current value in Amps */ public static double getCurrent6V() { @@ -125,10 +121,9 @@ public class ControllerPower { } /** - * Get the enabled state of the 6V rail. The rail may be disabled due to a - * controller brownout, a short circuit on the rail, or controller - * over-voltage - *$ + * Get the enabled state of the 6V rail. The rail may be disabled due to a controller brownout, a + * short circuit on the rail, or controller over-voltage. + * * @return The controller 6V rail enabled value */ public static boolean getEnabled6V() { @@ -136,9 +131,8 @@ public class ControllerPower { } /** - * Get the count of the total current faults on the 6V rail since the - * controller has booted - *$ + * Get the count of the total current faults on the 6V rail since the controller has booted. + * * @return The number of faults */ public static int getFaultCount6V() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Counter.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Counter.java index dab521295f..fe8e46bab2 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Counter.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Counter.java @@ -19,43 +19,44 @@ import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.util.BoundaryException; /** - * Class for counting the number of ticks on a digital input channel. This is a - * general purpose class for counting repetitive events. It can return the - * number of counts, the period of the most recent cycle, and detect when the - * signal being counted has stopped by supplying a maximum cycle time. + * Class for counting the number of ticks on a digital input channel. This is a general purpose + * class for counting repetitive events. It can return the number of counts, the period of the most + * recent cycle, and detect when the signal being counted has stopped by supplying a maximum cycle + * time. * - * All counters will immediately start counting - reset() them if you need them - * to be zeroed before use. + *

All counters will immediately start counting - reset() them if you need them to be zeroed + * before use. */ public class Counter extends SensorBase implements CounterBase, LiveWindowSendable, PIDSource { /** - * Mode determines how and what the counter counts + * Mode determines how and what the counter counts. */ - public static enum Mode { + public enum Mode { /** - * mode: two pulse + * mode: two pulse. */ kTwoPulse(0), /** - * mode: semi period + * mode: semi period. */ kSemiperiod(1), /** - * mode: pulse length + * mode: pulse length. */ kPulseLength(2), /** - * mode: external direction + * mode: external direction. */ kExternalDirection(3); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; - private Mode(int value) { + Mode(int value) { this.value = value; } } @@ -87,41 +88,38 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Create an instance of a counter where no sources are selected. Then they - * all must be selected by calling functions to specify the upsource and the - * downsource independently. + * Create an instance of a counter where no sources are selected. Then they all must be selected + * by calling functions to specify the upsource and the downsource independently. * - * The counter will start counting immediately. + *

The counter will start counting immediately. */ public Counter() { initCounter(Mode.kTwoPulse); } /** - * Create an instance of a counter from a Digital Input. This is used if an - * existing digital input is to be shared by multiple other objects such as - * encoders or if the Digital Source is not a DIO channel (such as an Analog - * Trigger) + * Create an instance of a counter from a Digital Input. This is used if an existing digital input + * is to be shared by multiple other objects such as encoders or if the Digital Source is not a + * DIO channel (such as an Analog Trigger) * - * The counter will start counting immediately. + *

The counter will start counting immediately. * * @param source the digital source to count */ public Counter(DigitalSource source) { - if (source == null) + if (source == null) { throw new NullPointerException("Digital Source given was null"); + } initCounter(Mode.kTwoPulse); setUpSource(source); } /** - * Create an instance of a Counter object. Create an up-Counter instance given - * a channel. + * Create an instance of a Counter object. Create an up-Counter instance given a channel. * - * The counter will start counting immediately. + *

The counter will start counting immediately. * - * @param channel the DIO channel to use as the up source. 0-9 are on-board, - * 10-25 are on the MXP + * @param channel the DIO channel to use as the up source. 0-9 are on-board, 10-25 are on the MXP */ public Counter(int channel) { initCounter(Mode.kTwoPulse); @@ -129,33 +127,35 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Create an instance of a Counter object. Create an instance of a simple - * up-Counter given an analog trigger. Use the trigger state output from the - * analog trigger. + * Create an instance of a Counter object. Create an instance of a simple up-Counter given an + * analog trigger. Use the trigger state output from the analog trigger. * - * The counter will start counting immediately. + *

The counter will start counting immediately. * * @param encodingType which edges to count - * @param upSource first source to count - * @param downSource second source for direction - * @param inverted true to invert the count + * @param upSource first source to count + * @param downSource second source for direction + * @param inverted true to invert the count */ public Counter(EncodingType encodingType, DigitalSource upSource, DigitalSource downSource, - boolean inverted) { + boolean inverted) { initCounter(Mode.kExternalDirection); + if (encodingType == null) { + throw new NullPointerException("Encoding type given was null"); + } + if (encodingType != EncodingType.k1X && encodingType != EncodingType.k2X) { throw new RuntimeException("Counters only support 1X and 2X quadreature decoding!"); } - if (upSource == null) + if (upSource == null) { throw new NullPointerException("Up Source given was null"); + } setUpSource(upSource); - if (downSource == null) + if (downSource == null) { throw new NullPointerException("Down Source given was null"); + } setDownSource(downSource); - if (encodingType == null) - throw new NullPointerException("Encoding type given was null"); - if (encodingType == EncodingType.k1X) { setUpSourceEdge(true, false); CounterJNI.setCounterAverageSize(m_counter, 1); @@ -168,11 +168,10 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Create an instance of a Counter object. Create an instance of a simple - * up-Counter given an analog trigger. Use the trigger state output from the - * analog trigger. + * Create an instance of a Counter object. Create an instance of a simple up-Counter given an + * analog trigger. Use the trigger state output from the analog trigger. * - * The counter will start counting immediately. + *

The counter will start counting immediately. * * @param trigger the analog trigger to count */ @@ -199,8 +198,11 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** + * The counter's FPGA index. + * * @return the Counter's FPGA index */ + @SuppressWarnings("AbbreviationAsWordInName") public int getFPGAIndex() { return m_index; } @@ -208,8 +210,7 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab /** * Set the upsource for the counter as a digital input channel. * - * @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the - * MXP + * @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the MXP */ public void setUpSource(int channel) { setUpSource(new DigitalInput(channel)); @@ -217,8 +218,7 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set the source object that causes the counter to count up. Set the up - * counting DigitalSource. + * Set the source object that causes the counter to count up. Set the up counting DigitalSource. * * @param source the digital source to count */ @@ -235,9 +235,8 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab /** * Set the up counting source to be an analog trigger. * - * @param analogTrigger The analog trigger object that is used for the Up - * Source - * @param triggerType The analog trigger output that will trigger the counter. + * @param analogTrigger The analog trigger object that is used for the Up Source + * @param triggerType The analog trigger output that will trigger the counter. */ public void setUpSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) { if (analogTrigger == null) { @@ -251,15 +250,16 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set the edge sensitivity on an up counting source. Set the up source to - * either detect rising edges or falling edges. + * Set the edge sensitivity on an up counting source. Set the up source to either detect rising + * edges or falling edges. * - * @param risingEdge true to count rising edge + * @param risingEdge true to count rising edge * @param fallingEdge true to count falling edge */ public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) { - if (m_upSource == null) + if (m_upSource == null) { throw new RuntimeException("Up Source must be set before setting the edge!"); + } CounterJNI.setCounterUpSourceEdge(m_counter, risingEdge, fallingEdge); } @@ -279,8 +279,7 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab /** * Set the down counting source to be a digital input channel. * - * @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the - * MXP + * @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the MXP */ public void setDownSource(int channel) { setDownSource(new DigitalInput(channel)); @@ -288,8 +287,8 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set the source object that causes the counter to count down. Set the down - * counting DigitalSource. + * Set the source object that causes the counter to count down. Set the down counting + * DigitalSource. * * @param source the digital source to count */ @@ -310,9 +309,8 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab /** * Set the down counting source to be an analog trigger. * - * @param analogTrigger The analog trigger object that is used for the Down - * Source - * @param triggerType The analog trigger output that will trigger the counter. + * @param analogTrigger The analog trigger object that is used for the Down Source + * @param triggerType The analog trigger output that will trigger the counter. */ public void setDownSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) { if (analogTrigger == null) { @@ -327,15 +325,16 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set the edge sensitivity on a down counting source. Set the down source to - * either detect rising edges or falling edges. + * Set the edge sensitivity on a down counting source. Set the down source to either detect rising + * edges or falling edges. * - * @param risingEdge true to count the rising edge + * @param risingEdge true to count the rising edge * @param fallingEdge true to count the falling edge */ public void setDownSourceEdge(boolean risingEdge, boolean fallingEdge) { - if (m_downSource == null) + if (m_downSource == null) { throw new RuntimeException(" Down Source must be set before setting the edge!"); + } CounterJNI.setCounterDownSourceEdge(m_counter, risingEdge, fallingEdge); } @@ -353,24 +352,23 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set standard up / down counting mode on this counter. Up and down counts - * are sourced independently from two inputs. + * Set standard up / down counting mode on this counter. Up and down counts are sourced + * independently from two inputs. */ public void setUpDownCounterMode() { CounterJNI.setCounterUpDownMode(m_counter); } /** - * Set external direction mode on this counter. Counts are sourced on the Up - * counter input. The Down counter input represents the direction to count. + * Set external direction mode on this counter. Counts are sourced on the Up counter input. The + * Down counter input represents the direction to count. */ public void setExternalDirectionMode() { CounterJNI.setCounterExternalDirectionMode(m_counter); } /** - * Set Semi-period mode on this counter. Counts up on both rising and falling - * edges. + * Set Semi-period mode on this counter. Counts up on both rising and falling edges. * * @param highSemiPeriod true to count up on both rising and falling */ @@ -379,21 +377,19 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Configure the counter to count in up or down based on the length of the - * input pulse. This mode is most useful for direction sensitive gear tooth - * sensors. + * Configure the counter to count in up or down based on the length of the input pulse. This mode + * is most useful for direction sensitive gear tooth sensors. * - * @param threshold The pulse length beyond which the counter counts the - * opposite direction. Units are seconds. + * @param threshold The pulse length beyond which the counter counts the opposite direction. Units + * are seconds. */ public void setPulseLengthMode(double threshold) { CounterJNI.setCounterPulseLengthMode(m_counter, threshold); } /** - * Read the current counter value. Read the value at this instant. It may - * still be running, so it reflects the current value. Next time it is read, - * it might have a different value. + * Read the current counter value. Read the value at this instant. It may still be running, so it + * reflects the current value. Next time it is read, it might have a different value. */ @Override public int get() { @@ -401,8 +397,8 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Read the current scaled counter value. Read the value at this instant, - * scaled by the distance per pulse (defaults to 1). + * Read the current scaled counter value. Read the value at this instant, scaled by the distance + * per pulse (defaults to 1). * * @return The distance since the last reset */ @@ -411,9 +407,8 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Reset the Counter to zero. Set the counter value to zero. This doesn't - * effect the running state of the counter, just sets the current value to - * zero. + * Reset the Counter to zero. Set the counter value to zero. This doesn't effect the running state + * of the counter, just sets the current value to zero. */ @Override public void reset() { @@ -421,13 +416,11 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set the maximum period where the device is still considered "moving". Sets - * the maximum period where the device is considered moving. This value is - * used to determine the "stopped" state of the counter using the GetStopped - * method. + * Set the maximum period where the device is still considered "moving". Sets the maximum period + * where the device is considered moving. This value is used to determine the "stopped" state of + * the counter using the GetStopped method. * - * @param maxPeriod The maximum period where the counted device is considered - * moving in seconds. + * @param maxPeriod The maximum period where the counted device is considered moving in seconds. */ @Override public void setMaxPeriod(double maxPeriod) { @@ -435,18 +428,15 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Select whether you want to continue updating the event timer output when - * there are no samples captured. The output of the event timer has a buffer - * of periods that are averaged and posted to a register on the FPGA. When the - * timer detects that the event source has stopped (based on the MaxPeriod) - * the buffer of samples to be averaged is emptied. If you enable the update - * when empty, you will be notified of the stopped source and the event time - * will report 0 samples. If you disable update when empty, the most recent - * average will remain on the output until a new sample is acquired. You will - * never see 0 samples output (except when there have been no events since an - * FPGA reset) and you will likely not see the stopped bit become true (since - * it is updated at the end of an average and there are no samples to - * average). + * Select whether you want to continue updating the event timer output when there are no samples + * captured. The output of the event timer has a buffer of periods that are averaged and posted to + * a register on the FPGA. When the timer detects that the event source has stopped (based on the + * MaxPeriod) the buffer of samples to be averaged is emptied. If you enable the update when + * empty, you will be notified of the stopped source and the event time will report 0 samples. If + * you disable update when empty, the most recent average will remain on the output until a new + * sample is acquired. You will never see 0 samples output (except when there have been no events + * since an FPGA reset) and you will likely not see the stopped bit become true (since it is + * updated at the end of an average and there are no samples to average). * * @param enabled true to continue updating */ @@ -455,13 +445,11 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Determine if the clock is stopped. Determine if the clocked input is - * stopped based on the MaxPeriod value set using the SetMaxPeriod method. If - * the clock exceeds the MaxPeriod, then the device (and counter) are assumed - * to be stopped and it returns true. + * Determine if the clock is stopped. Determine if the clocked input is stopped based on the + * MaxPeriod value set using the SetMaxPeriod method. If the clock exceeds the MaxPeriod, then the + * device (and counter) are assumed to be stopped and it returns true. * - * @return Returns true if the most recent counter period exceeds the - * MaxPeriod value set by SetMaxPeriod. + * @return true if the most recent counter period exceeds the MaxPeriod value set by SetMaxPeriod. */ @Override public boolean getStopped() { @@ -479,9 +467,9 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set the Counter to return reversed sensing on the direction. This allows - * counters to change the direction they are counting in the case of 1X and 2X - * quadrature encoding only. Any other counter mode isn't supported. + * Set the Counter to return reversed sensing on the direction. This allows counters to change the + * direction they are counting in the case of 1X and 2X quadrature encoding only. Any other + * counter mode isn't supported. * * @param reverseDirection true if the value counted should be negated. */ @@ -490,9 +478,8 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Get the Period of the most recent count. Returns the time interval of the - * most recent count. This can be used for velocity calculations to determine - * shaft speed. + * Get the Period of the most recent count. Returns the time interval of the most recent count. + * This can be used for velocity calculations to determine shaft speed. * * @return The period of the last two pulses in units of seconds. */ @@ -502,9 +489,9 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Get the current rate of the Counter. Read the current rate of the counter - * accounting for the distance per pulse value. The default value for distance - * per pulse (1) yields units of pulses per second. + * Get the current rate of the Counter. Read the current rate of the counter accounting for the + * distance per pulse value. The default value for distance per pulse (1) yields units of pulses + * per second. * * @return The rate in units/sec */ @@ -513,9 +500,9 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Set the Samples to Average which specifies the number of samples of the - * timer to average when calculating the period. Perform averaging to account - * for mechanical imperfections or as oversampling to increase resolution. + * Set the Samples to Average which specifies the number of samples of the timer to average when + * calculating the period. Perform averaging to account for mechanical imperfections or as + * oversampling to increase resolution. * * @param samplesToAverage The number of samples to average from 1 to 127. */ @@ -524,33 +511,31 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } /** - * Get the Samples to Average which specifies the number of samples of the - * timer to average when calculating the period. Perform averaging to account - * for mechanical imperfections or as oversampling to increase resolution. + * Get the Samples to Average which specifies the number of samples of the timer to average when + * calculating the period. Perform averaging to account for mechanical imperfections or as + * oversampling to increase resolution. * - * @return SamplesToAverage The number of samples being averaged (from 1 to - * 127) + * @return SamplesToAverage The number of samples being averaged (from 1 to 127) */ public int getSamplesToAverage() { return CounterJNI.getCounterSamplesToAverage(m_counter); } /** - * Set the distance per pulse for this counter. This sets the multiplier used - * to determine the distance driven based on the count value from the encoder. - * Set this value based on the Pulses per Revolution and factor in any gearing - * reductions. This distance can be in any units you like, linear or angular. + * Set the distance per pulse for this counter. This sets the multiplier used to determine the + * distance driven based on the count value from the encoder. Set this value based on the Pulses + * per Revolution and factor in any gearing reductions. This distance can be in any units you + * like, linear or angular. * - * @param distancePerPulse The scale factor that will be used to convert - * pulses to useful units. + * @param distancePerPulse The scale factor that will be used to convert pulses to useful units. */ public void setDistancePerPulse(double distancePerPulse) { m_distancePerPulse = distancePerPulse; } /** - * Set which parameter of the encoder you are using as a process control - * variable. The counter class supports the rate and distance parameters. + * Set which parameter of the encoder you are using as a process control variable. The counter + * class supports the rate and distance parameters. * * @param pidSource An enum to select the parameter. */ @@ -562,9 +547,6 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ public PIDSourceType getPIDSourceType() { return m_pidSource; } @@ -581,9 +563,6 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } } - /** - * Live Window code, only does anything if live window is activated. - */ @Override public String getSmartDashboardType() { return "Counter"; @@ -591,26 +570,17 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab private ITable m_table; - /** - * {@inheritDoc} - */ @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ @Override public void updateTable() { if (m_table != null) { @@ -618,15 +588,11 @@ public class Counter extends SensorBase implements CounterBase, LiveWindowSendab } } - /** - * {@inheritDoc} - */ @Override - public void startLiveWindowMode() {} + public void startLiveWindowMode() { + } - /** - * {@inheritDoc} - */ @Override - public void stopLiveWindowMode() {} + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CounterBase.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CounterBase.java index 8b4d030331..01a98979ec 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CounterBase.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/CounterBase.java @@ -8,78 +8,79 @@ package edu.wpi.first.wpilibj; /** - * Interface for counting the number of ticks on a digital input channel. - * Encoders, Gear tooth sensors, and counters should all subclass this so it can - * be used to build more advanced classes for control and driving. + * Interface for counting the number of ticks on a digital input channel. Encoders, Gear tooth + * sensors, and counters should all subclass this so it can be used to build more advanced classes + * for control and driving. * - * All counters will immediately start counting - reset() them if you need them - * to be zeroed before use. + *

All counters will immediately start counting - reset() them if you need them to be zeroed + * before use. */ public interface CounterBase { /** - * The number of edges for the counterbase to increment or decrement on + * The number of edges for the counterbase to increment or decrement on. */ - public enum EncodingType { + enum EncodingType { /** - * Count only the rising edge + * Count only the rising edge. */ k1X(0), /** - * Count both the rising and falling edge + * Count both the rising and falling edge. */ k2X(1), /** - * Count rising and falling on both channels + * Count rising and falling on both channels. */ k4X(2); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; - private EncodingType(int value) { + EncodingType(int value) { this.value = value; } } /** - * Get the count - *$ + * Get the count. + * * @return the count */ int get(); /** - * Reset the count to zero + * Reset the count to zero. */ void reset(); /** - * Get the time between the last two edges counted - *$ + * Get the time between the last two edges counted. + * * @return the time beteween the last two ticks in seconds */ double getPeriod(); /** - * Set the maximum time between edges to be considered stalled - *$ + * Set the maximum time between edges to be considered stalled. + * * @param maxPeriod the maximum period in seconds */ void setMaxPeriod(double maxPeriod); /** - * Determine if the counter is not moving - *$ + * Determine if the counter is not moving. + * * @return true if the counter has not changed for the max period */ boolean getStopped(); /** - * Determine which direction the counter is going - *$ + * Determine which direction the counter is going. + * * @return true for one direction, false for the other */ boolean getDirection(); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java index fe0cafca26..5113661e76 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java @@ -10,40 +10,41 @@ package edu.wpi.first.wpilibj; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import edu.wpi.first.wpilibj.DigitalSource; -import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.Counter; - import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; - import edu.wpi.first.wpilibj.hal.DigitalGlitchFilterJNI; /** - * Class to enable glitch filtering on a set of digital inputs. - * This class will manage adding and removing digital inputs from a FPGA glitch - * filter. The filter lets the user configure the time that an input must remain - * high or low before it is classified as high or low. + * Class to enable glitch filtering on a set of digital inputs. This class will manage adding and + * removing digital inputs from a FPGA glitch filter. The filter lets the user configure the time + * that an input must remain high or low before it is classified as high or low. */ public class DigitalGlitchFilter extends SensorBase { + + /** + * Configures the Digital Glitch Filter to its default settings. + */ public DigitalGlitchFilter() { - synchronized(m_mutex) { - int i = 0; - while (m_filterAllocated[i] != false && i < m_filterAllocated.length) { - i++; + synchronized (m_mutex) { + int index = 0; + while (m_filterAllocated[index] != false && index < m_filterAllocated.length) { + index++; } - if (i != m_filterAllocated.length) { - m_channelIndex = i; - m_filterAllocated[i] = true; + if (index != m_filterAllocated.length) { + m_channelIndex = index; + m_filterAllocated[index] = true; UsageReporting.report(tResourceType.kResourceType_DigitalFilter, - m_channelIndex, 0); + m_channelIndex, 0); } } } + /** + * Free the resources used by this object. + */ public void free() { if (m_channelIndex >= 0) { - synchronized(m_mutex) { + synchronized (m_mutex) { m_filterAllocated[m_channelIndex] = false; } m_channelIndex = -1; @@ -121,30 +122,30 @@ public class DigitalGlitchFilter extends SensorBase { } /** - * Sets the number of FPGA cycles that the input must hold steady to pass - * through this glitch filter. + * Sets the number of FPGA cycles that the input must hold steady to pass through this glitch + * filter. * - * @param fpga_cycles The number of FPGA cycles. + * @param fpgaCycles The number of FPGA cycles. */ - public void setPeriodCycles(int fpga_cycles) { - DigitalGlitchFilterJNI.setFilterPeriod(m_channelIndex, fpga_cycles); + public void setPeriodCycles(int fpgaCycles) { + DigitalGlitchFilterJNI.setFilterPeriod(m_channelIndex, fpgaCycles); } /** - * Sets the number of nanoseconds that the input must hold steady to pass - * through this glitch filter. + * Sets the number of nanoseconds that the input must hold steady to pass through this glitch + * filter. * * @param nanoseconds The number of nanoseconds. */ public void setPeriodNanoSeconds(long nanoseconds) { - int fpga_cycles = (int) (nanoseconds * kSystemClockTicksPerMicrosecond / 4 / - 1000); - setPeriodCycles(fpga_cycles); + int fpgaCycles = (int) (nanoseconds * kSystemClockTicksPerMicrosecond / 4 + / 1000); + setPeriodCycles(fpgaCycles); } /** - * Gets the number of FPGA cycles that the input must hold steady to pass - * through this glitch filter. + * Gets the number of FPGA cycles that the input must hold steady to pass through this glitch + * filter. * * @return The number of cycles. */ @@ -153,19 +154,19 @@ public class DigitalGlitchFilter extends SensorBase { } /** - * Gets the number of nanoseconds that the input must hold steady to pass - * through this glitch filter. + * Gets the number of nanoseconds that the input must hold steady to pass through this glitch + * filter. * * @return The number of nanoseconds. */ public long getPeriodNanoSeconds() { - int fpga_cycles = getPeriodCycles(); + int fpgaCycles = getPeriodCycles(); - return (long) fpga_cycles * 1000L / - (long) (kSystemClockTicksPerMicrosecond / 4); + return (long) fpgaCycles * 1000L + / (long) (kSystemClockTicksPerMicrosecond / 4); } private int m_channelIndex = -1; private static final Lock m_mutex = new ReentrantLock(true); private static final boolean[] m_filterAllocated = new boolean[3]; -}; +} diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalInput.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalInput.java index 85698dabb0..c8cf32e1a6 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalInput.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalInput.java @@ -15,20 +15,17 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class to read a digital input. This class will read digital inputs and return - * the current value on the channel. Other devices such as encoders, gear tooth - * sensors, etc. that are implemented elsewhere will automatically allocate - * digital inputs and outputs as required. This class is only for devices like - * switches etc. that aren't implemented anywhere else. + * Class to read a digital input. This class will read digital inputs and return the current value + * on the channel. Other devices such as encoders, gear tooth sensors, etc. that are implemented + * elsewhere will automatically allocate digital inputs and outputs as required. This class is only + * for devices like switches etc. that aren't implemented anywhere else. */ public class DigitalInput extends DigitalSource implements LiveWindowSendable { /** - * Create an instance of a Digital Input class. Creates a digital input given - * a channel. + * Create an instance of a Digital Input class. Creates a digital input given a channel. * - * @param channel the DIO channel for the digital input 0-9 are on-board, - * 10-25 are on the MXP + * @param channel the DIO channel for the digital input 0-9 are on-board, 10-25 are on the MXP */ public DigitalInput(int channel) { initDigitalPort(channel, true); @@ -38,13 +35,13 @@ public class DigitalInput extends DigitalSource implements LiveWindowSendable { } /** - * Get the value from a digital input channel. Retrieve the value of a single - * digital input channel from the FPGA. + * Get the value from a digital input channel. Retrieve the value of a single digital input + * channel from the FPGA. * * @return the status of the digital input */ public boolean get() { - return DIOJNI.getDIO(m_port); + return DIOJNI.getDIO(super.m_port); } /** @@ -53,7 +50,7 @@ public class DigitalInput extends DigitalSource implements LiveWindowSendable { * @return The GPIO channel number that this object represents. */ public int getChannel() { - return m_channel; + return super.m_channel; } @Override @@ -61,9 +58,7 @@ public class DigitalInput extends DigitalSource implements LiveWindowSendable { return false; } - /* - * Live Window code, only does anything if live window is activated. - */ + @Override public String getSmartDashboardType() { return "Digital Input"; @@ -71,18 +66,14 @@ public class DigitalInput extends DigitalSource implements LiveWindowSendable { private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { @@ -90,23 +81,19 @@ public class DigitalInput extends DigitalSource implements LiveWindowSendable { } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() {} - /** - * {@inheritDoc} - */ @Override - public void stopLiveWindowMode() {} + public void startLiveWindowMode() { + } + + + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalOutput.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalOutput.java index 554fae8371..5d584a2e6e 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalOutput.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalOutput.java @@ -7,18 +7,17 @@ package edu.wpi.first.wpilibj; +import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.hal.DIOJNI; import edu.wpi.first.wpilibj.hal.PWMJNI; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; /** - * Class to write digital outputs. This class will write digital outputs. Other - * devices that are implemented elsewhere will automatically allocate digital - * inputs and outputs as required. + * Class to write digital outputs. This class will write digital outputs. Other devices that are + * implemented elsewhere will automatically allocate digital inputs and outputs as required. */ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { @@ -27,11 +26,11 @@ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { private long m_pwmGenerator = invalidPwmGenerator; /** - * Create an instance of a digital output. Create an instance of a digital - * output given a channel. + * Create an instance of a digital output. Create an instance of a digital output given a + * channel. * - * @param channel the DIO channel to use for the digital output. 0-9 are - * on-board, 10-25 are on the MXP + * @param channel the DIO channel to use for the digital output. 0-9 are on-board, 10-25 are on + * the MXP */ public DigitalOutput(int channel) { initDigitalPort(channel, false); @@ -57,34 +56,32 @@ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { * @param value true is on, off is false */ public void set(boolean value) { - DIOJNI.setDIO(m_port, (short) (value ? 1 : 0)); + DIOJNI.setDIO(super.m_port, (short) (value ? 1 : 0)); } /** * @return The GPIO channel number that this object represents. */ public int getChannel() { - return m_channel; + return super.m_channel; } /** - * Generate a single pulse. Write a pulse to the specified digital output - * channel. There can only be a single pulse going at any time. + * Generate a single pulse. Write a pulse to the specified digital output channel. There can only + * be a single pulse going at any time. * - * @param channel The channel to pulse. + * @param channel The channel to pulse. * @param pulseLength The length of the pulse. */ public void pulse(final int channel, final float pulseLength) { - DIOJNI.pulse(m_port, pulseLength); + DIOJNI.pulse(super.m_port, pulseLength); } /** - * @deprecated Generate a single pulse. Write a pulse to the specified digital - * output channel. There can only be a single pulse going at any - * time. - * - * @param channel The channel to pulse. + * @param channel The channel to pulse. * @param pulseLength The length of the pulse. + * @deprecated Generate a single pulse. Write a pulse to the specified digital output channel. + * There can only be a single pulse going at any time. */ @Deprecated public void pulse(final int channel, final int pulseLength) { @@ -92,26 +89,24 @@ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { (float) (pulseLength / 1.0e9 * (DIOJNI.getLoopTiming() * 25)); System.err .println("You should use the float version of pulse for portability. This is deprecated"); - DIOJNI.pulse(m_port, convertedPulse); + DIOJNI.pulse(super.m_port, convertedPulse); } /** - * Determine if the pulse is still going. Determine if a previously started - * pulse is still going. + * Determine if the pulse is still going. Determine if a previously started pulse is still going. * * @return true if pulsing */ public boolean isPulsing() { - return DIOJNI.isPulsing(m_port); + return DIOJNI.isPulsing(super.m_port); } /** * Change the PWM frequency of the PWM output on a Digital Output line. * - * The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is - * logarithmic. + *

The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is logarithmic. * - * There is only one PWM frequency for all channnels. + *

There is only one PWM frequency for all channnels. * * @param rate The frequency to output all digital output PWM signals. */ @@ -122,19 +117,19 @@ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { /** * Enable a PWM Output on this line. * - * Allocate one of the 6 DO PWM generator resources. + *

Allocate one of the 6 DO PWM generator resources. * - * Supply the initial duty-cycle to output so as to avoid a glitch when first - * starting. + *

Supply the initial duty-cycle to output so as to avoid a glitch when first starting. * - * The resolution of the duty cycle is 8-bit for low frequencies (1kHz or - * less) but is reduced the higher the frequency of the PWM signal is. + *

The resolution of the duty cycle is 8-bit for low frequencies (1kHz or less) but is reduced + * the higher the frequency of the PWM signal is. * * @param initialDutyCycle The duty-cycle to start generating. [0..1] */ public void enablePWM(double initialDutyCycle) { - if (m_pwmGenerator != invalidPwmGenerator) + if (m_pwmGenerator != invalidPwmGenerator) { return; + } m_pwmGenerator = PWMJNI.allocatePWM(); PWMJNI.setPWMDutyCycle(m_pwmGenerator, initialDutyCycle); PWMJNI.setPWMOutputChannel(m_pwmGenerator, m_channel); @@ -143,11 +138,12 @@ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { /** * Change this line from a PWM output back to a static Digital Output line. * - * Free up one of the 6 DO PWM generator resources that were in use. + *

Free up one of the 6 DO PWM generator resources that were in use. */ public void disablePWM() { - if (m_pwmGenerator == invalidPwmGenerator) + if (m_pwmGenerator == invalidPwmGenerator) { return; + } // Disable the output by routing to a dead bit. PWMJNI.setPWMOutputChannel(m_pwmGenerator, kDigitalChannels); PWMJNI.freePWM(m_pwmGenerator); @@ -157,14 +153,16 @@ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { /** * Change the duty-cycle that is being generated on the line. * - * The resolution of the duty cycle is 8-bit for low frequencies (1kHz or - * less) but is reduced the higher the frequency of the PWM signal is. + *

The resolution of the duty cycle is 8-bit for low frequencies (1kHz or less) but is reduced + * the + * higher the frequency of the PWM signal is. * * @param dutyCycle The duty-cycle to change to. [0..1] */ public void updateDutyCycle(double dutyCycle) { - if (m_pwmGenerator == invalidPwmGenerator) + if (m_pwmGenerator == invalidPwmGenerator) { return; + } PWMJNI.setPWMDutyCycle(m_pwmGenerator, dutyCycle); } @@ -177,53 +175,43 @@ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { } private ITable m_table; - private ITableListener m_table_listener; + private ITableListener m_tableListener; + - /** - * {@inheritDoc} - */ @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { // TODO: Put current value. } - /** - * {@inheritDoc} - */ + @Override public void startLiveWindowMode() { - m_table_listener = new ITableListener() { + m_tableListener = new ITableListener() { @Override public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Boolean) value).booleanValue()); + set((Boolean) value); } }; - m_table.addTableListener("Value", m_table_listener, true); + m_table.addTableListener("Value", m_tableListener, true); } - /** - * {@inheritDoc} - */ + @Override public void stopLiveWindowMode() { // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalSource.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalSource.java index e889e4d1b5..1f9224db18 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalSource.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DigitalSource.java @@ -12,11 +12,10 @@ import edu.wpi.first.wpilibj.util.AllocationException; import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** - * DigitalSource Interface. The DigitalSource represents all the possible inputs - * for a counter or a quadrature encoder. The source may be either a digital - * input or an analog input. If the caller just provides a channel, then a - * digital input will be constructed and freed when finished for the source. The - * source can either be a digital input or analog trigger but not both. + * DigitalSource Interface. The DigitalSource represents all the possible inputs for a counter or a + * quadrature encoder. The source may be either a digital input or an analog input. If the caller + * just provides a channel, then a digital input will be constructed and freed when finished for the + * source. The source can either be a digital input or analog trigger but not both. */ public abstract class DigitalSource extends InterruptableSensorBase { @@ -36,8 +35,8 @@ public abstract class DigitalSource extends InterruptableSensorBase { throw new AllocationException("Digital input " + m_channel + " is already allocated"); } - long port_pointer = DIOJNI.getPort((byte) channel); - m_port = DIOJNI.initializeDigitalPort(port_pointer); + long portPointer = DIOJNI.getPort((byte) channel); + m_port = DIOJNI.initializeDigitalPort(portPointer); DIOJNI.allocateDIO(m_port, input); } @@ -51,7 +50,7 @@ public abstract class DigitalSource extends InterruptableSensorBase { } /** - * Get the channel routing number + * Get the channel routing number. * * @return channel routing number */ @@ -61,7 +60,7 @@ public abstract class DigitalSource extends InterruptableSensorBase { } /** - * Get the module routing number + * Get the module routing number. * * @return 0 */ @@ -71,8 +70,8 @@ public abstract class DigitalSource extends InterruptableSensorBase { } /** - * Is this an analog trigger - *$ + * Is this an analog trigger. + * * @return true if this is an analog trigger */ @Override diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DoubleSolenoid.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DoubleSolenoid.java index c7432bf153..b91a889457 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DoubleSolenoid.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DoubleSolenoid.java @@ -19,24 +19,22 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * DoubleSolenoid class for running 2 channels of high voltage Digital Output. * - * The DoubleSolenoid class is typically used for pneumatics solenoids that have - * two positions controlled by two separate channels. + *

The DoubleSolenoid class is typically used for pneumatics solenoids that have two positions + * controlled by two separate channels. */ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { /** - * Possible values for a DoubleSolenoid + * Possible values for a DoubleSolenoid. */ - public static enum Value { + public enum Value { kOff, kForward, kReverse } - private int m_forwardChannel; // /< The forward channel on the module to - // control. - private int m_reverseChannel; // /< The reverse channel on the module to - // control. + private int m_forwardChannel; // /< The forward channel on the module to control. + private int m_reverseChannel; // /< The reverse channel on the module to control. private byte m_forwardMask; // /< The mask for the forward channel. private byte m_reverseMask; // /< The mask for the reverse channel. @@ -49,14 +47,14 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { checkSolenoidChannel(m_reverseChannel); try { - m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_forwardChannel); - } catch (CheckedAllocationException e) { + allocated.allocate(m_moduleNumber * kSolenoidChannels + m_forwardChannel); + } catch (CheckedAllocationException exception) { throw new AllocationException("Solenoid channel " + m_forwardChannel + " on module " + m_moduleNumber + " is already allocated"); } try { - m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_reverseChannel); - } catch (CheckedAllocationException e) { + allocated.allocate(m_moduleNumber * kSolenoidChannels + m_reverseChannel); + } catch (CheckedAllocationException exception) { throw new AllocationException("Solenoid channel " + m_reverseChannel + " on module " + m_moduleNumber + " is already allocated"); } @@ -69,8 +67,8 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { } /** - * Constructor. Uses the default PCM ID of 0 - *$ + * Constructor. Uses the default PCM ID of 0. + * * @param forwardChannel The forward channel number on the PCM (0..7). * @param reverseChannel The reverse channel number on the PCM (0..7). */ @@ -84,11 +82,12 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { /** * Constructor. * - * @param moduleNumber The module number of the solenoid module to use. + * @param moduleNumber The module number of the solenoid module to use. * @param forwardChannel The forward channel on the module to control (0..7). * @param reverseChannel The reverse channel on the module to control (0..7). */ - public DoubleSolenoid(final int moduleNumber, final int forwardChannel, final int reverseChannel) { + public DoubleSolenoid(final int moduleNumber, final int forwardChannel, + final int reverseChannel) { super(moduleNumber); m_forwardChannel = forwardChannel; m_reverseChannel = reverseChannel; @@ -99,8 +98,8 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { * Destructor. */ public synchronized void free() { - m_allocated.free(m_moduleNumber * kSolenoidChannels + m_forwardChannel); - m_allocated.free(m_moduleNumber * kSolenoidChannels + m_reverseChannel); + allocated.free(m_moduleNumber * kSolenoidChannels + m_forwardChannel); + allocated.free(m_moduleNumber * kSolenoidChannels + m_reverseChannel); super.free(); } @@ -110,7 +109,7 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { * @param value The value to set (Off, Forward, Reverse) */ public void set(final Value value) { - byte rawValue = 0; + final byte rawValue; switch (value) { case kOff: @@ -122,6 +121,9 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { case kReverse: rawValue = m_reverseMask; break; + default: + throw new AssertionError("Illegal value: " + value); + } set(rawValue, m_forwardMask | m_reverseMask); @@ -135,21 +137,21 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { public Value get() { byte value = getAll(); - if ((value & m_forwardMask) != 0) + if ((value & m_forwardMask) != 0) { return Value.kForward; - if ((value & m_reverseMask) != 0) + } + if ((value & m_reverseMask) != 0) { return Value.kReverse; + } return Value.kOff; } /** - * Check if the forward solenoid is blacklisted. If a solenoid is shorted, it - * is added to the blacklist and disabled until power cycle, or until faults - * are cleared. - * - * @see #clearAllPCMStickyFaults() + * Check if the forward solenoid is blacklisted. If a solenoid is shorted, it is added to the + * blacklist and disabled until power cycle, or until faults are cleared. * * @return If solenoid is disabled due to short. + * @see #clearAllPCMStickyFaults() */ public boolean isFwdSolenoidBlackListed() { int blackList = getPCMSolenoidBlackList(); @@ -157,13 +159,11 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { } /** - * Check if the reverse solenoid is blacklisted. If a solenoid is shorted, it - * is added to the blacklist and disabled until power cycle, or until faults - * are cleared. - * - * @see #clearAllPCMStickyFaults() + * Check if the reverse solenoid is blacklisted. If a solenoid is shorted, it is added to the + * blacklist and disabled until power cycle, or until faults are cleared. * * @return If solenoid is disabled due to short. + * @see #clearAllPCMStickyFaults() */ public boolean isRevSolenoidBlackListed() { int blackList = getPCMSolenoidBlackList(); @@ -178,26 +178,20 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { } private ITable m_table; - private ITableListener m_table_listener; + private ITableListener m_tableListener; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { // TODO: this is bad @@ -206,31 +200,28 @@ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { } } - /** - * {@inheritDoc} - */ + @Override public void startLiveWindowMode() { set(Value.kOff); // Stop for safety - m_table_listener = new ITableListener() { + m_tableListener = new ITableListener() { public void valueChanged(ITable itable, String key, Object value, boolean bln) { // TODO: this is bad also - if (value.toString().equals("Reverse")) + if (value.toString().equals("Reverse")) { set(Value.kReverse); - else if (value.toString().equals("Forward")) + } else if (value.toString().equals("Forward")) { set(Value.kForward); - else + } else { set(Value.kOff); + } } }; - m_table.addTableListener("Value", m_table_listener, true); + m_table.addTableListener("Value", m_tableListener, true); } - /** - * {@inheritDoc} - */ + @Override public void stopLiveWindowMode() { set(Value.kOff); // Stop for safety // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DriverStation.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DriverStation.java index 650b271bb9..7f95b5d738 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DriverStation.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/DriverStation.java @@ -10,29 +10,28 @@ package edu.wpi.first.wpilibj; import java.nio.ByteBuffer; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; -import edu.wpi.first.wpilibj.communication.HALControlWord; import edu.wpi.first.wpilibj.communication.HALAllianceStationID; +import edu.wpi.first.wpilibj.communication.HALControlWord; import edu.wpi.first.wpilibj.hal.HALUtil; import edu.wpi.first.wpilibj.hal.PowerJNI; /** - * Provide access to the network communication data to / from the Driver - * Station. + * Provide access to the network communication data to / from the Driver Station. */ public class DriverStation implements RobotState.Interface { /** - * Number of Joystick Ports + * Number of Joystick Ports. */ public static final int kJoystickPorts = 6; private class HALJoystickButtons { - public int buttons; - public byte count; + public int m_buttons; + public byte m_count; } /** - * The robot alliance that the robot is a part of + * The robot alliance that the robot is a part of. */ public enum Alliance { Red, Blue, Invalid @@ -69,7 +68,7 @@ public class DriverStation implements RobotState.Interface { private Thread m_thread; private final Object m_dataSem; - private volatile boolean m_thread_keepalive = true; + private volatile boolean m_threadKeepAlive = true; private boolean m_userInDisabled = false; private boolean m_userInAutonomous = false; private boolean m_userInTeleop = false; @@ -90,8 +89,8 @@ public class DriverStation implements RobotState.Interface { /** * DriverStation constructor. * - * The single DriverStation instance is created statically with the instance - * static member variable. + *

The single DriverStation instance is created statically with the instance static member + * variable. */ protected DriverStation() { m_dataSem = new Object(); @@ -110,18 +109,18 @@ public class DriverStation implements RobotState.Interface { } /** - * Kill the thread + * Kill the thread. */ public void release() { - m_thread_keepalive = false; + m_threadKeepAlive = false; } /** - * Provides the service routine for the DS polling thread. + * Provides the service routine for the DS polling m_thread. */ private void task() { int safetyCounter = 0; - while (m_thread_keepalive) { + while (m_threadKeepAlive) { HALUtil.takeMultiWait(m_packetDataAvailableSem, m_packetDataAvailableMutex); synchronized (this) { getData(); @@ -156,8 +155,8 @@ public class DriverStation implements RobotState.Interface { } /** - * Wait for new data or for timeout, which ever comes first. If timeout is 0, - * wait for new data only. + * Wait for new data or for timeout, which ever comes first. If timeout is 0, wait for new data + * only. * * @param timeout The maximum time in milliseconds to wait. */ @@ -166,14 +165,14 @@ public class DriverStation implements RobotState.Interface { try { m_dataSem.wait(timeout); } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } } } /** - * Copy data from the DS task for the user. If no new data exists, it will - * just be returned, otherwise the data will be copied from the DS polling - * loop. + * Copy data from the DS task for the user. If no new data exists, it will just be returned, + * otherwise the data will be copied from the DS polling loop. */ protected synchronized void getData() { @@ -182,9 +181,9 @@ public class DriverStation implements RobotState.Interface { m_joystickAxes[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickAxes(stick); m_joystickPOVs[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickPOVs(stick); ByteBuffer countBuffer = ByteBuffer.allocateDirect(1); - m_joystickButtons[stick].buttons = - FRCNetworkCommunicationsLibrary.HALGetJoystickButtons((byte) stick, countBuffer); - m_joystickButtons[stick].count = countBuffer.get(); + m_joystickButtons[stick].m_buttons = + FRCNetworkCommunicationsLibrary.HALGetJoystickButtons(stick, countBuffer); + m_joystickButtons[stick].m_count = countBuffer.get(); } m_newControlData = true; @@ -200,8 +199,8 @@ public class DriverStation implements RobotState.Interface { } /** - * Reports errors related to unplugged joysticks Throttles the errors so that - * they don't overwhelm the DS + * Reports errors related to unplugged joysticks Throttles the errors so that they don't overwhelm + * the DS. */ private void reportJoystickUnpluggedError(String message) { double currentTime = Timer.getFPGATimestamp(); @@ -212,8 +211,8 @@ public class DriverStation implements RobotState.Interface { } /** - * Reports errors related to unplugged joysticks Throttles the errors so that - * they don't overwhelm the DS + * Reports errors related to unplugged joysticks Throttles the errors so that they don't overwhelm + * the DS. */ private void reportJoystickUnpluggedWarning(String message) { double currentTime = Timer.getFPGATimestamp(); @@ -224,11 +223,11 @@ public class DriverStation implements RobotState.Interface { } /** - * Get the value of the axis on a joystick. This depends on the mapping of the - * joystick connected to the specified port. + * Get the value of the axis on a joystick. This depends on the mapping of the joystick connected + * to the specified port. * * @param stick The joystick to read. - * @param axis The analog axis value to read from the joystick. + * @param axis The analog axis value to read from the joystick. * @return The value of the axis on the joystick. */ public synchronized double getStickAxis(int stick, int axis) { @@ -256,7 +255,7 @@ public class DriverStation implements RobotState.Interface { } /** - * Returns the number of axes on a given joystick port + * Returns the number of axes on a given joystick port. * * @param stick The joystick port number * @return The number of axes on the indicated joystick @@ -294,7 +293,7 @@ public class DriverStation implements RobotState.Interface { } /** - * Returns the number of POVs on a given joystick port + * Returns the number of POVs on a given joystick port. * * @param stick The joystick port number * @return The number of POVs on the indicated joystick @@ -319,13 +318,13 @@ public class DriverStation implements RobotState.Interface { throw new RuntimeException("Joystick index is out of range, should be 0-3"); } - return m_joystickButtons[stick].buttons; + return m_joystickButtons[stick].m_buttons; } /** * The state of one joystick button. Button indexes begin at 1. * - * @param stick The joystick to read. + * @param stick The joystick to read. * @param button The button index, beginning at 1. * @return The state of the joystick button. */ @@ -335,7 +334,7 @@ public class DriverStation implements RobotState.Interface { } - if (button > m_joystickButtons[stick].count) { + if (button > m_joystickButtons[stick].m_count) { reportJoystickUnpluggedWarning("Joystick Button " + button + " on port " + stick + " not available, check if controller is plugged in"); return false; @@ -344,11 +343,11 @@ public class DriverStation implements RobotState.Interface { reportJoystickUnpluggedError("Button indexes begin at 1 in WPILib for C++ and Java"); return false; } - return ((0x1 << (button - 1)) & m_joystickButtons[stick].buttons) != 0; + return ((0x1 << (button - 1)) & m_joystickButtons[stick].m_buttons) != 0; } /** - * Gets the number of buttons on a joystick + * Gets the number of buttons on a joystick. * * @param stick The joystick port number * @return The number of buttons on the indicated joystick @@ -360,11 +359,11 @@ public class DriverStation implements RobotState.Interface { } - return m_joystickButtons[stick].count; + return m_joystickButtons[stick].m_count; } /** - * Gets the value of isXbox on a joystick + * Gets the value of isXbox on a joystick. * * @param stick The joystick port number * @return A boolean that returns the value of isXbox @@ -376,7 +375,7 @@ public class DriverStation implements RobotState.Interface { } // TODO: Remove this when calling for descriptor on empty stick no longer // crashes - if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { + if (1 > m_joystickButtons[stick].m_count && 1 > m_joystickAxes[stick].length) { reportJoystickUnpluggedWarning("Joystick on port " + stick + " not available, check if controller is plugged in"); return false; @@ -389,7 +388,7 @@ public class DriverStation implements RobotState.Interface { } /** - * Gets the value of type on a joystick + * Gets the value of type on a joystick. * * @param stick The joystick port number * @return The value of type @@ -401,7 +400,7 @@ public class DriverStation implements RobotState.Interface { } // TODO: Remove this when calling for descriptor on empty stick no longer // crashes - if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { + if (1 > m_joystickButtons[stick].m_count && 1 > m_joystickAxes[stick].length) { reportJoystickUnpluggedWarning("Joystick on port " + stick + " not available, check if controller is plugged in"); return -1; @@ -410,7 +409,7 @@ public class DriverStation implements RobotState.Interface { } /** - * Gets the name of the joystick at a port + * Gets the name of the joystick at a port. * * @param stick The joystick port number * @return The value of name @@ -422,7 +421,7 @@ public class DriverStation implements RobotState.Interface { } // TODO: Remove this when calling for descriptor on empty stick no longer // crashes - if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { + if (1 > m_joystickButtons[stick].m_count && 1 > m_joystickAxes[stick].length) { reportJoystickUnpluggedWarning("Joystick on port " + stick + " not available, check if controller is plugged in"); return ""; @@ -431,8 +430,7 @@ public class DriverStation implements RobotState.Interface { } /** - * Gets a value indicating whether the Driver Station requires the robot to be - * enabled. + * Gets a value indicating whether the Driver Station requires the robot to be enabled. * * @return True if the robot is enabled, false otherwise. */ @@ -442,8 +440,7 @@ public class DriverStation implements RobotState.Interface { } /** - * Gets a value indicating whether the Driver Station requires the robot to be - * disabled. + * Gets a value indicating whether the Driver Station requires the robot to be disabled. * * @return True if the robot should be disabled, false otherwise. */ @@ -452,8 +449,8 @@ public class DriverStation implements RobotState.Interface { } /** - * Gets a value indicating whether the Driver Station requires the robot to be - * running in autonomous mode. + * Gets a value indicating whether the Driver Station requires the robot to be running in + * autonomous mode. * * @return True if autonomous mode should be enabled, false otherwise. */ @@ -463,9 +460,9 @@ public class DriverStation implements RobotState.Interface { } /** - * Gets a value indicating whether the Driver Station requires the robot to be - * running in test mode. - *$ + * Gets a value indicating whether the Driver Station requires the robot to be running in test + * mode. + * * @return True if test mode should be enabled, false otherwise. */ public boolean isTest() { @@ -474,20 +471,18 @@ public class DriverStation implements RobotState.Interface { } /** - * Gets a value indicating whether the Driver Station requires the robot to be - * running in operator-controlled mode. + * Gets a value indicating whether the Driver Station requires the robot to be running in + * operator-controlled mode. * - * @return True if operator-controlled mode should be enabled, false - * otherwise. + * @return True if operator-controlled mode should be enabled, false otherwise. */ public boolean isOperatorControl() { return !(isAutonomous() || isTest()); } /** - * Gets a value indicating whether the FPGA outputs are enabled. The outputs - * may be disabled if the robot is disabled or e-stopped, the watdhog has - * expired, or if the roboRIO browns out. + * Gets a value indicating whether the FPGA outputs are enabled. The outputs may be disabled if + * the robot is disabled or e-stopped, the watdhog has expired, or if the roboRIO browns out. * * @return True if the FPGA outputs are enabled. */ @@ -497,7 +492,7 @@ public class DriverStation implements RobotState.Interface { /** * Check if the system is browned out. - *$ + * * @return True if the system is browned out */ public boolean isBrownedOut() { @@ -505,9 +500,9 @@ public class DriverStation implements RobotState.Interface { } /** - * Has a new control packet from the driver station arrived since the last - * time this function was called? - *$ + * Has a new control packet from the driver station arrived since the last time this function was + * called? + * * @return True if the control data has been updated since the last call. */ public synchronized boolean isNewControlData() { @@ -517,8 +512,8 @@ public class DriverStation implements RobotState.Interface { } /** - * Get the current alliance from the FMS - *$ + * Get the current alliance from the FMS. + * * @return the current alliance */ public Alliance getAlliance() { @@ -574,11 +569,10 @@ public class DriverStation implements RobotState.Interface { } /** - * Is the driver station attached to a Field Management System? Note: This - * does not work with the Blue DS. - *$ - * @return True if the robot is competing on a field being controlled by a - * Field Management System + * Is the driver station attached to a Field Management System? Note: This does not work with the + * Blue DS. + * + * @return True if the robot is competing on a field being controlled by a Field Management System */ public boolean isFMSAttached() { HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); @@ -591,14 +585,12 @@ public class DriverStation implements RobotState.Interface { } /** - * Return the approximate match time The FMS does not send an official match - * time to the robots, but does send an approximate match time. The value will - * count down the time remaining in the current period (auto or teleop). - * Warning: This is not an official time (so it cannot be used to dispute ref - * calls or guarantee that a function will trigger before the match ends) The - * Practice Match function of the DS approximates the behaviour seen on the - * field. - *$ + * Return the approximate match time The FMS does not send an official match time to the robots, + * but does send an approximate match time. The value will count down the time remaining in the + * current period (auto or teleop). Warning: This is not an official time (so it cannot be used to + * dispute ref calls or guarantee that a function will trigger before the match ends) The + * Practice Match function of the DS approximates the behaviour seen on the field. + * * @return Time remaining in current match period (auto or teleop) in seconds */ public double getMatchTime() { @@ -606,9 +598,9 @@ public class DriverStation implements RobotState.Interface { } /** - * Report error to Driver Station. Also prints error to System.err Optionally - * appends Stack trace to error message - *$ + * Report error to Driver Station. Also prints error to System.err Optionally appends Stack trace + * to error message. + * * @param printTrace If true, append stack trace to error string */ public static void reportError(String error, boolean printTrace) { @@ -616,25 +608,26 @@ public class DriverStation implements RobotState.Interface { } /** - * Report warning to Driver Station. Also prints error to System.err Optionally - * appends Stack trace to warning message - *$ + * Report warning to Driver Station. Also prints error to System.err Optionally appends Stack + * trace to warning message. + * * @param printTrace If true, append stack trace to warning string */ public static void reportWarning(String error, boolean printTrace) { reportErrorImpl(false, 1, error, printTrace); } - private static void reportErrorImpl(boolean is_error, int code, String error, boolean printTrace) { + private static void reportErrorImpl(boolean isError, int code, String error, boolean + printTrace) { StackTraceElement[] traces = Thread.currentThread().getStackTrace(); String locString; - if (traces.length > 3) + if (traces.length > 3) { locString = traces[3].toString(); - else + } else { locString = new String(); + } boolean haveLoc = false; - String traceString = new String(); - traceString = " at "; + String traceString = " at "; for (int i = 3; i < traces.length; i++) { String loc = traces[i].toString(); traceString += loc + "\n"; @@ -644,48 +637,50 @@ public class DriverStation implements RobotState.Interface { haveLoc = true; } } - FRCNetworkCommunicationsLibrary.HALSendError(is_error, code, false, error, locString, printTrace ? traceString : "", true); + FRCNetworkCommunicationsLibrary.HALSendError(isError, code, false, error, locString, + printTrace ? traceString : "", true); } /** - * Only to be used to tell the Driver Station what code you claim to be - * executing for diagnostic purposes only - *$ - * @param entering If true, starting disabled code; if false, leaving disabled - * code + * Only to be used to tell the Driver Station what code you claim to be executing for diagnostic + * purposes only. + * + * @param entering If true, starting disabled code; if false, leaving disabled code */ + @SuppressWarnings("MethodName") public void InDisabled(boolean entering) { m_userInDisabled = entering; } /** - * Only to be used to tell the Driver Station what code you claim to be - * executing for diagnostic purposes only - *$ - * @param entering If true, starting autonomous code; if false, leaving - * autonomous code + * Only to be used to tell the Driver Station what code you claim to be executing for diagnostic + * purposes only. + * + * @param entering If true, starting autonomous code; if false, leaving autonomous code */ + @SuppressWarnings("MethodName") public void InAutonomous(boolean entering) { m_userInAutonomous = entering; } /** - * Only to be used to tell the Driver Station what code you claim to be - * executing for diagnostic purposes only - *$ - * @param entering If true, starting teleop code; if false, leaving teleop - * code + * Only to be used to tell the Driver Station what code you claim to be executing for diagnostic + * purposes only. + * + * @param entering If true, starting teleop code; if false, leaving teleop code */ + @SuppressWarnings("MethodName") public void InOperatorControl(boolean entering) { m_userInTeleop = entering; } /** - * Only to be used to tell the Driver Station what code you claim to be - * executing for diagnostic purposes only - *$ + * Only to be used to tell the Driver Station what code you claim to be executing for diagnostic + * purposes only. + * * @param entering If true, starting test code; if false, leaving test code */ + @SuppressWarnings("MethodName") public void InTest(boolean entering) { m_userInTest = entering; } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Encoder.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Encoder.java index 403bf9911d..4937cc9106 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Encoder.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Encoder.java @@ -7,30 +7,27 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; import java.nio.ByteBuffer; +import java.nio.ByteOrder; -import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.hal.EncoderJNI; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; -import edu.wpi.first.wpilibj.util.BoundaryException; /** - * Class to read quad encoders. Quadrature encoders are devices that count shaft - * rotation and can sense direction. The output of the QuadEncoder class is an - * integer that can count either up or down, and can go negative for reverse - * direction counting. When creating QuadEncoders, a direction is supplied that - * changes the sense of the output to make code more readable if the encoder is - * mounted such that forward movement generates negative values. Quadrature - * encoders have two digital outputs, an A Channel and a B Channel that are out - * of phase with each other to allow the FPGA to do direction sensing. + * Class to read quad encoders. Quadrature encoders are devices that count shaft rotation and can + * sense direction. The output of the QuadEncoder class is an integer that can count either up or + * down, and can go negative for reverse direction counting. When creating QuadEncoders, a direction + * is supplied that changes the sense of the output to make code more readable if the encoder is + * mounted such that forward movement generates negative values. Quadrature encoders have two + * digital outputs, an A Channel and a B Channel that are out of phase with each other to allow the + * FPGA to do direction sensing. * - * All encoders will immediately start counting - reset() them if you need them - * to be zeroed before use. + *

All encoders will immediately start counting - reset() them if you need them to be zeroed + * before use. */ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveWindowSendable { public enum IndexingType { @@ -38,15 +35,17 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * The a source + * The a source. */ + @SuppressWarnings("MemberName") protected DigitalSource m_aSource; // the A phase of the quad encoder /** - * The b source + * The b source. */ + @SuppressWarnings("MemberName") protected DigitalSource m_bSource; // the B phase of the quad encoder /** - * The index source + * The index source. */ protected DigitalSource m_indexSource = null; // Index on some encoders private long m_encoder; @@ -54,27 +53,27 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW private double m_distancePerPulse; // distance of travel for each encoder // tick private Counter m_counter; // Counter object for 1x and 2x encoding + /** + * Either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is selected, then an encoder + * FPGA object is used and the returned counts will be 4x the encoder spec'd value since all + * rising and falling edges are counted. If 1X or 2X are selected then a counter object will be + * used and the returned value will either exactly match the spec'd count or be double (2x) the + * spec'd count. + */ private EncodingType m_encodingType = EncodingType.k4X; - private int m_encodingScale; // 1x, 2x, or 4x, per the encodingType + private int m_encodingScale; // 1x, 2x, or 4x, per the m_encodingType private boolean m_allocatedA; private boolean m_allocatedB; private boolean m_allocatedI; private PIDSourceType m_pidSource; /** - * Common initialization code for Encoders. This code allocates resources for - * Encoders and is common to all constructors. + * Common initialization code for Encoders. This code allocates resources for Encoders and is + * common to all constructors. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param reverseDirection If true, counts down instead of up (this is all - * relative) - * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X - * decoding. If 4X is selected, then an encoder FPGA object is used and - * the returned counts will be 4x the encoder spec'd value since all - * rising and falling edges are counted. If 1X or 2X are selected then - * a counter object will be used and the returned value will either - * exactly match the spec'd count or be double (2x) the spec'd count. + * @param reverseDirection If true, counts down instead of up (this is all relative) */ private void initEncoder(boolean reverseDirection) { switch (m_encodingType) { @@ -84,9 +83,9 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW // set the byte order index.order(ByteOrder.LITTLE_ENDIAN); m_encoder = - EncoderJNI.initializeEncoder((byte) m_aSource.getModuleForRouting(), m_aSource - .getChannelForRouting(), m_aSource.getAnalogTriggerForRouting(), - (byte) m_bSource.getModuleForRouting(), m_bSource.getChannelForRouting(), + EncoderJNI.initializeEncoder(m_aSource.getModuleForRouting(), m_aSource + .getChannelForRouting(), m_aSource.getAnalogTriggerForRouting(), + m_bSource.getModuleForRouting(), m_bSource.getChannelForRouting(), m_bSource.getAnalogTriggerForRouting(), reverseDirection, index.asIntBuffer()); m_index = index.asIntBuffer().get(0); @@ -99,6 +98,8 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW m_counter = new Counter(m_encodingType, m_aSource, m_bSource, reverseDirection); m_index = m_counter.getFPGAIndex(); break; + default: + throw new AssertionError("Illegal encoding type: " + m_encodingType); } m_distancePerPulse = 1.0; m_pidSource = PIDSourceType.kDisplacement; @@ -110,249 +111,249 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW /** * Encoder constructor. Construct a Encoder given a and b channels. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25 are on - * the MXP port - * @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25 are on - * the MXP port - * @param reverseDirection represents the orientation of the encoder and - * inverts the output values if necessary so forward represents - * positive values. + * @param channelA The a channel DIO channel. 0-9 are on-board, 10-25 are on the MXP port + * @param channelB The b channel DIO channel. 0-9 are on-board, 10-25 are on the MXP port + * @param reverseDirection represents the orientation of the encoder and inverts the output values + * if necessary so forward represents positive values. */ - public Encoder(final int aChannel, final int bChannel, boolean reverseDirection) { + public Encoder(final int channelA, final int channelB, boolean reverseDirection) { m_allocatedA = true; m_allocatedB = true; m_allocatedI = false; - m_aSource = new DigitalInput(aChannel); - m_bSource = new DigitalInput(bChannel); + m_aSource = new DigitalInput(channelA); + m_bSource = new DigitalInput(channelB); initEncoder(reverseDirection); } /** * Encoder constructor. Construct a Encoder given a and b channels. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aChannel The a channel digital input channel. - * @param bChannel The b channel digital input channel. + * @param channelA The a channel digital input channel. + * @param channelB The b channel digital input channel. */ - public Encoder(final int aChannel, final int bChannel) { - this(aChannel, bChannel, false); + public Encoder(final int channelA, final int channelB) { + this(channelA, channelB, false); } /** * Encoder constructor. Construct a Encoder given a and b channels. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aChannel The a channel digital input channel. - * @param bChannel The b channel digital input channel. - * @param reverseDirection represents the orientation of the encoder and - * inverts the output values if necessary so forward represents - * positive values. - * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X - * decoding. If 4X is selected, then an encoder FPGA object is used and - * the returned counts will be 4x the encoder spec'd value since all - * rising and falling edges are counted. If 1X or 2X are selected then - * a counter object will be used and the returned value will either - * exactly match the spec'd count or be double (2x) the spec'd count. + * @param channelA The a channel digital input channel. + * @param channelB The b channel digital input channel. + * @param reverseDirection represents the orientation of the encoder and inverts the output values + * if necessary so forward represents positive values. + * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is + * selected, then an encoder FPGA object is used and the returned counts + * will be 4x the encoder spec'd value since all rising and falling edges + * are counted. If 1X or 2X are selected then a m_counter object will be + * used and the returned value will either exactly match the spec'd count + * or be double (2x) the spec'd count. */ - public Encoder(final int aChannel, final int bChannel, boolean reverseDirection, - final EncodingType encodingType) { + public Encoder(final int channelA, final int channelB, boolean reverseDirection, + final EncodingType encodingType) { m_allocatedA = true; m_allocatedB = true; m_allocatedI = false; - if (encodingType == null) + if (encodingType == null) { throw new NullPointerException("Given encoding type was null"); + } m_encodingType = encodingType; - m_aSource = new DigitalInput(aChannel); - m_bSource = new DigitalInput(bChannel); + m_aSource = new DigitalInput(channelA); + m_bSource = new DigitalInput(channelB); initEncoder(reverseDirection); } /** - * Encoder constructor. Construct a Encoder given a and b channels. Using an - * index pulse forces 4x encoding + * Encoder constructor. Construct a Encoder given a and b channels. Using an index pulse forces 4x + * encoding * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aChannel The a channel digital input channel. - * @param bChannel The b channel digital input channel. - * @param indexChannel The index channel digital input channel. - * @param reverseDirection represents the orientation of the encoder and - * inverts the output values if necessary so forward represents - * positive values. + * @param channelA The a channel digital input channel. + * @param channelB The b channel digital input channel. + * @param indexChannel The index channel digital input channel. + * @param reverseDirection represents the orientation of the encoder and inverts the output values + * if necessary so forward represents positive values. */ - public Encoder(final int aChannel, final int bChannel, final int indexChannel, - boolean reverseDirection) { + public Encoder(final int channelA, final int channelB, final int indexChannel, + boolean reverseDirection) { m_allocatedA = true; m_allocatedB = true; m_allocatedI = true; - m_aSource = new DigitalInput(aChannel); - m_bSource = new DigitalInput(bChannel); + m_aSource = new DigitalInput(channelA); + m_bSource = new DigitalInput(channelB); m_indexSource = new DigitalInput(indexChannel); initEncoder(reverseDirection); setIndexSource(indexChannel); } /** - * Encoder constructor. Construct a Encoder given a and b channels. Using an - * index pulse forces 4x encoding + * Encoder constructor. Construct a Encoder given a and b channels. Using an index pulse forces 4x + * encoding * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aChannel The a channel digital input channel. - * @param bChannel The b channel digital input channel. + * @param channelA The a channel digital input channel. + * @param channelB The b channel digital input channel. * @param indexChannel The index channel digital input channel. */ - public Encoder(final int aChannel, final int bChannel, final int indexChannel) { - this(aChannel, bChannel, indexChannel, false); + public Encoder(final int channelA, final int channelB, final int indexChannel) { + this(channelA, channelB, indexChannel, false); } /** - * Encoder constructor. Construct a Encoder given a and b channels as digital - * inputs. This is used in the case where the digital inputs are shared. The - * Encoder class will not allocate the digital inputs and assume that they - * already are counted. + * Encoder constructor. Construct a Encoder given a and b channels as digital inputs. This is used + * in the case where the digital inputs are shared. The Encoder class will not allocate the + * digital inputs and assume that they already are counted. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aSource The source that should be used for the a channel. - * @param bSource the source that should be used for the b channel. - * @param reverseDirection represents the orientation of the encoder and - * inverts the output values if necessary so forward represents - * positive values. + * @param sourceA The source that should be used for the a channel. + * @param sourceB the source that should be used for the b channel. + * @param reverseDirection represents the orientation of the encoder and inverts the output values + * if necessary so forward represents positive values. */ - public Encoder(DigitalSource aSource, DigitalSource bSource, boolean reverseDirection) { + public Encoder(DigitalSource sourceA, DigitalSource sourceB, boolean reverseDirection) { m_allocatedA = false; m_allocatedB = false; m_allocatedI = false; - if (aSource == null) + if (sourceA == null) { throw new NullPointerException("Digital Source A was null"); - m_aSource = aSource; - if (bSource == null) + } + m_aSource = sourceA; + if (sourceB == null) { throw new NullPointerException("Digital Source B was null"); - m_bSource = bSource; + } + m_bSource = sourceB; initEncoder(reverseDirection); } /** - * Encoder constructor. Construct a Encoder given a and b channels as digital - * inputs. This is used in the case where the digital inputs are shared. The - * Encoder class will not allocate the digital inputs and assume that they - * already are counted. + * Encoder constructor. Construct a Encoder given a and b channels as digital inputs. This is used + * in the case where the digital inputs are shared. The Encoder class will not allocate the + * digital inputs and assume that they already are counted. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aSource The source that should be used for the a channel. - * @param bSource the source that should be used for the b channel. + * @param sourceA The source that should be used for the a channel. + * @param sourceB the source that should be used for the b channel. */ - public Encoder(DigitalSource aSource, DigitalSource bSource) { - this(aSource, bSource, false); + public Encoder(DigitalSource sourceA, DigitalSource sourceB) { + this(sourceA, sourceB, false); } /** - * Encoder constructor. Construct a Encoder given a and b channels as digital - * inputs. This is used in the case where the digital inputs are shared. The - * Encoder class will not allocate the digital inputs and assume that they - * already are counted. + * Encoder constructor. Construct a Encoder given a and b channels as digital inputs. This is used + * in the case where the digital inputs are shared. The Encoder class will not allocate the + * digital inputs and assume that they already are counted. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aSource The source that should be used for the a channel. - * @param bSource the source that should be used for the b channel. - * @param reverseDirection represents the orientation of the encoder and - * inverts the output values if necessary so forward represents - * positive values. - * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X - * decoding. If 4X is selected, then an encoder FPGA object is used and - * the returned counts will be 4x the encoder spec'd value since all - * rising and falling edges are counted. If 1X or 2X are selected then - * a counter object will be used and the returned value will either - * exactly match the spec'd count or be double (2x) the spec'd count. + * @param sourceA The source that should be used for the a channel. + * @param sourceB the source that should be used for the b channel. + * @param reverseDirection represents the orientation of the encoder and inverts the output values + * if necessary so forward represents positive values. + * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is + * selected, then an encoder FPGA object is used and the returned counts + * will be 4x the encoder spec'd value since all rising and falling edges + * are counted. If 1X or 2X are selected then a m_counter object will be + * used and the returned value will either exactly match the spec'd count + * or be double (2x) the spec'd count. */ - public Encoder(DigitalSource aSource, DigitalSource bSource, boolean reverseDirection, - final EncodingType encodingType) { + public Encoder(DigitalSource sourceA, DigitalSource sourceB, boolean reverseDirection, + final EncodingType encodingType) { m_allocatedA = false; m_allocatedB = false; m_allocatedI = false; - if (encodingType == null) + if (encodingType == null) { throw new NullPointerException("Given encoding type was null"); + } m_encodingType = encodingType; - if (aSource == null) + if (sourceA == null) { throw new NullPointerException("Digital Source A was null"); - m_aSource = aSource; - if (bSource == null) + } + m_aSource = sourceA; + if (sourceB == null) { throw new NullPointerException("Digital Source B was null"); - m_aSource = aSource; - m_bSource = bSource; + } + m_aSource = sourceA; + m_bSource = sourceB; initEncoder(reverseDirection); } /** - * Encoder constructor. Construct a Encoder given a, b and index channels as - * digital inputs. This is used in the case where the digital inputs are - * shared. The Encoder class will not allocate the digital inputs and assume - * that they already are counted. + * Encoder constructor. Construct a Encoder given a, b and index channels as digital inputs. This + * is used in the case where the digital inputs are shared. The Encoder class will not allocate + * the digital inputs and assume that they already are counted. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aSource The source that should be used for the a channel. - * @param bSource the source that should be used for the b channel. - * @param indexSource the source that should be used for the index channel. - * @param reverseDirection represents the orientation of the encoder and - * inverts the output values if necessary so forward represents - * positive values. + * @param sourceA The source that should be used for the a channel. + * @param sourceB the source that should be used for the b channel. + * @param indexSource the source that should be used for the index channel. + * @param reverseDirection represents the orientation of the encoder and inverts the output values + * if necessary so forward represents positive values. */ - public Encoder(DigitalSource aSource, DigitalSource bSource, DigitalSource indexSource, - boolean reverseDirection) { + public Encoder(DigitalSource sourceA, DigitalSource sourceB, DigitalSource indexSource, + boolean reverseDirection) { m_allocatedA = false; m_allocatedB = false; m_allocatedI = false; - if (aSource == null) + if (sourceB == null) { throw new NullPointerException("Digital Source A was null"); - m_aSource = aSource; - if (bSource == null) + } + m_aSource = sourceA; + if (sourceB == null) { throw new NullPointerException("Digital Source B was null"); - m_aSource = aSource; - m_bSource = bSource; + } + m_aSource = sourceA; + m_bSource = sourceB; m_indexSource = indexSource; initEncoder(reverseDirection); setIndexSource(indexSource); } /** - * Encoder constructor. Construct a Encoder given a, b and index channels as - * digital inputs. This is used in the case where the digital inputs are - * shared. The Encoder class will not allocate the digital inputs and assume - * that they already are counted. + * Encoder constructor. Construct a Encoder given a, b and index channels as digital inputs. This + * is used in the case where the digital inputs are shared. The Encoder class will not allocate + * the digital inputs and assume that they already are counted. * - * The encoder will start counting immediately. + *

The encoder will start counting immediately. * - * @param aSource The source that should be used for the a channel. - * @param bSource the source that should be used for the b channel. + * @param sourceA The source that should be used for the a channel. + * @param sourceB the source that should be used for the b channel. * @param indexSource the source that should be used for the index channel. */ - public Encoder(DigitalSource aSource, DigitalSource bSource, DigitalSource indexSource) { - this(aSource, bSource, indexSource, false); + public Encoder(DigitalSource sourceA, DigitalSource sourceB, DigitalSource indexSource) { + this(sourceA, sourceB, indexSource, false); } /** - * @return the Encoder's FPGA index + * @return The Encoder's FPGA index. */ + @SuppressWarnings("AbbreviationAsWordInName") public int getFPGAIndex() { return m_index; } /** - * @return the encoding scale factor 1x, 2x, or 4x, per the requested - * encodingType. Used to divide raw edge counts down to spec'd counts. + * Used to divide raw edge counts down to spec'd counts. + * + * @return The encoding scale factor 1x, 2x, or 4x, per the requested encoding type. */ public int getEncodingScale() { return m_encodingScale; } + /** + * Free the resources used by this object. + */ public void free() { if (m_aSource != null && m_allocatedA) { m_aSource.free(); @@ -379,8 +380,8 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Gets the raw value from the encoder. The raw value is the actual count - * unscaled by the 1x, 2x, or 4x scale factor. + * Gets the raw value from the encoder. The raw value is the actual count unscaled by the 1x, 2x, + * or 4x scale factor. * * @return Current raw count from the encoder */ @@ -395,19 +396,17 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Gets the current count. Returns the current count on the Encoder. This - * method compensates for the decoding type. + * Gets the current count. Returns the current count on the Encoder. This method compensates for + * the decoding type. * - * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale - * factor. + * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale factor. */ public int get() { return (int) (getRaw() * decodingScaleFactor()); } /** - * Reset the Encoder distance to zero. Resets the current count to zero on the - * encoder. + * Reset the Encoder distance to zero. Resets the current count to zero on the encoder. */ public void reset() { if (m_counter != null) { @@ -418,15 +417,14 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Returns the period of the most recent pulse. Returns the period of the most - * recent Encoder pulse in seconds. This method compensates for the decoding - * type. + * Returns the period of the most recent pulse. Returns the period of the most recent Encoder + * pulse in seconds. This method compensates for the decoding type. * - * @deprecated Use getRate() in favor of this method. This returns unscaled - * periods and getRate() scales using value from - * setDistancePerPulse(). + *

Warning: This returns unscaled periods and getRate() scales using value from + * setDistancePerPulse(). * * @return Period in seconds of the most recent pulse. + * @deprecated Use getRate() in favor of this method. */ public double getPeriod() { double measuredPeriod; @@ -439,16 +437,13 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Sets the maximum period for stopped detection. Sets the value that - * represents the maximum period of the Encoder before it will assume that the - * attached device is stopped. This timeout allows users to determine if the - * wheels or other shaft has stopped rotating. This method compensates for the - * decoding type. + * Sets the maximum period for stopped detection. Sets the value that represents the maximum + * period of the Encoder before it will assume that the attached device is stopped. This timeout + * allows users to determine if the wheels or other shaft has stopped rotating. This method + * compensates for the decoding type. * - * - * @param maxPeriod The maximum time between rising and falling edges before - * the FPGA will report the device stopped. This is expressed in - * seconds. + * @param maxPeriod The maximum time between rising and falling edges before the FPGA will report + * the device stopped. This is expressed in seconds. */ public void setMaxPeriod(double maxPeriod) { if (m_counter != null) { @@ -459,10 +454,9 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Determine if the encoder is stopped. Using the MaxPeriod value, a boolean - * is returned that is true if the encoder is considered stopped and false if - * it is still moving. A stopped encoder is one where the most recent pulse - * width exceeds the MaxPeriod. + * Determine if the encoder is stopped. Using the MaxPeriod value, a boolean is returned that is + * true if the encoder is considered stopped and false if it is still moving. A stopped encoder is + * one where the most recent pulse width exceeds the MaxPeriod. * * @return True if the encoder is considered stopped. */ @@ -488,8 +482,7 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * The scale needed to convert a raw counter value into a number of encoder - * pulses. + * The scale needed to convert a raw counter value into a number of encoder pulses. */ private double decodingScaleFactor() { switch (m_encodingType) { @@ -506,18 +499,18 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Get the distance the robot has driven since the last reset. + * Get the distance the robot has driven since the last reset as scaled by the value from {@link + * #setDistancePerPulse(double)}. * - * @return The distance driven since the last reset as scaled by the value - * from setDistancePerPulse(). + * @return The distance driven since the last reset */ public double getDistance() { return getRaw() * decodingScaleFactor() * m_distancePerPulse; } /** - * Get the current rate of the encoder. Units are distance per second as - * scaled by the value from setDistancePerPulse(). + * Get the current rate of the encoder. Units are distance per second as scaled by the value from + * setDistancePerPulse(). * * @return The current rate of the encoder. */ @@ -528,51 +521,42 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW /** * Set the minimum rate of the device before the hardware reports it stopped. * - * @param minRate The minimum rate. The units are in distance per second as - * scaled by the value from setDistancePerPulse(). + * @param minRate The minimum rate. The units are in distance per second as scaled by the value + * from setDistancePerPulse(). */ public void setMinRate(double minRate) { setMaxPeriod(m_distancePerPulse / minRate); } /** - * Set the distance per pulse for this encoder. This sets the multiplier used - * to determine the distance driven based on the count value from the encoder. - * Do not include the decoding type in this scale. The library already - * compensates for the decoding type. Set this value based on the encoder's - * rated Pulses per Revolution and factor in gearing reductions following the - * encoder shaft. This distance can be in any units you like, linear or - * angular. + * Set the distance per pulse for this encoder. This sets the multiplier used to determine the + * distance driven based on the count value from the encoder. Do not include the decoding type in + * this scale. The library already compensates for the decoding type. Set this value based on the + * encoder's rated Pulses per Revolution and factor in gearing reductions following the encoder + * shaft. This distance can be in any units you like, linear or angular. * - * @param distancePerPulse The scale factor that will be used to convert - * pulses to useful units. + * @param distancePerPulse The scale factor that will be used to convert pulses to useful units. */ public void setDistancePerPulse(double distancePerPulse) { m_distancePerPulse = distancePerPulse; } /** - * Set the direction sensing for this encoder. This sets the direction sensing - * on the encoder so that it could count in the correct software direction - * regardless of the mounting. + * Set the direction sensing for this encoder. This sets the direction sensing on the encoder so + * that it could count in the correct software direction regardless of the mounting. * * @param reverseDirection true if the encoder direction should be reversed */ public void setReverseDirection(boolean reverseDirection) { if (m_counter != null) { m_counter.setReverseDirection(reverseDirection); - } else { - } } /** - * Set the Samples to Average which specifies the number of samples of the - * timer to average when calculating the period. Perform averaging to account - * for mechanical imperfections or as oversampling to increase resolution. - * - * TODO: Should this throw a checked exception, so that the user has to deal - * with giving an incorrect value? + * Set the Samples to Average which specifies the number of samples of the timer to average when + * calculating the period. Perform averaging to account for mechanical imperfections or as + * oversampling to increase resolution. * * @param samplesToAverage The number of samples to average from 1 to 127. */ @@ -584,17 +568,18 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW case k1X: case k2X: m_counter.setSamplesToAverage(samplesToAverage); - break; + break; + default: + throw new AssertionError("Illegal encoding type: " + m_encodingType); } } /** - * Get the Samples to Average which specifies the number of samples of the - * timer to average when calculating the period. Perform averaging to account - * for mechanical imperfections or as oversampling to increase resolution. + * Get the Samples to Average which specifies the number of samples of the timer to average when + * calculating the period. Perform averaging to account for mechanical imperfections or as + * oversampling to increase resolution. * - * @return SamplesToAverage The number of samples being averaged (from 1 to - * 127) + * @return SamplesToAverage The number of samples being averaged (from 1 to 127) */ public int getSamplesToAverage() { switch (m_encodingType) { @@ -603,13 +588,14 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW case k1X: case k2X: return m_counter.getSamplesToAverage(); + default: + return 1; } - return 1; } /** - * Set which parameter of the encoder you are using as a process control - * variable. The encoder class supports the rate and distance parameters. + * Set which parameter of the encoder you are using as a process control variable. The encoder + * class supports the rate and distance parameters. * * @param pidSource An enum to select the parameter. */ @@ -617,9 +603,7 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_pidSource; } @@ -641,11 +625,31 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Set the index source for the encoder. When this source rises, the encoder - * count automatically resets. + * Set the index source for the encoder. When this source is activated, the encoder count + * automatically resets. * * @param channel A DIO channel to set as the encoder index - * @param type The state that will cause the encoder to reset + */ + public void setIndexSource(int channel) { + setIndexSource(channel, IndexingType.kResetOnRisingEdge); + } + + /** + * Set the index source for the encoder. When this source is activated, the encoder count + * automatically resets. + * + * @param source A digital source to set as the encoder index + */ + public void setIndexSource(DigitalSource source) { + setIndexSource(source, IndexingType.kResetOnRisingEdge); + } + + /** + * Set the index source for the encoder. When this source rises, the encoder count automatically + * resets. + * + * @param channel A DIO channel to set as the encoder index + * @param type The state that will cause the encoder to reset */ public void setIndexSource(int channel, IndexingType type) { boolean activeHigh = @@ -657,21 +661,11 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Set the index source for the encoder. When this source is activated, the - * encoder count automatically resets. - * - * @param channel A DIO channel to set as the encoder index - */ - public void setIndexSource(int channel) { - this.setIndexSource(channel, IndexingType.kResetOnRisingEdge); - } - - /** - * Set the index source for the encoder. When this source rises, the encoder - * count automatically resets. + * Set the index source for the encoder. When this source rises, the encoder count automatically + * resets. * * @param source A digital source to set as the encoder index - * @param type The state that will cause the encoder to reset + * @param type The state that will cause the encoder to reset */ public void setIndexSource(DigitalSource source, IndexingType type) { boolean activeHigh = @@ -684,16 +678,6 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } /** - * Set the index source for the encoder. When this source is activated, the - * encoder count automatically resets. - * - * @param source A digital source to set as the encoder index - */ - public void setIndexSource(DigitalSource source) { - this.setIndexSource(source, IndexingType.kResetOnRisingEdge); - } - - /* * Live Window code, only does anything if live window is activated. */ public String getSmartDashboardType() { @@ -707,24 +691,18 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Speed", getRate()); @@ -733,13 +711,11 @@ public class Encoder extends SensorBase implements CounterBase, PIDSource, LiveW } } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/GearTooth.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/GearTooth.java index f98bba9e46..b12188d31d 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/GearTooth.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/GearTooth.java @@ -12,10 +12,9 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * Alias for counter class. Implement the gear tooth sensor supplied by FIRST. - * Currently there is no reverse sensing on the gear tooth sensor, but in future - * versions we might implement the necessary timing in the FPGA to sense - * direction. + * Alias for counter class. Implement the gear tooth sensor supplied by FIRST. Currently there is no + * reverse sensing on the gear tooth sensor, but in future versions we might implement the necessary + * timing in the FPGA to sense direction. */ public class GearTooth extends Counter { @@ -33,7 +32,7 @@ public class GearTooth extends Counter { /** * Construct a GearTooth sensor given a channel. * - * No direction sensing is assumed. + *

No direction sensing is assumed. * * @param channel The GPIO channel that the sensor is connected to. */ @@ -44,10 +43,10 @@ public class GearTooth extends Counter { /** * Construct a GearTooth sensor given a channel. * - * @param channel The DIO channel that the sensor is connected to. 0-9 are - * on-board, 10-25 are on the MXP port - * @param directionSensitive True to enable the pulse length decoding in - * hardware to specify count direction. + * @param channel The DIO channel that the sensor is connected to. 0-9 are on-board, + * 10-25 are on the MXP port + * @param directionSensitive True to enable the pulse length decoding in hardware to specify count + * direction. */ public GearTooth(final int channel, boolean directionSensitive) { super(channel); @@ -61,12 +60,12 @@ public class GearTooth extends Counter { } /** - * Construct a GearTooth sensor given a digital input. This should be used - * when sharing digital inputs. + * Construct a GearTooth sensor given a digital input. This should be used when sharing digital + * inputs. * - * @param source An existing DigitalSource object (such as a DigitalInput) - * @param directionSensitive True to enable the pulse length decoding in - * hardware to specify count direction. + * @param source An existing DigitalSource object (such as a DigitalInput) + * @param directionSensitive True to enable the pulse length decoding in hardware to specify count + * direction. */ public GearTooth(DigitalSource source, boolean directionSensitive) { super(source); @@ -74,13 +73,12 @@ public class GearTooth extends Counter { } /** - * Construct a GearTooth sensor given a digital input. This should be used - * when sharing digial inputs. + * Construct a GearTooth sensor given a digital input. This should be used when sharing digial + * inputs. * - * No direction sensing is assumed. + *

No direction sensing is assumed. * - * @param source An object that fully descibes the input that the sensor is - * connected to. + * @param source An object that fully descibes the input that the sensor is connected to. */ public GearTooth(DigitalSource source) { this(source, false); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/I2C.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/I2C.java index eecafe48ec..d84d81df09 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/I2C.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/I2C.java @@ -7,7 +7,6 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; import java.nio.ByteBuffer; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; @@ -18,38 +17,38 @@ import edu.wpi.first.wpilibj.util.BoundaryException; /** * I2C bus interface class. * - * This class is intended to be used by sensor (and other I2C device) drivers. - * It probably should not be used directly. - * + *

This class is intended to be used by sensor (and other I2C device) drivers. It probably should + * not be used directly. */ public class I2C extends SensorBase { public enum Port { kOnboard(0), kMXP(1); - private int value; + private int m_value; - private Port(int value) { - this.value = value; + Port(int value) { + m_value = value; } public int getValue() { - return this.value; + return m_value; } - }; + } - private Port m_port; - private int m_deviceAddress; + + private final Port m_port; + private final int m_deviceAddress; /** * Constructor. * - * @param port The I2C port the device is connected to. + * @param port The I2C port the device is connected to. * @param deviceAddress The address of the device on the I2C bus. */ public I2C(Port port, int deviceAddress) { m_port = port; m_deviceAddress = deviceAddress; - I2CJNI.i2CInitialize((byte) m_port.getValue()); + I2CJNI.i2CInitialize((byte) port.getValue()); UsageReporting.report(tResourceType.kResourceType_I2C, deviceAddress); } @@ -57,23 +56,24 @@ public class I2C extends SensorBase { /** * Destructor. */ - public void free() {} + public void free() { + } /** * Generic transaction. * - * This is a lower-level interface to the I2C hardware giving you more control - * over each transaction. + *

This is a lower-level interface to the I2C hardware giving you more control over each + * transaction. * - * @param dataToSend Buffer of data to send as part of the transaction. - * @param sendSize Number of bytes to send as part of the transaction. + * @param dataToSend Buffer of data to send as part of the transaction. + * @param sendSize Number of bytes to send as part of the transaction. * @param dataReceived Buffer to read data into. - * @param receiveSize Number of bytes to read from the device. + * @param receiveSize Number of bytes to read from the device. * @return Transfer Aborted... false for success, true for aborted. */ - public synchronized boolean transaction(byte[] dataToSend, int sendSize, byte[] dataReceived, - int receiveSize) { - int status = -1; + public synchronized boolean transaction(byte[] dataToSend, int sendSize, + byte[] dataReceived, int receiveSize) { + final int status; ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(sendSize); if (sendSize > 0 && dataToSend != null) { @@ -81,9 +81,10 @@ public class I2C extends SensorBase { } ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(receiveSize); - status = - I2CJNI.i2CTransaction((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, - (byte) sendSize, dataReceivedBuffer, (byte) receiveSize); + status = I2CJNI + .i2CTransaction((byte) m_port.getValue(), (byte) m_deviceAddress, + dataToSendBuffer, (byte) sendSize, dataReceivedBuffer, + (byte) receiveSize); if (receiveSize > 0 && dataReceived != null) { dataReceivedBuffer.get(dataReceived); } @@ -93,54 +94,58 @@ public class I2C extends SensorBase { /** * Generic transaction. * - * This is a lower-level interface to the I2C hardware giving you more control - * over each transaction. + *

This is a lower-level interface to the I2C hardware giving you more control over each + * transaction. * - * @param dataToSend Buffer of data to send as part of the transaction. Must - * be allocated using ByteBuffer.allocateDirect(). - * @param sendSize Number of bytes to send as part of the transaction. - * @param dataReceived Buffer to read data into. Must be allocated using - * ByteBuffer.allocateDirect(). - * @param receiveSize Number of bytes to read from the device. + * @param dataToSend Buffer of data to send as part of the transaction. Must be allocated using + * ByteBuffer.allocateDirect(). + * @param sendSize Number of bytes to send as part of the transaction. + * @param dataReceived Buffer to read data into. Must be allocated using {@link + * ByteBuffer#allocateDirect(int)}. + * @param receiveSize Number of bytes to read from the device. * @return Transfer Aborted... false for success, true for aborted. */ - public synchronized boolean transaction(ByteBuffer dataToSend, int sendSize, ByteBuffer dataReceived, - int receiveSize) { - boolean aborted = true; - - if (!dataToSend.isDirect()) + public synchronized boolean transaction(ByteBuffer dataToSend, int sendSize, + ByteBuffer dataReceived, int receiveSize) { + if (!dataToSend.isDirect()) { throw new IllegalArgumentException("dataToSend must be a direct buffer"); - if (dataToSend.capacity() < sendSize) + } + if (dataToSend.capacity() < sendSize) { throw new IllegalArgumentException("dataToSend is too small, must be at least " + sendSize); - if (!dataReceived.isDirect()) + } + if (!dataReceived.isDirect()) { throw new IllegalArgumentException("dataReceived must be a direct buffer"); - if (dataReceived.capacity() < receiveSize) - throw new IllegalArgumentException("dataReceived is too small, must be at least " + receiveSize); + } + if (dataReceived.capacity() < receiveSize) { + throw new IllegalArgumentException( + "dataReceived is too small, must be at least " + receiveSize); + } - return I2CJNI.i2CTransaction((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSend, (byte) sendSize, dataReceived, (byte) receiveSize) < receiveSize; + return I2CJNI + .i2CTransaction((byte) m_port.getValue(), (byte) m_deviceAddress, + dataToSend, (byte) sendSize, dataReceived, (byte) receiveSize) + < receiveSize; } /** * Attempt to address a device on the I2C bus. * - * This allows you to figure out if there is a device on the I2C bus that - * responds to the address specified in the constructor. + *

This allows you to figure out if there is a device on the I2C bus that responds to the + * address specified in the constructor. * * @return Transfer Aborted... false for success, true for aborted. */ public boolean addressOnly() { - return transaction((byte[]) null, (byte) 0, (byte[]) null, (byte) 0); + return transaction((byte[]) null, (byte) 0, null, (byte) 0); } /** * Execute a write transaction with the device. * - * Write a single byte to a register on a device and wait until the - * transaction is complete. + *

Write a single byte to a register on a device and wait until the transaction is complete. * - * @param registerAddress The address of the register on the device to be - * written. - * @param data The byte to write to the register on the device. + * @param registerAddress The address of the register on the device to be written. + * @param data The byte to write to the register on the device. */ public synchronized boolean write(int registerAddress, int data) { byte[] buffer = new byte[2]; @@ -150,15 +155,14 @@ public class I2C extends SensorBase { ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(2); dataToSendBuffer.put(buffer); - return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, - (byte) buffer.length) < buffer.length; + return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, + dataToSendBuffer, (byte) buffer.length) < buffer.length; } /** * Execute a write transaction with the device. * - * Write multiple bytes to a register on a device and wait until the - * transaction is complete. + *

Write multiple bytes to a register on a device and wait until the transaction is complete. * * @param data The data to write to the device. */ @@ -166,46 +170,44 @@ public class I2C extends SensorBase { ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(data.length); dataToSendBuffer.put(data); - return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, - (byte) data.length) < data.length; + return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, + dataToSendBuffer, (byte) data.length) < data.length; } /** * Execute a write transaction with the device. * - * Write multiple bytes to a register on a device and wait until the - * transaction is complete. + *

Write multiple bytes to a register on a device and wait until the transaction is complete. * - * @param data The data to write to the device. Must be created using - * ByteBuffer.allocateDirect(). + * @param data The data to write to the device. Must be created using ByteBuffer.allocateDirect(). */ public synchronized boolean writeBulk(ByteBuffer data, int size) { - if (!data.isDirect()) + if (!data.isDirect()) { throw new IllegalArgumentException("must be a direct buffer"); - if (data.capacity() < size) - throw new IllegalArgumentException("buffer is too small, must be at least " + size); + } + if (data.capacity() < size) { + throw new IllegalArgumentException( + "buffer is too small, must be at least " + size); + } - return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, data, - (byte) size) < size; + return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, + data, (byte) size) < size; } /** * Execute a read transaction with the device. * - * Read bytes from a device. Most I2C devices will auto-increment the - * register pointer internally allowing you to read consecutive - * registers on a device in a single transaction. + *

Read bytes from a device. Most I2C devices will auto-increment the register pointer + * internally allowing you to read consecutive registers on a device in a single transaction. * * @param registerAddress The register to read first in the transaction. - * @param count The number of bytes to read in the transaction. - * @param buffer A pointer to the array of bytes to store the data read from - * the device. + * @param count The number of bytes to read in the transaction. + * @param buffer A pointer to the array of bytes to store the data read from the device. * @return Transfer Aborted... false for success, true for aborted. */ public boolean read(int registerAddress, int count, byte[] buffer) { if (count < 1) { - throw new BoundaryException("Value must be at least 1, " + count + - " given"); + throw new BoundaryException("Value must be at least 1, " + count + " given"); } if (buffer == null) { @@ -220,26 +222,26 @@ public class I2C extends SensorBase { /** * Execute a read transaction with the device. * - * Read bytes from a device. Most I2C devices will auto-increment the - * register pointer internally allowing you to read consecutive - * registers on a device in a single transaction. + *

Read bytes from a device. Most I2C devices will auto-increment the register pointer + * internally allowing you to read consecutive registers on a device in a single transaction. * * @param registerAddress The register to read first in the transaction. - * @param count The number of bytes to read in the transaction. - * @param buffer A buffer to store the data read from the device. Must be - * created using ByteBuffer.allocateDirect(). + * @param count The number of bytes to read in the transaction. + * @param buffer A buffer to store the data read from the device. Must be created using + * ByteBuffer.allocateDirect(). * @return Transfer Aborted... false for success, true for aborted. */ public boolean read(int registerAddress, int count, ByteBuffer buffer) { if (count < 1) { - throw new BoundaryException("Value must be at least 1, " + count + - " given"); + throw new BoundaryException("Value must be at least 1, " + count + " given"); } - if (!buffer.isDirect()) + if (!buffer.isDirect()) { throw new IllegalArgumentException("must be a direct buffer"); - if (buffer.capacity() < count) + } + if (buffer.capacity() < count) { throw new IllegalArgumentException("buffer is too small, must be at least " + count); + } ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(1); dataToSendBuffer.put(0, (byte) registerAddress); @@ -250,18 +252,15 @@ public class I2C extends SensorBase { /** * Execute a read only transaction with the device. * - * Read bytes from a device. This method does not write any data to prompt - * the device. + *

Read bytes from a device. This method does not write any data to prompt the device. * - * @param buffer A pointer to the array of bytes to store the data read from - * the device. - * @param count The number of bytes to read in the transaction. + * @param buffer A pointer to the array of bytes to store the data read from the device. + * @param count The number of bytes to read in the transaction. * @return Transfer Aborted... false for success, true for aborted. */ public boolean readOnly(byte[] buffer, int count) { if (count < 1) { - throw new BoundaryException("Value must be at least 1, " + count + - " given"); + throw new BoundaryException("Value must be at least 1, " + count + " given"); } if (buffer == null) { @@ -270,8 +269,8 @@ public class I2C extends SensorBase { ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count); - int retVal = - I2CJNI.i2CRead((byte) m_port.getValue(), (byte) m_deviceAddress, dataReceivedBuffer, + int retVal = I2CJNI + .i2CRead((byte) m_port.getValue(), (byte) m_deviceAddress, dataReceivedBuffer, (byte) count); dataReceivedBuffer.get(buffer); return retVal < count; @@ -280,61 +279,62 @@ public class I2C extends SensorBase { /** * Execute a read only transaction with the device. * - * Read bytes from a device. This method does not write any data to prompt - * the device. + *

Read bytes from a device. This method does not write any data to prompt the device. * - * @param buffer A pointer to the array of bytes to store the data read from - * the device. Must be created using ByteBuffer.allocateDirect(). - * @param count The number of bytes to read in the transaction. + * @param buffer A pointer to the array of bytes to store the data read from the device. Must be + * created using ByteBuffer.allocateDirect(). + * @param count The number of bytes to read in the transaction. * @return Transfer Aborted... false for success, true for aborted. */ public boolean readOnly(ByteBuffer buffer, int count) { if (count < 1) { - throw new BoundaryException("Value must be at least 1, " + count + - " given"); + throw new BoundaryException("Value must be at least 1, " + count + + " given"); } - if (!buffer.isDirect()) + if (!buffer.isDirect()) { throw new IllegalArgumentException("must be a direct buffer"); - if (buffer.capacity() < count) + } + if (buffer.capacity() < count) { throw new IllegalArgumentException("buffer is too small, must be at least " + count); + } - return I2CJNI.i2CRead((byte) m_port.getValue(), (byte) m_deviceAddress, buffer, - (byte) count) < count; + return I2CJNI + .i2CRead((byte) m_port.getValue(), (byte) m_deviceAddress, buffer, (byte) count) < count; } /** * Send a broadcast write to all devices on the I2C bus. * - * This is not currently implemented! + *

This is not currently implemented! * * @param registerAddress The register to write on all devices on the bus. - * @param data The value to write to the devices. + * @param data The value to write to the devices. */ - public void broadcast(int registerAddress, int data) {} + public void broadcast(int registerAddress, int data) { + } /** * Verify that a device's registers contain expected values. * - * Most devices will have a set of registers that contain a known value that - * can be used to identify them. This allows an I2C device driver to easily - * verify that the device contains the expected value. - * - * @pre The device must support and be configured to use register - * auto-increment. + *

Most devices will have a set of registers that contain a known value that can be used to + * identify them. This allows an I2C device driver to easily verify that the device contains the + * expected value. * * @param registerAddress The base register to start reading from the device. - * @param count The size of the field to be verified. - * @param expected A buffer containing the values expected from the device. + * @param count The size of the field to be verified. + * @param expected A buffer containing the values expected from the device. * @return true if the sensor was verified to be connected + * @pre The device must support and be configured to use register auto-increment. */ - public boolean verifySensor(int registerAddress, int count, byte[] expected) { + public boolean verifySensor(int registerAddress, int count, + byte[] expected) { // TODO: Make use of all 7 read bytes ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(1); ByteBuffer deviceData = ByteBuffer.allocateDirect(4); - for (int i = 0, curRegisterAddress = registerAddress; i < count; i += 4, curRegisterAddress += - 4) { + for (int i = 0, curRegisterAddress = registerAddress; + i < count; i += 4, curRegisterAddress += 4) { int toRead = count - i < 4 ? count - i : 4; // Read the chunk of data. Return false if the sensor does not // respond. diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java index 1e8182d04a..9d8b28c3b2 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java @@ -11,21 +11,19 @@ import edu.wpi.first.wpilibj.hal.InterruptJNI.InterruptJNIHandlerFunction; /** - * It is recommended that you use this class in conjunction with classes from - * {@link java.util.concurrent.atomic} as these objects are all thread safe. + * It is recommended that you use this class in conjunction with classes from {@link + * java.util.concurrent.atomic} as these objects are all thread safe. * + * @param The type of the parameter that should be returned to the the method {@link + * #interruptFired(int, Object)} * @author Jonathan Leitschuh - * - * @param The type of the parameter that should be returned to the the - * method {@link #interruptFired(int, Object)} */ public abstract class InterruptHandlerFunction { /** - * The entry point for the interrupt. When the interrupt fires the - * {@link #apply(int, Object)} method is called. The outer class is provided - * as an interface to allow the implementer to pass a generic object to the - * interrupt fired method. - *$ + * The entry point for the interrupt. When the interrupt fires the {@link #apply(int, Object)} + * method is called. The outer class is provided as an interface to allow the implementer to pass + * a generic object to the interrupt fired method. + * * @author Jonathan Leitschuh */ private class Function implements InterruptJNIHandlerFunction { @@ -36,25 +34,23 @@ public abstract class InterruptHandlerFunction { } } - final Function function = new Function(); + final Function m_function = new Function(); /** * This method is run every time an interrupt is fired. - *$ + * * @param interruptAssertedMask Interrupt Mask - * @param param The parameter provided by overriding the - * {@link #overridableParameter()} method. + * @param param The parameter provided by overriding the {@link + * #overridableParameter()} method. */ public abstract void interruptFired(int interruptAssertedMask, T param); /** - * Override this method if you would like to pass a specific parameter to the - * {@link #interruptFired(int, Object)} when it is fired by the interrupt. - * This method is called once when - * {@link InterruptableSensorBase#requestInterrupts(InterruptHandlerFunction)} - * is run. - *$ + * Override this method if you would like to pass a specific parameter to the {@link + * #interruptFired(int, Object)} when it is fired by the interrupt. This method is called once + * when {@link InterruptableSensorBase#requestInterrupts(InterruptHandlerFunction)} is run. + * * @return The object that should be passed to the interrupt when it runs */ public T overridableParameter() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java index fc7cf5e71e..8d543a6201 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java @@ -12,15 +12,18 @@ import edu.wpi.first.wpilibj.util.AllocationException; import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** - * Base for sensors to be used with interrupts + * Base for sensors to be used with interrupts. */ public abstract class InterruptableSensorBase extends SensorBase { - public static enum WaitResult { + @SuppressWarnings("JavadocMethod") + public enum WaitResult { kTimeout(0x0), kRisingEdge(0x1), kFallingEdge(0x100), kBoth(0x101); + @SuppressWarnings("MemberName") public final int value; + @SuppressWarnings("JavadocMethod") public static WaitResult valueOf(int value) { for (WaitResult mode : values()) { if (mode.value == value) { @@ -31,48 +34,54 @@ public abstract class InterruptableSensorBase extends SensorBase { } - private WaitResult(int value) { + WaitResult(int value) { this.value = value; } } /** - * The interrupt resource + * The interrupt resource. */ protected long m_interrupt = 0; /** - * Flags if the interrupt being allocated is synchronous + * Flags if the interrupt being allocated is synchronous. */ protected boolean m_isSynchronousInterrupt = false; /** - * The index of the interrupt + * The index of the interrupt. */ protected int m_interruptIndex; /** - * Resource manager + * Resource manager. */ - protected static Resource interrupts = new Resource(8); + protected static Resource m_interrupts = new Resource(8); /** - * Create a new InterrupatableSensorBase + * Create a new InterrupatableSensorBase. */ public InterruptableSensorBase() { m_interrupt = 0; } /** - * @return true if this is an analog trigger + * If this is an analog trigger. + * + * @return true if this is an analog trigger. */ abstract boolean getAnalogTriggerForRouting(); /** + * The channel routing number. + * * @return channel routing number */ abstract int getChannelForRouting(); /** + * The modules routing number. + * * @return module routing number */ abstract byte getModuleForRouting(); @@ -80,12 +89,11 @@ public abstract class InterruptableSensorBase extends SensorBase { /** * Request one of the 8 interrupts asynchronously on this digital input. * - * @param handler The {@link InterruptHandlerFunction} that contains the - * method {@link InterruptHandlerFunction#interruptFired(int, Object)} - * that will be called whenever there is an interrupt on this device. - * Request interrupts in synchronous mode where the user program - * interrupt handler will be called when an interrupt occurs. The - * default is interrupt on rising edges only. + * @param handler The {@link InterruptHandlerFunction} that contains the method {@link + * InterruptHandlerFunction#interruptFired(int, Object)} that will be called + * whenever there is an interrupt on this device. Request interrupts in synchronous + * mode where the user program interrupt handler will be called when an interrupt + * occurs. The default is interrupt on rising edges only. */ public void requestInterrupts(InterruptHandlerFunction handler) { if (m_interrupt != 0) { @@ -99,15 +107,14 @@ public abstract class InterruptableSensorBase extends SensorBase { InterruptJNI.requestInterrupts(m_interrupt, getModuleForRouting(), getChannelForRouting(), getAnalogTriggerForRouting()); setUpSourceEdge(true, false); - InterruptJNI.attachInterruptHandler(m_interrupt, handler.function, + InterruptJNI.attachInterruptHandler(m_interrupt, handler.m_function, handler.overridableParameter()); } /** - * Request one of the 8 interrupts synchronously on this digital input. - * Request interrupts in synchronous mode where the user program will have to - * explicitly wait for the interrupt to occur using {@link #waitForInterrupt}. - * The default is interrupt on rising edges only. + * Request one of the 8 interrupts synchronously on this digital input. Request interrupts in + * synchronous mode where the user program will have to explicitly wait for the interrupt to occur + * using {@link #waitForInterrupt}. The default is interrupt on rising edges only. */ public void requestInterrupts() { if (m_interrupt != 0) { @@ -127,14 +134,13 @@ public abstract class InterruptableSensorBase extends SensorBase { /** * Allocate the interrupt * - * @param watcher true if the interrupt should be in synchronous mode where - * the user program will have to explicitly wait for the interrupt to - * occur. + * @param watcher true if the interrupt should be in synchronous mode where the user program will + * have to explicitly wait for the interrupt to occur. */ protected void allocateInterrupts(boolean watcher) { try { - m_interruptIndex = interrupts.allocate(); - } catch (CheckedAllocationException e) { + m_interruptIndex = m_interrupts.allocate(); + } catch (CheckedAllocationException ex) { throw new AllocationException("No interrupts are left to be allocated"); } m_isSynchronousInterrupt = watcher; @@ -144,8 +150,8 @@ public abstract class InterruptableSensorBase extends SensorBase { } /** - * Cancel interrupts on this device. This deallocates all the chipobject - * structures and disables any interrupts. + * Cancel interrupts on this device. This deallocates all the chipobject structures and disables + * any interrupts. */ public void cancelInterrupts() { if (m_interrupt == 0) { @@ -153,15 +159,15 @@ public abstract class InterruptableSensorBase extends SensorBase { } InterruptJNI.cleanInterrupts(m_interrupt); m_interrupt = 0; - interrupts.free(m_interruptIndex); + m_interrupts.free(m_interruptIndex); } /** * In synchronous mode, wait for the defined interrupt to occur. * - * @param timeout Timeout in seconds - * @param ignorePrevious If true, ignore interrupts that happened before - * waitForInterrupt was called. + * @param timeout Timeout in seconds + * @param ignorePrevious If true, ignore interrupts that happened before waitForInterrupt was + * called. * @return Result of the wait. */ public WaitResult waitForInterrupt(double timeout, boolean ignorePrevious) { @@ -184,9 +190,9 @@ public abstract class InterruptableSensorBase extends SensorBase { } /** - * Enable interrupts to occur on this input. Interrupts are disabled when the - * RequestInterrupt call is made. This gives time to do the setup of the other - * options before starting to field interrupts. + * Enable interrupts to occur on this input. Interrupts are disabled when the RequestInterrupt + * call is made. This gives time to do the setup of the other options before starting to field + * interrupts. */ public void enableInterrupts() { if (m_interrupt == 0) { @@ -212,10 +218,10 @@ public abstract class InterruptableSensorBase extends SensorBase { } /** - * Return the timestamp for the rising interrupt that occurred most recently. - * This is in the same time domain as getClock(). The rising-edge interrupt - * should be enabled with {@link #setUpSourceEdge} - *$ + * Return the timestamp for the rising interrupt that occurred most recently. This is in the same + * time domain as getClock(). The rising-edge interrupt should be enabled with {@link + * #setUpSourceEdge}. + * * @return Timestamp in seconds since boot. */ public double readRisingTimestamp() { @@ -226,10 +232,10 @@ public abstract class InterruptableSensorBase extends SensorBase { } /** - * Return the timestamp for the falling interrupt that occurred most recently. - * This is in the same time domain as getClock(). The falling-edge interrupt - * should be enabled with {@link #setUpSourceEdge} - *$ + * Return the timestamp for the falling interrupt that occurred most recently. This is in the same + * time domain as getClock(). The falling-edge interrupt should be enabled with {@link + * #setUpSourceEdge}. + * * @return Timestamp in seconds since boot. */ public double readFallingTimestamp() { @@ -240,9 +246,9 @@ public abstract class InterruptableSensorBase extends SensorBase { } /** - * Set which edge to trigger interrupts on + * Set which edge to trigger interrupts on. * - * @param risingEdge true to interrupt on rising edge + * @param risingEdge true to interrupt on rising edge * @param fallingEdge true to interrupt on falling edge */ public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/IterativeRobot.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/IterativeRobot.java index 4a77a92379..ae3d580d2c 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/IterativeRobot.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/IterativeRobot.java @@ -11,35 +11,29 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; -import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * IterativeRobot implements a specific type of Robot Program framework, - * extending the RobotBase class. + * IterativeRobot implements a specific type of Robot Program framework, extending the RobotBase + * class. * - * The IterativeRobot class is intended to be subclassed by a user creating a - * robot program. + *

The IterativeRobot class is intended to be subclassed by a user creating a robot program. * - * This class is intended to implement the "old style" default code, by - * providing the following functions which are called by the main loop, - * startCompetition(), at the appropriate times: + *

This class is intended to implement the "old style" default code, by providing the following + * functions which are called by the main loop, startCompetition(), at the appropriate times: * - * robotInit() -- provide for initialization at robot power-on + *

robotInit() -- provide for initialization at robot power-on * - * init() functions -- each of the following functions is called once when the - * appropriate mode is entered: - DisabledInit() -- called only when first - * disabled - AutonomousInit() -- called each and every time autonomous is - * entered from another mode - TeleopInit() -- called each and every time teleop - * is entered from another mode - TestInit() -- called each and every time test - * mode is entered from anothermode - * - * Periodic() functions -- each of these functions is called iteratively at the - * appropriate periodic rate (aka the "slow loop"). The period of the iterative - * robot is synced to the driver station control packets, giving a periodic - * frequency of about 50Hz (50 times per second). - disabledPeriodic() - - * autonomousPeriodic() - teleopPeriodic() - testPeriodoc() + *

init() functions -- each of the following functions is called once when the appropriate mode + * is entered: - DisabledInit() -- called only when first disabled - AutonomousInit() -- called each + * and every time autonomous is entered from another mode - TeleopInit() -- called each and every + * time teleop is entered from another mode - TestInit() -- called each and every time test mode is + * entered from anothermode * + *

Periodic() functions -- each of these functions is called iteratively at the appropriate + * periodic rate (aka the "slow loop"). The period of the iterative robot is synced to the driver + * station control packets, giving a periodic frequency of about 50Hz (50 times per second). - + * disabledPeriodic() - autonomousPeriodic() - teleopPeriodic() - testPeriodoc() */ public class IterativeRobot extends RobotBase { private boolean m_disabledInitialized; @@ -48,11 +42,10 @@ public class IterativeRobot extends RobotBase { private boolean m_testInitialized; /** - * Constructor for RobotIterativeBase + * Constructor for RobotIterativeBase. * - * The constructor initializes the instance variables for the robot to - * indicate the status of initialization for disabled, autonomous, and teleop - * code. + *

The constructor initializes the instance variables for the robot to indicate the status of + * initialization for disabled, autonomous, and teleop code. */ public IterativeRobot() { // set status for initialization of disabled, autonomous, and teleop code. @@ -64,7 +57,6 @@ public class IterativeRobot extends RobotBase { /** * Provide an alternate "main loop" via startCompetition(). - * */ public void startCompetition() { UsageReporting.report(tResourceType.kResourceType_Framework, tInstances.kFramework_Iterative); @@ -148,9 +140,8 @@ public class IterativeRobot extends RobotBase { } /** - * Determine if the appropriate next periodic function should be called. Call - * the periodic functions whenever a packet is received from the Driver - * Station, or about every 20ms. + * Determine if the appropriate next periodic function should be called. Call the periodic + * functions whenever a packet is received from the Driver Station, or about every 20ms. */ private boolean nextPeriodReady() { return m_ds.isNewControlData(); @@ -161,14 +152,12 @@ public class IterativeRobot extends RobotBase { /** * Robot-wide initialization code should go here. * - * Users should override this method for default Robot-wide initialization - * which will be called when the robot is first powered on. It will be called - * exactly one time. + *

Users should override this method for default Robot-wide initialization which will be called + * when the robot is first powered on. It will be called exactly one time. * - * Warning: the Driver Station "Robot Code" light and FMS "Robot Ready" - * indicators will be off until RobotInit() exits. Code in RobotInit() that - * waits for enable will cause the robot to never indicate that the code is - * ready, causing the robot to be bypassed in a match. + *

Warning: the Driver Station "Robot Code" light and FMS "Robot Ready" indicators will be off + * until RobotInit() exits. Code in RobotInit() that waits for enable will cause the robot to + * never indicate that the code is ready, causing the robot to be bypassed in a match. */ public void robotInit() { System.out.println("Default IterativeRobot.robotInit() method... Overload me!"); @@ -177,8 +166,8 @@ public class IterativeRobot extends RobotBase { /** * Initialization code for disabled mode should go here. * - * Users should override this method for initialization code which will be - * called each time the robot enters disabled mode. + *

Users should override this method for initialization code which will be called each time the + * robot enters disabled mode. */ public void disabledInit() { System.out.println("Default IterativeRobot.disabledInit() method... Overload me!"); @@ -187,8 +176,8 @@ public class IterativeRobot extends RobotBase { /** * Initialization code for autonomous mode should go here. * - * Users should override this method for initialization code which will be - * called each time the robot enters autonomous mode. + *

Users should override this method for initialization code which will be called each time the + * robot enters autonomous mode. */ public void autonomousInit() { System.out.println("Default IterativeRobot.autonomousInit() method... Overload me!"); @@ -197,8 +186,8 @@ public class IterativeRobot extends RobotBase { /** * Initialization code for teleop mode should go here. * - * Users should override this method for initialization code which will be - * called each time the robot enters teleop mode. + *

Users should override this method for initialization code which will be called each time the + * robot enters teleop mode. */ public void teleopInit() { System.out.println("Default IterativeRobot.teleopInit() method... Overload me!"); @@ -207,8 +196,8 @@ public class IterativeRobot extends RobotBase { /** * Initialization code for test mode should go here. * - * Users should override this method for initialization code which will be - * called each time the robot enters test mode. + *

Users should override this method for initialization code which will be called each time the + * robot enters test mode. */ public void testInit() { System.out.println("Default IterativeRobot.testInit() method... Overload me!"); @@ -216,66 +205,66 @@ public class IterativeRobot extends RobotBase { /* ----------- Overridable periodic code ----------------- */ - private boolean dpFirstRun = true; + private boolean m_dpFirstRun = true; /** * Periodic code for disabled mode should go here. * - * Users should override this method for code which will be called - * periodically at a regular rate while the robot is in disabled mode. + *

Users should override this method for code which will be called periodically at a regular + * rate while the robot is in disabled mode. */ public void disabledPeriodic() { - if (dpFirstRun) { + if (m_dpFirstRun) { System.out.println("Default IterativeRobot.disabledPeriodic() method... Overload me!"); - dpFirstRun = false; + m_dpFirstRun = false; } Timer.delay(0.001); } - private boolean apFirstRun = true; + private boolean m_apFirstRun = true; /** * Periodic code for autonomous mode should go here. * - * Users should override this method for code which will be called - * periodically at a regular rate while the robot is in autonomous mode. + *

Users should override this method for code which will be called periodically at a regular + * rate while the robot is in autonomous mode. */ public void autonomousPeriodic() { - if (apFirstRun) { + if (m_apFirstRun) { System.out.println("Default IterativeRobot.autonomousPeriodic() method... Overload me!"); - apFirstRun = false; + m_apFirstRun = false; } Timer.delay(0.001); } - private boolean tpFirstRun = true; + private boolean m_tpFirstRun = true; /** * Periodic code for teleop mode should go here. * - * Users should override this method for code which will be called - * periodically at a regular rate while the robot is in teleop mode. + *

Users should override this method for code which will be called periodically at a regular + * rate while the robot is in teleop mode. */ public void teleopPeriodic() { - if (tpFirstRun) { + if (m_tpFirstRun) { System.out.println("Default IterativeRobot.teleopPeriodic() method... Overload me!"); - tpFirstRun = false; + m_tpFirstRun = false; } Timer.delay(0.001); } - private boolean tmpFirstRun = true; + private boolean m_tmpFirstRun = true; /** - * Periodic code for test mode should go here + * Periodic code for test mode should go here. * - * Users should override this method for code which will be called - * periodically at a regular rate while the robot is in test mode. + *

Users should override this method for code which will be called periodically at a regular + * rate while the robot is in test mode. */ public void testPeriodic() { - if (tmpFirstRun) { + if (m_tmpFirstRun) { System.out.println("Default IterativeRobot.testPeriodic() method... Overload me!"); - tmpFirstRun = false; + m_tmpFirstRun = false; } } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Jaguar.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Jaguar.java index 870acea468..0dabd45559 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Jaguar.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Jaguar.java @@ -13,7 +13,7 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** * Texas Instruments / Vex Robotics Jaguar Speed Controller as a PWM device. - *$ + * * @see CANJaguar CANJaguar for CAN control */ public class Jaguar extends PWMSpeedController { @@ -24,7 +24,7 @@ public class Jaguar extends PWMSpeedController { private void initJaguar() { /* * Input profile defined by Luminary Micro. - *$ + * * Full reverse ranges from 0.671325ms to 0.6972211ms Proportional reverse * ranges from 0.6972211ms to 1.4482078ms Neutral ranges from 1.4482078ms to * 1.5517922ms Proportional forward ranges from 1.5517922ms to 2.3027789ms @@ -42,8 +42,8 @@ public class Jaguar extends PWMSpeedController { /** * Constructor. * - * @param channel The PWM channel that the Jaguar is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the Jaguar is attached to. 0-9 are on-board, 10-19 are on + * the MXP port */ public Jaguar(final int channel) { super(channel); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java index e139ef9dfc..3ca2aa3769 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java @@ -7,16 +7,15 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; +import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; /** - * Handle input from standard Joysticks connected to the Driver Station. This - * class handles standard input that comes from the Driver Station. Each time a - * value is requested the most recent value is returned. There is a single class - * instance for each joystick and the mapping of ports to hardware buttons - * depends on the code in the driver station. + * Handle input from standard Joysticks connected to the Driver Station. This class handles standard + * input that comes from the Driver Station. Each time a value is requested the most recent value is + * returned. There is a single class instance for each joystick and the mapping of ports to hardware + * buttons depends on the code in the driver station. */ public class Joystick extends GenericHID { @@ -31,11 +30,12 @@ public class Joystick extends GenericHID { /** * Represents an analog axis on a joystick. */ - public static class AxisType { + public static final class AxisType { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kX_val = 0; static final int kY_val = 1; @@ -44,27 +44,27 @@ public class Joystick extends GenericHID { static final int kThrottle_val = 4; static final int kNumAxis_val = 5; /** - * axis: x-axis + * axis: x-axis. */ public static final AxisType kX = new AxisType(kX_val); /** - * axis: y-axis + * axis: y-axis. */ public static final AxisType kY = new AxisType(kY_val); /** - * axis: z-axis + * axis: z-axis. */ public static final AxisType kZ = new AxisType(kZ_val); /** - * axis: twist + * axis: twist. */ public static final AxisType kTwist = new AxisType(kTwist_val); /** - * axis: throttle + * axis: throttle. */ public static final AxisType kThrottle = new AxisType(kThrottle_val); /** - * axis: number of axis + * axis: number of axis. */ public static final AxisType kNumAxis = new AxisType(kNumAxis_val); @@ -74,27 +74,28 @@ public class Joystick extends GenericHID { } /** - * Represents a digital button on the JoyStick + * Represents a digital button on the JoyStick. */ - public static class ButtonType { + public static final class ButtonType { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kTrigger_val = 0; static final int kTop_val = 1; static final int kNumButton_val = 2; /** - * button: trigger + * button: trigger. */ public static final ButtonType kTrigger = new ButtonType((kTrigger_val)); /** - * button: top button + * button: top button. */ public static final ButtonType kTop = new ButtonType(kTop_val); /** - * button: num button types + * button: num button types. */ public static final ButtonType kNumButton = new ButtonType((kNumButton_val)); @@ -105,22 +106,23 @@ public class Joystick extends GenericHID { /** - * Represents a rumble output on the JoyStick + * Represents a rumble output on the JoyStick. */ - public static class RumbleType { + public static final class RumbleType { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kLeftRumble_val = 0; static final int kRightRumble_val = 1; /** - * Left Rumble + * Left Rumble. */ public static final RumbleType kLeftRumble = new RumbleType((kLeftRumble_val)); /** - * Right Rumble + * Right Rumble. */ public static final RumbleType kRightRumble = new RumbleType(kRightRumble_val); @@ -129,7 +131,7 @@ public class Joystick extends GenericHID { } } - private DriverStation m_ds; + private final DriverStation m_ds; private final int m_port; private final byte[] m_axes; private final byte[] m_buttons; @@ -138,11 +140,10 @@ public class Joystick extends GenericHID { private short m_rightRumble; /** - * Construct an instance of a joystick. The joystick index is the usb port on - * the drivers station. + * Construct an instance of a joystick. The joystick index is the usb port on the drivers + * station. * - * @param port The port on the driver station that the joystick is plugged - * into. + * @param port The port on the driver station that the joystick is plugged into. */ public Joystick(final int port) { this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value); @@ -162,12 +163,11 @@ public class Joystick extends GenericHID { /** * Protected version of the constructor to be called by sub-classes. * - * This constructor allows the subclass to configure the number of constants - * for axes and buttons. + *

This constructor allows the subclass to configure the number of constants for axes and + * buttons. * - * @param port The port on the driver station that the joystick is plugged - * into. - * @param numAxisTypes The number of axis types in the enum. + * @param port The port on the driver station that the joystick is plugged into. + * @param numAxisTypes The number of axis types in the enum. * @param numButtonTypes The number of button types in the enum. */ protected Joystick(int port, int numAxisTypes, int numButtonTypes) { @@ -178,8 +178,8 @@ public class Joystick extends GenericHID { } /** - * Get the X value of the joystick. This depends on the mapping of the - * joystick connected to the current port. + * Get the X value of the joystick. This depends on the mapping of the joystick connected to the + * current port. * * @param hand Unused * @return The X value of the joystick. @@ -189,8 +189,8 @@ public class Joystick extends GenericHID { } /** - * Get the Y value of the joystick. This depends on the mapping of the - * joystick connected to the current port. + * Get the Y value of the joystick. This depends on the mapping of the joystick connected to the + * current port. * * @param hand Unused * @return The Y value of the joystick. @@ -200,8 +200,8 @@ public class Joystick extends GenericHID { } /** - * Get the Z value of the joystick. This depends on the mapping of the - * joystick connected to the current port. + * Get the Z value of the joystick. This depends on the mapping of the joystick connected to the + * current port. * * @param hand Unused * @return The Z value of the joystick. @@ -211,8 +211,8 @@ public class Joystick extends GenericHID { } /** - * Get the twist value of the current joystick. This depends on the mapping of - * the joystick connected to the current port. + * Get the twist value of the current joystick. This depends on the mapping of the joystick + * connected to the current port. * * @return The Twist value of the joystick. */ @@ -221,8 +221,8 @@ public class Joystick extends GenericHID { } /** - * Get the throttle value of the current joystick. This depends on the mapping - * of the joystick connected to the current port. + * Get the throttle value of the current joystick. This depends on the mapping of the joystick + * connected to the current port. * * @return The Throttle value of the joystick. */ @@ -243,9 +243,8 @@ public class Joystick extends GenericHID { /** * For the current joystick, return the axis determined by the argument. * - * This is for cases where the joystick axis is returned programatically, - * otherwise one of the previous functions would be preferable (for example - * getX()). + *

This is for cases where the joystick axis is returned programatically, otherwise one of the + * previous functions would be preferable (for example getX()). * * @param axis The axis to read. * @return The value of the axis. @@ -268,7 +267,7 @@ public class Joystick extends GenericHID { } /** - * For the current joystick, return the number of axis + * For the current joystick, return the number of axis. */ public int getAxisCount() { return m_ds.getStickAxisCount(m_port); @@ -277,10 +276,10 @@ public class Joystick extends GenericHID { /** * Read the state of the trigger on the joystick. * - * Look up which button has been assigned to the trigger and read its state. + *

Look up which button has been assigned to the trigger and read its state. * - * @param hand This parameter is ignored for the Joystick class and is only - * here to complete the GenericHID interface. + * @param hand This parameter is ignored for the Joystick class and is only here to complete the + * GenericHID interface. * @return The state of the trigger. */ public boolean getTrigger(Hand hand) { @@ -290,10 +289,10 @@ public class Joystick extends GenericHID { /** * Read the state of the top button on the joystick. * - * Look up which button has been assigned to the top and read its state. + *

Look up which button has been assigned to the top and read its state. * - * @param hand This parameter is ignored for the Joystick class and is only - * here to complete the GenericHID interface. + * @param hand This parameter is ignored for the Joystick class and is only here to complete the + * GenericHID interface. * @return The state of the top button. */ public boolean getTop(Hand hand) { @@ -301,11 +300,11 @@ public class Joystick extends GenericHID { } /** - * This is not supported for the Joystick. This method is only here to - * complete the GenericHID interface. + * This is not supported for the Joystick. This method is only here to complete the GenericHID + * interface. * - * @param hand This parameter is ignored for the Joystick class and is only - * here to complete the GenericHID interface. + * @param hand This parameter is ignored for the Joystick class and is only here to complete the + * GenericHID interface. * @return The state of the bumper (always false) */ public boolean getBumper(Hand hand) { @@ -313,9 +312,9 @@ public class Joystick extends GenericHID { } /** - * Get the button value (starting at button 1) + * Get the button value (starting at button 1). * - * The appropriate button is returned as a boolean value. + *

The appropriate button is returned as a boolean value. * * @param button The button number to be read (starting at 1). * @return The state of the button. @@ -325,7 +324,7 @@ public class Joystick extends GenericHID { } /** - * For the current joystick, return the number of buttons + * For the current joystick, return the number of buttons. */ public int getButtonCount() { return m_ds.getStickButtonCount(m_port); @@ -334,8 +333,8 @@ public class Joystick extends GenericHID { /** * Get the angle in degrees of a POV on the joystick. * - * The POV angles start at 0 in the up direction, and increase - * clockwise (eg right is 90, upper-left is 315). + *

The POV angles start at 0 in the up direction, and increase clockwise (eg right is 90, + * upper-left is 315). * * @param pov The index of the POV to read (starting at 0) * @return the angle of the POV in degrees, or -1 if the POV is not pressed. @@ -345,7 +344,7 @@ public class Joystick extends GenericHID { } /** - * For the current joystick, return the number of POVs + * For the current joystick, return the number of POVs. */ public int getPOVCount() { return m_ds.getStickPOVCount(m_port); @@ -354,7 +353,7 @@ public class Joystick extends GenericHID { /** * Get buttons based on an enumerated type. * - * The button type will be looked up in the list of buttons and then read. + *

The button type will be looked up in the list of buttons and then read. * * @param button The type of button to read. * @return The state of the button. @@ -371,8 +370,8 @@ public class Joystick extends GenericHID { } /** - * Get the magnitude of the direction vector formed by the joystick's current - * position relative to its origin + * Get the magnitude of the direction vector formed by the joystick's current position relative to + * its origin. * * @return The magnitude of the direction vector */ @@ -381,8 +380,7 @@ public class Joystick extends GenericHID { } /** - * Get the direction of the vector formed by the joystick and its origin in - * radians + * Get the direction of the vector formed by the joystick and its origin in radians. * * @return The direction of the vector in radians */ @@ -391,11 +389,9 @@ public class Joystick extends GenericHID { } /** - * Get the direction of the vector formed by the joystick and its origin in - * degrees + * Get the direction of the vector formed by the joystick and its origin in degrees. * - * uses acos(-1) to represent Pi due to absence of readily accessable Pi - * constant in C++ + *

Uses acos(-1) to represent Pi due to absence of readily accessable Pi constant in C++ * * @return The direction of the vector in degrees */ @@ -416,7 +412,7 @@ public class Joystick extends GenericHID { /** * Set the channel associated with a specified axis. * - * @param axis The axis to set the channel for. + * @param axis The axis to set the channel for. * @param channel The channel to set the axis to. */ public void setAxisChannel(AxisType axis, int channel) { @@ -425,9 +421,8 @@ public class Joystick extends GenericHID { /** * Get the value of isXbox for the current joystick. - *$ - * @return A boolean that is true if the controller is an xbox - * controller. + * + * @return A boolean that is true if the controller is an xbox controller. */ public boolean getIsXbox() { return m_ds.getJoystickIsXbox(m_port); @@ -435,7 +430,7 @@ public class Joystick extends GenericHID { /** * Get the HID type of the current joystick. - *$ + * * @return The HID type value of the current joystick. */ public int getType() { @@ -444,7 +439,7 @@ public class Joystick extends GenericHID { /** * Get the name of the current joystick. - *$ + * * @return The name of the current joystick. */ public String getName() { @@ -452,30 +447,32 @@ public class Joystick extends GenericHID { } /** - * Set the rumble output for the joystick. The DS currently supports 2 rumble - * values, left rumble and right rumble - *$ - * @param type Which rumble value to set + * Set the rumble output for the joystick. The DS currently supports 2 rumble values, left rumble + * and right rumble. + * + * @param type Which rumble value to set * @param value The normalized value (0 to 1) to set the rumble to */ public void setRumble(RumbleType type, float value) { - if (value < 0) + if (value < 0) { value = 0; - else if (value > 1) + } else if (value > 1) { value = 1; - if (type.value == RumbleType.kLeftRumble_val) + } + if (type.value == RumbleType.kLeftRumble_val) { m_leftRumble = (short) (value * 65535); - else + } else { m_rightRumble = (short) (value * 65535); + } FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble); } /** * Set a single HID output value for the joystick. - *$ + * * @param outputNumber The index of the output to set (1-32) - * @param value The value to set the output to + * @param value The value to set the output to */ public void setOutput(int outputNumber, boolean value) { @@ -486,7 +483,7 @@ public class Joystick extends GenericHID { /** * Set all HID output values for the joystick. - *$ + * * @param value The 32 bit output value (1 bit for each output) */ public void setOutputs(int value) { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java index fb3ba24c5d..14ad0b104d 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java @@ -7,48 +7,43 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.Timer; - /** - * The MotorSafetyHelper object is constructed for every object that wants to - * implement the Motor Safety protocol. The helper object has the code to - * actually do the timing and call the motors Stop() method when the timeout - * expires. The motor object is expected to call the Feed() method whenever the - * motors value is updated. + * The MotorSafetyHelper object is constructed for every object that wants to implement the Motor + * Safety protocol. The helper object has the code to actually do the timing and call the motors + * Stop() method when the timeout expires. The motor object is expected to call the Feed() method + * whenever the motors value is updated. * * @author brad */ -public class MotorSafetyHelper { +public final class MotorSafetyHelper { - double m_expiration; - boolean m_enabled; - double m_stopTime; - MotorSafety m_safeObject; - MotorSafetyHelper m_nextHelper; - static MotorSafetyHelper m_headHelper = null; + private double m_expiration; + private boolean m_enabled; + private double m_stopTime; + private final MotorSafety m_safeObject; + private final MotorSafetyHelper m_nextHelper; + private static MotorSafetyHelper headHelper = null; /** - * The constructor for a MotorSafetyHelper object. The helper object is - * constructed for every object that wants to implement the Motor Safety - * protocol. The helper object has the code to actually do the timing and call - * the motors Stop() method when the timeout expires. The motor object is - * expected to call the Feed() method whenever the motors value is updated. + * The constructor for a MotorSafetyHelper object. The helper object is constructed for every + * object that wants to implement the Motor Safety protocol. The helper object has the code to + * actually do the timing and call the motors Stop() method when the timeout expires. The motor + * object is expected to call the Feed() method whenever the motors value is updated. * - * @param safeObject a pointer to the motor object implementing MotorSafety. - * This is used to call the Stop() method on the motor. + * @param safeObject a pointer to the motor object implementing MotorSafety. This is used to call + * the Stop() method on the motor. */ public MotorSafetyHelper(MotorSafety safeObject) { m_safeObject = safeObject; m_enabled = false; m_expiration = MotorSafety.DEFAULT_SAFETY_EXPIRATION; m_stopTime = Timer.getFPGATimestamp(); - m_nextHelper = m_headHelper; - m_headHelper = this; + m_nextHelper = headHelper; + headHelper = this; } /** - * Feed the motor safety object. Resets the timer on this object that is used - * to do the timeouts. + * Feed the motor safety object. Resets the timer on this object that is used to do the timeouts. */ public void feed() { m_stopTime = Timer.getFPGATimestamp() + m_expiration; @@ -56,7 +51,7 @@ public class MotorSafetyHelper { /** * Set the expiration time for the corresponding motor safety object. - *$ + * * @param expirationTime The timeout value in seconds. */ public void setExpiration(double expirationTime) { @@ -65,7 +60,7 @@ public class MotorSafetyHelper { /** * Retrieve the timeout value for the corresponding motor safety object. - *$ + * * @return the timeout value in seconds. */ public double getExpiration() { @@ -74,34 +69,34 @@ public class MotorSafetyHelper { /** * Determine of the motor is still operating or has timed out. - *$ - * @return a true value if the motor is still operating normally and hasn't - * timed out. + * + * @return a true value if the motor is still operating normally and hasn't timed out. */ public boolean isAlive() { return !m_enabled || m_stopTime > Timer.getFPGATimestamp(); } /** - * Check if this motor has exceeded its timeout. This method is called - * periodically to determine if this motor has exceeded its timeout value. If - * it has, the stop method is called, and the motor is shut down until its - * value is updated again. + * Check if this motor has exceeded its timeout. This method is called periodically to determine + * if this motor has exceeded its timeout value. If it has, the stop method is called, and the + * motor is shut down until its value is updated again. */ public void check() { - if (!m_enabled || RobotState.isDisabled() || RobotState.isTest()) + if (!m_enabled || RobotState.isDisabled() || RobotState.isTest()) { return; + } if (m_stopTime < Timer.getFPGATimestamp()) { - DriverStation.reportError(m_safeObject.getDescription() + "... Output not updated often enough.", false); + DriverStation.reportError(m_safeObject.getDescription() + "... Output not updated often " + + "enough.", false); m_safeObject.stopMotor(); } } /** - * Enable/disable motor safety for this device Turn on and off the motor - * safety option for this PWM object. - *$ + * Enable/disable motor safety for this device Turn on and off the motor safety option for this + * PWM object. + * * @param enabled True if motor safety is enforced for this object */ public void setSafetyEnabled(boolean enabled) { @@ -109,9 +104,9 @@ public class MotorSafetyHelper { } /** - * Return the state of the motor safety enabled flag Return if the motor - * safety is currently enabled for this devicce. - *$ + * Return the state of the motor safety enabled flag Return if the motor safety is currently + * enabled for this devicce. + * * @return True if motor safety is enforced for this device */ public boolean isSafetyEnabled() { @@ -119,13 +114,13 @@ public class MotorSafetyHelper { } /** - * Check the motors to see if any have timed out. This static method is called - * periodically to poll all the motors and stop any that have timed out. + * Check the motors to see if any have timed out. This static method is called periodically to + * poll all the motors and stop any that have timed out. */ // TODO: these should be synchronized with the setting methods in case it's // called from a different thread public static void checkMotors() { - for (MotorSafetyHelper msh = m_headHelper; msh != null; msh = msh.m_nextHelper) { + for (MotorSafetyHelper msh = headHelper; msh != null; msh = msh.m_nextHelper) { msh.check(); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Notifier.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Notifier.java index 4a6b583642..c47a4f5b47 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Notifier.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Notifier.java @@ -7,18 +7,15 @@ package edu.wpi.first.wpilibj; -import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import java.lang.Runtime; import edu.wpi.first.wpilibj.hal.NotifierJNI; -import edu.wpi.first.wpilibj.Utility; public class Notifier { private static class Process implements NotifierJNI.NotifierJNIHandlerFunction { // The lock for the process information. - private ReentrantLock m_processLock = new ReentrantLock(); + private final ReentrantLock m_processLock = new ReentrantLock(); // The C pointer to the notifier object. We don't use it directly, it is // just passed to the JNI bindings. private long m_notifier; @@ -37,7 +34,7 @@ public class Notifier { // completed. This is only relevant if the handler takes a very long time // to complete (or the period is very short) and when everything is being // destructed. - private ReentrantLock m_handlerLock = new ReentrantLock(); + private final ReentrantLock m_handlerLock = new ReentrantLock(); public Process(Runnable run) { m_handler = run; @@ -45,10 +42,10 @@ public class Notifier { } @Override + @SuppressWarnings("NoFinalizer") protected void finalize() { NotifierJNI.cleanNotifier(m_notifier); m_handlerLock.lock(); - m_handlerLock = null; } /** @@ -59,8 +56,8 @@ public class Notifier { } /** - * Handler which is called by the HAL library; it handles the subsequent - * calling of the user handler. + * Handler which is called by the HAL library; it handles the subsequent calling of the user + * handler. */ @Override public void apply(long time) { @@ -81,7 +78,7 @@ public class Notifier { synchronized (m_processLock) { m_periodic = periodic; m_period = period; - m_expirationTime = Utility.getFPGATime() * 1e-6 + m_period; + m_expirationTime = Utility.getFPGATime() * 1e-6 + period; updateAlarm(); } } @@ -101,16 +98,16 @@ public class Notifier { /** * Create a Notifier for timer event notification. * - * @param run The handler that is called at the notification time which is set - * using StartSingle or StartPeriodic. + * @param run The handler that is called at the notification time which is set using StartSingle + * or StartPeriodic. */ public Notifier(Runnable run) { m_process = new Process(run); } /** - * Register for single event notification. A timer event is queued for a - * single event after the specified delay. + * Register for single event notification. A timer event is queued for a single event after the + * specified delay. * * @param delay Seconds to wait before the handler is called. */ @@ -119,22 +116,21 @@ public class Notifier { } /** - * Register for periodic event notification. A timer event is queued for - * periodic event notification. Each time the interrupt occurs, the event will - * be immediately requeued for the same time interval. + * Register for periodic event notification. A timer event is queued for periodic event + * notification. Each time the interrupt occurs, the event will be immediately requeued for the + * same time interval. * - * @param period Period in seconds to call the handler starting one period - * after the call to this method. + * @param period Period in seconds to call the handler starting one period after the call to this + * method. */ public void startPeriodic(double period) { m_process.start(period, true); } /** - * Stop timer events from occuring. Stop any repeating timer events from - * occuring. This will also remove any single notification events from the - * queue. If a timer-based call to the registered handler is in progress, this - * function will block until the handler call is complete. + * Stop timer events from occuring. Stop any repeating timer events from occuring. This will also + * remove any single notification events from the queue. If a timer-based call to the registered + * handler is in progress, this function will block until the handler call is complete. */ public void stop() { m_process.stop(); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWM.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWM.java index 2449145db5..8b82401447 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWM.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWM.java @@ -9,27 +9,24 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; -import edu.wpi.first.wpilibj.hal.PWMJNI; import edu.wpi.first.wpilibj.hal.DIOJNI; +import edu.wpi.first.wpilibj.hal.PWMJNI; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; import edu.wpi.first.wpilibj.util.AllocationException; -import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Class implements the PWM generation in the FPGA. * - * The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They - * are mapped to the hardware dependent values, in this case 0-2000 for the - * FPGA. Changes are immediately sent to the FPGA, and the update occurs at the - * next FPGA cycle. There is no delay. + *

The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They are mapped to + * the hardware dependent values, in this case 0-2000 for the FPGA. Changes are immediately sent to + * the FPGA, and the update occurs at the next FPGA cycle. There is no delay. * - * As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as - * follows: - 2000 = maximum pulse width - 1999 to 1001 = linear scaling from - * "full forward" to "center" - 1000 = center value - 999 to 2 = linear scaling - * from "center" to "full reverse" - 1 = minimum pulse width (currently .5ms) - - * 0 = disabled (i.e. PWM output is held low) + *

As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as follows: - 2000 = + * maximum pulse width - 1999 to 1001 = linear scaling from "full forward" to "center" - 1000 = + * center value - 999 to 2 = linear scaling from "center" to "full reverse" - 1 = minimum pulse + * width (currently .5ms) - 0 = disabled (i.e. PWM output is held low) */ public class PWM extends SensorBase implements LiveWindowSendable { /** @@ -38,22 +35,23 @@ public class PWM extends SensorBase implements LiveWindowSendable { public static class PeriodMultiplier { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int k1X_val = 1; static final int k2X_val = 2; static final int k4X_val = 4; /** - * Period Multiplier: don't skip pulses + * Period Multiplier: don't skip pulses. */ public static final PeriodMultiplier k1X = new PeriodMultiplier(k1X_val); /** - * Period Multiplier: skip every other pulse + * Period Multiplier: skip every other pulse. */ public static final PeriodMultiplier k2X = new PeriodMultiplier(k2X_val); /** - * Period Multiplier: skip three out of four pulses + * Period Multiplier: skip three out of four pulses. */ public static final PeriodMultiplier k4X = new PeriodMultiplier(k4X_val); @@ -64,55 +62,55 @@ public class PWM extends SensorBase implements LiveWindowSendable { private int m_channel; private long m_port; + /** - * kDefaultPwmPeriod is in ms + * kDefaultPwmPeriod is in ms. * - * - 20ms periods (50 Hz) are the "safest" setting in that this works for all - * devices - 20ms periods seem to be desirable for Vex Motors - 20ms periods - * are the specified period for HS-322HD servos, but work reliably down to - * 10.0 ms; starting at about 8.5ms, the servo sometimes hums and get hot; by - * 5.0ms the hum is nearly continuous - 10ms periods work well for Victor 884 - * - 5ms periods allows higher update rates for Luminary Micro Jaguar speed - * controllers. Due to the shipping firmware on the Jaguar, we can't run the - * update period less than 5.05 ms. + *

- 20ms periods (50 Hz) are the "safest" setting in that this works for all devices - 20ms + * periods seem to be desirable for Vex Motors - 20ms periods are the specified period for + * HS-322HD servos, but work reliably down to 10.0 ms; starting at about 8.5ms, the servo + * sometimes hums and get hot; by 5.0ms the hum is nearly continuous - 10ms periods work well for + * Victor 884 - 5ms periods allows higher update rates for Luminary Micro Jaguar speed + * controllers. Due to the shipping firmware on the Jaguar, we can't run the update period less + * than 5.05 ms. * - * kDefaultPwmPeriod is the 1x period (5.05 ms). In hardware, the period - * scaling is implemented as an output squelch to get longer periods for old - * devices. + *

kDefaultPwmPeriod is the 1x period (5.05 ms). In hardware, the period scaling is implemented + * as an output squelch to get longer periods for old devices. */ protected static final double kDefaultPwmPeriod = 5.05; /** - * kDefaultPwmCenter is the PWM range center in ms + * kDefaultPwmCenter is the PWM range center in ms. */ protected static final double kDefaultPwmCenter = 1.5; /** - * kDefaultPWMStepsDown is the number of PWM steps below the centerpoint + * kDefaultPWMStepsDown is the number of PWM steps below the centerpoint. */ protected static final int kDefaultPwmStepsDown = 1000; public static final int kPwmDisabled = 0; - boolean m_eliminateDeadband; - int m_maxPwm; - int m_deadbandMaxPwm; + private boolean m_eliminateDeadband; + private int m_maxPwm; + private int m_deadbandMaxPwm; + /* + * Intentionally package private + */ int m_centerPwm; - int m_deadbandMinPwm; - int m_minPwm; + private int m_deadbandMinPwm; + private int m_minPwm; /** * Initialize PWMs given a channel. * - * This method is private and is the common path for all the constructors for - * creating PWM instances. Checks channel value ranges and allocates the - * appropriate channel. The allocation is only done to help users ensure that - * they don't double assign channels. - *$ - * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the - * MXP port + *

This method is private and is the common path for all the constructors for creating PWM + * instances. Checks channel value ranges and allocates the appropriate channel. The allocation is + * only done to help users ensure that they don't double assign channels. + * + * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the MXP port */ private void initPWM(final int channel) { checkPWMChannel(channel); m_channel = channel; - m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) m_channel)); + m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) channel)); if (!PWMJNI.allocatePWMChannel(m_port)) { throw new AllocationException("PWM channel " + channel + " is already allocated"); @@ -137,10 +135,12 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Free the PWM channel. * - * Free the resource associated with the PWM channel and set the value to 0. + *

Free the resource associated with the PWM channel and set the value to 0. */ public void free() { - if (m_port == 0) return; + if (m_port == 0) { + return; + } PWMJNI.setPWM(m_port, (short) 0); PWMJNI.freePWMChannel(m_port); PWMJNI.freeDIO(m_port); @@ -150,30 +150,30 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Optionally eliminate the deadband from a speed controller. - *$ - * @param eliminateDeadband If true, set the motor curve on the Jaguar to - * eliminate the deadband in the middle of the range. Otherwise, keep - * the full range without modifying any values. + * + * @param eliminateDeadband If true, set the motor curve on the Jaguar to eliminate the deadband + * in the middle of the range. Otherwise, keep the full range without + * modifying any values. */ public void enableDeadbandElimination(boolean eliminateDeadband) { m_eliminateDeadband = eliminateDeadband; } /** - * Set the bounds on the PWM values. This sets the bounds on the PWM values - * for a particular each type of controller. The values determine the upper - * and lower speeds as well as the deadband bracket. - *$ - * @deprecated Recommended to set bounds in ms using - * {@link #setBounds(double, double, double, double, double)} - * @param max The Minimum pwm value + * Set the bounds on the PWM values. This sets the bounds on the PWM values for a particular each + * type of controller. The values determine the upper and lower speeds as well as the deadband + * bracket. + * + * @param max The Minimum pwm value * @param deadbandMax The high end of the deadband range - * @param center The center speed (off) + * @param center The center speed (off) * @param deadbandMin The low end of the deadband range - * @param min The minimum pwm value + * @param min The minimum pwm value + * @deprecated Recommended to set bounds in ms using {@link #setBounds(double, double, double, + * double, double)} */ public void setBounds(final int max, final int deadbandMax, final int center, - final int deadbandMin, final int min) { + final int deadbandMin, final int min) { m_maxPwm = max; m_deadbandMaxPwm = deadbandMax; m_centerPwm = center; @@ -182,18 +182,18 @@ public class PWM extends SensorBase implements LiveWindowSendable { } /** - * Set the bounds on the PWM pulse widths. This sets the bounds on the PWM - * values for a particular type of controller. The values determine the upper - * and lower speeds as well as the deadband bracket. - *$ - * @param max The max PWM pulse width in ms + * Set the bounds on the PWM pulse widths. This sets the bounds on the PWM values for a particular + * type of controller. The values determine the upper and lower speeds as well as the deadband + * bracket. + * + * @param max The max PWM pulse width in ms * @param deadbandMax The high end of the deadband range pulse width in ms - * @param center The center (off) pulse width in ms + * @param center The center (off) pulse width in ms * @param deadbandMin The low end of the deadband pulse width in ms - * @param min The minimum pulse width in ms + * @param min The minimum pulse width in ms */ protected void setBounds(double max, double deadbandMax, double center, double deadbandMin, - double min) { + double min) { double loopTime = DIOJNI.getLoopTiming() / (kSystemClockTicksPerMicrosecond * 1e3); @@ -218,12 +218,11 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Set the PWM value based on a position. * - * This is intended to be used by servos. - * - * @pre SetMaxPositivePwm() called. - * @pre SetMinNegativePwm() called. + *

This is intended to be used by servos. * * @param pos The position to set the servo between 0.0 and 1.0. + * @pre SetMaxPositivePwm() called. + * @pre SetMinNegativePwm() called. */ public void setPosition(double pos) { if (pos < 0.0) { @@ -244,12 +243,11 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Get the PWM value in terms of a position. * - * This is intended to be used by servos. - * - * @pre SetMaxPositivePwm() called. - * @pre SetMinNegativePwm() called. + *

This is intended to be used by servos. * * @return The position the servo is set to between 0.0 and 1.0. + * @pre SetMaxPositivePwm() called. + * @pre SetMinNegativePwm() called. */ public double getPosition() { int value = getRaw(); @@ -265,15 +263,14 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Set the PWM value based on a speed. * - * This is intended to be used by speed controllers. + *

This is intended to be used by speed controllers. * + * @param speed The speed to set the speed controller between -1.0 and 1.0. * @pre SetMaxPositivePwm() called. * @pre SetMinPositivePwm() called. * @pre SetCenterPwm() called. * @pre SetMaxNegativePwm() called. * @pre SetMinNegativePwm() called. - * - * @param speed The speed to set the speed controller between -1.0 and 1.0. */ final void setSpeed(double speed) { // clamp speed to be in the range 1.0 >= speed >= -1.0 @@ -289,10 +286,12 @@ public class PWM extends SensorBase implements LiveWindowSendable { rawValue = getCenterPwm(); } else if (speed > 0.0) { rawValue = - (int) (speed * ((double) getPositiveScaleFactor()) + ((double) getMinPositivePwm()) + 0.5); + (int) (speed * ((double) getPositiveScaleFactor()) + + ((double) getMinPositivePwm()) + 0.5); } else { rawValue = - (int) (speed * ((double) getNegativeScaleFactor()) + ((double) getMaxNegativePwm()) + 0.5); + (int) (speed * ((double) getNegativeScaleFactor()) + + ((double) getMaxNegativePwm()) + 0.5); } // send the computed pwm value to the FPGA @@ -302,14 +301,13 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Get the PWM value in terms of speed. * - * This is intended to be used by speed controllers. + *

This is intended to be used by speed controllers. * + * @return The most recently set speed between -1.0 and 1.0. * @pre SetMaxPositivePwm() called. * @pre SetMinPositivePwm() called. * @pre SetMaxNegativePwm() called. * @pre SetMinNegativePwm() called. - * - * @return The most recently set speed between -1.0 and 1.0. */ public double getSpeed() { int value = getRaw(); @@ -329,7 +327,7 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Set the PWM value directly to the hardware. * - * Write a raw value to a PWM channel. + *

Write a raw value to a PWM channel. * * @param value Raw PWM value. Range 0 - 255. */ @@ -340,7 +338,7 @@ public class PWM extends SensorBase implements LiveWindowSendable { /** * Get the PWM value directly from the hardware. * - * Read a raw value from a PWM channel. + *

Read a raw value from a PWM channel. * * @return Raw PWM control value. Range: 0 - 255. */ @@ -411,56 +409,47 @@ public class PWM extends SensorBase implements LiveWindowSendable { /* * Live Window code, only does anything if live window is activated. */ + @Override public String getSmartDashboardType() { return "Speed Controller"; } private ITable m_table; - private ITableListener m_table_listener; + private ITableListener m_tableListener; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", getSpeed()); } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void startLiveWindowMode() { setSpeed(0); // Stop for safety - m_table_listener = new ITableListener() { + m_tableListener = new ITableListener() { public void valueChanged(ITable itable, String key, Object value, boolean bln) { - setSpeed(((Double) value).doubleValue()); + setSpeed((Double) value); } }; - m_table.addTableListener("Value", m_table_listener, true); + m_table.addTableListener("Value", m_tableListener, true); } - /** - * {@inheritDoc} - */ + @Override public void stopLiveWindowMode() { setSpeed(0); // Stop for safety // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWMSpeedController.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWMSpeedController.java index e3fc112638..40c7ebe84d 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWMSpeedController.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PWMSpeedController.java @@ -11,13 +11,13 @@ package edu.wpi.first.wpilibj; * Common base class for all PWM Speed Controllers. */ public abstract class PWMSpeedController extends SafePWM implements SpeedController { - private boolean isInverted = false; + private boolean m_isInverted = false; /** * Constructor. * - * @param channel The PWM channel that the controller is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the controller is attached to. 0-9 are on-board, 10-19 are + * on the MXP port */ protected PWMSpeedController(int channel) { super(channel); @@ -26,53 +26,54 @@ public abstract class PWMSpeedController extends SafePWM implements SpeedControl /** * Set the PWM value. * + *

The PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update + * immediately. * @deprecated For compatibility with CANJaguar * - * The PWM value is set using a range of -1.0 to 1.0, - * appropriately scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending - * UpdateSyncGroup(). If 0, update immediately. */ @Deprecated + @Override public void set(double speed, byte syncGroup) { - setSpeed(isInverted ? -speed : speed); + setSpeed(m_isInverted ? -speed : speed); Feed(); } /** * Set the PWM value. * - * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling - * the value for the FPGA. + *

The PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. * * @param speed The speed value between -1.0 and 1.0 to set. */ + @Override public void set(double speed) { - setSpeed(isInverted ? -speed : speed); + setSpeed(m_isInverted ? -speed : speed); Feed(); } /** - * Common interface for inverting direction of a speed controller + * Common interface for inverting direction of a speed controller. * * @param isInverted The state of inversion true is inverted */ @Override public void setInverted(boolean isInverted) { - this.isInverted = isInverted; + m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. * * @return isInverted The state of inversion, true is inverted. - * */ @Override public boolean getInverted() { - return this.isInverted; + return m_isInverted; } /** @@ -80,6 +81,7 @@ public abstract class PWMSpeedController extends SafePWM implements SpeedControl * * @return The most recently set value for the PWM between -1.0 and 1.0. */ + @Override public double get() { return getSpeed(); } @@ -89,7 +91,8 @@ public abstract class PWMSpeedController extends SafePWM implements SpeedControl * * @param output Write out the PWM value as was found in the PIDController */ + @Override public void pidWrite(double output) { set(output); } -} \ No newline at end of file +} diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java index 551c001120..9c5d8da2cf 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java @@ -8,35 +8,34 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.hal.PDPJNI; -import edu.wpi.first.wpilibj.hal.HALUtil; -import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class for getting voltage, current, temperature, power and energy from the - * CAN PDP. - *$ + * Class for getting voltage, current, temperature, power and energy from the CAN PDP. + * * @author Thomas Clark */ public class PowerDistributionPanel extends SensorBase implements LiveWindowSendable { - int m_module; + private final int m_module; + @SuppressWarnings("JavadocMethod") public PowerDistributionPanel(int module) { m_module = module; - checkPDPModule(m_module); - PDPJNI.initializePDP(m_module); + checkPDPModule(module); + PDPJNI.initializePDP(module); } + @SuppressWarnings("JavadocMethod") public PowerDistributionPanel() { this(0); } /** - * Query the input voltage of the PDP - *$ + * Query the input voltage of the PDP. + * * @return The voltage of the PDP in volts */ public double getVoltage() { @@ -44,8 +43,8 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend } /** - * Query the temperature of the PDP - *$ + * Query the temperature of the PDP. + * * @return The temperature of the PDP in degrees Celsius */ public double getTemperature() { @@ -53,8 +52,8 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend } /** - * Query the current of a single channel of the PDP - *$ + * Query the current of a single channel of the PDP. + * * @return The current of one of the PDP channels (channels 0-15) in Amperes */ public double getCurrent(int channel) { @@ -66,8 +65,8 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend } /** - * Query the current of all monitored PDP channels (0-15) - *$ + * Query the current of all monitored PDP channels (0-15). + * * @return The current of all the channels in Amperes */ public double getTotalCurrent() { @@ -75,8 +74,8 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend } /** - * Query the total power drawn from the monitored PDP channels - *$ + * Query the total power drawn from the monitored PDP channels. + * * @return the total power in Watts */ public double getTotalPower() { @@ -84,8 +83,8 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend } /** - * Query the total energy drawn from the monitored PDP channels - *$ + * Query the total energy drawn from the monitored PDP channels. + * * @return the total energy in Joules */ public double getTotalEnergy() { @@ -93,19 +92,20 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend } /** - * Reset the total energy to 0 + * Reset the total energy to 0. */ public void resetTotalEnergy() { PDPJNI.resetPDPTotalEnergy(m_module); } /** - * Clear all PDP sticky faults + * Clear all PDP sticky faults. */ public void clearStickyFaults() { PDPJNI.clearPDPStickyFaults(m_module); } + @Override public String getSmartDashboardType() { return "PowerDistributionPanel"; } @@ -115,24 +115,18 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend */ private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Chan0", getCurrent(0)); @@ -157,15 +151,17 @@ public class PowerDistributionPanel extends SensorBase implements LiveWindowSend } /** - * PDP doesn't have to do anything special when entering the LiveWindow. - * {@inheritDoc} + * PDP doesn't have to do anything special when entering the LiveWindow. {@inheritDoc} */ - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } /** - * PDP doesn't have to do anything special when exiting the LiveWindow. - * {@inheritDoc} + * PDP doesn't have to do anything special when exiting the LiveWindow. {@inheritDoc} */ - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Preferences.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Preferences.java index a6cbf48a54..626a38fcdb 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Preferences.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Preferences.java @@ -17,49 +17,44 @@ import edu.wpi.first.wpilibj.tables.ITableListener; import edu.wpi.first.wpilibj.tables.TableKeyNotDefinedException; /** - * The preferences class provides a relatively simple way to save important - * values to the RoboRIO to access the next time the RoboRIO is booted. + * The preferences class provides a relatively simple way to save important values to the RoboRIO to + * access the next time the RoboRIO is booted. * - *

- * This class loads and saves from a file inside the RoboRIO. The user can not - * access the file directly, but may modify values at specific fields which will - * then be automatically saved to the file by the NetworkTables server. - *

+ *

This class loads and saves from a file inside the RoboRIO. The user can not access the file + * directly, but may modify values at specific fields which will then be automatically saved to the + * file by the NetworkTables server.

* - *

- * This class is thread safe. - *

+ *

This class is thread safe.

* - *

- * This will also interact with {@link NetworkTable} by creating a table called - * "Preferences" with all the key-value pairs. - *

+ *

This will also interact with {@link NetworkTable} by creating a table called "Preferences" + * with all the key-value pairs.

* * @author Joe Grinstead */ public class Preferences { /** - * The Preferences table name + * The Preferences table name. */ private static final String TABLE_NAME = "Preferences"; /** - * The singleton instance + * The singleton instance. */ private static Preferences instance; /** - * The network table + * The network table. */ - private NetworkTable table; + private final NetworkTable m_table; /** - * Listener to set all Preferences values to persistent (for backwards - * compatibility with old dashboards). + * Listener to set all Preferences values to persistent (for backwards compatibility with old + * dashboards). */ - private final ITableListener listener = new ITableListener() { + private final ITableListener m_listener = new ITableListener() { @Override public void valueChanged(ITable table, String key, Object value, boolean isNew) { // unused } + @Override public void valueChangedEx(ITable table, String key, Object value, int flags) { table.setPersistent(key); @@ -71,7 +66,7 @@ public class Preferences { * * @return the preferences instance */ - public synchronized static Preferences getInstance() { + public static synchronized Preferences getInstance() { if (instance == null) { instance = new Preferences(); } @@ -82,17 +77,18 @@ public class Preferences { * Creates a preference class. */ private Preferences() { - table = NetworkTable.getTable(TABLE_NAME); - table.addTableListenerEx(listener, ITable.NOTIFY_NEW | ITable.NOTIFY_IMMEDIATE); + m_table = NetworkTable.getTable(TABLE_NAME); + m_table.addTableListenerEx(m_listener, ITable.NOTIFY_NEW | ITable.NOTIFY_IMMEDIATE); UsageReporting.report(tResourceType.kResourceType_Preferences, 0); } /** + * Gets the vector of keys. * @return a vector of the keys */ public Vector getKeys() { Vector keys = new Vector(); - for (String key : table.getKeys()) { + for (String key : m_table.getKeys()) { keys.add(key); } return keys; @@ -101,71 +97,71 @@ public class Preferences { /** * Puts the given string into the preferences table. * - * @param key the key + * @param key the key * @param value the value * @throws NullPointerException if value is null */ public void putString(String key, String value) { if (value == null) { - throw new NullPointerException(); + throw new NullPointerException("Value is null"); } - table.putString(key, value); - table.setPersistent(key); + m_table.putString(key, value); + m_table.setPersistent(key); } /** * Puts the given int into the preferences table. * - * @param key the key + * @param key the key * @param value the value */ public void putInt(String key, int value) { - table.putNumber(key, value); - table.setPersistent(key); + m_table.putNumber(key, value); + m_table.setPersistent(key); } /** * Puts the given double into the preferences table. * - * @param key the key + * @param key the key * @param value the value */ public void putDouble(String key, double value) { - table.putNumber(key, value); - table.setPersistent(key); + m_table.putNumber(key, value); + m_table.setPersistent(key); } /** * Puts the given float into the preferences table. * - * @param key the key + * @param key the key * @param value the value */ public void putFloat(String key, float value) { - table.putNumber(key, value); - table.setPersistent(key); + m_table.putNumber(key, value); + m_table.setPersistent(key); } /** * Puts the given boolean into the preferences table. * - * @param key the key + * @param key the key * @param value the value */ public void putBoolean(String key, boolean value) { - table.putBoolean(key, value); - table.setPersistent(key); + m_table.putBoolean(key, value); + m_table.setPersistent(key); } /** * Puts the given long into the preferences table. * - * @param key the key + * @param key the key * @param value the value */ public void putLong(String key, long value) { - table.putNumber(key, value); - table.setPersistent(key); + m_table.putNumber(key, value); + m_table.setPersistent(key); } /** @@ -175,106 +171,106 @@ public class Preferences { * @return if there is a value at the given key */ public boolean containsKey(String key) { - return table.containsKey(key); + return m_table.containsKey(key); } /** - * Remove a preference + * Remove a preference. * * @param key the key */ public void remove(String key) { - table.delete(key); + m_table.delete(key); } /** - * Returns the string at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. + * Returns the string at the given key. If this table does not have a value for that position, + * then the given backup value will be returned. * - * @param key the key + * @param key the key * @param backup the value to return if none exists in the table * @return either the value in the table, or the backup */ public String getString(String key, String backup) { - return table.getString(key, backup); + return m_table.getString(key, backup); } /** - * Returns the int at the given key. If this table does not have a value for - * that position, then the given backup value will be returned. + * Returns the int at the given key. If this table does not have a value for that position, then + * the given backup value will be returned. * - * @param key the key + * @param key the key * @param backup the value to return if none exists in the table * @return either the value in the table, or the backup */ public int getInt(String key, int backup) { try { - return (int)table.getNumber(key); - } catch (TableKeyNotDefinedException e) { + return (int) m_table.getNumber(key); + } catch (TableKeyNotDefinedException ex) { return backup; } } /** - * Returns the double at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. + * Returns the double at the given key. If this table does not have a value for that position, + * then the given backup value will be returned. * - * @param key the key + * @param key the key * @param backup the value to return if none exists in the table * @return either the value in the table, or the backup */ public double getDouble(String key, double backup) { - return table.getDouble(key, backup); + return m_table.getDouble(key, backup); } /** - * Returns the boolean at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. + * Returns the boolean at the given key. If this table does not have a value for that position, + * then the given backup value will be returned. * - * @param key the key + * @param key the key * @param backup the value to return if none exists in the table * @return either the value in the table, or the backup */ public boolean getBoolean(String key, boolean backup) { - return table.getBoolean(key, backup); + return m_table.getBoolean(key, backup); } /** - * Returns the float at the given key. If this table does not have a value for - * that position, then the given backup value will be returned. + * Returns the float at the given key. If this table does not have a value for that position, then + * the given backup value will be returned. * - * @param key the key + * @param key the key * @param backup the value to return if none exists in the table * @return either the value in the table, or the backup */ public float getFloat(String key, float backup) { try { - return (float)table.getNumber(key); - } catch (TableKeyNotDefinedException e) { + return (float) m_table.getNumber(key); + } catch (TableKeyNotDefinedException ex) { return backup; } } /** - * Returns the long at the given key. If this table does not have a value for - * that position, then the given backup value will be returned. + * Returns the long at the given key. If this table does not have a value for that position, then + * the given backup value will be returned. * - * @param key the key + * @param key the key * @param backup the value to return if none exists in the table * @return either the value in the table, or the backup */ public long getLong(String key, long backup) { try { - return (long)table.getNumber(key); - } catch (TableKeyNotDefinedException e) { + return (long) m_table.getNumber(key); + } catch (TableKeyNotDefinedException ex) { return backup; } } /** - * This function is no longer required, as NetworkTables automatically - * saves persistent values (which all Preferences values are) periodically - * when running as a server. + * This function is no longer required, as NetworkTables automatically saves persistent values + * (which all Preferences values are) periodically when running as a server. + * * @deprecated backwards compatibility shim */ public void save() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Relay.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Relay.java index 27e039aa79..7713e21907 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Relay.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Relay.java @@ -18,27 +18,28 @@ import edu.wpi.first.wpilibj.tables.ITableListener; import edu.wpi.first.wpilibj.util.AllocationException; import edu.wpi.first.wpilibj.util.CheckedAllocationException; +import static java.util.Objects.requireNonNull; + /** - * Class for VEX Robotics Spike style relay outputs. Relays are intended to be - * connected to Spikes or similar relays. The relay channels controls a pair of - * pins that are either both off, one on, the other on, or both on. This - * translates into two Spike outputs at 0v, one at 12v and one at 0v, one at 0v - * and the other at 12v, or two Spike outputs at 12V. This allows off, full - * forward, or full reverse control of motors without variable speed. It also - * allows the two channels (forward and reverse) to be used independently for - * something that does not care about voltage polarity (like a solenoid). + * Class for VEX Robotics Spike style relay outputs. Relays are intended to be connected to Spikes + * or similar relays. The relay channels controls a pair of pins that are either both off, one on, + * the other on, or both on. This translates into two Spike outputs at 0v, one at 12v and one at 0v, + * one at 0v and the other at 12v, or two Spike outputs at 12V. This allows off, full forward, or + * full reverse control of motors without variable speed. It also allows the two channels (forward + * and reverse) to be used independently for something that does not care about voltage polarity + * (like a solenoid). */ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable { private MotorSafetyHelper m_safetyHelper; /** - * This class represents errors in trying to set relay values contradictory to - * the direction to which the relay is set. + * This class represents errors in trying to set relay values contradictory to the direction to + * which the relay is set. */ public class InvalidValueException extends RuntimeException { /** - * Create a new exception with the given message + * Create a new exception with the given message. * * @param message the message to pass with the exception */ @@ -50,30 +51,31 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable /** * The state to drive a Relay to. */ - public static enum Value { + public enum Value { /** - * value: off + * value: off. */ kOff(0), /** - * value: on for relays with defined direction + * value: on for relays with defined direction. */ kOn(1), /** - * value: forward + * value: forward. */ kForward(2), /** - * value: reverse + * value: reverse. */ kReverse(3); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; - private Value(int value) { + Value(int value) { this.value = value; } } @@ -81,27 +83,28 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable /** * The Direction(s) that a relay is configured to operate in. */ - public static enum Direction { + public enum Direction { /** - * direction: both directions are valid + * direction: both directions are valid. */ kBoth(0), /** - * direction: Only forward is valid + * direction: Only forward is valid. */ kForward(1), /** - * direction: only reverse is valid + * direction: only reverse is valid. */ kReverse(2); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; - private Direction(int value) { + Direction(int value) { this.value = value; } @@ -114,9 +117,9 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable private static Resource relayChannels = new Resource(kRelayChannels * 2); /** - * Common relay initialization method. This code is common to all Relay - * constructors and initializes the relay and reserves all resources that need - * to be locked. Initially the relay is set to both lines at 0v. + * Common relay initialization method. This code is common to all Relay constructors and + * initializes the relay and reserves all resources that need to be locked. Initially the relay is + * set to both lines at 0v. */ private void initRelay() { SensorBase.checkRelayChannel(m_channel); @@ -129,7 +132,7 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable relayChannels.allocate(m_channel * 2 + 1); UsageReporting.report(tResourceType.kResourceType_Relay, m_channel + 128); } - } catch (CheckedAllocationException e) { + } catch (CheckedAllocationException ex) { throw new AllocationException("Relay channel " + m_channel + " is already allocated"); } @@ -144,14 +147,12 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable /** * Relay constructor given a channel. * - * @param channel The channel number for this relay (0 - 3). + * @param channel The channel number for this relay (0 - 3). * @param direction The direction that the Relay object will control. */ public Relay(final int channel, Direction direction) { - if (direction == null) - throw new NullPointerException("Null Direction was given"); m_channel = channel; - m_direction = direction; + m_direction = requireNonNull( direction, "Null Direction was given"); initRelay(); set(Value.kOff); } @@ -185,15 +186,13 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable /** * Set the relay state. * - * Valid values depend on which directions of the relay are controlled by the - * object. + *

Valid values depend on which directions of the relay are controlled by the object. * - * When set to kBothDirections, the relay can be set to any of the four - * states: 0v-0v, 12v-0v, 0v-12v, 12v-12v + *

When set to kBothDirections, the relay can be set to any of the four states: 0v-0v, 12v-0v, + * 0v-12v, 12v-12v * - * When set to kForwardOnly or kReverseOnly, you can specify the constant for - * the direction or you can simply specify kOff_val and kOn_val. Using only - * kOff_val and kOn_val is recommended. + *

When set to kForwardOnly or kReverseOnly, you can specify the constant for the direction or + * you can simply specify kOff_val and kOn_val. Using only kOff_val and kOn_val is recommended. * * @param value The state to set the relay. */ @@ -216,8 +215,10 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable } break; case kForward: - if (m_direction == Direction.kReverse) - throw new InvalidValueException("A relay configured for reverse cannot be set to forward"); + if (m_direction == Direction.kReverse) { + throw new InvalidValueException("A relay configured for reverse cannot be set to " + + "forward"); + } if (m_direction == Direction.kBoth || m_direction == Direction.kForward) { RelayJNI.setRelayForward(m_port, true); } @@ -226,8 +227,10 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable } break; case kReverse: - if (m_direction == Direction.kForward) - throw new InvalidValueException("A relay configured for forward cannot be set to reverse"); + if (m_direction == Direction.kForward) { + throw new InvalidValueException("A relay configured for forward cannot be set to " + + "reverse"); + } if (m_direction == Direction.kBoth) { RelayJNI.setRelayForward(m_port, false); } @@ -241,11 +244,11 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable } /** - * Get the Relay State + * Get the Relay State. * - * Gets the current state of the relay. + *

Gets the current state of the relay. * - * When set to kForwardOnly or kReverseOnly, value is returned as kOn/kOff not + *

When set to kForwardOnly or kReverseOnly, value is returned as kOn/kOff not * kForward/kReverse (per the recommendation in Set) * * @return The current state of the relay as a Relay::Value @@ -319,18 +322,18 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable } /** - * Set the Relay Direction + * Set the Relay Direction. * - * Changes which values the relay can be set to depending on which direction - * is used + *

Changes which values the relay can be set to depending on which direction is used * - * Valid inputs are kBothDirections, kForwardOnly, and kReverseOnly + *

Valid inputs are kBothDirections, kForwardOnly, and kReverseOnly * * @param direction The direction for the relay to operate in */ public void setDirection(Direction direction) { - if (direction == null) + if (direction == null) { throw new NullPointerException("Null Direction was given"); + } if (m_direction == direction) { return; } @@ -351,28 +354,19 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable } private ITable m_table; - private ITableListener m_table_listener; + private ITableListener m_tableListener; - /** - * {@inheritDoc} - */ @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ @Override public void updateTable() { if (m_table != null) { @@ -388,12 +382,9 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable } } - /** - * {@inheritDoc} - */ @Override public void startLiveWindowMode() { - m_table_listener = new ITableListener() { + m_tableListener = new ITableListener() { @Override public void valueChanged(ITable itable, String key, Object value, boolean bln) { String val = ((String) value); @@ -408,15 +399,12 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable } } }; - m_table.addTableListener("Value", m_table_listener, true); + m_table.addTableListener("Value", m_tableListener, true); } - /** - * {@inheritDoc} - */ @Override public void stopLiveWindowMode() { // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Resource.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Resource.java index 739b4304c0..c59dc7c088 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Resource.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Resource.java @@ -11,31 +11,30 @@ import edu.wpi.first.wpilibj.util.AllocationException; import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** - * Track resources in the program. The Resource class is a convenient way of - * keeping track of allocated arbitrary resources in the program. Resources are - * just indicies that have an lower and upper bound that are tracked by this - * class. In the library they are used for tracking allocation of hardware - * channels but this is purely arbitrary. The resource class does not do any - * actual allocation, but simply tracks if a given index is currently in use. + * Track resources in the program. The Resource class is a convenient way of keeping track of + * allocated arbitrary resources in the program. Resources are just indicies that have an lower and + * upper bound that are tracked by this class. In the library they are used for tracking allocation + * of hardware channels but this is purely arbitrary. The resource class does not do any actual + * allocation, but simply tracks if a given index is currently in use. * - * WARNING: this should only be statically allocated. When the program loads - * into memory all the static constructors are called. At that time a linked - * list of all the "Resources" is created. Then when the program actually starts - * - in the Robot constructor, all resources are initialized. This ensures that - * the program is restartable in memory without having to unload/reload. + *

WARNING: this should only be statically allocated. When the program loads into memory + * all the static constructors are called. At that time a linked list of all the "Resources" is + * created. Then when the program actually starts - in the Robot constructor, all resources are + * initialized. This ensures that the program is restartable in memory without having to + * unload/reload. */ -public class Resource { +public final class Resource { - private static Resource m_resourceList = null; - private final boolean m_numAllocated[]; + private static Resource resourceList = null; + private final boolean[] m_numAllocated; private final int m_size; private final Resource m_nextResource; /** - * Clears all allocated resources + * Clears all allocated resources. */ public static void restartProgram() { - for (Resource r = Resource.m_resourceList; r != null; r = r.m_nextResource) { + for (Resource r = Resource.resourceList; r != null; r = r.m_nextResource) { for (int i = 0; i < r.m_size; i++) { r.m_numAllocated[i] = false; } @@ -43,30 +42,28 @@ public class Resource { } /** - * Allocate storage for a new instance of Resource. Allocate a bool array of - * values that will get initialized to indicate that no resources have been - * allocated yet. The indicies of the resources are 0..size-1. + * Allocate storage for a new instance of Resource. Allocate a bool array of values that will get + * initialized to indicate that no resources have been allocated yet. The indicies of the + * resources are 0..size-1. * * @param size The number of blocks to allocate */ public Resource(final int size) { m_size = size; - m_numAllocated = new boolean[m_size]; - for (int i = 0; i < m_size; i++) { + m_numAllocated = new boolean[size]; + for (int i = 0; i < size; i++) { m_numAllocated[i] = false; } - m_nextResource = Resource.m_resourceList; - Resource.m_resourceList = this; + m_nextResource = Resource.resourceList; + Resource.resourceList = this; } /** - * Allocate a resource. When a resource is requested, mark it allocated. In - * this case, a free resource value within the range is located and returned - * after it is marked allocated. + * Allocate a resource. When a resource is requested, mark it allocated. In this case, a free + * resource value within the range is located and returned after it is marked allocated. * * @return The index of the allocated block. - * @throws CheckedAllocationException If there are no resources available to - * be allocated. + * @throws CheckedAllocationException If there are no resources available to be allocated. */ public int allocate() throws CheckedAllocationException { for (int i = 0; i < m_size; i++) { @@ -79,13 +76,12 @@ public class Resource { } /** - * Allocate a specific resource value. The user requests a specific resource - * value, i.e. channel number and it is verified unallocated, then returned. + * Allocate a specific resource value. The user requests a specific resource value, i.e. channel + * number and it is verified unallocated, then returned. * * @param index The resource to allocate * @return The index of the allocated block - * @throws CheckedAllocationException If there are no resources available to - * be allocated. + * @throws CheckedAllocationException If there are no resources available to be allocated. */ public int allocate(final int index) throws CheckedAllocationException { if (index >= m_size || index < 0) { @@ -99,16 +95,16 @@ public class Resource { } /** - * Free an allocated resource. After a resource is no longer needed, for - * example a destructor is called for a channel assignment class, Free will - * release the resource value so it can be reused somewhere else in the - * program. + * Free an allocated resource. After a resource is no longer needed, for example a destructor is + * called for a channel assignment class, Free will release the resource value so it can be reused + * somewhere else in the program. * * @param index The index of the resource to free. */ public void free(final int index) { - if (m_numAllocated[index] == false) + if (m_numAllocated[index] == false) { throw new AllocationException("No resource available to be freed"); + } m_numAllocated[index] = false; } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotBase.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotBase.java index 5567aed51b..5fafa08ca5 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotBase.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotBase.java @@ -10,12 +10,10 @@ package edu.wpi.first.wpilibj; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; -import java.io.IOException; import java.net.URL; +import java.util.Arrays; import java.util.Enumeration; import java.util.jar.Manifest; -import java.util.Arrays; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; @@ -24,35 +22,30 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.internal.HardwareHLUsageReporting; import edu.wpi.first.wpilibj.internal.HardwareTimer; import edu.wpi.first.wpilibj.networktables.NetworkTable; -import edu.wpi.first.wpilibj.Utility; /** - * Implement a Robot Program framework. The RobotBase class is intended to be - * subclassed by a user creating a robot program. Overridden autonomous() and - * operatorControl() methods are called at the appropriate time as the match - * proceeds. In the current implementation, the Autonomous code will run to - * completion before the OperatorControl code could start. In the future the - * Autonomous code might be spawned as a task, then killed at the end of the - * Autonomous period. + * Implement a Robot Program framework. The RobotBase class is intended to be subclassed by a user + * creating a robot program. Overridden autonomous() and operatorControl() methods are called at the + * appropriate time as the match proceeds. In the current implementation, the Autonomous code will + * run to completion before the OperatorControl code could start. In the future the Autonomous code + * might be spawned as a task, then killed at the end of the Autonomous period. */ public abstract class RobotBase { /** - * The VxWorks priority that robot code should work at (so Java code should - * run at) + * The VxWorks priority that robot code should work at (so Java code should run at). */ public static final int ROBOT_TASK_PRIORITY = 101; protected final DriverStation m_ds; /** - * Constructor for a generic robot program. User code should be placed in the - * constructor that runs before the Autonomous or Operator Control period - * starts. The constructor will run to completion before Autonomous is - * entered. + * Constructor for a generic robot program. User code should be placed in the constructor that + * runs before the Autonomous or Operator Control period starts. The constructor will run to + * completion before Autonomous is entered. * - * This must be used to ensure that the communications code starts. In the - * future it would be nice to put this code into it's own task that loads on - * boot so ensure that it runs. + *

This must be used to ensure that the communications code starts. In the future it would be + * nice + * to put this code into it's own task that loads on boot so ensure that it runs. */ protected RobotBase() { // TODO: StartCAPI(); @@ -70,7 +63,8 @@ public abstract class RobotBase { /** * Free the resources for a RobotBase class. */ - public void free() {} + public void free() { + } /** * @return If the robot is running in simulation. @@ -88,7 +82,7 @@ public abstract class RobotBase { /** * Determine if the Robot is currently disabled. - *$ + * * @return True if the Robot is currently disabled by the field controls. */ public boolean isDisabled() { @@ -97,7 +91,7 @@ public abstract class RobotBase { /** * Determine if the Robot is currently enabled. - *$ + * * @return True if the Robot is currently enabled by the field controls. */ public boolean isEnabled() { @@ -105,30 +99,30 @@ public abstract class RobotBase { } /** - * Determine if the robot is currently in Autonomous mode. - *$ - * @return True if the robot is currently operating Autonomously as determined - * by the field controls. + * Determine if the robot is currently in Autonomous mode as determined by the field + * controls. + * + * @return True if the robot is currently operating Autonomously. */ public boolean isAutonomous() { return m_ds.isAutonomous(); } /** - * Determine if the robot is currently in Test mode - *$ - * @return True if the robot is currently operating in Test mode as determined - * by the driver station. + * Determine if the robot is currently in Test mode as determined by the driver + * station. + * + * @return True if the robot is currently operating in Test mode. */ public boolean isTest() { return m_ds.isTest(); } /** - * Determine if the robot is currently in Operator Control mode. - *$ - * @return True if the robot is currently operating in Tele-Op mode as - * determined by the field controls. + * Determine if the robot is currently in Operator Control mode as determined by the field + * controls. + * + * @return True if the robot is currently operating in Tele-Op mode. */ public boolean isOperatorControl() { return m_ds.isOperatorControl(); @@ -136,9 +130,8 @@ public abstract class RobotBase { /** * Indicates if new data is available from the driver station. - *$ - * @return Has new data arrived over the network since the last time this - * function was called? + * + * @return Has new data arrived over the network since the last time this function was called? */ public boolean isNewDataAvailable() { return m_ds.isNewControlData(); @@ -149,6 +142,7 @@ public abstract class RobotBase { */ public abstract void startCompetition(); + @SuppressWarnings("JavadocMethod") public static boolean getBooleanProperty(String name, boolean defaultValue) { String propVal = System.getProperty(name); if (propVal == null) { @@ -178,7 +172,7 @@ public abstract class RobotBase { /** * Starting point for the applications. */ - public static void main(String args[]) { + public static void main(String... args) { initializeHardwareConfiguration(); UsageReporting.report(tResourceType.kResourceType_Language, tInstances.kLanguage_Java); @@ -187,70 +181,63 @@ public abstract class RobotBase { Enumeration resources = null; try { resources = RobotBase.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); } while (resources != null && resources.hasMoreElements()) { try { Manifest manifest = new Manifest(resources.nextElement().openStream()); robotName = manifest.getMainAttributes().getValue("Robot-Class"); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); } } RobotBase robot; try { robot = (RobotBase) Class.forName(robotName).newInstance(); - } catch (Throwable t) { + } catch (Throwable throwable) { DriverStation.reportError("ERROR Unhandled exception instantiating robot " + robotName + " " - + t.toString() + " at " + Arrays.toString(t.getStackTrace()), false); + + throwable.toString() + " at " + Arrays.toString(throwable.getStackTrace()), false); System.err.println("WARNING: Robots don't quit!"); System.err.println("ERROR: Could not instantiate robot " + robotName + "!"); System.exit(1); return; } - File file = null; - FileOutputStream output = null; try { - file = new File("/tmp/frc_versions/FRC_Lib_Version.ini"); + final File file = new File("/tmp/frc_versions/FRC_Lib_Version.ini"); - if (file.exists()) + if (file.exists()) { file.delete(); + } file.createNewFile(); - output = new FileOutputStream(file); - - output.write("2016 Java Release 5".getBytes()); + try (FileOutputStream output = new FileOutputStream(file)) { + output.write("2016 Java Release 5".getBytes()); + } } catch (IOException ex) { ex.printStackTrace(); - } finally { - if (output != null) { - try { - output.close(); - } catch (IOException ex) { - } - } } boolean errorOnExit = false; try { System.out.println("********** Robot program starting **********"); robot.startCompetition(); - } catch (Throwable t) { + } catch (Throwable throwable) { DriverStation.reportError( - "ERROR Unhandled exception: " + t.toString() + " at " - + Arrays.toString(t.getStackTrace()), false); + "ERROR Unhandled exception: " + throwable.toString() + " at " + + Arrays.toString(throwable.getStackTrace()), false); errorOnExit = true; } finally { // startCompetition never returns unless exception occurs.... System.err.println("WARNING: Robots don't quit!"); if (errorOnExit) { System.err - .println("---> The startCompetition() method (or methods called by it) should have handled the exception above."); + .println("---> The startCompetition() method (or methods called by it) should have " + + "handled the exception above."); } else { System.err.println("---> Unexpected return from startCompetition() method."); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotDrive.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotDrive.java index 97338d297d..fe3545acaa 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotDrive.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/RobotDrive.java @@ -11,47 +11,48 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInst import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; +import static java.util.Objects.requireNonNull; + /** - * Utility class for handling Robot drive based on a definition of the motor - * configuration. The robot drive class handles basic driving for a robot. - * Currently, 2 and 4 motor tank and mecanum drive trains are supported. In the - * future other drive types like swerve might be implemented. Motor channel - * numbers are supplied on creation of the class. Those are used for either the - * drive function (intended for hand created drive code, such as autonomous) or - * with the Tank/Arcade functions intended to be used for Operator Control - * driving. + * Utility class for handling Robot drive based on a definition of the motor configuration. The + * robot drive class handles basic driving for a robot. Currently, 2 and 4 motor tank and mecanum + * drive trains are supported. In the future other drive types like swerve might be implemented. + * Motor channel numbers are supplied on creation of the class. Those are used for either the drive + * function (intended for hand created drive code, such as autonomous) or with the Tank/Arcade + * functions intended to be used for Operator Control driving. */ public class RobotDrive implements MotorSafety { protected MotorSafetyHelper m_safetyHelper; /** - * The location of a motor on the robot for the purpose of driving + * The location of a motor on the robot for the purpose of driving. */ public static class MotorType { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kFrontLeft_val = 0; static final int kFrontRight_val = 1; static final int kRearLeft_val = 2; static final int kRearRight_val = 3; /** - * motortype: front left + * motortype: front left. */ public static final MotorType kFrontLeft = new MotorType(kFrontLeft_val); /** - * motortype: front right + * motortype: front right. */ public static final MotorType kFrontRight = new MotorType(kFrontRight_val); /** - * motortype: rear left + * motortype: rear left. */ public static final MotorType kRearLeft = new MotorType(kRearLeft_val); /** - * motortype: rear right + * motortype: rear right. */ public static final MotorType kRearRight = new MotorType(kRearRight_val); @@ -79,14 +80,12 @@ public class RobotDrive implements MotorSafety { protected static boolean kMecanumPolar_Reported = false; /** - * Constructor for RobotDrive with 2 motors specified with channel numbers. - * Set up parameters for a two wheel drive system where the left and right - * motor pwm channels are specified in the call. This call assumes Talons for - * controlling the motors. - *$ - * @param leftMotorChannel The PWM channel number that drives the left motor. - * @param rightMotorChannel The PWM channel number that drives the right - * motor. + * Constructor for RobotDrive with 2 motors specified with channel numbers. Set up parameters for + * a two wheel drive system where the left and right motor pwm channels are specified in the call. + * This call assumes Talons for controlling the motors. + * + * @param leftMotorChannel The PWM channel number that drives the left motor. + * @param rightMotorChannel The PWM channel number that drives the right motor. */ public RobotDrive(final int leftMotorChannel, final int rightMotorChannel) { m_sensitivity = kDefaultSensitivity; @@ -101,18 +100,17 @@ public class RobotDrive implements MotorSafety { } /** - * Constructor for RobotDrive with 4 motors specified with channel numbers. - * Set up parameters for a four wheel drive system where all four motor pwm - * channels are specified in the call. This call assumes Talons for - * controlling the motors. - *$ - * @param frontLeftMotor Front left motor channel number - * @param rearLeftMotor Rear Left motor channel number + * Constructor for RobotDrive with 4 motors specified with channel numbers. Set up parameters for + * a four wheel drive system where all four motor pwm channels are specified in the call. This + * call assumes Talons for controlling the motors. + * + * @param frontLeftMotor Front left motor channel number + * @param rearLeftMotor Rear Left motor channel number * @param frontRightMotor Front right motor channel number - * @param rearRightMotor Rear Right motor channel number + * @param rearRightMotor Rear Right motor channel number */ public RobotDrive(final int frontLeftMotor, final int rearLeftMotor, final int frontRightMotor, - final int rearRightMotor) { + final int rearRightMotor) { m_sensitivity = kDefaultSensitivity; m_maxOutput = kDefaultMaxOutput; m_rearLeftMotor = new Talon(rearLeftMotor); @@ -125,13 +123,12 @@ public class RobotDrive implements MotorSafety { } /** - * Constructor for RobotDrive with 2 motors specified as SpeedController - * objects. The SpeedController version of the constructor enables programs to - * use the RobotDrive classes with subclasses of the SpeedController objects, - * for example, versions with ramping or reshaping of the curve to suit motor - * bias or dead-band elimination. - *$ - * @param leftMotor The left SpeedController object used to drive the robot. + * Constructor for RobotDrive with 2 motors specified as SpeedController objects. The + * SpeedController version of the constructor enables programs to use the RobotDrive classes with + * subclasses of the SpeedController objects, for example, versions with ramping or reshaping of + * the curve to suit motor bias or dead-band elimination. + * + * @param leftMotor The left SpeedController object used to drive the robot. * @param rightMotor the right SpeedController object used to drive the robot. */ public RobotDrive(SpeedController leftMotor, SpeedController rightMotor) { @@ -151,30 +148,20 @@ public class RobotDrive implements MotorSafety { } /** - * Constructor for RobotDrive with 4 motors specified as SpeedController - * objects. Speed controller input version of RobotDrive (see previous - * comments). - *$ - * @param rearLeftMotor The back left SpeedController object used to drive the - * robot. - * @param frontLeftMotor The front left SpeedController object used to drive - * the robot - * @param rearRightMotor The back right SpeedController object used to drive - * the robot. - * @param frontRightMotor The front right SpeedController object used to drive - * the robot. + * Constructor for RobotDrive with 4 motors specified as SpeedController objects. Speed controller + * input version of RobotDrive (see previous comments). + * + * @param rearLeftMotor The back left SpeedController object used to drive the robot. + * @param frontLeftMotor The front left SpeedController object used to drive the robot + * @param rearRightMotor The back right SpeedController object used to drive the robot. + * @param frontRightMotor The front right SpeedController object used to drive the robot. */ public RobotDrive(SpeedController frontLeftMotor, SpeedController rearLeftMotor, - SpeedController frontRightMotor, SpeedController rearRightMotor) { - if (frontLeftMotor == null || rearLeftMotor == null || frontRightMotor == null - || rearRightMotor == null) { - m_frontLeftMotor = m_rearLeftMotor = m_frontRightMotor = m_rearRightMotor = null; - throw new NullPointerException("Null motor provided"); - } - m_frontLeftMotor = frontLeftMotor; - m_rearLeftMotor = rearLeftMotor; - m_frontRightMotor = frontRightMotor; - m_rearRightMotor = rearRightMotor; + SpeedController frontRightMotor, SpeedController rearRightMotor) { + m_frontLeftMotor = requireNonNull(frontLeftMotor, "frontLeftMotor cannot be null"); + m_rearLeftMotor = requireNonNull(rearLeftMotor, "rearLeftMotor cannot be null"); + m_frontRightMotor = requireNonNull(frontRightMotor, "frontRightMotor cannot be null"); + m_rearRightMotor = requireNonNull(rearRightMotor, "rearRightMotor cannot be null"); m_sensitivity = kDefaultSensitivity; m_maxOutput = kDefaultMaxOutput; m_allocatedSpeedControllers = false; @@ -183,27 +170,26 @@ public class RobotDrive implements MotorSafety { } /** - * Drive the motors at "outputMagnitude" and "curve". - * Both outputMagnitude and curve are -1.0 to +1.0 values, where 0.0 - * represents stopped and not turning. {@literal curve < 0 will turn left and curve > 0} - * will turn right. + * Drive the motors at "outputMagnitude" and "curve". Both outputMagnitude and curve are -1.0 to + * +1.0 values, where 0.0 represents stopped and not turning. {@literal curve < 0 will turn left + * and curve > 0} will turn right. * - * The algorithm for steering provides a constant turn radius for any normal - * speed range, both forward and backward. Increasing m_sensitivity causes - * sharper turns for fixed values of curve. + *

The algorithm for steering provides a constant turn radius for any normal speed range, both + * forward and backward. Increasing sensitivity causes sharper turns for fixed values of curve. * - * This function will most likely be used in an autonomous routine. + *

This function will most likely be used in an autonomous routine. * - * @param outputMagnitude The speed setting for the outside wheel in a turn, - * forward or backwards, +1 to -1. - * @param curve The rate of turn, constant for different forward speeds. Set - * {@literal curve < 0 for left turn or curve > 0 for right turn.} - * Set curve = e^(-r/w) to get a turn radius r for wheelbase w of your robot. - * Conversely, turn radius r = -ln(curve)*w for a given value of curve and - * wheelbase w. + * @param outputMagnitude The speed setting for the outside wheel in a turn, forward or backwards, + * +1 to -1. + * @param curve The rate of turn, constant for different forward speeds. Set {@literal + * curve < 0 for left turn or curve > 0 for right turn.} Set curve = + * e^(-r/w) to get a turn radius r for wheelbase w of your robot. + * Conversely, turn radius r = -ln(curve)*w for a given value of curve and + * wheelbase w. */ public void drive(double outputMagnitude, double curve) { - double leftOutput, rightOutput; + final double leftOutput; + final double rightOutput; if (!kArcadeRatioCurve_Reported) { UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), @@ -234,11 +220,10 @@ public class RobotDrive implements MotorSafety { } /** - * Provide tank steering using the stored robot configuration. drive the robot - * using two joystick inputs. The Y-axis will be selected from each Joystick - * object. - *$ - * @param leftStick The joystick to control the left side of the robot. + * Provide tank steering using the stored robot configuration. drive the robot using two joystick + * inputs. The Y-axis will be selected from each Joystick object. + * + * @param leftStick The joystick to control the left side of the robot. * @param rightStick The joystick to control the right side of the robot. */ public void tankDrive(GenericHID leftStick, GenericHID rightStick) { @@ -249,14 +234,12 @@ public class RobotDrive implements MotorSafety { } /** - * Provide tank steering using the stored robot configuration. drive the robot - * using two joystick inputs. The Y-axis will be selected from each Joystick - * object. - *$ - * @param leftStick The joystick to control the left side of the robot. - * @param rightStick The joystick to control the right side of the robot. - * @param squaredInputs Setting this parameter to true decreases the - * sensitivity at lower speeds + * Provide tank steering using the stored robot configuration. drive the robot using two joystick + * inputs. The Y-axis will be selected from each Joystick object. + * + * @param leftStick The joystick to control the left side of the robot. + * @param rightStick The joystick to control the right side of the robot. + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds */ public void tankDrive(GenericHID leftStick, GenericHID rightStick, boolean squaredInputs) { if (leftStick == null || rightStick == null) { @@ -266,18 +249,16 @@ public class RobotDrive implements MotorSafety { } /** - * Provide tank steering using the stored robot configuration. This function - * lets you pick the axis to be used on each Joystick object for the left and - * right sides of the robot. - *$ - * @param leftStick The Joystick object to use for the left side of the robot. - * @param leftAxis The axis to select on the left side Joystick object. - * @param rightStick The Joystick object to use for the right side of the - * robot. - * @param rightAxis The axis to select on the right side Joystick object. + * Provide tank steering using the stored robot configuration. This function lets you pick the + * axis to be used on each Joystick object for the left and right sides of the robot. + * + * @param leftStick The Joystick object to use for the left side of the robot. + * @param leftAxis The axis to select on the left side Joystick object. + * @param rightStick The Joystick object to use for the right side of the robot. + * @param rightAxis The axis to select on the right side Joystick object. */ public void tankDrive(GenericHID leftStick, final int leftAxis, GenericHID rightStick, - final int rightAxis) { + final int rightAxis) { if (leftStick == null || rightStick == null) { throw new NullPointerException("Null HID provided"); } @@ -285,20 +266,17 @@ public class RobotDrive implements MotorSafety { } /** - * Provide tank steering using the stored robot configuration. This function - * lets you pick the axis to be used on each Joystick object for the left and - * right sides of the robot. - *$ - * @param leftStick The Joystick object to use for the left side of the robot. - * @param leftAxis The axis to select on the left side Joystick object. - * @param rightStick The Joystick object to use for the right side of the - * robot. - * @param rightAxis The axis to select on the right side Joystick object. - * @param squaredInputs Setting this parameter to true decreases the - * sensitivity at lower speeds + * Provide tank steering using the stored robot configuration. This function lets you pick the + * axis to be used on each Joystick object for the left and right sides of the robot. + * + * @param leftStick The Joystick object to use for the left side of the robot. + * @param leftAxis The axis to select on the left side Joystick object. + * @param rightStick The Joystick object to use for the right side of the robot. + * @param rightAxis The axis to select on the right side Joystick object. + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds */ public void tankDrive(GenericHID leftStick, final int leftAxis, GenericHID rightStick, - final int rightAxis, boolean squaredInputs) { + final int rightAxis, boolean squaredInputs) { if (leftStick == null || rightStick == null) { throw new NullPointerException("Null HID provided"); } @@ -306,13 +284,12 @@ public class RobotDrive implements MotorSafety { } /** - * Provide tank steering using the stored robot configuration. This function - * lets you directly provide joystick values from any source. - *$ - * @param leftValue The value of the left stick. - * @param rightValue The value of the right stick. - * @param squaredInputs Setting this parameter to true decreases the - * sensitivity at lower speeds + * Provide tank steering using the stored robot configuration. This function lets you directly + * provide joystick values from any source. + * + * @param leftValue The value of the left stick. + * @param rightValue The value of the right stick. + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds */ public void tankDrive(double leftValue, double rightValue, boolean squaredInputs) { @@ -342,10 +319,10 @@ public class RobotDrive implements MotorSafety { } /** - * Provide tank steering using the stored robot configuration. This function - * lets you directly provide joystick values from any source. - *$ - * @param leftValue The value of the left stick. + * Provide tank steering using the stored robot configuration. This function lets you directly + * provide joystick values from any source. + * + * @param leftValue The value of the left stick. * @param rightValue The value of the right stick. */ public void tankDrive(double leftValue, double rightValue) { @@ -353,16 +330,14 @@ public class RobotDrive implements MotorSafety { } /** - * Arcade drive implements single stick driving. Given a single Joystick, the - * class assumes the Y axis for the move value and the X axis for the rotate - * value. (Should add more information here regarding the way that arcade - * drive works.) - *$ - * @param stick The joystick to use for Arcade single-stick driving. The - * Y-axis will be selected for forwards/backwards and the X-axis will - * be selected for rotation rate. - * @param squaredInputs If true, the sensitivity will be decreased for small - * values + * Arcade drive implements single stick driving. Given a single Joystick, the class assumes the Y + * axis for the move value and the X axis for the rotate value. (Should add more information here + * regarding the way that arcade drive works.) + * + * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be + * selected for forwards/backwards and the X-axis will be selected for + * rotation rate. + * @param squaredInputs If true, the sensitivity will be decreased for small values */ public void arcadeDrive(GenericHID stick, boolean squaredInputs) { // simply call the full-featured arcadeDrive with the appropriate values @@ -370,35 +345,31 @@ public class RobotDrive implements MotorSafety { } /** - * Arcade drive implements single stick driving. Given a single Joystick, the - * class assumes the Y axis for the move value and the X axis for the rotate - * value. (Should add more information here regarding the way that arcade - * drive works.) - *$ - * @param stick The joystick to use for Arcade single-stick driving. The - * Y-axis will be selected for forwards/backwards and the X-axis will - * be selected for rotation rate. + * Arcade drive implements single stick driving. Given a single Joystick, the class assumes the Y + * axis for the move value and the X axis for the rotate value. (Should add more information here + * regarding the way that arcade drive works.) + * + * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected + * for forwards/backwards and the X-axis will be selected for rotation rate. */ public void arcadeDrive(GenericHID stick) { - this.arcadeDrive(stick, true); + arcadeDrive(stick, true); } /** - * Arcade drive implements single stick driving. Given two joystick instances - * and two axis, compute the values to send to either two or four motors. - *$ - * @param moveStick The Joystick object that represents the forward/backward - * direction - * @param moveAxis The axis on the moveStick object to use for - * forwards/backwards (typically Y_AXIS) - * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate - * right/left (typically X_AXIS) - * @param squaredInputs Setting this parameter to true decreases the - * sensitivity at lower speeds + * Arcade drive implements single stick driving. Given two joystick instances and two axis, + * compute the values to send to either two or four motors. + * + * @param moveStick The Joystick object that represents the forward/backward direction + * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically + * Y_AXIS) + * @param rotateStick The Joystick object that represents the rotation value + * @param rotateAxis The axis on the rotation object to use for the rotate right/left + * (typically X_AXIS) + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds */ public void arcadeDrive(GenericHID moveStick, final int moveAxis, GenericHID rotateStick, - final int rotateAxis, boolean squaredInputs) { + final int rotateAxis, boolean squaredInputs) { double moveValue = moveStick.getRawAxis(moveAxis); double rotateValue = rotateStick.getRawAxis(rotateAxis); @@ -406,28 +377,27 @@ public class RobotDrive implements MotorSafety { } /** - * Arcade drive implements single stick driving. Given two joystick instances - * and two axis, compute the values to send to either two or four motors. - *$ - * @param moveStick The Joystick object that represents the forward/backward - * direction - * @param moveAxis The axis on the moveStick object to use for - * forwards/backwards (typically Y_AXIS) + * Arcade drive implements single stick driving. Given two joystick instances and two axis, + * compute the values to send to either two or four motors. + * + * @param moveStick The Joystick object that represents the forward/backward direction + * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically + * Y_AXIS) * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate - * right/left (typically X_AXIS) + * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically + * X_AXIS) */ public void arcadeDrive(GenericHID moveStick, final int moveAxis, GenericHID rotateStick, - final int rotateAxis) { - this.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true); + final int rotateAxis) { + arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true); } /** - * Arcade drive implements single stick driving. This function lets you - * directly provide joystick values from any source. - *$ - * @param moveValue The value to use for forwards/backwards - * @param rotateValue The value to use for the rotate right/left + * Arcade drive implements single stick driving. This function lets you directly provide + * joystick values from any source. + * + * @param moveValue The value to use for forwards/backwards + * @param rotateValue The value to use for the rotate right/left * @param squaredInputs If set, decreases the sensitivity at low speeds */ public void arcadeDrive(double moveValue, double rotateValue, boolean squaredInputs) { @@ -481,52 +451,52 @@ public class RobotDrive implements MotorSafety { } /** - * Arcade drive implements single stick driving. This function lets you - * directly provide joystick values from any source. - *$ - * @param moveValue The value to use for fowards/backwards + * Arcade drive implements single stick driving. This function lets you directly provide + * joystick values from any source. + * + * @param moveValue The value to use for fowards/backwards * @param rotateValue The value to use for the rotate right/left */ public void arcadeDrive(double moveValue, double rotateValue) { - this.arcadeDrive(moveValue, rotateValue, true); + arcadeDrive(moveValue, rotateValue, true); } /** * Drive method for Mecanum wheeled robots. * - * A method for driving with Mecanum wheeled robots. There are 4 wheels on the - * robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X - * across the robot. + *

A method for driving with Mecanum wheeled robots. There are 4 wheels on the robot, arranged + * so that the front and back wheels are toed in 45 degrees. When looking at the wheels from the + * top, the roller axles should form an X across the robot. * - * This is designed to be directly driven by joystick axes. + *

This is designed to be directly driven by joystick axes. * - * @param x The speed that the robot should drive in the X direction. - * [-1.0..1.0] - * @param y The speed that the robot should drive in the Y direction. This - * input is inverted to match the forward == -1.0 that joysticks - * produce. [-1.0..1.0] - * @param rotation The rate of rotation for the robot that is completely - * independent of the translation. [-1.0..1.0] - * @param gyroAngle The current angle reading from the gyro. Use this to - * implement field-oriented controls. + * @param x The speed that the robot should drive in the X direction. [-1.0..1.0] + * @param y The speed that the robot should drive in the Y direction. This input is + * inverted to match the forward == -1.0 that joysticks produce. [-1.0..1.0] + * @param rotation The rate of rotation for the robot that is completely independent of the + * translation. [-1.0..1.0] + * @param gyroAngle The current angle reading from the gyro. Use this to implement field-oriented + * controls. */ + @SuppressWarnings("ParameterName") public void mecanumDrive_Cartesian(double x, double y, double rotation, double gyroAngle) { if (!kMecanumCartesian_Reported) { UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), tInstances.kRobotDrive_MecanumCartesian); kMecanumCartesian_Reported = true; } + @SuppressWarnings("LocalVariableName") double xIn = x; + @SuppressWarnings("LocalVariableName") double yIn = y; // Negate y for the joystick. yIn = -yIn; // Compenstate for gyro angle. - double rotated[] = rotateVector(xIn, yIn, gyroAngle); + double[] rotated = rotateVector(xIn, yIn, gyroAngle); xIn = rotated[0]; yIn = rotated[1]; - double wheelSpeeds[] = new double[kMaxNumberOfMotors]; + double[] wheelSpeeds = new double[kMaxNumberOfMotors]; wheelSpeeds[MotorType.kFrontLeft_val] = xIn + yIn + rotation; wheelSpeeds[MotorType.kFrontRight_val] = -xIn + yIn - rotation; wheelSpeeds[MotorType.kRearLeft_val] = -xIn + yIn + rotation; @@ -542,24 +512,23 @@ public class RobotDrive implements MotorSafety { CANJaguar.updateSyncGroup(m_syncGroup); } - if (m_safetyHelper != null) + if (m_safetyHelper != null) { m_safetyHelper.feed(); + } } /** * Drive method for Mecanum wheeled robots. * - * A method for driving with Mecanum wheeled robots. There are 4 wheels on the - * robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X - * across the robot. + *

A method for driving with Mecanum wheeled robots. There are 4 wheels on the robot, arranged + * so that the front and back wheels are toed in 45 degrees. When looking at the wheels from the + * top, the roller axles should form an X across the robot. * - * @param magnitude The speed that the robot should drive in a given - * direction. - * @param direction The direction the robot should drive in degrees. The - * direction and maginitute are independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely - * independent of the magnitute or direction. [-1.0..1.0] + * @param magnitude The speed that the robot should drive in a given direction. + * @param direction The direction the robot should drive in degrees. The direction and maginitute + * are independent of the rotation rate. + * @param rotation The rate of rotation for the robot that is completely independent of the + * magnitute or direction. [-1.0..1.0] */ public void mecanumDrive_Polar(double magnitude, double direction, double rotation) { if (!kMecanumPolar_Reported) { @@ -567,7 +536,6 @@ public class RobotDrive implements MotorSafety { tInstances.kRobotDrive_MecanumPolar); kMecanumPolar_Reported = true; } - double frontLeftSpeed, rearLeftSpeed, frontRightSpeed, rearRightSpeed; // Normalized for full power along the Cartesian axes. magnitude = limit(magnitude) * Math.sqrt(2.0); // The rollers are at 45 degree angles. @@ -575,7 +543,7 @@ public class RobotDrive implements MotorSafety { double cosD = Math.cos(dirInRad); double sinD = Math.sin(dirInRad); - double wheelSpeeds[] = new double[kMaxNumberOfMotors]; + double[] wheelSpeeds = new double[kMaxNumberOfMotors]; wheelSpeeds[MotorType.kFrontLeft_val] = (sinD * magnitude + rotation); wheelSpeeds[MotorType.kFrontRight_val] = (cosD * magnitude - rotation); wheelSpeeds[MotorType.kRearLeft_val] = (cosD * magnitude + rotation); @@ -588,37 +556,36 @@ public class RobotDrive implements MotorSafety { m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_maxOutput, m_syncGroup); m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_maxOutput, m_syncGroup); - if (this.m_syncGroup != 0) { + if (m_syncGroup != 0) { CANJaguar.updateSyncGroup(m_syncGroup); } - if (m_safetyHelper != null) + if (m_safetyHelper != null) { m_safetyHelper.feed(); + } } /** * Holonomic Drive method for Mecanum wheeled robots. * - * This is an alias to mecanumDrive_Polar() for backward compatability + *

This is an alias to mecanumDrive_Polar() for backward compatability * - * @param magnitude The speed that the robot should drive in a given - * direction. [-1.0..1.0] - * @param direction The direction the robot should drive. The direction and - * maginitute are independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely - * independent of the magnitute or direction. [-1.0..1.0] + * @param magnitude The speed that the robot should drive in a given direction. [-1.0..1.0] + * @param direction The direction the robot should drive. The direction and maginitute are + * independent of the rotation rate. + * @param rotation The rate of rotation for the robot that is completely independent of the + * magnitute or direction. [-1.0..1.0] */ void holonomicDrive(float magnitude, float direction, float rotation) { mecanumDrive_Polar(magnitude, direction, rotation); } /** - * Set the speed of the right and left motors. This is used once an - * appropriate drive setup function is called such as twoWheelDrive(). The - * motors are set to "leftSpeed" and "rightSpeed" and includes flipping the - * direction of one side for opposing motors. - *$ - * @param leftOutput The speed to send to the left side of the robot. + * Set the speed of the right and left motors. This is used once an appropriate drive setup + * function is called such as twoWheelDrive(). The motors are set to "leftSpeed" and + * "rightSpeed" and includes flipping the direction of one side for opposing motors. + * + * @param leftOutput The speed to send to the left side of the robot. * @param rightOutput The speed to send to the right side of the robot. */ public void setLeftRightMotorOutputs(double leftOutput, double rightOutput) { @@ -636,12 +603,13 @@ public class RobotDrive implements MotorSafety { } m_rearRightMotor.set(-limit(rightOutput) * m_maxOutput, m_syncGroup); - if (this.m_syncGroup != 0) { + if (m_syncGroup != 0) { CANJaguar.updateSyncGroup(m_syncGroup); } - if (m_safetyHelper != null) + if (m_safetyHelper != null) { m_safetyHelper.feed(); + } } /** @@ -658,19 +626,18 @@ public class RobotDrive implements MotorSafety { } /** - * Normalize all wheel speeds if the magnitude of any wheel is greater than - * 1.0. + * Normalize all wheel speeds if the magnitude of any wheel is greater than 1.0. */ - protected static void normalize(double wheelSpeeds[]) { + protected static void normalize(double[] wheelSpeeds) { double maxMagnitude = Math.abs(wheelSpeeds[0]); - int i; - for (i = 1; i < kMaxNumberOfMotors; i++) { + for (int i = 1; i < kMaxNumberOfMotors; i++) { double temp = Math.abs(wheelSpeeds[i]); - if (maxMagnitude < temp) + if (maxMagnitude < temp) { maxMagnitude = temp; + } } if (maxMagnitude > 1.0) { - for (i = 0; i < kMaxNumberOfMotors; i++) { + for (int i = 0; i < kMaxNumberOfMotors; i++) { wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude; } } @@ -679,22 +646,22 @@ public class RobotDrive implements MotorSafety { /** * Rotate a vector in Cartesian space. */ + @SuppressWarnings("ParameterName") protected static double[] rotateVector(double x, double y, double angle) { double cosA = Math.cos(angle * (3.14159 / 180.0)); double sinA = Math.sin(angle * (3.14159 / 180.0)); - double out[] = new double[2]; + double[] out = new double[2]; out[0] = x * cosA - y * sinA; out[1] = x * sinA + y * cosA; return out; } /** - * Invert a motor direction. This is used when a motor should run in the - * opposite direction as the drive code would normally run it. Motors that are - * direct drive would be inverted, the drive code assumes that the motors are - * geared with one reversal. - *$ - * @param motor The motor index to invert. + * Invert a motor direction. This is used when a motor should run in the opposite direction as the + * drive code would normally run it. Motors that are direct drive would be inverted, the drive + * code assumes that the motors are geared with one reversal. + * + * @param motor The motor index to invert. * @param isInverted True if the motor should be inverted when operated. */ public void setInvertedMotor(MotorType motor, boolean isInverted) { @@ -711,36 +678,36 @@ public class RobotDrive implements MotorSafety { case MotorType.kRearRight_val: m_rearRightMotor.setInverted(isInverted); break; + default: + throw new IllegalArgumentException("Illegal motor type: " + motor); } } /** * Set the turning sensitivity. * - * This only impacts the drive() entry-point. - *$ - * @param sensitivity Effectively sets the turning sensitivity (or turn radius - * for a given value) + *

This only impacts the drive() entry-point. + * + * @param sensitivity Effectively sets the turning sensitivity (or turn radius for a given value) */ public void setSensitivity(double sensitivity) { m_sensitivity = sensitivity; } /** - * Configure the scaling factor for using RobotDrive with motor controllers in - * a mode other than PercentVbus. - *$ - * @param maxOutput Multiplied with the output percentage computed by the - * drive functions. + * Configure the scaling factor for using RobotDrive with motor controllers in a mode other than + * PercentVbus. + * + * @param maxOutput Multiplied with the output percentage computed by the drive functions. */ public void setMaxOutput(double maxOutput) { m_maxOutput = maxOutput; } /** - * Set the number of the sync group for the motor controllers. If the motor - * controllers are {@link CANJaguar}s, then they will all be added to this - * sync group, causing them to update their values at the same time. + * Set the number of the sync group for the motor controllers. If the motor controllers are {@link + * CANJaguar}s, then they will all be added to this sync group, causing them to update their + * values at the same time. * * @param syncGroup the update group to add the motor controllers to */ @@ -749,7 +716,7 @@ public class RobotDrive implements MotorSafety { } /** - * Free the speed controllers if they were allocated locally + * Free the speed controllers if they were allocated locally. */ public void free() { if (m_allocatedSpeedControllers) { @@ -768,30 +735,37 @@ public class RobotDrive implements MotorSafety { } } + @Override public void setExpiration(double timeout) { m_safetyHelper.setExpiration(timeout); } + @Override public double getExpiration() { return m_safetyHelper.getExpiration(); } + @Override public boolean isAlive() { return m_safetyHelper.isAlive(); } + @Override public boolean isSafetyEnabled() { return m_safetyHelper.isSafetyEnabled(); } + @Override public void setSafetyEnabled(boolean enabled) { m_safetyHelper.setSafetyEnabled(enabled); } + @Override public String getDescription() { return "Robot Drive"; } + @Override public void stopMotor() { if (m_frontLeftMotor != null) { m_frontLeftMotor.stopMotor(); @@ -805,8 +779,9 @@ public class RobotDrive implements MotorSafety { if (m_rearRightMotor != null) { m_rearRightMotor.stopMotor(); } - if (m_safetyHelper != null) + if (m_safetyHelper != null) { m_safetyHelper.feed(); + } } private void setupMotorSafety() { @@ -817,14 +792,18 @@ public class RobotDrive implements MotorSafety { protected int getNumMotors() { int motors = 0; - if (m_frontLeftMotor != null) + if (m_frontLeftMotor != null) { motors++; - if (m_frontRightMotor != null) + } + if (m_frontRightMotor != null) { motors++; - if (m_rearLeftMotor != null) + } + if (m_rearLeftMotor != null) { motors++; - if (m_rearRightMotor != null) + } + if (m_rearRightMotor != null) { motors++; + } return motors; } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SD540.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SD540.java index adad37e02b..2f2f74aa2a 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SD540.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SD540.java @@ -12,23 +12,22 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * Mindsensors SD540 Speed Controller + * Mindsensors SD540 Speed Controller. */ public class SD540 extends PWMSpeedController { /** * Common initialization code called by all constructors. * - * Note that the SD540 uses the following bounds for PWM values. These - * values should work reasonably well for most controllers, but if users - * experience issues such as asymmetric behavior around the deadband or - * inability to saturate the controller in either direction, calibration is - * recommended. The calibration procedure can be found in the SD540 User - * Manual available from Mindsensors. + *

Note that the SD540 uses the following bounds for PWM values. These values should work + * reasonably well for most controllers, but if users experience issues such as asymmetric + * behavior around the deadband or inability to saturate the controller in either direction, + * calibration is recommended. The calibration procedure can be found in the SD540 User Manual + * available from Mindsensors. * - * - 2.05ms = full "forward" - 1.55ms = the "high end" of the deadband range - * - 1.50ms = center of the deadband range (off) - 1.44ms = the "low end" of - * the deadband range - .94ms = full "reverse" + *

- 2.05ms = full "forward" - 1.55ms = the "high end" of the deadband range - 1.50ms = center + * of the deadband range (off) - 1.44ms = the "low end" of the deadband range - .94ms = full + * "reverse" */ protected void initSD540() { setBounds(2.05, 1.55, 1.50, 1.44, .94); @@ -43,8 +42,8 @@ public class SD540 extends PWMSpeedController { /** * Constructor. * - * @param channel The PWM channel that the SD540 is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the SD540 is attached to. 0-9 are on-board, 10-19 are on + * the MXP port */ public SD540(final int channel) { super(channel); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SPI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SPI.java index dd63d45317..d2a1194d7d 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SPI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SPI.java @@ -7,19 +7,16 @@ package edu.wpi.first.wpilibj; -import java.nio.ByteOrder; import java.nio.ByteBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; +import java.nio.ByteOrder; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.hal.SPIJNI; /** + * Represents a SPI bus port. * - * Represents a SPI bus port - *$ * @author koconnor */ public class SPI extends SensorBase { @@ -27,26 +24,26 @@ public class SPI extends SensorBase { public enum Port { kOnboardCS0(0), kOnboardCS1(1), kOnboardCS2(2), kOnboardCS3(3), kMXP(4); - private int value; + private int m_value; - private Port(int value) { - this.value = value; + Port(int value) { + m_value = value; } public int getValue() { - return this.value; + return m_value; } - }; + } private static int devices = 0; private byte m_port; - private int bitOrder; - private int clockPolarity; - private int dataOnTrailing; + private int m_bitOrder; + private int m_clockPolarity; + private int m_dataOnTrailing; /** - * Constructor + * Constructor. * * @param port the physical SPI port */ @@ -60,15 +57,15 @@ public class SPI extends SensorBase { } /** - * Free the resources used by this object + * Free the resources used by this object. */ public void free() { SPIJNI.spiClose(m_port); } /** - * Configure the rate of the generated clock signal. The default value is - * 500,000 Hz. The maximum value is 4,000,000 Hz. + * Configure the rate of the generated clock signal. The default value is 500,000 Hz. The maximum + * value is 4,000,000 Hz. * * @param hz The clock rate in Hertz. */ @@ -77,57 +74,55 @@ public class SPI extends SensorBase { } /** - * Configure the order that bits are sent and received on the wire to be most - * significant bit first. + * Configure the order that bits are sent and received on the wire to be most significant bit + * first. */ public final void setMSBFirst() { - this.bitOrder = 1; - SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity); + m_bitOrder = 1; + SPIJNI.spiSetOpts(m_port, m_bitOrder, m_dataOnTrailing, m_clockPolarity); } /** - * Configure the order that bits are sent and received on the wire to be least - * significant bit first. + * Configure the order that bits are sent and received on the wire to be least significant bit + * first. */ public final void setLSBFirst() { - this.bitOrder = 0; - SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity); + m_bitOrder = 0; + SPIJNI.spiSetOpts(m_port, m_bitOrder, m_dataOnTrailing, m_clockPolarity); } /** - * Configure the clock output line to be active low. This is sometimes called - * clock polarity high or clock idle high. + * Configure the clock output line to be active low. This is sometimes called clock polarity high + * or clock idle high. */ public final void setClockActiveLow() { - this.clockPolarity = 1; - SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity); + m_clockPolarity = 1; + SPIJNI.spiSetOpts(m_port, m_bitOrder, m_dataOnTrailing, m_clockPolarity); } /** - * Configure the clock output line to be active high. This is sometimes called - * clock polarity low or clock idle low. + * Configure the clock output line to be active high. This is sometimes called clock polarity low + * or clock idle low. */ public final void setClockActiveHigh() { - this.clockPolarity = 0; - SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity); + m_clockPolarity = 0; + SPIJNI.spiSetOpts(m_port, m_bitOrder, m_dataOnTrailing, m_clockPolarity); } /** - * Configure that the data is stable on the falling edge and the data changes - * on the rising edge. + * Configure that the data is stable on the falling edge and the data changes on the rising edge. */ public final void setSampleDataOnFalling() { - this.dataOnTrailing = 1; - SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity); + m_dataOnTrailing = 1; + SPIJNI.spiSetOpts(m_port, m_bitOrder, m_dataOnTrailing, m_clockPolarity); } /** - * Configure that the data is stable on the rising edge and the data changes - * on the falling edge. + * Configure that the data is stable on the rising edge and the data changes on the falling edge. */ public final void setSampleDataOnRising() { - this.dataOnTrailing = 0; - SPIJNI.spiSetOpts(m_port, this.bitOrder, this.dataOnTrailing, this.clockPolarity); + m_dataOnTrailing = 0; + SPIJNI.spiSetOpts(m_port, m_bitOrder, m_dataOnTrailing, m_clockPolarity); } /** @@ -145,11 +140,10 @@ public class SPI extends SensorBase { } /** - * Write data to the slave device. Blocks until there is space in the output - * FIFO. + * Write data to the slave device. Blocks until there is space in the output FIFO. * - * If not running in output only mode, also saves the data received on the - * MISO input during the transfer into the receive FIFO. + *

If not running in output only mode, also saves the data received on the MISO input during + * the transfer into the receive FIFO. */ public int write(byte[] dataToSend, int size) { ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size); @@ -158,43 +152,44 @@ public class SPI extends SensorBase { } /** - * Write data to the slave device. Blocks until there is space in the output - * FIFO. + * Write data to the slave device. Blocks until there is space in the output FIFO. * - * If not running in output only mode, also saves the data received on the - * MISO input during the transfer into the receive FIFO. + *

If not running in output only mode, also saves the data received on the MISO input during + * the transfer into the receive FIFO. * - * @param dataToSend The buffer containing the data to send. Must be created - * using ByteBuffer.allocateDirect(). + * @param dataToSend The buffer containing the data to send. Must be created using + * ByteBuffer.allocateDirect(). */ public int write(ByteBuffer dataToSend, int size) { - if (!dataToSend.isDirect()) + if (!dataToSend.isDirect()) { throw new IllegalArgumentException("must be a direct buffer"); - if (dataToSend.capacity() < size) + } + if (dataToSend.capacity() < size) { throw new IllegalArgumentException("buffer is too small, must be at least " + size); + } return SPIJNI.spiWrite(m_port, dataToSend, (byte) size); } /** * Read a word from the receive FIFO. * - * Waits for the current transfer to complete if the receive FIFO is empty. + *

Waits for the current transfer to complete if the receive FIFO is empty. * - * If the receive FIFO is empty, there is no active transfer, and initiate is - * false, errors. + *

If the receive FIFO is empty, there is no active transfer, and initiate is false, errors. * - * @param initiate If true, this function pushes "0" into the transmit buffer - * and initiates a transfer. If false, this function assumes that data - * is already in the receive FIFO from a previous write. + * @param initiate If true, this function pushes "0" into the transmit buffer and initiates a + * transfer. If false, this function assumes that data is already in the receive + * FIFO from a previous write. */ public int read(boolean initiate, byte[] dataReceived, int size) { - int retVal = 0; + final int retVal; ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(size); ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size); - if (initiate) + if (initiate) { retVal = SPIJNI.spiTransaction(m_port, dataToSendBuffer, dataReceivedBuffer, (byte) size); - else + } else { retVal = SPIJNI.spiRead(m_port, dataReceivedBuffer, (byte) size); + } dataReceivedBuffer.get(dataReceived); return retVal; } @@ -202,25 +197,24 @@ public class SPI extends SensorBase { /** * Read a word from the receive FIFO. * - * Waits for the current transfer to complete if the receive FIFO is empty. + *

Waits for the current transfer to complete if the receive FIFO is empty. * - * If the receive FIFO is empty, there is no active transfer, and initiate is - * false, errors. + *

If the receive FIFO is empty, there is no active transfer, and initiate is false, errors. * - * @param initiate If true, this function pushes "0" into the transmit buffer - * and initiates a transfer. If false, this function assumes that data - * is already in the receive FIFO from a previous write. - * - * @param dataReceived The buffer to be filled with the received data. Must be - * created using ByteBuffer.allocateDirect(). - * - * @param size The length of the transaction, in bytes + * @param initiate If true, this function pushes "0" into the transmit buffer and initiates + * a transfer. If false, this function assumes that data is already in the + * receive FIFO from a previous write. + * @param dataReceived The buffer to be filled with the received data. Must be created using + * ByteBuffer.allocateDirect(). + * @param size The length of the transaction, in bytes */ public int read(boolean initiate, ByteBuffer dataReceived, int size) { - if (!dataReceived.isDirect()) + if (!dataReceived.isDirect()) { throw new IllegalArgumentException("must be a direct buffer"); - if (dataReceived.capacity() < size) + } + if (dataReceived.capacity() < size) { throw new IllegalArgumentException("buffer is too small, must be at least " + size); + } if (initiate) { ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size); return SPIJNI.spiTransaction(m_port, dataToSendBuffer, dataReceived, (byte) size); @@ -229,11 +223,11 @@ public class SPI extends SensorBase { } /** - * Perform a simultaneous read/write transaction with the device + * Perform a simultaneous read/write transaction with the device. * - * @param dataToSend The data to be written out to the device + * @param dataToSend The data to be written out to the device * @param dataReceived Buffer to receive data from the device - * @param size The length of the transaction, in bytes + * @param size The length of the transaction, in bytes */ public int transaction(byte[] dataToSend, byte[] dataReceived, int size) { ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(size); @@ -247,46 +241,48 @@ public class SPI extends SensorBase { /** * Perform a simultaneous read/write transaction with the device * - * @param dataToSend The data to be written out to the device. Must be - * created using ByteBuffer.allocateDirect(). - * @param dataReceived Buffer to receive data from the device. Must be - * created using ByteBuffer.allocateDirect(). - * @param size The length of the transaction, in bytes + * @param dataToSend The data to be written out to the device. Must be created using + * ByteBuffer.allocateDirect(). + * @param dataReceived Buffer to receive data from the device. Must be created using + * ByteBuffer.allocateDirect(). + * @param size The length of the transaction, in bytes */ public int transaction(ByteBuffer dataToSend, ByteBuffer dataReceived, int size) { - if (!dataToSend.isDirect()) + if (!dataToSend.isDirect()) { throw new IllegalArgumentException("dataToSend must be a direct buffer"); - if (dataToSend.capacity() < size) + } + if (dataToSend.capacity() < size) { throw new IllegalArgumentException("dataToSend is too small, must be at least " + size); - if (!dataReceived.isDirect()) + } + if (!dataReceived.isDirect()) { throw new IllegalArgumentException("dataReceived must be a direct buffer"); - if (dataReceived.capacity() < size) + } + if (dataReceived.capacity() < size) { throw new IllegalArgumentException("dataReceived is too small, must be at least " + size); + } return SPIJNI.spiTransaction(m_port, dataToSend, dataReceived, (byte) size); } /** * Initialize the accumulator. * - * @param period Time between reads - * @param cmd SPI command to send to request data - * @param xfer_size SPI transfer size, in bytes - * @param valid_mask Mask to apply to received data for validity checking - * @param valid_data After valid_mask is applied, required matching value for - * validity checking - * @param data_shift Bit shift to apply to received data to get actual data - * value - * @param data_size Size (in bits) of data field - * @param is_signed Is data field signed? - * @param big_endian Is device big endian? + * @param period Time between reads + * @param cmd SPI command to send to request data + * @param xferSize SPI transfer size, in bytes + * @param validMask Mask to apply to received data for validity checking + * @param validValue After validMask is applied, required matching value for validity checking + * @param dataShift Bit shift to apply to received data to get actual data value + * @param dataSize Size (in bits) of data field + * @param isSigned Is data field signed? + * @param bigEndian Is device big endian? */ - public void initAccumulator(double period, int cmd, int xfer_size, - int valid_mask, int valid_value, - int data_shift, int data_size, - boolean is_signed, boolean big_endian) { - SPIJNI.spiInitAccumulator(m_port, (int)(period * 1.0e6), cmd, - (byte)xfer_size, valid_mask, valid_value, (byte)data_shift, - (byte)data_size, is_signed, big_endian); + public void initAccumulator(double period, int cmd, int xferSize, + int validMask, int validValue, + int dataShift, int dataSize, + boolean isSigned, boolean bigEndian) { + SPIJNI.spiInitAccumulator(m_port, (int) (period * 1.0e6), cmd, + (byte) xferSize, validMask, validValue, (byte) dataShift, + (byte) dataSize, isSigned, bigEndian); } /** @@ -306,7 +302,7 @@ public class SPI extends SensorBase { /** * Set the center value of the accumulator. * - * The center value is subtracted from each value before it is added to the accumulator. This + *

The center value is subtracted from each value before it is added to the accumulator. This * is used for the center value of devices like gyros and accelerometers to make integration work * and to take the device offset into account when integrating. */ @@ -340,7 +336,7 @@ public class SPI extends SensorBase { /** * Read the number of accumulated values. * - * Read the count of the accumulated values since the accumulator was last Reset(). + *

Read the count of the accumulated values since the accumulator was last Reset(). * * @return The number of times samples from the channel were accumulated. */ @@ -360,8 +356,7 @@ public class SPI extends SensorBase { /** * Read the accumulated value and the number of accumulated values atomically. * - * This function reads the value and count atomically. - * This can be used for averaging. + *

This function reads the value and count atomically. This can be used for averaging. * * @param result AccumulatorResult object to store the results in. */ diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SafePWM.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SafePWM.java index ea184e2ffa..5d51acf892 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SafePWM.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SafePWM.java @@ -8,37 +8,30 @@ package edu.wpi.first.wpilibj; /** + * Manages a PWM object. * * @author brad */ public class SafePWM extends PWM implements MotorSafety { - private MotorSafetyHelper m_safetyHelper; + private final MotorSafetyHelper m_safetyHelper; /** - * Initialize a SafePWM object by setting defaults + * Constructor for a SafePWM object taking a channel number. + * + * @param channel The channel number to be used for the underlying PWM object. 0-9 are on-board, + * 10-19 are on the MXP port. */ - void initSafePWM() { + public SafePWM(final int channel) { + super(channel); m_safetyHelper = new MotorSafetyHelper(this); m_safetyHelper.setExpiration(0.0); m_safetyHelper.setSafetyEnabled(false); } - /** - * Constructor for a SafePWM object taking a channel number - *$ - * @param channel The channel number to be used for the underlying PWM object. - * 0-9 are on-board, 10-19 are on the MXP port. - */ - public SafePWM(final int channel) { - super(channel); - initSafePWM(); - } - - /* - * Set the expiration time for the PWM object - *$ + * Set the expiration time for the PWM object. + * * @param timeout The timeout (in seconds) for this motor object */ public void setExpiration(double timeout) { @@ -47,7 +40,7 @@ public class SafePWM extends PWM implements MotorSafety { /** * Return the expiration time for the PWM object. - *$ + * * @return The expiration time value. */ public double getExpiration() { @@ -56,26 +49,24 @@ public class SafePWM extends PWM implements MotorSafety { /** * Check if the PWM object is currently alive or stopped due to a timeout. - *$ - * @return a bool value that is true if the motor has NOT timed out and should - * still be running. + * + * @return a bool value that is true if the motor has NOT timed out and should still be running. */ public boolean isAlive() { return m_safetyHelper.isAlive(); } /** - * Stop the motor associated with this PWM object. This is called by the - * MotorSafetyHelper object when it has a timeout for this PWM and needs to - * stop it from running. + * Stop the motor associated with this PWM object. This is called by the MotorSafetyHelper object + * when it has a timeout for this PWM and needs to stop it from running. */ public void stopMotor() { disable(); } /** - * Check if motor safety is enabled for this object - *$ + * Check if motor safety is enabled for this object. + * * @return True if motor safety is enforced for this object */ public boolean isSafetyEnabled() { @@ -83,9 +74,10 @@ public class SafePWM extends PWM implements MotorSafety { } /** - * Feed the MotorSafety timer. This method is called by the subclass motor - * whenever it updates its speed, thereby reseting the timeout value. + * Feed the MotorSafety timer. This method is called by the subclass motor whenever it updates its + * speed, thereby reseting the timeout value. */ + @SuppressWarnings("MethodName") public void Feed() { m_safetyHelper.feed(); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SampleRobot.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SampleRobot.java index 3eae306f86..a44d4af323 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SampleRobot.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SampleRobot.java @@ -7,31 +7,29 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tInstances; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; -import edu.wpi.first.wpilibj.Timer; +import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * A simple robot base class that knows the standard FRC competition states - * (disabled, autonomous, or operator controlled). + * A simple robot base class that knows the standard FRC competition states (disabled, autonomous, + * or operator controlled). * - * You can build a simple robot program off of this by overriding the - * robotinit(), disabled(), autonomous() and operatorControl() methods. The - * startCompetition() method will calls these methods (sometimes repeatedly). - * depending on the state of the competition. + *

You can build a simple robot program off of this by overriding the robotinit(), disabled(), + * autonomous() and operatorControl() methods. The startCompetition() method will calls these + * methods (sometimes repeatedly). depending on the state of the competition. * - * Alternatively you can override the robotMain() method and manage all aspects - * of the robot yourself. + *

Alternatively you can override the robotMain() method and manage all aspects of the robot + * yourself. */ public class SampleRobot extends RobotBase { private boolean m_robotMainOverridden; /** - * Create a new SampleRobot + * Create a new SampleRobot. */ public SampleRobot() { super(); @@ -41,53 +39,50 @@ public class SampleRobot extends RobotBase { /** * Robot-wide initialization code should go here. * - * Users should override this method for default Robot-wide initialization - * which will be called when the robot is first powered on. It will be called - * exactly one time. + *

Users should override this method for default Robot-wide initialization which will be called + * when the robot is first powered on. It will be called exactly one time. * - * Warning: the Driver Station "Robot Code" light and FMS "Robot Ready" - * indicators will be off until RobotInit() exits. Code in RobotInit() that - * waits for enable will cause the robot to never indicate that the code is - * ready, causing the robot to be bypassed in a match. + *

Warning: the Driver Station "Robot Code" light and FMS "Robot Ready" indicators will be off + * until RobotInit() exits. Code in RobotInit() that waits for enable will cause the robot to + * never indicate that the code is ready, causing the robot to be bypassed in a match. */ protected void robotInit() { System.out.println("Default robotInit() method running, consider providing your own"); } /** - * Disabled should go here. Users should overload this method to run code that - * should run while the field is disabled. + * Disabled should go here. Users should overload this method to run code that should run while + * the field is disabled. * - * Called once each time the robot enters the disabled state. + *

Called once each time the robot enters the disabled state. */ protected void disabled() { System.out.println("Default disabled() method running, consider providing your own"); } /** - * Autonomous should go here. Users should add autonomous code to this method - * that should run while the field is in the autonomous period. + * Autonomous should go here. Users should add autonomous code to this method that should run + * while the field is in the autonomous period. * - * Called once each time the robot enters the autonomous state. + *

Called once each time the robot enters the autonomous state. */ public void autonomous() { System.out.println("Default autonomous() method running, consider providing your own"); } /** - * Operator control (tele-operated) code should go here. Users should add - * Operator Control code to this method that should run while the field is in - * the Operator Control (tele-operated) period. + * Operator control (tele-operated) code should go here. Users should add Operator Control code to + * this method that should run while the field is in the Operator Control (tele-operated) period. * - * Called once each time the robot enters the operator-controlled state. + *

Called once each time the robot enters the operator-controlled state. */ public void operatorControl() { System.out.println("Default operatorControl() method running, consider providing your own"); } /** - * Test code should go here. Users should add test code to this method that - * should run while the robot is in test mode. + * Test code should go here. Users should add test code to this method that should run while the + * robot is in test mode. */ public void test() { System.out.println("Default test() method running, consider providing your own"); @@ -96,27 +91,24 @@ public class SampleRobot extends RobotBase { /** * Robot main program for free-form programs. * - * This should be overridden by user subclasses if the intent is to not use - * the autonomous() and operatorControl() methods. In that case, the program - * is responsible for sensing when to run the autonomous and operator control - * functions in their program. + *

This should be overridden by user subclasses if the intent is to not use the autonomous() + * and operatorControl() methods. In that case, the program is responsible for sensing when to run + * the autonomous and operator control functions in their program. * - * This method will be called immediately after the constructor is called. If - * it has not been overridden by a user subclass (i.e. the default version - * runs), then the robotInit(), disabled(), autonomous() and operatorControl() - * methods will be called. + *

This method will be called immediately after the constructor is called. If it has not been + * overridden by a user subclass (i.e. the default version runs), then the robotInit(), + * disabled(), autonomous() and operatorControl() methods will be called. */ public void robotMain() { m_robotMainOverridden = false; } /** - * Start a competition. This code tracks the order of the field starting to - * ensure that everything happens in the right order. Repeatedly run the - * correct method, either Autonomous or OperatorControl when the robot is - * enabled. After running the correct method, wait for some state to change, - * either the other mode starts or the robot is disabled. Then go back and - * wait for the robot to be enabled again. + * Start a competition. This code tracks the order of the field starting to ensure that everything + * happens in the right order. Repeatedly run the correct method, either Autonomous or + * OperatorControl when the robot is enabled. After running the correct method, wait for some + * state to change, either the other mode starts or the robot is disabled. Then go back and wait + * for the robot to be enabled again. */ public void startCompetition() { UsageReporting.report(tResourceType.kResourceType_Framework, tInstances.kFramework_Sample); @@ -151,8 +143,9 @@ public class SampleRobot extends RobotBase { m_ds.InTest(true); test(); m_ds.InTest(false); - while (isTest() && isEnabled()) + while (isTest() && isEnabled()) { Timer.delay(0.01); + } LiveWindow.setEnabled(false); } else { m_ds.InOperatorControl(true); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SerialPort.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SerialPort.java index b0b780dd97..cc4b010146 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SerialPort.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SerialPort.java @@ -8,7 +8,6 @@ package edu.wpi.first.wpilibj; import java.io.UnsupportedEncodingException; - import java.nio.ByteBuffer; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; @@ -18,14 +17,13 @@ import edu.wpi.first.wpilibj.hal.SerialPortJNI; /** * Driver for the RS-232 serial port on the RoboRIO. * - * The current implementation uses the VISA formatted I/O mode. This means that - * all traffic goes through the formatted buffers. This allows the intermingled - * use of print(), readString(), and the raw buffer accessors read() and - * write(). + *

The current implementation uses the VISA formatted I/O mode. This means that all traffic goes + * through the formatted buffers. This allows the intermingled use of print(), readString(), and the + * raw buffer accessors read() and write(). * - * More information can be found in the NI-VISA User Manual here: - * http://www.ni.com/pdf/manuals/370423a.pdf and the NI-VISA Programmer's - * Reference Manual here: http://www.ni.com/pdf/manuals/370132c.pdf + *

More information can be found in the NI-VISA User Manual here: http://www.ni + * .com/pdf/manuals/370423a.pdf and the NI-VISA Programmer's Reference Manual here: + * http://www.ni.com/pdf/manuals/370132c.pdf */ public class SerialPort { @@ -34,25 +32,26 @@ public class SerialPort { public enum Port { kOnboard(0), kMXP(1), kUSB(2); - private int value; + private int m_value; - private Port(int value) { - this.value = value; + Port(int value) { + m_value = value; } public int getValue() { - return this.value; + return m_value; } - }; + } /** - * Represents the parity to use for serial communications + * Represents the parity to use for serial communications. */ public static class Parity { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kNone_val = 0; static final int kOdd_val = 1; @@ -60,23 +59,23 @@ public class SerialPort { static final int kMark_val = 3; static final int kSpace_val = 4; /** - * parity: Use no parity + * parity: Use no parity. */ public static final Parity kNone = new Parity(kNone_val); /** - * parity: Use odd parity + * parity: Use odd parity. */ public static final Parity kOdd = new Parity(kOdd_val); /** - * parity: Use even parity + * parity: Use even parity. */ public static final Parity kEven = new Parity(kEven_val); /** - * parity: Use mark parity + * parity: Use mark parity. */ public static final Parity kMark = new Parity(kMark_val); /** - * parity: Use space parity + * parity: Use space parity. */ public static final Parity kSpace = new Parity((kSpace_val)); @@ -86,27 +85,28 @@ public class SerialPort { } /** - * Represents the number of stop bits to use for Serial Communication + * Represents the number of stop bits to use for Serial Communication. */ public static class StopBits { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kOne_val = 10; static final int kOnePointFive_val = 15; static final int kTwo_val = 20; /** - * stopBits: use 1 + * stopBits: use 1. */ public static final StopBits kOne = new StopBits(kOne_val); /** - * stopBits: use 1.5 + * stopBits: use 1.5. */ public static final StopBits kOnePointFive = new StopBits(kOnePointFive_val); /** - * stopBits: use 2 + * stopBits: use 2. */ public static final StopBits kTwo = new StopBits(kTwo_val); @@ -116,32 +116,33 @@ public class SerialPort { } /** - * Represents what type of flow control to use for serial communication + * Represents what type of flow control to use for serial communication. */ public static class FlowControl { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kNone_val = 0; static final int kXonXoff_val = 1; static final int kRtsCts_val = 2; static final int kDtrDsr_val = 4; /** - * flowControl: use none + * flowControl: use none. */ public static final FlowControl kNone = new FlowControl(kNone_val); /** - * flowcontrol: use on/off + * flowcontrol: use on/off. */ public static final FlowControl kXonXoff = new FlowControl(kXonXoff_val); /** - * flowcontrol: use rts cts + * flowcontrol: use rts cts. */ public static final FlowControl kRtsCts = new FlowControl(kRtsCts_val); /** - * flowcontrol: use dts dsr + * flowcontrol: use dts dsr. */ public static final FlowControl kDtrDsr = new FlowControl(kDtrDsr_val); @@ -151,22 +152,23 @@ public class SerialPort { } /** - * Represents which type of buffer mode to use when writing to a serial port + * Represents which type of buffer mode to use when writing to a serial m_port. */ public static class WriteBufferMode { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kFlushOnAccess_val = 1; static final int kFlushWhenFull_val = 2; /** - * Flush on access + * Flush on access. */ public static final WriteBufferMode kFlushOnAccess = new WriteBufferMode(kFlushOnAccess_val); /** - * Flush when full + * Flush when full. */ public static final WriteBufferMode kFlushWhenFull = new WriteBufferMode(kFlushWhenFull_val); @@ -179,15 +181,13 @@ public class SerialPort { * Create an instance of a Serial Port class. * * @param baudRate The baud rate to configure the serial port. - * @param port The Serial port to use - * @param dataBits The number of data bits per transfer. Valid values are - * between 5 and 8 bits. - * @param parity Select the type of parity checking to use. - * @param stopBits The number of stop bits to use as defined by the enum - * StopBits. + * @param port The Serial port to use + * @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits. + * @param parity Select the type of parity checking to use. + * @param stopBits The number of stop bits to use as defined by the enum StopBits. */ public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity, - StopBits stopBits) { + StopBits stopBits) { m_port = (byte) port.getValue(); SerialPortJNI.serialInitializePort(m_port); @@ -214,29 +214,26 @@ public class SerialPort { * Create an instance of a Serial Port class. Defaults to one stop bit. * * @param baudRate The baud rate to configure the serial port. - * @param dataBits The number of data bits per transfer. Valid values are - * between 5 and 8 bits. - * @param parity Select the type of parity checking to use. + * @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits. + * @param parity Select the type of parity checking to use. */ public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity) { this(baudRate, port, dataBits, parity, StopBits.kOne); } /** - * Create an instance of a Serial Port class. Defaults to no parity and one - * stop bit. + * Create an instance of a Serial Port class. Defaults to no parity and one stop bit. * * @param baudRate The baud rate to configure the serial port. - * @param dataBits The number of data bits per transfer. Valid values are - * between 5 and 8 bits. + * @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits. */ public SerialPort(final int baudRate, Port port, final int dataBits) { this(baudRate, port, dataBits, Parity.kNone, StopBits.kOne); } /** - * Create an instance of a Serial Port class. Defaults to 8 databits, no - * parity, and one stop bit. + * Create an instance of a Serial Port class. Defaults to 8 databits, no parity, and one stop + * bit. * * @param baudRate The baud rate to configure the serial port. */ @@ -254,9 +251,9 @@ public class SerialPort { /** * Set the type of flow control to enable on this port. * - * By default, flow control is disabled. - *$ - * @param flowControl the FlowControl value to use + *

By default, flow control is disabled. + * + * @param flowControl the FlowControl m_value to use */ public void setFlowControl(FlowControl flowControl) { SerialPortJNI.serialSetFlowControl(m_port, (byte) flowControl.value); @@ -265,9 +262,9 @@ public class SerialPort { /** * Enable termination and specify the termination character. * - * Termination is currently only implemented for receive. When the the - * terminator is received, the read() or readString() will return fewer bytes - * than requested, stopping after the terminator. + *

Termination is currently only implemented for receive. When the the terminator is received, + * the read() or readString() will return fewer bytes than requested, stopping after the + * terminator. * * @param terminator The character to use for termination. */ @@ -278,14 +275,14 @@ public class SerialPort { /** * Enable termination with the default terminator '\n' * - * Termination is currently only implemented for receive. When the the - * terminator is received, the read() or readString() will return fewer bytes - * than requested, stopping after the terminator. + *

Termination is currently only implemented for receive. When the the terminator is received, + * the read() or readString() will return fewer bytes than requested, stopping after the + * terminator. * - * The default terminator is '\n' + *

The default terminator is '\n' */ public void enableTermination() { - this.enableTermination('\n'); + enableTermination('\n'); } /** @@ -325,7 +322,7 @@ public class SerialPort { return new String(out, 0, out.length, "US-ASCII"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); - return new String(); + return ""; } } @@ -347,7 +344,7 @@ public class SerialPort { * Write raw bytes to the serial port. * * @param buffer The buffer of bytes to write. - * @param count The maximum number of bytes to write. + * @param count The maximum number of bytes to write. * @return The number of bytes actually written into the port. */ public int write(byte[] buffer, int count) { @@ -367,11 +364,10 @@ public class SerialPort { } /** - * Configure the timeout of the serial port. + * Configure the timeout of the serial m_port. * - * This defines the timeout for transactions with the hardware. It will affect - * reads if less bytes are available than the read buffer size (defaults to 1) - * and very large writes. + *

This defines the timeout for transactions with the hardware. It will affect reads if less + * bytes are available than the read buffer size (defaults to 1) and very large writes. * * @param timeout The number of seconds to to wait for I/O. */ @@ -382,12 +378,11 @@ public class SerialPort { /** * Specify the size of the input buffer. * - * Specify the amount of data that can be stored before data from the device - * is returned to Read. If you want data that is received to be returned - * immediately, set this to 1. + *

Specify the amount of data that can be stored before data from the device is returned to + * Read. If you want data that is received to be returned immediately, set this to 1. * - * It the buffer is not filled before the read timeout expires, all data that - * has been received so far will be returned. + *

It the buffer is not filled before the read timeout expires, all data that has been received + * so far will be returned. * * @param size The read buffer size. */ @@ -398,8 +393,7 @@ public class SerialPort { /** * Specify the size of the output buffer. * - * Specify the amount of data that can be stored before being transmitted to - * the device. + *

Specify the amount of data that can be stored before being transmitted to the device. * * @param size The write buffer size. */ @@ -410,11 +404,11 @@ public class SerialPort { /** * Specify the flushing behavior of the output buffer. * - * When set to kFlushOnAccess, data is synchronously written to the serial - * port after each call to either print() or write(). + *

When set to kFlushOnAccess, data is synchronously written to the serial port after each + * call to either print() or write(). * - * When set to kFlushWhenFull, data will only be written to the serial port - * when the buffer is full or when flush() is called. + *

When set to kFlushWhenFull, data will only be written to the serial port when the buffer + * is full or when flush() is called. * * @param mode The write buffer mode. */ @@ -425,8 +419,8 @@ public class SerialPort { /** * Force the output buffer to be written to the port. * - * This is used when setWriteBufferMode() is set to kFlushWhenFull to force a - * flush before the buffer is full. + *

This is used when setWriteBufferMode() is set to kFlushWhenFull to force a flush before the + * buffer is full. */ public void flush() { SerialPortJNI.serialFlush(m_port); @@ -435,7 +429,7 @@ public class SerialPort { /** * Reset the serial port driver to a known state. * - * Empty the transmit and receive buffers in the device and formatted I/O. + *

Empty the transmit and receive buffers in the device and formatted I/O. */ public void reset() { SerialPortJNI.serialClear(m_port); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Servo.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Servo.java index a386a36862..6d2c0982f1 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Servo.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Servo.java @@ -16,8 +16,8 @@ import edu.wpi.first.wpilibj.tables.ITableListener; /** * Standard hobby style servo. * - * The range parameters default to the appropriate values for the Hitec HS-322HD - * servo provided in the FIRST Kit of Parts in 2008. + *

The range parameters default to the appropriate values for the Hitec HS-322HD servo provided + * in the FIRST Kit of Parts in 2008. */ public class Servo extends PWM { @@ -30,10 +30,8 @@ public class Servo extends PWM { /** * Common initialization code called by all constructors. * - * InitServo() assigns defaults for the period multiplier for the servo PWM - * control signal, as well as the minimum and maximum PWM values supported by - * the servo. - * + *

InitServo() assigns defaults for the period multiplier for the servo PWM control signal, as + * well as the minimum and maximum PWM values supported by the servo. */ private void initServo() { setBounds(kDefaultMaxServoPWM, 0, 0, 0, kDefaultMinServoPWM); @@ -46,11 +44,11 @@ public class Servo extends PWM { /** * Constructor.
* - * By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value
- * By default {@value #kDefaultMinServoPWM} ms is used as the minPWM value
+ *

By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value
By default + * {@value #kDefaultMinServoPWM} ms is used as the minPWM value
* - * @param channel The PWM channel to which the servo is attached. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel to which the servo is attached. 0-9 are on-board, 10-19 are on + * the MXP port */ public Servo(final int channel) { super(channel); @@ -61,8 +59,7 @@ public class Servo extends PWM { /** * Set the servo position. * - * Servo values range from 0.0 to 1.0 corresponding to the range of full left - * to full right. + *

Servo values range from 0.0 to 1.0 corresponding to the range of full left to full right. * * @param value Position from 0.0 to 1.0. */ @@ -73,8 +70,7 @@ public class Servo extends PWM { /** * Get the servo position. * - * Servo values range from 0.0 to 1.0 corresponding to the range of full left - * to full right. + *

Servo values range from 0.0 to 1.0 corresponding to the range of full left to full right. * * @return Position from 0.0 to 1.0. */ @@ -85,14 +81,13 @@ public class Servo extends PWM { /** * Set the servo angle. * - * Assume that the servo angle is linear with respect to the PWM value (big - * assumption, need to test). + *

Assume that the servo angle is linear with respect to the PWM value (big assumption, need to + * test). * - * Servo angles that are out of the supported range of the servo simply - * "saturate" in that direction In other words, if the servo has a range of (X - * degrees to Y degrees) than angles of less than X result in an angle of X - * being set and angles of more than Y degrees result in an angle of Y being - * set. + *

Servo angles that are out of the supported range of the servo simply "saturate" in that + * direction In other words, if the servo has a range of (X degrees to Y degrees) than angles of + * less than X result in an angle of X being set and angles of more than Y degrees result in an + * angle of Y being set. * * @param degrees The angle in degrees to set the servo. */ @@ -109,9 +104,9 @@ public class Servo extends PWM { /** * Get the servo angle. * - * Assume that the servo angle is linear with respect to the PWM value (big - * assumption, need to test). - *$ + *

Assume that the servo angle is linear with respect to the PWM value (big assumption, need to + * test). + * * @return The angle in degrees to which the servo is set. */ public double getAngle() { @@ -130,42 +125,34 @@ public class Servo extends PWM { } private ITable m_table; - private ITableListener m_table_listener; + private ITableListener m_tableListener; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", get()); } } - /** - * {@inheritDoc} - */ + @Override public void startLiveWindowMode() { - m_table_listener = new ITableListener() { + m_tableListener = new ITableListener() { public void valueChanged(ITable itable, String key, Object value, boolean bln) { set(((Double) value).doubleValue()); } }; - m_table.addTableListener("Value", m_table_listener, true); + m_table.addTableListener("Value", m_tableListener, true); } - /** - * {@inheritDoc} - */ + @Override public void stopLiveWindowMode() { // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Solenoid.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Solenoid.java index 2f0636e3ab..1f35951a4c 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Solenoid.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Solenoid.java @@ -20,13 +20,13 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Solenoid class for running high voltage Digital Output. * - * The Solenoid class is typically used for pneumatics solenoids, but could be - * used for any device within the current spec of the PCM. + *

The Solenoid class is typically used for pneumatics solenoids, but could be used for any + * device within the current spec of the PCM. */ public class Solenoid extends SolenoidBase implements LiveWindowSendable { - private int m_channel; // /< The channel to control. - private long m_solenoid_port; + private final int m_channel; // /< The channel to control. + private long m_solenoidPort; /** * Common function to implement constructor behavior. @@ -36,14 +36,14 @@ public class Solenoid extends SolenoidBase implements LiveWindowSendable { checkSolenoidChannel(m_channel); try { - m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_channel); - } catch (CheckedAllocationException e) { + allocated.allocate(m_moduleNumber * kSolenoidChannels + m_channel); + } catch (CheckedAllocationException ex) { throw new AllocationException("Solenoid channel " + m_channel + " on module " - + m_moduleNumber + " is already allocated"); + + m_moduleNumber + " is already allocated"); } long port = SolenoidJNI.getPortWithModule((byte) m_moduleNumber, (byte) m_channel); - m_solenoid_port = SolenoidJNI.initializeSolenoidPort(port); + m_solenoidPort = SolenoidJNI.initializeSolenoidPort(port); LiveWindow.addActuator("Solenoid", m_moduleNumber, m_channel, this); UsageReporting.report(tResourceType.kResourceType_Solenoid, m_channel, m_moduleNumber); @@ -64,7 +64,7 @@ public class Solenoid extends SolenoidBase implements LiveWindowSendable { * Constructor. * * @param moduleNumber The CAN ID of the PCM the solenoid is attached to. - * @param channel The channel on the PCM to control (0..7). + * @param channel The channel on the PCM to control (0..7). */ public Solenoid(final int moduleNumber, final int channel) { super(moduleNumber); @@ -76,9 +76,9 @@ public class Solenoid extends SolenoidBase implements LiveWindowSendable { * Destructor. */ public synchronized void free() { - m_allocated.free(m_moduleNumber * kSolenoidChannels + m_channel); - SolenoidJNI.freeSolenoidPort(m_solenoid_port); - m_solenoid_port = 0; + allocated.free(m_moduleNumber * kSolenoidChannels + m_channel); + SolenoidJNI.freeSolenoidPort(m_solenoidPort); + m_solenoidPort = 0; super.free(); } @@ -105,12 +105,11 @@ public class Solenoid extends SolenoidBase implements LiveWindowSendable { } /** - * Check if solenoid is blacklisted. If a solenoid is shorted, it is added to - * the blacklist and disabled until power cycle, or until faults are cleared. - * - * @see #clearAllPCMStickyFaults() + * Check if solenoid is blacklisted. If a solenoid is shorted, it is added to the blacklist and + * disabled until power cycle, or until faults are cleared. * * @return If solenoid is disabled due to short. + * @see #clearAllPCMStickyFaults() */ public boolean isBlackListed() { int value = getPCMSolenoidBlackList() & (1 << m_channel); @@ -125,26 +124,20 @@ public class Solenoid extends SolenoidBase implements LiveWindowSendable { } private ITable m_table; - private ITableListener m_table_listener; + private ITableListener m_tableListener; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putBoolean("Value", get()); @@ -152,25 +145,17 @@ public class Solenoid extends SolenoidBase implements LiveWindowSendable { } - /** - * {@inheritDoc} - */ + @Override public void startLiveWindowMode() { set(false); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Boolean) value).booleanValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); + m_tableListener = (itable, key, value, bln) -> set((Boolean) value); + m_table.addTableListener("Value", m_tableListener, true); } - /** - * {@inheritDoc} - */ + @Override public void stopLiveWindowMode() { set(false); // Stop for safety // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); + m_table.removeTableListener(m_tableListener); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SolenoidBase.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SolenoidBase.java index 1a92885fe0..15c9e8bd7f 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SolenoidBase.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SolenoidBase.java @@ -10,15 +10,14 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.hal.SolenoidJNI; /** - * SolenoidBase class is the common base class for the Solenoid and - * DoubleSolenoid classes. + * SolenoidBase class is the common base class for the Solenoid and DoubleSolenoid classes. */ public abstract class SolenoidBase extends SensorBase { - private long[] m_ports; - protected int m_moduleNumber; // /< The number of the solenoid module being - // used. - protected static Resource m_allocated = new Resource(63 * SensorBase.kSolenoidChannels); + private final long[] m_ports; + protected final int m_moduleNumber; // /< The number of the solenoid module being + // used. + protected static final Resource allocated = new Resource(63 * SensorBase.kSolenoidChannels); /** * Constructor. @@ -49,18 +48,19 @@ public abstract class SolenoidBase extends SensorBase { * Set the value of a solenoid. * * @param value The value you want to set on the module. - * @param mask The channels you want to be affected. + * @param mask The channels you want to be affected. */ protected synchronized void set(int value, int mask) { for (int i = 0; i < SensorBase.kSolenoidChannels; i++) { - int local_mask = 1 << i; - if ((mask & local_mask) != 0) - SolenoidJNI.setSolenoid(m_ports[i], (value & local_mask) != 0); + int localMask = 1 << i; + if ((mask & localMask) != 0) { + SolenoidJNI.setSolenoid(m_ports[i], (value & localMask) != 0); + } } } /** - * Read all 8 solenoids from the module used by this solenoid as a single byte + * Read all 8 solenoids from the module used by this solenoid as a single byte. * * @return The current value of all 8 solenoids on this module. */ @@ -69,30 +69,32 @@ public abstract class SolenoidBase extends SensorBase { } /** - * Reads complete solenoid blacklist for all 8 solenoids as a single byte. - *$ - * If a solenoid is shorted, it is added to the blacklist and disabled until - * power cycle, or until faults are cleared. + * Reads complete solenoid blacklist for all 8 solenoids as a single byte. If a solenoid is + * shorted, it is added to the blacklist and disabled until power cycle, or until faults are + * cleared. * - * @see #clearAllPCMStickyFaults() - *$ * @return The solenoid blacklist of all 8 solenoids on the module. + * @see #clearAllPCMStickyFaults() */ public byte getPCMSolenoidBlackList() { - return (byte)SolenoidJNI.getPCMSolenoidBlackList(m_ports[0]); + return (byte) SolenoidJNI.getPCMSolenoidBlackList(m_ports[0]); } /** - * @return true if PCM sticky fault is set : The common highside solenoid - * voltage rail is too low, most likely a solenoid channel is shorted. + * If true, the common highside solenoid voltage rail is too low, most likely a solenoid channel + * is shorted. + * + * @return true if PCM sticky fault is set */ public boolean getPCMSolenoidVoltageStickyFault() { return SolenoidJNI.getPCMSolenoidVoltageStickyFault(m_ports[0]); } /** - * @return true if PCM is in fault state : The common highside solenoid - * voltage rail is too low, most likely a solenoid channel is shorted. + * The common highside solenoid voltage rail is too low, most likely a solenoid channel is + * shorted. + * + * @return true if PCM is in fault state. */ public boolean getPCMSolenoidVoltageFault() { return SolenoidJNI.getPCMSolenoidVoltageFault(m_ports[0]); @@ -101,12 +103,11 @@ public abstract class SolenoidBase extends SensorBase { /** * Clear ALL sticky faults inside PCM that Compressor is wired to. * - * If a sticky fault is set, then it will be persistently cleared. Compressor - * drive maybe momentarily disable while flags are being cleared. Care should - * be taken to not call this too frequently, otherwise normal compressor - * functionality may be prevented. + *

If a sticky fault is set, then it will be persistently cleared. Compressor drive maybe + * momentarily disable while flags are being cleared. Care should be taken to not call this too + * frequently, otherwise normal compressor functionality may be prevented. * - * If no sticky faults are set then this call will have no effect. + *

If no sticky faults are set then this call will have no effect. */ public void clearAllPCMStickyFaults() { SolenoidJNI.clearAllPCMStickyFaults(m_ports[0]); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Spark.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Spark.java index 8f9dcf097f..e85cb082c3 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Spark.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Spark.java @@ -12,23 +12,22 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * REV Robotics SPARK Speed Controller + * REV Robotics SPARK Speed Controller. */ public class Spark extends PWMSpeedController { /** * Common initialization code called by all constructors. * - * Note that the SPARK uses the following bounds for PWM values. These - * values should work reasonably well for most controllers, but if users - * experience issues such as asymmetric behavior around the deadband or - * inability to saturate the controller in either direction, calibration is - * recommended. The calibration procedure can be found in the Spark User - * Manual available from REV Robotics. + *

Note that the SPARK uses the following bounds for PWM values. These values should work + * reasonably well for most controllers, but if users experience issues such as asymmetric + * behavior around the deadband or inability to saturate the controller in either direction, + * calibration is recommended. The calibration procedure can be found in the Spark User Manual + * available from REV Robotics. * - * - 2.003ms = full "forward" - 1.55ms = the "high end" of the deadband range - * - 1.50ms = center of the deadband range (off) - 1.46ms = the "low end" of - * the deadband range - .999ms = full "reverse" + *

- 2.003ms = full "forward" - 1.55ms = the "high end" of the deadband range - 1.50ms = + * center of the deadband range (off) - 1.46ms = the "low end" of the deadband range - .999ms = + * full "reverse" */ protected void initSpark() { setBounds(2.003, 1.55, 1.50, 1.46, .999); @@ -43,8 +42,8 @@ public class Spark extends PWMSpeedController { /** * Constructor. * - * @param channel The PWM channel that the SPARK is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the SPARK is attached to. 0-9 are on-board, 10-19 are on + * the MXP port */ public Spark(final int channel) { super(channel); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Talon.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Talon.java index 179697a907..70a78c9ecc 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Talon.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Talon.java @@ -12,23 +12,22 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * Cross the Road Electronics (CTRE) Talon and Talon SR Speed Controller + * Cross the Road Electronics (CTRE) Talon and Talon SR Speed Controller. */ public class Talon extends PWMSpeedController { /** * Common initialization code called by all constructors. * - * Note that the Talon uses the following bounds for PWM values. These values - * should work reasonably well for most controllers, but if users experience - * issues such as asymmetric behavior around the deadband or inability to - * saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the Talon User Manual available - * from CTRE. + *

Note that the Talon uses the following bounds for PWM values. These values should work + * reasonably well for most controllers, but if users experience issues such as asymmetric + * behavior around the deadband or inability to saturate the controller in either direction, + * calibration is recommended. The calibration procedure can be found in the Talon User Manual + * available from CTRE. * - * - 2.037ms = full "forward" - 1.539ms = the "high end" of the deadband range - * - 1.513ms = center of the deadband range (off) - 1.487ms = the "low end" of - * the deadband range - .989ms = full "reverse" + *

- 2.037ms = full "forward" - 1.539ms = the "high end" of the deadband range - 1.513ms = + * center of the deadband range (off) - 1.487ms = the "low end" of the deadband range - .989ms + * = full "reverse" */ private void initTalon() { setBounds(2.037, 1.539, 1.513, 1.487, .989); @@ -41,10 +40,10 @@ public class Talon extends PWMSpeedController { } /** - * Constructor for a Talon (original or Talon SR) + * Constructor for a Talon (original or Talon SR). * - * @param channel The PWM channel that the Talon is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the Talon is attached to. 0-9 are on-board, 10-19 are on + * the MXP port */ public Talon(final int channel) { super(channel); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/TalonSRX.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/TalonSRX.java index b1fd39c8f0..c89fdb894c 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/TalonSRX.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/TalonSRX.java @@ -12,8 +12,8 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * Cross the Road Electronics (CTRE) Talon SRX Speed Controller with PWM control - *$ + * Cross the Road Electronics (CTRE) Talon SRX Speed Controller with PWM control. + * * @see CANTalon CANTalon for CAN control of Talon SRX */ public class TalonSRX extends PWMSpeedController { @@ -21,16 +21,16 @@ public class TalonSRX extends PWMSpeedController { /** * Common initialization code called by all constructors. * - * Note that the TalonSRX uses the following bounds for PWM values. These - * values should work reasonably well for most controllers, but if users - * experience issues such as asymmetric behavior around the deadband or - * inability to saturate the controller in either direction, calibration is - * recommended. The calibration procedure can be found in the TalonSRX User - * Manual available from CTRE. + *

Note that the TalonSRX uses the following bounds for PWM values. These values should work + * reasonably well for most controllers, but if users experience issues such as asymmetric + * behavior around the deadband or inability to saturate the controller in either direction, + * calibration is recommended. The calibration procedure can be found in the TalonSRX User Manual + * available from CTRE. * - * - 2.0004ms = full "forward" - 1.52ms = the "high end" of the deadband range - * - 1.50ms = center of the deadband range (off) - 1.48ms = the "low end" of - * the deadband range - .997ms = full "reverse" + *

- 2.0004ms = full "forward" - 1.52ms = the "high end" of the deadband range - 1.50ms = + * center + * of the deadband range (off) - 1.48ms = the "low end" of the deadband range - .997ms = full + * "reverse" */ protected void initTalonSRX() { setBounds(2.004, 1.52, 1.50, 1.48, .997); @@ -43,10 +43,10 @@ public class TalonSRX extends PWMSpeedController { } /** - * Constructor for a TalonSRX connected via PWM + * Constructor for a TalonSRX connected via PWM. * - * @param channel The PWM channel that the TalonSRX is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the TalonSRX is attached to. 0-9 are on-board, 10-19 are on + * the MXP port */ public TalonSRX(final int channel) { super(channel); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Ultrasonic.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Ultrasonic.java index 6da2c84062..85abc52fc1 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Ultrasonic.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Ultrasonic.java @@ -9,104 +9,101 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; -import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Ultrasonic rangefinder class. The Ultrasonic rangefinder measures absolute - * distance based on the round-trip time of a ping generated by the controller. - * These sensors use two transducers, a speaker and a microphone both tuned to - * the ultrasonic range. A common ultrasonic sensor, the Daventech SRF04 - * requires a short pulse to be generated on a digital channel. This causes the - * chirp to be emmitted. A second line becomes high as the ping is transmitted - * and goes low when the echo is received. The time that the line is high - * determines the round trip distance (time of flight). + * Ultrasonic rangefinder class. The Ultrasonic rangefinder measures absolute distance based on the + * round-trip time of a ping generated by the controller. These sensors use two transducers, a + * speaker and a microphone both tuned to the ultrasonic range. A common ultrasonic sensor, the + * Daventech SRF04 requires a short pulse to be generated on a digital channel. This causes the + * chirp to be emmitted. A second line becomes high as the ping is transmitted and goes low when the + * echo is received. The time that the line is high determines the round trip distance (time of + * flight). */ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSendable { /** - * The units to return when PIDGet is called + * The units to return when PIDGet is called. */ - public static enum Unit { + public enum Unit { /** - * Use inches for PIDGet + * Use inches for PIDGet. */ kInches, /** - * Use millimeters for PIDGet + * Use millimeters for PIDGet. */ kMillimeters } - private static final double kPingTime = 10 * 1e-6; // /< Time (sec) for the - // ping trigger pulse. - private static final int kPriority = 90; // /< Priority that the ultrasonic - // round robin task runs. - private static final double kMaxUltrasonicTime = 0.1; // /< Max time (ms) - // between readings. + // Time (sec) for the ping trigger pulse. + private static final double kPingTime = 10 * 1e-6; + // Priority that the ultrasonic round robin task runs. + private static final int kPriority = 90; + // Max time (ms) between readings. + private static final double kMaxUltrasonicTime = 0.1; private static final double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0; - private static Ultrasonic m_firstSensor = null; // head of the ultrasonic - // sensor list - private static boolean m_automaticEnabled = false; // automatic round robin - // mode - private DigitalInput m_echoChannel = null; + // head of the ultrasonic sensor list + private static Ultrasonic m_firstSensor = null; + // automatic round robin mode + private static boolean m_automaticEnabled = false; + private DigitalInput m_echoChannel; private DigitalOutput m_pingChannel = null; private boolean m_allocatedChannels; private boolean m_enabled = false; private Counter m_counter = null; private Ultrasonic m_nextSensor = null; - private static Thread m_task = null; // task doing the round-robin automatic - // sensing + // task doing the round-robin automatic sensing + private static Thread m_task = null; private Unit m_units; private static int m_instances = 0; protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement; /** - * Background task that goes through the list of ultrasonic sensors and pings - * each one in turn. The counter is configured to read the timing of the - * returned echo pulse. + * Background task that goes through the list of ultrasonic sensors and pings each one in turn. + * The counter is configured to read the timing of the returned echo pulse. * - * DANGER WILL ROBINSON, DANGER WILL ROBINSON: This code runs as a task and - * assumes that none of the ultrasonic sensors will change while it's running. - * If one does, then this will certainly break. Make sure to disable automatic - * mode before changing anything with the sensors!! + *

DANGER WILL ROBINSON, DANGER WILL ROBINSON: This code runs as a task and assumes that + * none of the ultrasonic sensors will change while it's running. If one does, then this will + * certainly break. Make sure to disable automatic mode before changing anything with the + * sensors!! */ private class UltrasonicChecker extends Thread { + @Override public synchronized void run() { - Ultrasonic u = null; + Ultrasonic ultrasonic = null; while (m_automaticEnabled) { - if (u == null) { - u = m_firstSensor; + if (ultrasonic == null) { + ultrasonic = m_firstSensor; } - if (u == null) { + if (ultrasonic == null) { return; } - if (u.isEnabled()) { - u.m_pingChannel.pulse(m_pingChannel.m_channel, (float) kPingTime); // do - // the - // ping + if (ultrasonic.isEnabled()) { + ultrasonic.m_pingChannel.pulse(m_pingChannel.m_channel, (float) kPingTime); // do + // the + // ping } - u = u.m_nextSensor; + ultrasonic = ultrasonic.m_nextSensor; Timer.delay(.1); // wait for ping to return } } } /** - * Initialize the Ultrasonic Sensor. This is the common code that initializes - * the ultrasonic sensor given that there are two digital I/O channels - * allocated. If the system was running in automatic mode (round robin) when - * the new sensor is added, it is stopped, the sensor is added, then automatic - * mode is restored. + * Initialize the Ultrasonic Sensor. This is the common code that initializes the ultrasonic + * sensor given that there are two digital I/O channels allocated. If the system was running in + * automatic mode (round robin) when the new sensor is added, it is stopped, the sensor is added, + * then automatic mode is restored. */ private synchronized void initialize() { if (m_task == null) { m_task = new UltrasonicChecker(); } - boolean originalMode = m_automaticEnabled; + final boolean originalMode = m_automaticEnabled; setAutomaticMode(false); // kill task when adding a new sensor m_nextSensor = m_firstSensor; m_firstSensor = this; @@ -125,15 +122,15 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Create an instance of the Ultrasonic Sensor. This is designed to supchannel - * the Daventech SRF04 and Vex ultrasonic sensors. + * Create an instance of the Ultrasonic Sensor. This is designed to supchannel the Daventech SRF04 + * and Vex ultrasonic sensors. * - * @param pingChannel The digital output channel that sends the pulse to - * initiate the sensor sending the ping. - * @param echoChannel The digital input channel that receives the echo. The - * length of time that the echo is high represents the round trip time - * of the ping, and the distance. - * @param units The units returned in either kInches or kMilliMeters + * @param pingChannel The digital output channel that sends the pulse to initiate the sensor + * sending the ping. + * @param echoChannel The digital input channel that receives the echo. The length of time that + * the echo is high represents the round trip time of the ping, and the + * distance. + * @param units The units returned in either kInches or kMilliMeters */ public Ultrasonic(final int pingChannel, final int echoChannel, Unit units) { m_pingChannel = new DigitalOutput(pingChannel); @@ -144,28 +141,28 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Create an instance of the Ultrasonic Sensor. This is designed to supchannel - * the Daventech SRF04 and Vex ultrasonic sensors. Default unit is inches. + * Create an instance of the Ultrasonic Sensor. This is designed to supchannel the Daventech SRF04 + * and Vex ultrasonic sensors. Default unit is inches. * - * @param pingChannel The digital output channel that sends the pulse to - * initiate the sensor sending the ping. - * @param echoChannel The digital input channel that receives the echo. The - * length of time that the echo is high represents the round trip time - * of the ping, and the distance. + * @param pingChannel The digital output channel that sends the pulse to initiate the sensor + * sending the ping. + * @param echoChannel The digital input channel that receives the echo. The length of time that + * the echo is high represents the round trip time of the ping, and the + * distance. */ public Ultrasonic(final int pingChannel, final int echoChannel) { this(pingChannel, echoChannel, Unit.kInches); } /** - * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo - * channel and a DigitalOutput for the ping channel. + * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a + * DigitalOutput for the ping channel. * - * @param pingChannel The digital output object that starts the sensor doing a - * ping. Requires a 10uS pulse to start. - * @param echoChannel The digital input object that times the return pulse to - * determine the range. - * @param units The units returned in either kInches or kMilliMeters + * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a + * 10uS pulse to start. + * @param echoChannel The digital input object that times the return pulse to determine the + * range. + * @param units The units returned in either kInches or kMilliMeters */ public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel, Unit units) { if (pingChannel == null || echoChannel == null) { @@ -179,26 +176,27 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo - * channel and a DigitalOutput for the ping channel. Default unit is inches. + * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a + * DigitalOutput for the ping channel. Default unit is inches. * - * @param pingChannel The digital output object that starts the sensor doing a - * ping. Requires a 10uS pulse to start. - * @param echoChannel The digital input object that times the return pulse to - * determine the range. + * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a + * 10uS pulse to start. + * @param echoChannel The digital input object that times the return pulse to determine the + * range. */ public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel) { this(pingChannel, echoChannel, Unit.kInches); } /** - * Destructor for the ultrasonic sensor. Delete the instance of the ultrasonic - * sensor by freeing the allocated digital channels. If the system was in - * automatic mode (round robin), then it is stopped, then started again after - * this sensor is removed (provided this wasn't the last sensor). + * Destructor for the ultrasonic sensor. Delete the instance of the ultrasonic sensor by freeing + * the allocated digital channels. If the system was in automatic mode (round robin), then it is + * stopped, then started again after this sensor is removed (provided this wasn't the last + * sensor). */ + @Override public synchronized void free() { - boolean wasAutomaticMode = m_automaticEnabled; + final boolean wasAutomaticMode = m_automaticEnabled; setAutomaticMode(false); if (m_allocatedChannels) { if (m_pingChannel != null) { @@ -236,15 +234,14 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Turn Automatic mode on/off. When in Automatic mode, all sensors will fire - * in round robin, waiting a set time between each sensor. + * Turn Automatic mode on/off. When in Automatic mode, all sensors will fire in round robin, + * waiting a set time between each sensor. * - * @param enabling Set to true if round robin scheduling should start for all - * the ultrasonic sensors. This scheduling method assures that the - * sensors are non-interfering because no two sensors fire at the same - * time. If another scheduling algorithm is preffered, it can be - * implemented by pinging the sensors manually and waiting for the - * results to come back. + * @param enabling Set to true if round robin scheduling should start for all the ultrasonic + * sensors. This scheduling method assures that the sensors are non-interfering + * because no two sensors fire at the same time. If another scheduling algorithm + * is preffered, it can be implemented by pinging the sensors manually and waiting + * for the results to come back. */ public void setAutomaticMode(boolean enabling) { if (enabling == m_automaticEnabled) { @@ -266,8 +263,9 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda // Wait for background task to stop running try { m_task.join(); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + ex.printStackTrace(); } /* Clear all the counters (data now invalid) since automatic mode is @@ -281,10 +279,10 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Single ping to ultrasonic sensor. Send out a single ping to the ultrasonic - * sensor. This only works if automatic (round robin) mode is disabled. A - * single ping is sent out, and the counter should count the semi-period when - * it comes in. The counter is reset to make the current value invalid. + * Single ping to ultrasonic sensor. Send out a single ping to the ultrasonic sensor. This only + * works if automatic (round robin) mode is disabled. A single ping is sent out, and the counter + * should count the semi-period when it comes in. The counter is reset to make the current value + * invalid. */ public void ping() { setAutomaticMode(false); // turn off automatic round robin if pinging @@ -302,10 +300,9 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Check if there is a valid range measurement. The ranges are accumulated in - * a counter that will increment on each edge of the echo (return) signal. If - * the count is not at least 2, then the range has not yet been measured, and - * is invalid. + * Check if there is a valid range measurement. The ranges are accumulated in a counter that will + * increment on each edge of the echo (return) signal. If the count is not at least 2, then the + * range has not yet been measured, and is invalid. * * @return true if the range is valid */ @@ -314,11 +311,10 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Get the range in inches from the ultrasonic sensor. + * Get the range in inches from the ultrasonic sensor. If there is no valid value yet, i.e. at + * least one measurement hasn't completed, then return 0. * - * @return double Range in inches of the target returned from the ultrasonic - * sensor. If there is no valid value yet, i.e. at least one - * measurement hasn't completed, then return 0. + * @return double Range in inches of the target returned from the ultrasonic sensor. */ public double getRangeInches() { if (isRangeValid()) { @@ -329,19 +325,16 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Get the range in millimeters from the ultrasonic sensor. + * Get the range in millimeters from the ultrasonic sensor. If there is no valid value yet, i.e. + * at least one measurement hasn't completed, then return 0. * - * @return double Range in millimeters of the target returned by the - * ultrasonic sensor. If there is no valid value yet, i.e. at least - * one measurement hasn't complted, then return 0. + * @return double Range in millimeters of the target returned by the ultrasonic sensor. */ public double getRangeMM() { return getRangeInches() * 25.4; } - /** - * {@inheritDoc} - */ + @Override public void setPIDSourceType(PIDSourceType pidSource) { if (!pidSource.equals(PIDSourceType.kDisplacement)) { throw new IllegalArgumentException("Only displacement PID is allowed for ultrasonics."); @@ -349,9 +342,7 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_pidSource; } @@ -361,6 +352,7 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda * * @return The range in DistanceUnit */ + @Override public double pidGet() { switch (m_units) { case kInches: @@ -373,8 +365,7 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Set the current DistanceUnit that should be used for the PIDSource base - * object. + * Set the current DistanceUnit that should be used for the PIDSource base object. * * @param units The DistanceUnit that should be used. */ @@ -392,7 +383,7 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Is the ultrasonic enabled + * Is the ultrasonic enabled. * * @return true if the ultrasonic is enabled */ @@ -401,7 +392,7 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda } /** - * Set if the ultrasonic is enabled + * Set if the ultrasonic is enabled. * * @param enable set to true to enable the ultrasonic */ @@ -409,46 +400,39 @@ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSenda m_enabled = enable; } - /* + /** * Live Window code, only does anything if live window is activated. */ + @Override public String getSmartDashboardType() { return "Ultrasonic"; } private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ + @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", getRangeInches()); } } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() {} + @Override + public void startLiveWindowMode() { + } - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() {} + @Override + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Utility.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Utility.java index 4c5918d0e2..281bf7c4fe 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Utility.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Utility.java @@ -10,28 +10,31 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.hal.HALUtil; /** - * Contains global utility functions + * Contains global utility functions. */ -public class Utility { +public final class Utility { - private Utility() {} + private Utility() { + } /** * Return the FPGA Version number. For now, expect this to be 2009. * * @return FPGA Version number. */ + @SuppressWarnings("AbbreviationAsWordInName") int getFPGAVersion() { return HALUtil.getFPGAVersion(); } /** - * Return the FPGA Revision number. The format of the revision is 3 numbers. - * The 12 most significant bits are the Major Revision. the next 8 bits are - * the Minor Revision. The 12 least significant bits are the Build Number. + * Return the FPGA Revision number. The format of the revision is 3 numbers. The 12 most + * significant bits are the Major Revision. the next 8 bits are the Minor Revision. The 12 least + * significant bits are the Build Number. * * @return FPGA Revision number. */ + @SuppressWarnings("AbbreviationAsWordInName") long getFPGARevision() { return (long) HALUtil.getFPGARevision(); } @@ -46,8 +49,8 @@ public class Utility { } /** - * Get the state of the "USER" button on the RoboRIO - *$ + * Get the state of the "USER" button on the RoboRIO. + * * @return true if the button is currently pressed down */ public static boolean getUserButton() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Victor.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Victor.java index e4a54a822e..a66f213e1d 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Victor.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/Victor.java @@ -12,28 +12,24 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * VEX Robotics Victor 888 Speed Controller - *$ - * The Vex Robotics Victor 884 Speed Controller can also be used with this class - * but may need to be calibrated per the Victor 884 user manual. + * VEX Robotics Victor 888 Speed Controller The Vex Robotics Victor 884 Speed Controller can also + * be used with this class but may need to be calibrated per the Victor 884 user manual. */ public class Victor extends PWMSpeedController { /** * Common initialization code called by all constructors. * - * Note that the Victor uses the following bounds for PWM values. These values - * were determined empirically and optimized for the Victor 888. These values - * should work reasonably well for Victor 884 controllers also but if users - * experience issues such as asymmetric behaviour around the deadband or - * inability to saturate the controller in either direction, calibration is - * recommended. The calibration procedure can be found in the Victor 884 User - * Manual available from VEX Robotics: - * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf + *

Note that the Victor uses the following bounds for PWM values. These values were determined + * empirically and optimized for the Victor 888. These values should work reasonably well for + * Victor 884 controllers also but if users experience issues such as asymmetric behaviour around + * the deadband or inability to saturate the controller in either direction, calibration is + * recommended. The calibration procedure can be found in the Victor 884 User Manual available + * from VEX Robotics: http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf * - * - 2.027ms = full "forward" - 1.525ms = the "high end" of the deadband range - * - 1.507ms = center of the deadband range (off) - 1.49ms = the "low end" of - * the deadband range - 1.026ms = full "reverse" + *

- 2.027ms = full "forward" - 1.525ms = the "high end" of the deadband range - 1.507ms = + * center of the deadband range (off) - 1.49ms = the "low end" of the deadband range - 1.026ms = + * full "reverse" */ private void initVictor() { setBounds(2.027, 1.525, 1.507, 1.49, 1.026); @@ -48,8 +44,8 @@ public class Victor extends PWMSpeedController { /** * Constructor. * - * @param channel The PWM channel that the Victor is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the Victor is attached to. 0-9 are on-board, 10-19 are on + * the MXP port */ public Victor(final int channel) { super(channel); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/VictorSP.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/VictorSP.java index 9967823803..d2f888cab0 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/VictorSP.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/VictorSP.java @@ -12,23 +12,22 @@ import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * VEX Robotics Victor SP Speed Controller + * VEX Robotics Victor SP Speed Controller. */ public class VictorSP extends PWMSpeedController { /** * Common initialization code called by all constructors. * - * Note that the VictorSP uses the following bounds for PWM values. These - * values should work reasonably well for most controllers, but if users - * experience issues such as asymmetric behavior around the deadband or - * inability to saturate the controller in either direction, calibration is - * recommended. The calibration procedure can be found in the VictorSP User - * Manual available from CTRE. + *

Note that the VictorSP uses the following bounds for PWM values. These values should work + * reasonably well for most controllers, but if users experience issues such as asymmetric + * behavior around the deadband or inability to saturate the controller in either direction, + * calibration is recommended. The calibration procedure can be found in the VictorSP User Manual + * available from CTRE. * - * - 2.004ms = full "forward" - 1.52ms = the "high end" of the deadband range - * - 1.50ms = center of the deadband range (off) - 1.48ms = the "low end" of - * the deadband range - .997ms = full "reverse" + *

- 2.004ms = full "forward" - 1.52ms = the "high end" of the deadband range - 1.50ms = + * center of the deadband range (off) - 1.48ms = the "low end" of the deadband range - .997ms = + * full "reverse" */ protected void initVictorSP() { setBounds(2.004, 1.52, 1.50, 1.48, .997); @@ -43,8 +42,8 @@ public class VictorSP extends PWMSpeedController { /** * Constructor. * - * @param channel The PWM channel that the VictorSP is attached to. 0-9 are - * on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the VictorSP is attached to. 0-9 are on-board, 10-19 are on + * the MXP port */ public VictorSP(final int channel) { super(channel); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java index 4995d3e930..2c484d04fd 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java @@ -17,6 +17,7 @@ public class CANExceptionFactory { static final int ERR_CANSessionMux_NotAllowed = -44088; static final int ERR_CANSessionMux_NotInitialized = -44089; + @SuppressWarnings("JavadocMethod") public static void checkStatus(int status, int messageID) throws CANInvalidBufferException, CANMessageNotAllowedException, CANNotInitializedException, UncleanStatusException { switch (status) { @@ -36,7 +37,8 @@ public class CANExceptionFactory { case NIRioStatus.kRIOStatusResourceNotInitialized: throw new CANNotInitializedException(); default: - throw new UncleanStatusException("Fatal status code detected: " + Integer.toString(status)); + throw new UncleanStatusException("Fatal status code detected: " + Integer.toString( + status)); } } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java index 34f6194c51..0c4064abfc 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java @@ -8,9 +8,8 @@ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that a CAN driver library entry-point was passed an - * invalid buffer. Typically, this is due to a buffer being too small to include - * the needed safety token. + * Exception indicating that a CAN driver library entry-point was passed an invalid buffer. + * Typically, this is due to a buffer being too small to include the needed safety token. */ public class CANInvalidBufferException extends RuntimeException { public CANInvalidBufferException() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJNI.java index 4f8ecce3ae..5ed057e83c 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJNI.java @@ -14,486 +14,917 @@ package edu.wpi.first.wpilibj.can; // import com.sun.jna.NativeLibrary; // import com.sun.jna.Pointer; // import com.sun.jna.ptr.IntByReference; -import edu.wpi.first.wpilibj.hal.JNIWrapper; + import java.nio.ByteBuffer; import java.nio.IntBuffer; +import edu.wpi.first.wpilibj.hal.JNIWrapper; + /** - * JNA Wrapper for library CAN
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few - * opensource projects..
- * For help, please visit NativeLibs4Java , Rococoa, or JNA. + * JNA Wrapper for library CAN
This file was autogenerated by JNAerator,
a tool written by Olivier Chafik that + * uses + * a few opensource projects..
For help, please visit + * NativeLibs4Java + * , Rococoa, or + * JNA. */ +@SuppressWarnings("AbbreviationAsWordInName") public class CANJNI extends JNIWrapper { - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_REV = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_MAX_VOUT = ((0x00020000 | 0x02000000 | 0x00001c00) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_CANERR_B0 = 30; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_DIS = ((0x00020000 | 0x02000000 | 0x00000400) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_ACCEL = 0x05000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_FAULT = ((0x00020000 | 0x02000000 | 0x00001400) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_FIRMVER = 0x00000200; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_ENUMERATE = 0x00000240; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_LIMIT_REV = ((0x00020000 | 0x02000000 | 0x00001c00) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_POS_B2 = 11; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_POS_B3 = 12; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_POS_B0 = 9; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_POS_B1 = 10; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_HWVER = ((0x00020000 | 0x1f000000) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_FAULT_ILIMIT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_DC = ((0x00020000 | 0x02000000 | 0x00001000) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT = (0x00020000 | 0x02000000 | 0x00000000); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_VCOMP = 0x00000800; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_END = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_LIMIT_FWD = ((0x00020000 | 0x02000000 | 0x00001c00) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_M = 0x1f000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_ICTRL = 0x00001000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_CFG = 0x00001c00; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_MFR_DEKA = 0x00030000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_SYSRST = 0x00000040; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_REF_QUAD_ENCODER = 0x03; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SYNC_PEND_NOW = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_CMODE_CURRENT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_TEMP = ((0x00020000 | 0x02000000 | 0x00001400) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_DC = ((0x00020000 | 0x02000000 | 0x00000400) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_POS = 0x00000c00; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_SFWD = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_DIS = ((0x00020000 | 0x02000000 | 0x00001000) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_HEARTBEAT = 0x00000140; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_FAULT_CURRENT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_GYRO = 0x04000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_FAULT_TLIMIT = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_MFR_S = 16; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000400) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_MFR_M = 0x00ff0000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_CMODE_POS = 0x03; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_REF_POT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_HWVER_UNKNOWN = 0x00; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_BRAKE_COAST = ((0x00020000 | 0x02000000 | 0x00001c00) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_HWVER_JAG_1_0 = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DEVNO_BCAST = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_T_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_STKY_SREV = 0x80; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_IC = ((0x00020000 | 0x02000000 | 0x00001000) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_FAULT_COMM = 0x10; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00001000) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_SPD_B2 = 15; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_SPD_B1 = 14; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_STKY_FLT_CLR = 21; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_SPD_B3 = 16; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_STATUS_MFG_S = 16; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000400) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_LIMIT = ((0x00020000 | 0x02000000 | 0x00001400) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_RAMP_DIS = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_TEMP_B0 = 7; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_TEMP_B1 = 8; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_IC = ((0x00020000 | 0x02000000 | 0x00000c00) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_MOTOR = 0x02000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_T_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DEVNO_M = 0x0000003f; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_VOLTBUS_B1 = 4; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UPD_PING = ((0x00020000 | 0x1f000000) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000c00) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DEVNO_S = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_TRUST_HEARTBEAT = ((0x00020000 | 0x1f000000) | (13 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_VOLTBUS_B0 = 3; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_SPD_B0 = 13; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG = (0x00020000 | 0x02000000 | 0x00001c00); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_FLT_COUNT_COMM = 28; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_SYSHALT = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UPD_DOWNLOAD = ((0x00020000 | 0x1f000000) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_CMODE = ((0x00020000 | 0x02000000 | 0x00001400) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_IN_RAMP = ((0x00020000 | 0x02000000 | 0x00000800) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_FAULT_VLIMIT = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_SREV = 0x08; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_S = 24; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_FLT_COUNT_VOLTBUS = 26; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_STATUS = 0x00001400; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_T_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_VOLTBUS = ((0x00020000 | 0x02000000 | 0x00001400) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UPD = (0x00020000 | 0x1f000000); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UPD_REQUEST = ((0x00020000 | 0x1f000000) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_VOLTAGE = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_PER_EN_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_PER_EN_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_PSTAT = 0x00001800; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_CANERR_B1 = 31; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_PER_EN_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_REF_ENCODER = 0x00; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_PER_EN_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_CURRENT = ((0x00020000 | 0x02000000 | 0x00001400) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_STKY_FWD = 0x10; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL = (0x00020000 | 0x02000000 | 0x00001000); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_HWVER_JAG_2_0 = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_STATUS_MFG_M = 0x00ff0000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_LIMIT_CLR = 18; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_POT_TURNS = ((0x00020000 | 0x02000000 | 0x00001c00) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_REF = ((0x00020000 | 0x02000000 | 0x00000c00) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_PC = ((0x00020000 | 0x02000000 | 0x00000400) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_VOUT = ((0x00020000 | 0x02000000 | 0x00001400) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_SYSRESUME = 0x00000280; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UNTRUST_EN = ((0x00020000 | 0x1f000000) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_CANSTS = 29; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_DC = ((0x00020000 | 0x02000000 | 0x00000c00) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_POS = ((0x00020000 | 0x02000000 | 0x00001400) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_FULL_M = 0x1fffffff; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_SPD = ((0x00020000 | 0x02000000 | 0x00001400) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_STKY_FLT_NCLR = 20; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS = (0x00020000 | 0x02000000 | 0x00001400); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_TRUST_EN = ((0x00020000 | 0x1f000000) | (12 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_T_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_STATUS_CODE_M = 0x0000ffff; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_STATUS_CODE_S = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_T_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT = (0x00020000 | 0x02000000 | 0x00001800); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_FAULT = 19; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_FLT_COUNT_GATE = 27; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_T_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_DEVQUERY = 0x000000c0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_USONIC = 0x06000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_CMODE_VCOMP = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_T_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_DIS = ((0x00020000 | 0x02000000 | 0x00000000) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_FWD = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_DIS = ((0x00020000 | 0x02000000 | 0x00000800) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_REF_INV_ENCODER = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_NUM_BRUSHES = ((0x00020000 | 0x02000000 | 0x00001c00) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_RELAY = 0x03000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_DEVASSIGN = 0x00000080; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000000) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_SPD = 0x00000400; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_ENC_LINES = ((0x00020000 | 0x02000000 | 0x00001c00) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_REF_NONE = 0xff; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_FAULT_VBUS = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_SET_RAMP = ((0x00020000 | 0x02000000 | 0x00000000) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_REF = ((0x00020000 | 0x02000000 | 0x00000400) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_POWER = ((0x00020000 | 0x02000000 | 0x00001400) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_VOLTOUT_B1 = 2; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000800) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_VOLTOUT_B0 = 1; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_LIMIT_MODE = ((0x00020000 | 0x02000000 | 0x00001c00) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_VOUT_B1 = 23; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UPD_SEND_DATA = ((0x00020000 | 0x1f000000) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_FLT_COUNT_CURRENT = 24; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_VOUT_B0 = 22; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_CFG_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_LIMIT_NCLR = 17; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_CFG_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_CFG_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_CFG_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_UPDATE = 0x000001c0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_CFG_FAULT_TIME = ((0x00020000 | 0x02000000 | 0x00001c00) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_VOLTOUT = ((0x00020000 | 0x02000000 | 0x00001400) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_M = 0x0000ffc0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_CMODE_SPEED = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_CLASS_M = 0x0000fc00; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_DATA_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_S = 6; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_FLT_COUNT = ((0x00020000 | 0x02000000 | 0x00001400) | (12 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_DATA_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_DATA_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_PSTAT_DATA_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_PC = ((0x00020000 | 0x02000000 | 0x00001000) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_PC = ((0x00020000 | 0x02000000 | 0x00000c00) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_MFR_LM = 0x00020000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_DIS = ((0x00020000 | 0x02000000 | 0x00000c00) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_BCAST = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_CMODE_VOLT = 0x00; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_STATUS_DTYPE_S = 24; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000c00) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_FAULT_GATE_DRIVE = 0x08; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_STATUS_DTYPE_M = 0x1f000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_STKY_REV = 0x20; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_ROBOT = 0x01000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_API_MC_ACK = 0x00002000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP = (0x00020000 | 0x02000000 | 0x00000800); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UPD_ACK = ((0x00020000 | 0x1f000000) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_COMP_RAMP = ((0x00020000 | 0x02000000 | 0x00000800) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000800) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS = (0x00020000 | 0x02000000 | 0x00000c00); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_SYNC = 0x00000180; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ICTRL_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00001000) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_CURRENT_B1 = 6; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD = (0x00020000 | 0x02000000 | 0x00000400); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_CURRENT_B0 = 5; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_UPDATE = 0x1f000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_SPD_IC = ((0x00020000 | 0x02000000 | 0x00000400) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_ACK = (0x00020000 | 0x02000000 | 0x00002000); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_FAULT_TEMP = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_T_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_PSTAT_FLT_COUNT_TEMP = 25; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VOLT_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000000) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_DTYPE_GEART = 0x07000000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_MFR_NI = 0x00010000; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_POS_T_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_STATUS_STKY_FLT = ((0x00020000 | 0x02000000 | 0x00001400) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_UPD_RESET = ((0x00020000 | 0x1f000000) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int CAN_MSGID_API_ID_M = 0x000003c0; - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_API_VCOMP_T_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ + /** + * native declaration : src\main\include\CAN\can_proto.h + */ public static final int LM_STATUS_LIMIT_STKY_SFWD = 0x40; public static final int CAN_SEND_PERIOD_NO_REPEAT = 0; @@ -503,9 +934,12 @@ public class CANJNI extends JNIWrapper { public static final int CAN_IS_FRAME_REMOTE = 0x80000000; public static final int CAN_IS_FRAME_11BIT = 0x40000000; + @SuppressWarnings("MethodName") public static native void FRCNetworkCommunicationCANSessionMuxSendMessage(int messageID, - ByteBuffer data, int periodMs); + ByteBuffer data, + int periodMs); + @SuppressWarnings("MethodName") public static native ByteBuffer FRCNetworkCommunicationCANSessionMuxReceiveMessage( IntBuffer messageID, int messageIDMask, ByteBuffer timeStamp); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java index 9e48581f85..87c404eaec 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java @@ -8,9 +8,8 @@ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that the CAN driver layer has not been initialized. This - * happens when an entry-point is called before a CAN driver plugin has been - * installed. + * Exception indicating that the CAN driver layer has not been initialized. This happens when an + * entry-point is called before a CAN driver plugin has been installed. */ public class CANJaguarVersionException extends RuntimeException { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java index 472e5be07d..2c51848e12 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java @@ -8,8 +8,8 @@ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that the Jaguar CAN Driver layer refused to send a - * restricted message ID to the CAN bus. + * Exception indicating that the Jaguar CAN Driver layer refused to send a restricted message ID to + * the CAN bus. */ public class CANMessageNotAllowedException extends RuntimeException { public CANMessageNotAllowedException(String msg) { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java index a577ee8f8b..37a5a10811 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java @@ -8,9 +8,8 @@ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that a can message is not available from Network - * Communications. This usually just means we already have the most recent value - * cached locally. + * Exception indicating that a can message is not available from Network Communications. This + * usually just means we already have the most recent value cached locally. */ public class CANMessageNotFoundException extends RuntimeException { public CANMessageNotFoundException() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java index d060cf641a..0c3b8fca0f 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java @@ -8,9 +8,8 @@ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that the CAN driver layer has not been initialized. This - * happens when an entry-point is called before a CAN driver plugin has been - * installed. + * Exception indicating that the CAN driver layer has not been initialized. This happens when an + * entry-point is called before a CAN driver plugin has been installed. */ public class CANNotInitializedException extends RuntimeException { public CANNotInitializedException() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java index fdc2f9db2d..c5e88a1d78 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java @@ -8,160 +8,174 @@ package edu.wpi.first.wpilibj.communication; import java.nio.ByteBuffer; -import java.nio.IntBuffer; -import java.nio.ShortBuffer; import edu.wpi.first.wpilibj.hal.JNIWrapper; /** - * JNI Wrapper for library FRC_NetworkCommunications
+ * JNI Wrapper for library FRC_NetworkCommunications
. */ +@SuppressWarnings("MethodName") public class FRCNetworkCommunicationsLibrary extends JNIWrapper { - /** Module type from LoadOut.h */ - public static interface tModuleType { - public static final int kModuleType_Unknown = 0x00; - public static final int kModuleType_Analog = 0x01; - public static final int kModuleType_Digital = 0x02; - public static final int kModuleType_Solenoid = 0x03; - }; - /** Target class from LoadOut.h */ - public static interface tTargetClass { - public static final int kTargetClass_Unknown = 0x00; - public static final int kTargetClass_FRC1 = 0x10; - public static final int kTargetClass_FRC2 = 0x20; - public static final int kTargetClass_FRC2_Analog = + /** + * Module type from LoadOut.h + */ + @SuppressWarnings("TypeName") + public interface tModuleType { + int kModuleType_Unknown = 0x00; + int kModuleType_Analog = 0x01; + int kModuleType_Digital = 0x02; + int kModuleType_Solenoid = 0x03; + } + + /** + * Target class from LoadOut.h + */ + @SuppressWarnings("TypeName") + public interface tTargetClass { + int kTargetClass_Unknown = 0x00; + int kTargetClass_FRC1 = 0x10; + int kTargetClass_FRC2 = 0x20; + int kTargetClass_FRC2_Analog = kTargetClass_FRC2 | FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Analog; - public static final int kTargetClass_FRC2_Digital = + int kTargetClass_FRC2_Digital = kTargetClass_FRC2 | FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Digital; - public static final int kTargetClass_FRC2_Solenoid = + int kTargetClass_FRC2_Solenoid = kTargetClass_FRC2 | FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Solenoid; - public static final int kTargetClass_FamilyMask = 0xF0; - public static final int kTargetClass_ModuleMask = 0x0F; - }; - /** Resource types from UsageReporting.h */ - public static interface tResourceType { - public static final int kResourceType_Controller = 0; - public static final int kResourceType_Module = 1; - public static final int kResourceType_Language = 2; - public static final int kResourceType_CANPlugin = 3; - public static final int kResourceType_Accelerometer = 4; - public static final int kResourceType_ADXL345 = 5; - public static final int kResourceType_AnalogChannel = 6; - public static final int kResourceType_AnalogTrigger = 7; - public static final int kResourceType_AnalogTriggerOutput = 8; - public static final int kResourceType_CANJaguar = 9; - public static final int kResourceType_Compressor = 10; - public static final int kResourceType_Counter = 11; - public static final int kResourceType_Dashboard = 12; - public static final int kResourceType_DigitalInput = 13; - public static final int kResourceType_DigitalOutput = 14; - public static final int kResourceType_DriverStationCIO = 15; - public static final int kResourceType_DriverStationEIO = 16; - public static final int kResourceType_DriverStationLCD = 17; - public static final int kResourceType_Encoder = 18; - public static final int kResourceType_GearTooth = 19; - public static final int kResourceType_Gyro = 20; - public static final int kResourceType_I2C = 21; - public static final int kResourceType_Framework = 22; - public static final int kResourceType_Jaguar = 23; - public static final int kResourceType_Joystick = 24; - public static final int kResourceType_Kinect = 25; - public static final int kResourceType_KinectStick = 26; - public static final int kResourceType_PIDController = 27; - public static final int kResourceType_Preferences = 28; - public static final int kResourceType_PWM = 29; - public static final int kResourceType_Relay = 30; - public static final int kResourceType_RobotDrive = 31; - public static final int kResourceType_SerialPort = 32; - public static final int kResourceType_Servo = 33; - public static final int kResourceType_Solenoid = 34; - public static final int kResourceType_SPI = 35; - public static final int kResourceType_Task = 36; - public static final int kResourceType_Ultrasonic = 37; - public static final int kResourceType_Victor = 38; - public static final int kResourceType_Button = 39; - public static final int kResourceType_Command = 40; - public static final int kResourceType_AxisCamera = 41; - public static final int kResourceType_PCVideoServer = 42; - public static final int kResourceType_SmartDashboard = 43; - public static final int kResourceType_Talon = 44; - public static final int kResourceType_HiTechnicColorSensor = 45; - public static final int kResourceType_HiTechnicAccel = 46; - public static final int kResourceType_HiTechnicCompass = 47; - public static final int kResourceType_SRF08 = 48; - public static final int kResourceType_AnalogOutput = 49; - public static final int kResourceType_VictorSP = 50; - public static final int kResourceType_TalonSRX = 51; - public static final int kResourceType_CANTalonSRX = 52; - public static final int kResourceType_ADXL362 = 53; - public static final int kResourceType_ADXRS450 = 54; - public static final int kResourceType_RevSPARK = 55; - public static final int kResourceType_MindsensorsSD540 = 56; - public static final int kResourceType_DigitalFilter = 57; - }; - /** Instances from UsageReporting.h */ - public static interface tInstances { - public static final int kLanguage_LabVIEW = 1; - public static final int kLanguage_CPlusPlus = 2; - public static final int kLanguage_Java = 3; - public static final int kLanguage_Python = 4; + int kTargetClass_FamilyMask = 0xF0; + int kTargetClass_ModuleMask = 0x0F; + } - public static final int kCANPlugin_BlackJagBridge = 1; - public static final int kCANPlugin_2CAN = 2; + /** + * Resource types from UsageReporting.h + */ + @SuppressWarnings("TypeName") + public interface tResourceType { + int kResourceType_Controller = 0; + int kResourceType_Module = 1; + int kResourceType_Language = 2; + int kResourceType_CANPlugin = 3; + int kResourceType_Accelerometer = 4; + int kResourceType_ADXL345 = 5; + int kResourceType_AnalogChannel = 6; + int kResourceType_AnalogTrigger = 7; + int kResourceType_AnalogTriggerOutput = 8; + int kResourceType_CANJaguar = 9; + int kResourceType_Compressor = 10; + int kResourceType_Counter = 11; + int kResourceType_Dashboard = 12; + int kResourceType_DigitalInput = 13; + int kResourceType_DigitalOutput = 14; + int kResourceType_DriverStationCIO = 15; + int kResourceType_DriverStationEIO = 16; + int kResourceType_DriverStationLCD = 17; + int kResourceType_Encoder = 18; + int kResourceType_GearTooth = 19; + int kResourceType_Gyro = 20; + int kResourceType_I2C = 21; + int kResourceType_Framework = 22; + int kResourceType_Jaguar = 23; + int kResourceType_Joystick = 24; + int kResourceType_Kinect = 25; + int kResourceType_KinectStick = 26; + int kResourceType_PIDController = 27; + int kResourceType_Preferences = 28; + int kResourceType_PWM = 29; + int kResourceType_Relay = 30; + int kResourceType_RobotDrive = 31; + int kResourceType_SerialPort = 32; + int kResourceType_Servo = 33; + int kResourceType_Solenoid = 34; + int kResourceType_SPI = 35; + int kResourceType_Task = 36; + int kResourceType_Ultrasonic = 37; + int kResourceType_Victor = 38; + int kResourceType_Button = 39; + int kResourceType_Command = 40; + int kResourceType_AxisCamera = 41; + int kResourceType_PCVideoServer = 42; + int kResourceType_SmartDashboard = 43; + int kResourceType_Talon = 44; + int kResourceType_HiTechnicColorSensor = 45; + int kResourceType_HiTechnicAccel = 46; + int kResourceType_HiTechnicCompass = 47; + int kResourceType_SRF08 = 48; + int kResourceType_AnalogOutput = 49; + int kResourceType_VictorSP = 50; + int kResourceType_TalonSRX = 51; + int kResourceType_CANTalonSRX = 52; + int kResourceType_ADXL362 = 53; + int kResourceType_ADXRS450 = 54; + int kResourceType_RevSPARK = 55; + int kResourceType_MindsensorsSD540 = 56; + int kResourceType_DigitalFilter = 57; + } - public static final int kFramework_Iterative = 1; - public static final int kFramework_Sample = 2; - public static final int kFramework_CommandControl = 3; + /** + * Instances from UsageReporting.h + */ + @SuppressWarnings("TypeName") + public interface tInstances { + int kLanguage_LabVIEW = 1; + int kLanguage_CPlusPlus = 2; + int kLanguage_Java = 3; + int kLanguage_Python = 4; - public static final int kRobotDrive_ArcadeStandard = 1; - public static final int kRobotDrive_ArcadeButtonSpin = 2; - public static final int kRobotDrive_ArcadeRatioCurve = 3; - public static final int kRobotDrive_Tank = 4; - public static final int kRobotDrive_MecanumPolar = 5; - public static final int kRobotDrive_MecanumCartesian = 6; + int kCANPlugin_BlackJagBridge = 1; + int kCANPlugin_2CAN = 2; - public static final int kDriverStationCIO_Analog = 1; - public static final int kDriverStationCIO_DigitalIn = 2; - public static final int kDriverStationCIO_DigitalOut = 3; + int kFramework_Iterative = 1; + int kFramework_Sample = 2; + int kFramework_CommandControl = 3; - public static final int kDriverStationEIO_Acceleration = 1; - public static final int kDriverStationEIO_AnalogIn = 2; - public static final int kDriverStationEIO_AnalogOut = 3; - public static final int kDriverStationEIO_Button = 4; - public static final int kDriverStationEIO_LED = 5; - public static final int kDriverStationEIO_DigitalIn = 6; - public static final int kDriverStationEIO_DigitalOut = 7; - public static final int kDriverStationEIO_FixedDigitalOut = 8; - public static final int kDriverStationEIO_PWM = 9; - public static final int kDriverStationEIO_Encoder = 10; - public static final int kDriverStationEIO_TouchSlider = 11; + int kRobotDrive_ArcadeStandard = 1; + int kRobotDrive_ArcadeButtonSpin = 2; + int kRobotDrive_ArcadeRatioCurve = 3; + int kRobotDrive_Tank = 4; + int kRobotDrive_MecanumPolar = 5; + int kRobotDrive_MecanumCartesian = 6; - public static final int kADXL345_SPI = 1; - public static final int kADXL345_I2C = 2; + int kDriverStationCIO_Analog = 1; + int kDriverStationCIO_DigitalIn = 2; + int kDriverStationCIO_DigitalOut = 3; - public static final int kCommand_Scheduler = 1; + int kDriverStationEIO_Acceleration = 1; + int kDriverStationEIO_AnalogIn = 2; + int kDriverStationEIO_AnalogOut = 3; + int kDriverStationEIO_Button = 4; + int kDriverStationEIO_LED = 5; + int kDriverStationEIO_DigitalIn = 6; + int kDriverStationEIO_DigitalOut = 7; + int kDriverStationEIO_FixedDigitalOut = 8; + int kDriverStationEIO_PWM = 9; + int kDriverStationEIO_Encoder = 10; + int kDriverStationEIO_TouchSlider = 11; - public static final int kSmartDashboard_Instance = 1; - }; + int kADXL345_SPI = 1; + int kADXL345_I2C = 2; + + int kCommand_Scheduler = 1; + + int kSmartDashboard_Instance = 1; + } /** * Report the usage of a resource of interest.
* - *
- *$ - * @param resource one of the values in the tResourceType above (max value - * 51).
+ *

Original signature: uint32_t report(tResourceType, uint8_t, uint8_t, const + * char*) + * + * @param resource one of the values in the tResourceType above (max value 51).
* @param instanceNumber an index that identifies the resource instance.
- * @param context an optional additional context number for some cases (such - * as module number). Set to 0 to omit.
- * @param feature a string to be included describing features in use on a - * specific resource. Setting the same resource more than once allows - * you to change the feature string.
- * Original signature : - * uint32_t report(tResourceType, uint8_t, uint8_t, const char*) + * @param context an optional additional context number for some cases (such as module + * number). Set to 0 to omit.
+ * @param feature a string to be included describing features in use on a specific + * resource. Setting the same resource more than once allows you to change + * the feature string. */ public static native int FRCNetworkCommunicationUsageReportingReport(byte resource, - byte instanceNumber, byte context, String feature); + byte instanceNumber, + byte context, + String feature); public static native void setNewDataSem(long mutexId); @@ -179,6 +193,7 @@ public class FRCNetworkCommunicationsLibrary extends JNIWrapper { private static native int NativeHALGetControlWord(); + @SuppressWarnings("JavadocMethod") public static HALControlWord HALGetControlWord() { int word = NativeHALGetControlWord(); return new HALControlWord((word & 1) != 0, ((word >> 1) & 1) != 0, ((word >> 2) & 1) != 0, @@ -187,6 +202,7 @@ public class FRCNetworkCommunicationsLibrary extends JNIWrapper { private static native int NativeHALGetAllianceStation(); + @SuppressWarnings("JavadocMethod") public static HALAllianceStationID HALGetAllianceStation() { switch (NativeHALGetAllianceStation()) { case 0: @@ -216,7 +232,7 @@ public class FRCNetworkCommunicationsLibrary extends JNIWrapper { public static native int HALGetJoystickButtons(byte joystickNum, ByteBuffer count); public static native int HALSetJoystickOutputs(byte joystickNum, int outputs, short leftRumble, - short rightRumble); + short rightRumble); public static native int HALGetJoystickIsXbox(byte joystickNum); @@ -234,5 +250,7 @@ public class FRCNetworkCommunicationsLibrary extends JNIWrapper { public static native int HALSetErrorData(String error); - public static native int HALSendError(boolean isError, int errorCode, boolean isLVCode, String details, String location, String callStack, boolean printMsg); + public static native int HALSendError(boolean isError, int errorCode, boolean isLVCode, + String details, String location, String callStack, + boolean printMsg); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/HALControlWord.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/HALControlWord.java index c97c75847f..cb55b9d96a 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/HALControlWord.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/HALControlWord.java @@ -8,22 +8,22 @@ package edu.wpi.first.wpilibj.communication; /** - * A wrapper for the HALControlWord bitfield + * A wrapper for the HALControlWord bitfield. */ public class HALControlWord { - private boolean m_enabled; - private boolean m_autonomous; - private boolean m_test; - private boolean m_eStop; - private boolean m_fmsAttached; - private boolean m_dsAttached; + private final boolean m_enabled; + private final boolean m_autonomous; + private final boolean m_test; + private final boolean m_emergencyStop; + private final boolean m_fmsAttached; + private final boolean m_dsAttached; - protected HALControlWord(boolean enabled, boolean autonomous, boolean test, boolean eStop, - boolean fmsAttached, boolean dsAttached) { + protected HALControlWord(boolean enabled, boolean autonomous, boolean test, boolean emergencyStop, + boolean fmsAttached, boolean dsAttached) { m_enabled = enabled; m_autonomous = autonomous; m_test = test; - m_eStop = eStop; + m_emergencyStop = emergencyStop; m_fmsAttached = fmsAttached; m_dsAttached = dsAttached; } @@ -41,7 +41,7 @@ public class HALControlWord { } public boolean getEStop() { - return m_eStop; + return m_emergencyStop; } public boolean getFMSAttached() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/UsageReporting.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/UsageReporting.java index 2b7d15c185..d95fbd7ee7 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/UsageReporting.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/communication/UsageReporting.java @@ -9,17 +9,17 @@ package edu.wpi.first.wpilibj.communication; public class UsageReporting { - public static void report(int resource, int instanceNumber, int i) { - report(resource, instanceNumber, i, ""); + public static void report(int resource, int instanceNumber, int context) { + report(resource, instanceNumber, context, ""); } public static void report(int resource, int instanceNumber) { report(resource, instanceNumber, 0, ""); } - public static void report(int resource, int instanceNumber, int i, String string) { + public static void report(int resource, int instanceNumber, int context, String string) { FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationUsageReportingReport((byte) resource, - (byte) instanceNumber, (byte) i, string); + (byte) instanceNumber, (byte) context, string); } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java index 4cbb08a38e..3a68b207ff 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java @@ -12,40 +12,34 @@ import java.nio.LongBuffer; public class AnalogJNI extends JNIWrapper { /** - * native declaration : - * AthenaJava\target\native\include\HAL\Analog.h:58
- * enum values + * native declaration : AthenaJava\target\native\include\HAL\Analog.h:58
enum values */ - public static interface AnalogTriggerType { + public interface AnalogTriggerType { /** - * native declaration : - * AthenaJava\target\native\include\HAL\Analog.h:54 + * native declaration : AthenaJava\target\native\include\HAL\Analog.h:54 */ - public static final int kInWindow = 0; + int kInWindow = 0; /** - * native declaration : - * AthenaJava\target\native\include\HAL\Analog.h:55 + * native declaration : AthenaJava\target\native\include\HAL\Analog.h:55 */ - public static final int kState = 1; + int kState = 1; /** - * native declaration : - * AthenaJava\target\native\include\HAL\Analog.h:56 + * native declaration : AthenaJava\target\native\include\HAL\Analog.h:56 */ - public static final int kRisingPulse = 2; + int kRisingPulse = 2; /** - * native declaration : - * AthenaJava\target\native\include\HAL\Analog.h:57 + * native declaration : AthenaJava\target\native\include\HAL\Analog.h:57 */ - public static final int kFallingPulse = 3; - }; + int kFallingPulse = 3; + } - public static native long initializeAnalogInputPort(long port_pointer); + public static native long initializeAnalogInputPort(long portPointer); - public static native void freeAnalogInputPort(long port_pointer); + public static native void freeAnalogInputPort(long portPointer); - public static native long initializeAnalogOutputPort(long port_pointer); + public static native long initializeAnalogOutputPort(long portPointer); - public static native void freeAnalogOutputPort(long port_pointer); + public static native void freeAnalogOutputPort(long portPointer); public static native boolean checkAnalogModule(byte module); @@ -53,72 +47,72 @@ public class AnalogJNI extends JNIWrapper { public static native boolean checkAnalogOutputChannel(int pin); - public static native void setAnalogOutput(long port_pointer, double voltage); + public static native void setAnalogOutput(long portPointer, double voltage); - public static native double getAnalogOutput(long port_pointer); + public static native double getAnalogOutput(long portPointer); public static native void setAnalogSampleRate(double samplesPerSecond); public static native double getAnalogSampleRate(); - public static native void setAnalogAverageBits(long analog_port_pointer, int bits); + public static native void setAnalogAverageBits(long analogPortPointer, int bits); - public static native int getAnalogAverageBits(long analog_port_pointer); + public static native int getAnalogAverageBits(long analogPortPointer); - public static native void setAnalogOversampleBits(long analog_port_pointer, int bits); + public static native void setAnalogOversampleBits(long analogPortPointer, int bits); - public static native int getAnalogOversampleBits(long analog_port_pointer); + public static native int getAnalogOversampleBits(long analogPortPointer); - public static native short getAnalogValue(long analog_port_pointer); + public static native short getAnalogValue(long analogPortPointer); - public static native int getAnalogAverageValue(long analog_port_pointer); + public static native int getAnalogAverageValue(long analogPortPointer); - public static native int getAnalogVoltsToValue(long analog_port_pointer, double voltage); + public static native int getAnalogVoltsToValue(long analogPortPointer, double voltage); - public static native double getAnalogVoltage(long analog_port_pointer); + public static native double getAnalogVoltage(long analogPortPointer); - public static native double getAnalogAverageVoltage(long analog_port_pointer); + public static native double getAnalogAverageVoltage(long analogPortPointer); - public static native int getAnalogLSBWeight(long analog_port_pointer); + public static native int getAnalogLSBWeight(long analogPortPointer); - public static native int getAnalogOffset(long analog_port_pointer); + public static native int getAnalogOffset(long analogPortPointer); - public static native boolean isAccumulatorChannel(long analog_port_pointer); + public static native boolean isAccumulatorChannel(long analogPortPointer); - public static native void initAccumulator(long analog_port_pointer); + public static native void initAccumulator(long analogPortPointer); - public static native void resetAccumulator(long analog_port_pointer); + public static native void resetAccumulator(long analogPortPointer); - public static native void setAccumulatorCenter(long analog_port_pointer, int center); + public static native void setAccumulatorCenter(long analogPortPointer, int center); - public static native void setAccumulatorDeadband(long analog_port_pointer, int deadband); + public static native void setAccumulatorDeadband(long analogPortPointer, int deadband); - public static native long getAccumulatorValue(long analog_port_pointer); + public static native long getAccumulatorValue(long analogPortPointer); - public static native int getAccumulatorCount(long analog_port_pointer); + public static native int getAccumulatorCount(long analogPortPointer); - public static native void getAccumulatorOutput(long analog_port_pointer, LongBuffer value, - IntBuffer count); + public static native void getAccumulatorOutput(long analogPortPointer, LongBuffer value, + IntBuffer count); - public static native long initializeAnalogTrigger(long port_pointer, IntBuffer index); + public static native long initializeAnalogTrigger(long portPointer, IntBuffer index); - public static native void cleanAnalogTrigger(long analog_trigger_pointer); + public static native void cleanAnalogTrigger(long analogTriggerPointer); - public static native void setAnalogTriggerLimitsRaw(long analog_trigger_pointer, int lower, - int upper); + public static native void setAnalogTriggerLimitsRaw(long analogTriggerPointer, int lower, + int upper); - public static native void setAnalogTriggerLimitsVoltage(long analog_trigger_pointer, - double lower, double upper); + public static native void setAnalogTriggerLimitsVoltage(long analogTriggerPointer, + double lower, double upper); - public static native void setAnalogTriggerAveraged(long analog_trigger_pointer, - boolean useAveragedValue); + public static native void setAnalogTriggerAveraged(long analogTriggerPointer, + boolean useAveragedValue); - public static native void setAnalogTriggerFiltered(long analog_trigger_pointer, - boolean useFilteredValue); + public static native void setAnalogTriggerFiltered(long analogTriggerPointer, + boolean useFilteredValue); - public static native boolean getAnalogTriggerInWindow(long analog_trigger_pointer); + public static native boolean getAnalogTriggerInWindow(long analogTriggerPointer); - public static native boolean getAnalogTriggerTriggerState(long analog_trigger_pointer); + public static native boolean getAnalogTriggerTriggerState(long analogTriggerPointer); - public static native boolean getAnalogTriggerOutput(long analog_trigger_pointer, int type); + public static native boolean getAnalogTriggerOutput(long analogTriggerPointer, int type); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java index dd1ffe5cfb..6da630dc4a 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java @@ -7,19 +7,21 @@ package edu.wpi.first.wpilibj.hal; +@SuppressWarnings("MethodName") public class CanTalonJNI extends JNIWrapper { // Motion Profile status bits public static final int kMotionProfileFlag_ActTraj_IsValid = 0x1; - public static final int kMotionProfileFlag_HasUnderrun = 0x2; - public static final int kMotionProfileFlag_IsUnderrun = 0x4; - public static final int kMotionProfileFlag_ActTraj_IsLast = 0x8; + public static final int kMotionProfileFlag_HasUnderrun = 0x2; + public static final int kMotionProfileFlag_IsUnderrun = 0x4; + public static final int kMotionProfileFlag_ActTraj_IsLast = 0x8; public static final int kMotionProfileFlag_ActTraj_VelOnly = 0x10; /** - * Signal enumeration for generic signal access. - * Although every signal is enumerated, only use this for traffic that must be solicited. - * Use the auto generated getters/setters at bottom of this header as much as possible. + * Signal enumeration for generic signal access. Although every signal is enumerated, only use + * this for traffic that must be solicited. Use the auto generated getters/setters at bottom of + * this header as much as possible. */ + @SuppressWarnings("TypeName") public enum param_t { eProfileParamSlot0_P(1), eProfileParamSlot0_I(2), @@ -115,118 +117,227 @@ public class CanTalonJNI extends JNIWrapper { eReserved120(120), eLegacyControlMode(121); + @SuppressWarnings("MemberName") public final int value; - private param_t(int value) { + + param_t(int value) { this.value = value; } } - public static native long new_CanTalonSRX(int deviceNumber, int controlPeriodMs, int enablePeriodMs); + public static native long new_CanTalonSRX(int deviceNumber, int controlPeriodMs, + int enablePeriodMs); + public static native long new_CanTalonSRX(int deviceNumber, int controlPeriodMs); + public static native long new_CanTalonSRX(int deviceNumber); + public static native long new_CanTalonSRX(); + public static native void delete_CanTalonSRX(long handle); - public static native void GetMotionProfileStatus(long handle, Object canTalon, Object motionProfileStatus); + public static native void GetMotionProfileStatus(long handle, Object canTalon, + Object motionProfileStatus); public static native void Set(long handle, double value); + public static native void SetParam(long handle, int paramEnum, double value); + public static native void RequestParam(long handle, int paramEnum); + public static native double GetParamResponse(long handle, int paramEnum); + public static native int GetParamResponseInt32(long handle, int paramEnum); + public static native void SetPgain(long handle, int slotIdx, double gain); + public static native void SetIgain(long handle, int slotIdx, double gain); + public static native void SetDgain(long handle, int slotIdx, double gain); + public static native void SetFgain(long handle, int slotIdx, double gain); + public static native void SetIzone(long handle, int slotIdx, int zone); + public static native void SetCloseLoopRampRate(long handle, int slotIdx, int closeLoopRampRate); + public static native void SetVoltageCompensationRate(long handle, double voltagePerMs); + public static native void SetSensorPosition(long handle, int pos); + public static native void SetForwardSoftLimit(long handle, int forwardLimit); + public static native void SetReverseSoftLimit(long handle, int reverseLimit); + public static native void SetForwardSoftEnable(long handle, int enable); + public static native void SetReverseSoftEnable(long handle, int enable); + public static native double GetPgain(long handle, int slotIdx); + public static native double GetIgain(long handle, int slotIdx); + public static native double GetDgain(long handle, int slotIdx); + public static native double GetFgain(long handle, int slotIdx); + public static native int GetIzone(long handle, int slotIdx); + public static native int GetCloseLoopRampRate(long handle, int slotIdx); + public static native double GetVoltageCompensationRate(long handle); + public static native int GetForwardSoftLimit(long handle); + public static native int GetReverseSoftLimit(long handle); + public static native int GetForwardSoftEnable(long handle); + public static native int GetReverseSoftEnable(long handle); + public static native int GetPulseWidthRiseToFallUs(long handle); + public static native int IsPulseWidthSensorPresent(long handle); + public static native void SetModeSelect2(long handle, int modeSelect, int demand); + public static native void SetStatusFrameRate(long handle, int frameEnum, int periodMs); + public static native void ClearStickyFaults(long handle); + public static native void ChangeMotionControlFramePeriod(long handle, int periodMs); + public static native void ClearMotionProfileTrajectories(long handle); + public static native int GetMotionProfileTopLevelBufferCount(long handle); + public static native boolean IsMotionProfileTopLevelBufferFull(long handle); - public static native void PushMotionProfileTrajectory(long handle, int targPos, int targVel, int profileSlotSelect, int timeDurMs, int velOnly, int isLastPoint, int zeroPos); + + public static native void PushMotionProfileTrajectory(long handle, int targPos, int targVel, + int profileSlotSelect, int timeDurMs, + int velOnly, int isLastPoint, int zeroPos); + public static native void ProcessMotionProfileBuffer(long handle); + public static native int GetFault_OverTemp(long handle); + public static native int GetFault_UnderVoltage(long handle); + public static native int GetFault_ForLim(long handle); + public static native int GetFault_RevLim(long handle); + public static native int GetFault_HardwareFailure(long handle); + public static native int GetFault_ForSoftLim(long handle); + public static native int GetFault_RevSoftLim(long handle); + public static native int GetStckyFault_OverTemp(long handle); + public static native int GetStckyFault_UnderVoltage(long handle); + public static native int GetStckyFault_ForLim(long handle); + public static native int GetStckyFault_RevLim(long handle); + public static native int GetStckyFault_ForSoftLim(long handle); + public static native int GetStckyFault_RevSoftLim(long handle); + public static native int GetAppliedThrottle(long handle); + public static native int GetCloseLoopErr(long handle); + public static native int GetFeedbackDeviceSelect(long handle); + public static native int GetModeSelect(long handle); + public static native int GetLimitSwitchEn(long handle); + public static native int GetLimitSwitchClosedFor(long handle); + public static native int GetLimitSwitchClosedRev(long handle); + public static native int GetSensorPosition(long handle); + public static native int GetSensorVelocity(long handle); + public static native double GetCurrent(long handle); + public static native int GetBrakeIsEnabled(long handle); + public static native int GetEncPosition(long handle); + public static native int GetEncVel(long handle); + public static native int GetEncIndexRiseEvents(long handle); + public static native int GetQuadApin(long handle); + public static native int GetQuadBpin(long handle); + public static native int GetQuadIdxpin(long handle); + public static native int GetAnalogInWithOv(long handle); + public static native int GetAnalogInVel(long handle); + public static native double GetTemp(long handle); + public static native double GetBatteryV(long handle); + public static native int GetResetCount(long handle); + public static native int GetResetFlags(long handle); + public static native int GetFirmVers(long handle); + public static native int GetPulseWidthPosition(long handle); + public static native int GetPulseWidthVelocity(long handle); + public static native int GetPulseWidthRiseToRiseUs(long handle); + public static native int GetActTraj_IsValid(long handle); + public static native int GetActTraj_ProfileSlotSelect(long handle); + public static native int GetActTraj_VelOnly(long handle); + public static native int GetActTraj_IsLast(long handle); + public static native int GetOutputType(long handle); + public static native int GetHasUnderrun(long handle); + public static native int GetIsUnderrun(long handle); + public static native int GetNextID(long handle); + public static native int GetBufferIsFull(long handle); + public static native int GetCount(long handle); + public static native int GetActTraj_Velocity(long handle); + public static native int GetActTraj_Position(long handle); + public static native void SetDemand(long handle, int param); + public static native void SetOverrideLimitSwitchEn(long handle, int param); + public static native void SetFeedbackDeviceSelect(long handle, int param); + public static native void SetRevMotDuringCloseLoopEn(long handle, int param); + public static native void SetOverrideBrakeType(long handle, int param); + public static native void SetModeSelect(long handle, int param); + public static native void SetProfileSlotSelect(long handle, int param); + public static native void SetRampThrottle(long handle, int param); + public static native void SetRevFeedbackSensor(long handle, int param); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java index 6ebcb32617..36498dc2e5 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java @@ -12,27 +12,27 @@ public class CompressorJNI extends JNIWrapper { public static native boolean checkCompressorModule(byte module); - public static native boolean getCompressor(long pcm_pointer); + public static native boolean getCompressor(long pcmPointer); - public static native void setClosedLoopControl(long pcm_pointer, boolean value); + public static native void setClosedLoopControl(long pcmPointer, boolean value); - public static native boolean getClosedLoopControl(long pcm_pointer); + public static native boolean getClosedLoopControl(long pcmPointer); - public static native boolean getPressureSwitch(long pcm_pointer); + public static native boolean getPressureSwitch(long pcmPointer); - public static native float getCompressorCurrent(long pcm_pointer); + public static native float getCompressorCurrent(long pcmPointer); - public static native boolean getCompressorCurrentTooHighFault(long pcm_pointer); + public static native boolean getCompressorCurrentTooHighFault(long pcmPointer); - public static native boolean getCompressorCurrentTooHighStickyFault(long pcm_pointer); + public static native boolean getCompressorCurrentTooHighStickyFault(long pcmPointer); - public static native boolean getCompressorShortedStickyFault(long pcm_pointer); + public static native boolean getCompressorShortedStickyFault(long pcmPointer); - public static native boolean getCompressorShortedFault(long pcm_pointer); + public static native boolean getCompressorShortedFault(long pcmPointer); - public static native boolean getCompressorNotConnectedStickyFault(long pcm_pointer); + public static native boolean getCompressorNotConnectedStickyFault(long pcmPointer); - public static native boolean getCompressorNotConnectedFault(long pcm_pointer); + public static native boolean getCompressorNotConnectedFault(long pcmPointer); - public static native void clearAllPCMStickyFaults(long pcm_pointer); + public static native void clearAllPCMStickyFaults(long pcmPointer); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CounterJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CounterJNI.java index c10195f926..cb6cfc5fde 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CounterJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/CounterJNI.java @@ -12,54 +12,54 @@ import java.nio.IntBuffer; public class CounterJNI extends JNIWrapper { public static native long initializeCounter(int mode, IntBuffer index); - public static native void freeCounter(long counter_pointer); + public static native void freeCounter(long counterPointer); - public static native void setCounterAverageSize(long counter_pointer, int size); + public static native void setCounterAverageSize(long counterPointer, int size); - public static native void setCounterUpSource(long counter_pointer, int pin, - boolean analogTrigger); + public static native void setCounterUpSource(long counterPointer, int pin, + boolean analogTrigger); - public static native void setCounterUpSourceEdge(long counter_pointer, boolean risingEdge, - boolean fallingEdge); + public static native void setCounterUpSourceEdge(long counterPointer, boolean risingEdge, + boolean fallingEdge); - public static native void clearCounterUpSource(long counter_pointer); + public static native void clearCounterUpSource(long counterPointer); - public static native void setCounterDownSource(long counter_pointer, int pin, - boolean analogTrigger); + public static native void setCounterDownSource(long counterPointer, int pin, + boolean analogTrigger); - public static native void setCounterDownSourceEdge(long counter_pointer, boolean risingEdge, - boolean fallingEdge); + public static native void setCounterDownSourceEdge(long counterPointer, boolean risingEdge, + boolean fallingEdge); - public static native void clearCounterDownSource(long counter_pointer); + public static native void clearCounterDownSource(long counterPointer); - public static native void setCounterUpDownMode(long counter_pointer); + public static native void setCounterUpDownMode(long counterPointer); - public static native void setCounterExternalDirectionMode(long counter_pointer); + public static native void setCounterExternalDirectionMode(long counterPointer); - public static native void setCounterSemiPeriodMode(long counter_pointer, - boolean highSemiPeriod); + public static native void setCounterSemiPeriodMode(long counterPointer, + boolean highSemiPeriod); - public static native void setCounterPulseLengthMode(long counter_pointer, double threshold); + public static native void setCounterPulseLengthMode(long counterPointer, double threshold); - public static native int getCounterSamplesToAverage(long counter_pointer); + public static native int getCounterSamplesToAverage(long counterPointer); - public static native void setCounterSamplesToAverage(long counter_pointer, - int samplesToAverage); + public static native void setCounterSamplesToAverage(long counterPointer, + int samplesToAverage); - public static native void resetCounter(long counter_pointer); + public static native void resetCounter(long counterPointer); - public static native int getCounter(long counter_pointer); + public static native int getCounter(long counterPointer); - public static native double getCounterPeriod(long counter_pointer); + public static native double getCounterPeriod(long counterPointer); - public static native void setCounterMaxPeriod(long counter_pointer, double maxPeriod); + public static native void setCounterMaxPeriod(long counterPointer, double maxPeriod); - public static native void setCounterUpdateWhenEmpty(long counter_pointer, boolean enabled); + public static native void setCounterUpdateWhenEmpty(long counterPointer, boolean enabled); - public static native boolean getCounterStopped(long counter_pointer); + public static native boolean getCounterStopped(long counterPointer); - public static native boolean getCounterDirection(long counter_pointer); + public static native boolean getCounterDirection(long counterPointer); - public static native void setCounterReverseDirection(long counter_pointer, - boolean reverseDirection); + public static native void setCounterReverseDirection(long counterPointer, + boolean reverseDirection); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DIOJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DIOJNI.java index d9e2c4a316..bb6a5cfb50 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DIOJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DIOJNI.java @@ -7,24 +7,25 @@ package edu.wpi.first.wpilibj.hal; +@SuppressWarnings("AbbreviationAsWordInName") public class DIOJNI extends JNIWrapper { - public static native long initializeDigitalPort(long port_pointer); + public static native long initializeDigitalPort(long portPointer); - public static native void freeDigitalPort(long port_pointer); + public static native void freeDigitalPort(long portPointer); - public static native boolean allocateDIO(long digital_port_pointer, boolean input); + public static native boolean allocateDIO(long digitalPortPointer, boolean input); - public static native void freeDIO(long digital_port_pointer); + public static native void freeDIO(long digitalPortPointer); - public static native void setDIO(long digital_port_pointer, short value); + public static native void setDIO(long digitalPortPointer, short value); - public static native boolean getDIO(long digital_port_pointer); + public static native boolean getDIO(long digitalPortPointer); - public static native boolean getDIODirection(long digital_port_pointer); + public static native boolean getDIODirection(long digitalPortPointer); - public static native void pulse(long digital_port_pointer, double pulseLength); + public static native void pulse(long digitalPortPointer, double pulseLength); - public static native boolean isPulsing(long digital_port_pointer); + public static native boolean isPulsing(long digitalPortPointer); public static native boolean isAnyPulsing(); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DigitalGlitchFilterJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DigitalGlitchFilterJNI.java index 84c2e820d6..cf39a9537f 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DigitalGlitchFilterJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/DigitalGlitchFilterJNI.java @@ -8,8 +8,11 @@ package edu.wpi.first.wpilibj.hal; public class DigitalGlitchFilterJNI extends JNIWrapper { - public static native void setFilterSelect(long digital_port_pointer, int filter_index); - public static native int getFilterSelect(long digital_port_pointer); - public static native void setFilterPeriod(int filter_index, int fpga_cycles); - public static native int getFilterPeriod(int filter_index); + public static native void setFilterSelect(long digitalPortPointer, int filterIndex); + + public static native int getFilterSelect(long digitalPortPointer); + + public static native void setFilterPeriod(int filterIndex, int fpgaCycles); + + public static native int getFilterPeriod(int filterIndex); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java index c48c30194d..7c92636bd4 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java @@ -10,32 +10,34 @@ package edu.wpi.first.wpilibj.hal; import java.nio.IntBuffer; public class EncoderJNI extends JNIWrapper { - public static native long initializeEncoder(byte port_a_module, int port_a_pin, - boolean port_a_analog_trigger, byte port_b_module, int port_b_pin, boolean port_b_analog_trigger, - boolean reverseDirection, IntBuffer index); + public static native long initializeEncoder(byte portAModule, int portAPin, + boolean portAAnalogTrigger, byte portBModule, + int portBPin, boolean portBAnalogTrigger, + boolean reverseDirection, IntBuffer index); - public static native void freeEncoder(long encoder_pointer); + public static native void freeEncoder(long encoderPointer); - public static native void resetEncoder(long encoder_pointer); + public static native void resetEncoder(long encoderPointer); - public static native int getEncoder(long encoder_pointer); + public static native int getEncoder(long encoderPointer); - public static native double getEncoderPeriod(long encoder_pointer); + public static native double getEncoderPeriod(long encoderPointer); - public static native void setEncoderMaxPeriod(long encoder_pointer, double maxPeriod); + public static native void setEncoderMaxPeriod(long encoderPointer, double maxPeriod); - public static native boolean getEncoderStopped(long encoder_pointer); + public static native boolean getEncoderStopped(long encoderPointer); - public static native boolean getEncoderDirection(long encoder_pointer); + public static native boolean getEncoderDirection(long encoderPointer); - public static native void setEncoderReverseDirection(long encoder_pointer, - boolean reverseDirection); + public static native void setEncoderReverseDirection(long encoderPointer, + boolean reverseDirection); - public static native void setEncoderSamplesToAverage(long encoder_pointer, - int samplesToAverage); + public static native void setEncoderSamplesToAverage(long encoderPointer, + int samplesToAverage); - public static native int getEncoderSamplesToAverage(long encoder_pointer); + public static native int getEncoderSamplesToAverage(long encoderPointer); - public static native void setEncoderIndexSource(long digital_port, int pin, - boolean analogTrigger, boolean activeHigh, boolean edgeSensitive); + public static native void setEncoderIndexSource(long digitalPort, int pin, + boolean analogTrigger, boolean activeHigh, + boolean edgeSensitive); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/HALUtil.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/HALUtil.java index 757403e9f2..1e7ff0518d 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/HALUtil.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/HALUtil.java @@ -7,6 +7,7 @@ package edu.wpi.first.wpilibj.hal; +@SuppressWarnings("AbbreviationAsWordInName") public class HALUtil extends JNIWrapper { public static final int NULL_PARAMETER = -1005; public static final int SAMPLE_RATE_TOO_HIGH = 1001; @@ -33,7 +34,7 @@ public class HALUtil extends JNIWrapper { public static native void deleteMultiWait(long sem); - public static native void takeMultiWait(long sem, long m); + public static native void takeMultiWait(long sem, long ms); public static native short getFPGAVersion(); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/I2CJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/I2CJNI.java index d6b9dc8aa9..13d99e5e03 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/I2CJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/I2CJNI.java @@ -9,16 +9,17 @@ package edu.wpi.first.wpilibj.hal; import java.nio.ByteBuffer; +@SuppressWarnings("AbbreviationAsWordInName") public class I2CJNI extends JNIWrapper { public static native void i2CInitialize(byte port); public static native int i2CTransaction(byte port, byte address, ByteBuffer dataToSend, - byte sendSize, ByteBuffer dataReceived, byte receiveSize); + byte sendSize, ByteBuffer dataReceived, byte receiveSize); public static native int i2CWrite(byte port, byte address, ByteBuffer dataToSend, byte sendSize); public static native int i2CRead(byte port, byte address, ByteBuffer dataRecieved, - byte receiveSize); + byte receiveSize); public static native void i2CClose(byte port); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java index b653eba07f..dbe630f541 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java @@ -10,29 +10,30 @@ package edu.wpi.first.wpilibj.hal; public class InterruptJNI extends JNIWrapper { public interface InterruptJNIHandlerFunction { void apply(int interruptAssertedMask, Object param); - }; + } public static native long initializeInterrupts(int interruptIndex, boolean watcher); - public static native void cleanInterrupts(long interrupt_pointer); + public static native void cleanInterrupts(long interruptPointer); - public static native int waitForInterrupt(long interrupt_pointer, double timeout, - boolean ignorePrevious); + public static native int waitForInterrupt(long interruptPointer, double timeout, + boolean ignorePrevious); - public static native void enableInterrupts(long interrupt_pointer); + public static native void enableInterrupts(long interruptPointer); - public static native void disableInterrupts(long interrupt_pointer); + public static native void disableInterrupts(long interruptPointer); - public static native double readRisingTimestamp(long interrupt_pointer); + public static native double readRisingTimestamp(long interruptPointer); - public static native double readFallingTimestamp(long interrupt_pointer); + public static native double readFallingTimestamp(long interruptPointer); - public static native void requestInterrupts(long interrupt_pointer, byte routing_module, - int routing_pin, boolean routing_analog_trigger); + public static native void requestInterrupts(long interruptPointer, byte routingModule, + int routingPin, boolean routingAnalogTrigger); - public static native void attachInterruptHandler(long interrupt_pointer, - InterruptJNIHandlerFunction handler, Object param); + public static native void attachInterruptHandler(long interruptPointer, + InterruptJNIHandlerFunction handler, + Object param); - public static native void setInterruptUpSourceEdge(long interrupt_pointer, boolean risingEdge, - boolean fallingEdge); + public static native void setInterruptUpSourceEdge(long interruptPointer, boolean risingEdge, + boolean fallingEdge); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java index 5852951be9..56f1c14cdc 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java @@ -8,9 +8,9 @@ package edu.wpi.first.wpilibj.hal; import java.io.File; +import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; -import java.io.FileOutputStream; // // base class for all JNI wrappers @@ -18,6 +18,7 @@ import java.io.FileOutputStream; public class JNIWrapper { static boolean libraryLoaded = false; static File jniLibrary = null; + static { try { if (!libraryLoaded) { @@ -62,5 +63,5 @@ public class JNIWrapper { public static native long getPort(byte pin); - public static native void freePort(long port_pointer); + public static native void freePort(long portPointer); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java index 25e146ebd0..6276072024 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java @@ -7,18 +7,15 @@ package edu.wpi.first.wpilibj.hal; -import java.lang.Runtime; - /** * The NotifierJNI class directly wraps the C++ HAL Notifier. * - * This class is not meant for direct use by teams. Instead, the - * edu.wpi.first.wpilibj.Notifier class, which corresponds to the C++ Notifier - * class, should be used. + *

This class is not meant for direct use by teams. Instead, the edu.wpi.first.wpilibj.Notifier + * class, which corresponds to the C++ Notifier class, should be used. */ public class NotifierJNI extends JNIWrapper { /** - * Callback function + * Callback function. */ public interface NotifierJNIHandlerFunction { void apply(long curTime); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PDPJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PDPJNI.java index 7f11c8ea06..6bd7cfc65a 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PDPJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PDPJNI.java @@ -7,6 +7,7 @@ package edu.wpi.first.wpilibj.hal; +@SuppressWarnings("AbbreviationAsWordInName") public class PDPJNI extends JNIWrapper { public static native void initializePDP(int module); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PWMJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PWMJNI.java index c4c50dc7ad..50286599e2 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PWMJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/PWMJNI.java @@ -7,18 +7,19 @@ package edu.wpi.first.wpilibj.hal; +@SuppressWarnings("AbbreviationAsWordInName") public class PWMJNI extends DIOJNI { - public static native boolean allocatePWMChannel(long digital_port_pointer); + public static native boolean allocatePWMChannel(long digitalPortPointer); - public static native void freePWMChannel(long digital_port_pointer); + public static native void freePWMChannel(long digitalPortPointer); - public static native void setPWM(long digital_port_pointer, short value); + public static native void setPWM(long digitalPortPointer, short value); - public static native short getPWM(long digital_port_pointer); + public static native short getPWM(long digitalPortPointer); - public static native void latchPWMZero(long digital_port_pointer); + public static native void latchPWMZero(long digitalPortPointer); - public static native void setPWMPeriodScale(long digital_port_pointer, int squelchMask); + public static native void setPWMPeriodScale(long digitalPortPointer, int squelchMask); public static native long allocatePWM(); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/RelayJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/RelayJNI.java index f8445ece10..0162a96a04 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/RelayJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/RelayJNI.java @@ -8,11 +8,11 @@ package edu.wpi.first.wpilibj.hal; public class RelayJNI extends DIOJNI { - public static native void setRelayForward(long digital_port_pointer, boolean on); + public static native void setRelayForward(long digitalPortPointer, boolean on); - public static native void setRelayReverse(long digital_port_pointer, boolean on); + public static native void setRelayReverse(long digitalPortPointer, boolean on); - public static native boolean getRelayForward(long digital_port_pointer); + public static native boolean getRelayForward(long digitalPortPointer); - public static native boolean getRelayReverse(long digital_port_pointer); + public static native boolean getRelayReverse(long digitalPortPointer); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SPIJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SPIJNI.java index de8c1cb852..683011d1f0 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SPIJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SPIJNI.java @@ -11,11 +11,12 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; +@SuppressWarnings("AbbreviationAsWordInName") public class SPIJNI extends JNIWrapper { public static native void spiInitialize(byte port); public static native int spiTransaction(byte port, ByteBuffer dataToSend, - ByteBuffer dataReceived, byte size); + ByteBuffer dataReceived, byte size); public static native int spiWrite(byte port, ByteBuffer dataToSend, byte sendSize); @@ -25,16 +26,16 @@ public class SPIJNI extends JNIWrapper { public static native void spiSetSpeed(byte port, int speed); - public static native void spiSetOpts(byte port, int msb_first, int sample_on_trailing, - int clk_idle_high); + public static native void spiSetOpts(byte port, int msbFirst, int sampleOnTrailing, + int clkIdleHigh); public static native void spiSetChipSelectActiveHigh(byte port); public static native void spiSetChipSelectActiveLow(byte port); - public static native void spiInitAccumulator(byte port, int period, int cmd, - byte xferSize, int validMask, int validValue, byte dataShift, - byte dataSize, boolean isSigned, boolean bigEndian); + public static native void spiInitAccumulator(byte port, int period, int cmd, byte xferSize, + int validMask, int validValue, byte dataShift, + byte dataSize, boolean isSigned, boolean bigEndian); public static native void spiFreeAccumulator(byte port); @@ -53,5 +54,5 @@ public class SPIJNI extends JNIWrapper { public static native double spiGetAccumulatorAverage(byte port); public static native void spiGetAccumulatorOutput(byte port, LongBuffer value, - IntBuffer count); + IntBuffer count); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java index 61cc9b862a..3d8845c361 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java @@ -10,7 +10,7 @@ package edu.wpi.first.wpilibj.hal; public class SolenoidJNI extends JNIWrapper { public static native long initializeSolenoidPort(long portPointer); - public static native void freeSolenoidPort(long port_pointer); + public static native void freeSolenoidPort(long portPointer); public static native long getPortWithModule(byte module, byte channel); @@ -20,11 +20,11 @@ public class SolenoidJNI extends JNIWrapper { public static native byte getAllSolenoids(long port); - public static native int getPCMSolenoidBlackList(long pcm_pointer); + public static native int getPCMSolenoidBlackList(long pcmPointer); - public static native boolean getPCMSolenoidVoltageStickyFault(long pcm_pointer); + public static native boolean getPCMSolenoidVoltageStickyFault(long pcmPointer); - public static native boolean getPCMSolenoidVoltageFault(long pcm_pointer); + public static native boolean getPCMSolenoidVoltageFault(long pcmPointer); - public static native void clearAllPCMStickyFaults(long pcm_pointer); + public static native void clearAllPCMStickyFaults(long pcmPointer); } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/BinaryImage.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/BinaryImage.java index 4b89ab5d5e..e7e6b1eca9 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/BinaryImage.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/BinaryImage.java @@ -7,18 +7,20 @@ package edu.wpi.first.wpilibj.image; -import edu.wpi.first.wpilibj.util.SortedVector; import com.ni.vision.NIVision; +import edu.wpi.first.wpilibj.util.SortedVector; + /** * An image where each pixel is treated as either on or off. * * @author dtjones */ public class BinaryImage extends MonoImage { - private int numParticles = -1; + private int m_numParticles = -1; - BinaryImage() throws NIVisionException {} + BinaryImage() throws NIVisionException { + } BinaryImage(BinaryImage sourceImage) { super(sourceImage); @@ -30,25 +32,27 @@ public class BinaryImage extends MonoImage { * @return The number of particles */ public int getNumberParticles() throws NIVisionException { - if (numParticles < 0) - numParticles = NIVision.imaqCountParticles(image, 1); - return numParticles; + if (m_numParticles < 0) { + m_numParticles = NIVision.imaqCountParticles(image, 1); + } + return m_numParticles; } private class ParticleSizeReport { - final int index; - final double size; + final int m_index; + final double m_size; public ParticleSizeReport(int index) throws NIVisionException { - if ((!(index < BinaryImage.this.getNumberParticles())) || index < 0) + if ((!(index < BinaryImage.this.getNumberParticles())) || index < 0) { throw new IndexOutOfBoundsException(); - this.index = index; - size = ParticleAnalysisReport.getParticleToImagePercent(BinaryImage.this, index); + } + m_index = index; + m_size = ParticleAnalysisReport.getParticleToImagePercent(BinaryImage.this, index); } public ParticleAnalysisReport getParticleAnalysisReport() throws NIVisionException { - return new ParticleAnalysisReport(BinaryImage.this, index); + return new ParticleAnalysisReport(BinaryImage.this, m_index); } } @@ -59,47 +63,50 @@ public class BinaryImage extends MonoImage { * @return The ParticleAnalysisReport for the particle at the given index */ public ParticleAnalysisReport getParticleAnalysisReport(int index) throws NIVisionException { - if (!(index < getNumberParticles())) + if (!(index < getNumberParticles())) { throw new IndexOutOfBoundsException(); + } return new ParticleAnalysisReport(this, index); } /** - * Gets all the particle analysis reports ordered from largest area to - * smallest. + * Gets all the particle analysis reports ordered from largest area to smallest. * * @param size The number of particles to return * @return An array of ParticleReports from largest area to smallest */ public ParticleAnalysisReport[] getOrderedParticleAnalysisReports(int size) throws NIVisionException { - if (size > getNumberParticles()) + if (size > getNumberParticles()) { size = getNumberParticles(); + } ParticleSizeReport[] reports = new ParticleSizeReport[size]; SortedVector sorter = new SortedVector(new SortedVector.Comparator() { public int compare(Object object1, Object object2) { ParticleSizeReport p1 = (ParticleSizeReport) object1; ParticleSizeReport p2 = (ParticleSizeReport) object2; - if (p1.size < p2.size) + if (p1.m_size < p2.m_size) { return -1; - else if (p1.size > p2.size) + } else if (p1.m_size > p2.m_size) { return 1; + } return 0; } }); - for (int i = 0; i < getNumberParticles(); i++) + for (int i = 0; i < getNumberParticles(); i++) { sorter.addElement(new ParticleSizeReport(i)); + } sorter.setSize(size); sorter.copyInto(reports); ParticleAnalysisReport[] finalReports = new ParticleAnalysisReport[reports.length]; - for (int i = 0; i < finalReports.length; i++) + for (int i = 0; i < finalReports.length; i++) { finalReports[i] = reports[i].getParticleAnalysisReport(); + } return finalReports; } /** - * Gets all the particle analysis reports ordered from largest area to - * smallest. + * Gets all the particle analysis reports ordered from largest area to smallest. * * @return An array of ParticleReports from largest are to smallest */ @@ -107,7 +114,7 @@ public class BinaryImage extends MonoImage { return getOrderedParticleAnalysisReports(getNumberParticles()); } - + @SuppressWarnings({"summaryjavadoc", "javadocmethod"}) public void write(String fileName) throws NIVisionException { NIVision.RGBValue colorTable = new NIVision.RGBValue(0, 0, 255, 0); try { @@ -118,15 +125,14 @@ public class BinaryImage extends MonoImage { } /** - * removeSmallObjects filters particles based on their size. The algorithm - * erodes the image a specified number of times and keeps the particles from - * the original image that remain in the eroded image. + * removeSmallObjects filters particles based on their m_size. The algorithm erodes the image a + * specified number of times and keeps the particles from the original image that remain in the + * eroded image. * - * @param connectivity8 true to use connectivity-8 or false for connectivity-4 - * to determine whether particles are touching. For more information - * about connectivity, see Chapter 9, Binary Morphology, in the NI - * Vision Concepts manual. - * @param erosions the number of erosions to perform + * @param connectivity8 true to use connectivity-8 or false for connectivity-4 to determine + * whether particles are touching. For more information about connectivity, + * see Chapter 9, Binary Morphology, in the NI Vision Concepts manual. + * @param erosions the number of erosions to perform * @return a BinaryImage after applying the filter */ public BinaryImage removeSmallObjects(boolean connectivity8, int erosions) @@ -139,15 +145,14 @@ public class BinaryImage extends MonoImage { } /** - * removeLargeObjects filters particles based on their size. The algorithm - * erodes the image a specified number of times and discards the particles - * from the original image that remain in the eroded image. + * removeLargeObjects filters particles based on their m_size. The algorithm erodes the image a + * specified number of times and discards the particles from the original image that remain in the + * eroded image. * - * @param connectivity8 true to use connectivity-8 or false for connectivity-4 - * to determine whether particles are touching. For more information - * about connectivity, see Chapter 9, Binary Morphology, in the NI - * Vision Concepts manual. - * @param erosions the number of erosions to perform + * @param connectivity8 true to use connectivity-8 or false for connectivity-4 to determine + * whether particles are touching. For more information about connectivity, + * see Chapter 9, Binary Morphology, in the NI Vision Concepts manual. + * @param erosions the number of erosions to perform * @return a BinaryImage after applying the filter */ public BinaryImage removeLargeObjects(boolean connectivity8, int erosions) @@ -158,12 +163,14 @@ public class BinaryImage extends MonoImage { return result; } + @SuppressWarnings({"summaryjavadoc", "javadocmethod"}) public BinaryImage convexHull(boolean connectivity8) throws NIVisionException { BinaryImage result = new BinaryImage(); NIVision.imaqConvexHull(result.image, image, connectivity8 ? 1 : 0); return result; } + @SuppressWarnings({"summaryjavadoc", "javadocmethod"}) public BinaryImage particleFilter(NIVision.ParticleFilterCriteria2[] criteria) throws NIVisionException { BinaryImage result = new BinaryImage(); diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ColorImage.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ColorImage.java index 03beaea2b9..158c01ab9d 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ColorImage.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ColorImage.java @@ -25,7 +25,7 @@ public abstract class ColorImage extends ImageBase { } private BinaryImage threshold(NIVision.ColorMode colorMode, int low1, int high1, int low2, - int high2, int low3, int high3) throws NIVisionException { + int high2, int low3, int high3) throws NIVisionException { BinaryImage res = new BinaryImage(); NIVision.Range range1 = new NIVision.Range(low1, high1); NIVision.Range range2 = new NIVision.Range(low2, high2); @@ -39,73 +39,69 @@ public abstract class ColorImage extends ImageBase { } /** - * Return a mask of the areas of the image that fall within the given ranges - * for color values + * Return a mask of the areas of the image that fall within the given ranges for color values * - * @param redLow The lower red limit. - * @param redHigh The upper red limit. - * @param greenLow The lower green limit. + * @param redLow The lower red limit. + * @param redHigh The upper red limit. + * @param greenLow The lower green limit. * @param greenHigh The upper green limit. - * @param blueLow The lower blue limit. - * @param blueHigh The upper blue limit. + * @param blueLow The lower blue limit. + * @param blueHigh The upper blue limit. * @return A BinaryImage masking the areas which match the given thresholds. */ public BinaryImage thresholdRGB(int redLow, int redHigh, int greenLow, int greenHigh, - int blueLow, int blueHigh) throws NIVisionException { + int blueLow, int blueHigh) throws NIVisionException { return threshold(NIVision.ColorMode.RGB, redLow, redHigh, greenLow, greenHigh, blueLow, blueHigh); } /** - * Return a mask of the areas of the image that fall within the given ranges - * for color values + * Return a mask of the areas of the image that fall within the given ranges for color values * - * @param hueLow The lower hue limit. - * @param hueHigh The upper hue limit. - * @param saturationLow The lower saturation limit. + * @param hueLow The lower hue limit. + * @param hueHigh The upper hue limit. + * @param saturationLow The lower saturation limit. * @param saturationHigh The upper saturation limit. - * @param luminenceLow The lower luminence limit. - * @param luminenceHigh The upper luminence limit. + * @param luminenceLow The lower luminence limit. + * @param luminenceHigh The upper luminence limit. * @return A BinaryImage masking the areas which match the given thresholds. */ public BinaryImage thresholdHSL(int hueLow, int hueHigh, int saturationLow, int saturationHigh, - int luminenceLow, int luminenceHigh) throws NIVisionException { + int luminenceLow, int luminenceHigh) throws NIVisionException { return threshold(NIVision.ColorMode.HSL, hueLow, hueHigh, saturationLow, saturationHigh, luminenceLow, luminenceHigh); } /** - * Return a mask of the areas of the image that fall within the given ranges - * for color values + * Return a mask of the areas of the image that fall within the given ranges for color values * - * @param hueLow The lower hue limit. - * @param hueHigh The upper hue limit. - * @param saturationLow The lower saturation limit. + * @param hueLow The lower hue limit. + * @param hueHigh The upper hue limit. + * @param saturationLow The lower saturation limit. * @param saturationHigh The upper saturation limit. - * @param valueHigh The lower value limit. - * @param valueLow The upper value limit. + * @param valueHigh The lower value limit. + * @param valueLow The upper value limit. * @return A BinaryImage masking the areas which match the given thresholds. */ public BinaryImage thresholdHSV(int hueLow, int hueHigh, int saturationLow, int saturationHigh, - int valueLow, int valueHigh) throws NIVisionException { + int valueLow, int valueHigh) throws NIVisionException { return threshold(NIVision.ColorMode.HSV, hueLow, hueHigh, saturationLow, saturationHigh, valueLow, valueHigh); } /** - * Return a mask of the areas of the image that fall within the given ranges - * for color values + * Return a mask of the areas of the image that fall within the given ranges for color values * - * @param hueLow The lower hue limit. - * @param hueHigh The upper hue limit. - * @param saturationLow The lower saturation limit. + * @param hueLow The lower hue limit. + * @param hueHigh The upper hue limit. + * @param saturationLow The lower saturation limit. * @param saturationHigh The upper saturation limit. - * @param intansityLow The lower intensity limit. - * @param intensityHigh The upper intensity limit. + * @param intansityLow The lower intensity limit. + * @param intensityHigh The upper intensity limit. * @return A BinaryImage masking the areas which match the given thresholds. */ public BinaryImage thresholdHSI(int hueLow, int hueHigh, int saturationLow, int saturationHigh, - int intansityLow, int intensityHigh) throws NIVisionException { + int intansityLow, int intensityHigh) throws NIVisionException { return threshold(NIVision.ColorMode.HSI, hueLow, hueHigh, saturationLow, saturationHigh, intansityLow, intensityHigh); } @@ -141,8 +137,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the green color plane from the image when represented in RGB color - * space. + * Get the green color plane from the image when represented in RGB color space. * * @return The green color plane from the image. */ @@ -151,8 +146,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the blue color plane from the image when represented in RGB color - * space. + * Get the blue color plane from the image when represented in RGB color space. * * @return The blue color plane from the image. */ @@ -188,8 +182,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the saturation color plane from the image when represented in HSL color - * space. + * Get the saturation color plane from the image when represented in HSL color space. * * @return The saturation color plane from the image. */ @@ -198,8 +191,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the saturation color plane from the image when represented in HSV color - * space. + * Get the saturation color plane from the image when represented in HSV color space. * * @return The saturation color plane from the image. */ @@ -208,8 +200,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the saturation color plane from the image when represented in HSI color - * space. + * Get the saturation color plane from the image when represented in HSI color space. * * @return The saturation color plane from the image. */ @@ -218,8 +209,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the luminance color plane from the image when represented in HSL color - * space. + * Get the luminance color plane from the image when represented in HSL color space. * * @return The luminance color plane from the image. */ @@ -228,8 +218,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the value color plane from the image when represented in HSV color - * space. + * Get the value color plane from the image when represented in HSV color space. * * @return The value color plane from the image. */ @@ -238,8 +227,7 @@ public abstract class ColorImage extends ImageBase { } /** - * Get the intensity color plane from the image when represented in HSI color - * space. + * Get the intensity color plane from the image when represented in HSI color space. * * @return The intensity color plane from the image. */ @@ -266,9 +254,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the red color plane from the image when represented in RGB color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. + * Set the red color plane from the image when represented in RGB color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -278,9 +266,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the green color plane from the image when represented in RGB color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the green color plane from the image when represented in RGB color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -290,9 +278,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the blue color plane from the image when represented in RGB color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the blue color plane from the image when represented in RGB color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -302,9 +290,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the hue color plane from the image when represented in HSL color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. + * Set the hue color plane from the image when represented in HSL color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -314,9 +302,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the hue color plane from the image when represented in HSV color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. + * Set the hue color plane from the image when represented in HSV color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -326,9 +314,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the hue color plane from the image when represented in HSI color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. + * Set the hue color plane from the image when represented in HSI color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -338,9 +326,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the saturation color plane from the image when represented in HSL color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the saturation color plane from the image when represented in HSL color space. This does + * not create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -350,9 +338,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the saturation color plane from the image when represented in HSV color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the saturation color plane from the image when represented in HSV color space. This does + * not create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -362,9 +350,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the saturation color plane from the image when represented in HSI color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the saturation color plane from the image when represented in HSI color space. This does + * not create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -374,9 +362,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the luminance color plane from the image when represented in HSL color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the luminance color plane from the image when represented in HSL color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -386,9 +374,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the value color plane from the image when represented in HSV color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the value color plane from the image when represented in HSV color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -398,9 +386,9 @@ public abstract class ColorImage extends ImageBase { } /** - * Set the intensity color plane from the image when represented in HSI color - * space. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Set the intensity color plane from the image when represented in HSI color space. This does not + * create a new image, but modifies this one instead. Create a copy before hand if you need to + * continue using the original. * * @param plane The MonoImage representing the new color plane. * @return The resulting image. @@ -410,10 +398,10 @@ public abstract class ColorImage extends ImageBase { } /** - * Calculates the histogram of each plane of a color image and redistributes - * pixel values across the desired range while maintaining pixel value - * groupings. This does not create a new image, but modifies this one instead. - * Create a copy before hand if you need to continue using the original. + * Calculates the histogram of each plane of a color image and redistributes pixel values across + * the desired range while maintaining pixel value groupings. This does not create a new image, + * but modifies this one instead. Create a copy before hand if you need to continue using the + * original. * * @return The modified image. */ @@ -423,11 +411,10 @@ public abstract class ColorImage extends ImageBase { } /** - * Calculates the histogram of each plane of a color image and redistributes - * pixel values across the desired range while maintaining pixel value - * groupings for the Luminance plane only. This does not create a new image, - * but modifies this one instead. Create a copy before hand if you need to - * continue using the original. + * Calculates the histogram of each plane of a color image and redistributes pixel values across + * the desired range while maintaining pixel value groupings for the Luminance plane only. This + * does not create a new image, but modifies this one instead. Create a copy before hand if you + * need to continue using the original. * * @return The modified image. */ diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/HSLImage.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/HSLImage.java index afa487f3f1..7d7f7c385e 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/HSLImage.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/HSLImage.java @@ -11,7 +11,7 @@ import com.ni.vision.NIVision; /** * A color image represented in HSL color space at 3 bytes per pixel. - *$ + * * @author dtjones */ public class HSLImage extends ColorImage { @@ -29,7 +29,7 @@ public class HSLImage extends ColorImage { /** * Create a new image by loading a file. - *$ + * * @param fileName The path of the file to load. */ public HSLImage(String fileName) throws NIVisionException { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ImageBase.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ImageBase.java index d90fc0dd32..1dbc13b091 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ImageBase.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ImageBase.java @@ -12,14 +12,15 @@ import com.ni.vision.NIVision.Image; /** * Class representing a generic image. - *$ + * * @author dtjones */ public abstract class ImageBase { /** - * Pointer to the image memory + * Pointer to the image memory. */ + @SuppressWarnings("MemberName") public final Image image; static final int DEFAULT_BORDER_SIZE = 3; @@ -28,10 +29,9 @@ public abstract class ImageBase { } /** - * Creates a new image pointing to the same data as the source image. The - * imgae data is not copied, it is just referenced by both objects. Freeing - * one will free both. - *$ + * Creates a new image pointing to the same data as the source image. The imgae data is not + * copied, it is just referenced by both objects. Freeing one will free both. + * * @param sourceImage The image to reference */ ImageBase(ImageBase sourceImage) { @@ -41,8 +41,8 @@ public abstract class ImageBase { /** * Write the image to a file. * - * Supported extensions: .aipd or .apd AIPD .bmp BMP .jpg or .jpeg JPEG .jp2 - * JPEG2000 .png PNG .tif or .tiff TIFF + *

Supported extensions: .aipd or .apd AIPD .bmp BMP .jpg or .jpeg JPEG .jp2 JPEG2000 .png PNG + * .tif or .tiff TIFF * * @param fileName The path to write the image to. */ @@ -61,7 +61,7 @@ public abstract class ImageBase { /** * Get the height of the image in pixels. - *$ + * * @return The height of the image. */ public int getHeight() throws NIVisionException { @@ -70,7 +70,7 @@ public abstract class ImageBase { /** * Get the width of the image in pixels. - *$ + * * @return The width of the image. */ public int getWidth() throws NIVisionException { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/MonoImage.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/MonoImage.java index d71a1dabfa..da9f7ef039 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/MonoImage.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/MonoImage.java @@ -8,15 +8,15 @@ package edu.wpi.first.wpilibj.image; import com.ni.vision.NIVision; -import com.ni.vision.NIVision.EllipseDescriptor; import com.ni.vision.NIVision.CurveOptions; -import com.ni.vision.NIVision.ShapeDetectionOptions; -import com.ni.vision.NIVision.ROI; import com.ni.vision.NIVision.DetectEllipsesResult; +import com.ni.vision.NIVision.EllipseDescriptor; +import com.ni.vision.NIVision.ROI; +import com.ni.vision.NIVision.ShapeDetectionOptions; /** * A grey scale image represented at a byte per pixel. - *$ + * * @author dtjones */ public class MonoImage extends ImageBase { @@ -33,10 +33,11 @@ public class MonoImage extends ImageBase { } public DetectEllipsesResult detectEllipses(EllipseDescriptor ellipseDescriptor, - CurveOptions curveOptions, ShapeDetectionOptions shapeDetectionOptions, ROI roi) - throws NIVisionException { - return NIVision.imaqDetectEllipses(image, ellipseDescriptor, curveOptions, - shapeDetectionOptions, roi); + CurveOptions curveOptions, + ShapeDetectionOptions shapeDetectionOptions, + ROI roi) throws NIVisionException { + return NIVision + .imaqDetectEllipses(image, ellipseDescriptor, curveOptions, shapeDetectionOptions, roi); } public DetectEllipsesResult detectEllipses(EllipseDescriptor ellipseDescriptor) diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/NIVisionException.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/NIVisionException.java index d034107caa..c92d6582cd 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/NIVisionException.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/NIVisionException.java @@ -8,25 +8,25 @@ package edu.wpi.first.wpilibj.image; /** - * Exception class which looks up nivision error codes - *$ + * Exception class which looks up nivision error codes. + * * @author dtjones */ +@SuppressWarnings("all") public class NIVisionException extends Exception { /** * Create a new NIVisionException. - *$ - * @param msg The message to pass with the exception describing what caused - * it. + * + * @param msg The message to pass with the exception describing what caused it. */ public NIVisionException(String msg) { super(msg); } /** - * Create a new vision exception - *$ + * Create a new vision exception. + * * @param errorCode the bad status code */ public NIVisionException(int errorCode) { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java index 3abac25c35..a9eb5ed324 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java @@ -11,7 +11,7 @@ import com.ni.vision.NIVision; /** * Class to store commonly used information about a particle. - *$ + * * @author dtjones */ public class ParticleAnalysisReport { @@ -19,45 +19,72 @@ public class ParticleAnalysisReport { /** * The height of the image in pixels. */ + @SuppressWarnings("membername") public final int imageHeight; /** * The width of the image in pixels. */ + @SuppressWarnings("membername") public final int imageWidth; /** - * X-coordinate of the point representing the average position of the total - * particle mass, assuming every point in the particle has a constant density + * X-coordinate of the point representing the average position of the total particle mass, + * assuming every point in the particle has a constant density. */ + @SuppressWarnings("membername") public final int center_mass_x; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_X /** - * Y-coordinate of the point representing the average position of the total - * particle mass, assuming every point in the particle has a constant density + * Y-coordinate of the point representing the average position of the total particle mass, + * assuming every point in the particle has a constant density. */ + @SuppressWarnings("membername") public final int center_mass_y; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_Y /** * Center of mass x value normalized to -1.0 to +1.0 range. */ + @SuppressWarnings("membername") public final double center_mass_x_normalized; /** * Center of mass y value normalized to -1.0 to +1.0 range. */ + @SuppressWarnings("membername") public final double center_mass_y_normalized; - /** Area of the particle */ + /** + * Area of the particle. + */ + @SuppressWarnings("membername") public final double particleArea; // MeasurementType: IMAQ_MT_AREA - /** Bounding Rectangle */ + /** + * Bounding Rectangle. + */ + @SuppressWarnings("membername") public final int boundingRectLeft; // left/top/width/height - /** Bounding Rectangle */ + /** + * Bounding Rectangle. + */ + @SuppressWarnings("membername") public final int boundingRectTop; - /** Bounding Rectangle */ + /** + * Bounding Rectangle. + */ + @SuppressWarnings("membername") public final int boundingRectWidth; - /** Bounding Rectangle */ + /** + * Bounding Rectangle. + */ + @SuppressWarnings("membername") public final int boundingRectHeight; - /** Percentage of the particle Area covering the Image Area. */ + /** + * Percentage of the particle Area covering the Image Area. + */ + @SuppressWarnings("membername") public final double particleToImagePercent; // MeasurementType: - // IMAQ_MT_AREA_BY_IMAGE_AREA - /** Percentage of the particle Area in relation to its Particle and Holes Area */ + // IMAQ_MT_AREA_BY_IMAGE_AREA + /** + * Percentage of the particle Area in relation to its Particle and Holes Area. + */ + @SuppressWarnings("membername") public final double particleQuality; // MeasurementType: - // IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA + // IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA ParticleAnalysisReport(BinaryImage image, int index) throws NIVisionException { imageHeight = image.getHeight(); @@ -99,7 +126,7 @@ public class ParticleAnalysisReport { /** * Get string representation of the particle analysis report. - *$ + * * @return A string representation of the particle analysis report. */ public String toString() { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/RGBImage.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/RGBImage.java index 947968c45c..a1289ea9e5 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/RGBImage.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/RGBImage.java @@ -11,7 +11,7 @@ import com.ni.vision.NIVision; /** * A color image represented in RGB color space at 3 bytes per pixel. - *$ + * * @author dtjones */ public class RGBImage extends ColorImage { @@ -29,7 +29,7 @@ public class RGBImage extends ColorImage { /** * Create a new image by loading a file. - *$ + * * @param fileName The path of the file to load. */ public RGBImage(String fileName) throws NIVisionException { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/package.html b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/package.html index aae5898de6..31be4fb546 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/package.html +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/image/package.html @@ -1,12 +1,14 @@ - + Image Processing Wrappers - - -Provides classes to access National Instrument's nivison library for machine vision enables automated image processing -for color identification, tracking and analysis. The full specification for the simplified FRC Vision programming -interface is in the FRC Vision API Specification document, which is in the -WindRiver\docs\extensions\FRC directory of the Wind River installation with this document. + + +Provides classes to access National Instrument's nivison library for machine vision enables +automated image processing for color identification, tracking and analysis. The full +specification for the simplified FRC Vision programming interface is in the FRC Vision API +Specification document, which is in the WindRiver\docs\extensions\FRC directory of the Wind River +installation with this document. + diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java index 92da9e4bf6..a1b79fbccf 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java @@ -12,19 +12,17 @@ import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Utility; /** - * Timer objects measure accumulated time in milliseconds. The timer object - * functions like a stopwatch. It can be started, stopped, and cleared. When the - * timer is running its value counts up in milliseconds. When stopped, the timer - * holds the current value. The implementation simply records the time when - * started and subtracts the current time whenever the value is requested. + * Timer objects measure accumulated time in milliseconds. The timer object functions like a + * stopwatch. It can be started, stopped, and cleared. When the timer is running its value counts + * up in milliseconds. When stopped, the timer holds the current value. The implementation simply + * records the time when started and subtracts the current time whenever the value is requested. */ public class HardwareTimer implements Timer.StaticInterface { /** - * Pause the thread for a specified time. Pause the execution of the thread - * for a specified period of time given in seconds. Motors will continue to - * run at their last assigned values, and sensors will continue to update. - * Only the task containing the wait will pause until the wait time is - * expired. + * Pause the thread for a specified time. Pause the execution of the thread for a specified period + * of time given in seconds. Motors will continue to run at their last assigned values, and + * sensors will continue to update. Only the task containing the wait will pause until the wait + * time is expired. * * @param seconds Length of time to pause */ @@ -32,13 +30,14 @@ public class HardwareTimer implements Timer.StaticInterface { public void delay(final double seconds) { try { Thread.sleep((long) (seconds * 1e3)); - } catch (final InterruptedException e) { + } catch (final InterruptedException ex) { + Thread.currentThread().interrupt(); } } /** - * Return the system clock time in seconds. Return the time from the FPGA - * hardware clock in seconds since the FPGA started. + * Return the system clock time in seconds. Return the time from the FPGA hardware clock in + * seconds since the FPGA started. * * @return Robot running time in seconds. */ @@ -63,8 +62,8 @@ public class HardwareTimer implements Timer.StaticInterface { private boolean m_running; /** - * Create a new timer object. Create a new timer object and reset the time - * to zero. The timer is initially not running and must be started. + * Create a new timer object. Create a new timer object and reset the time to zero. The timer is + * initially not running and must be started. */ public TimerImpl() { reset(); @@ -75,24 +74,23 @@ public class HardwareTimer implements Timer.StaticInterface { } /** - * Get the current time from the timer. If the clock is running it is - * derived from the current system clock the start time stored in the timer - * class. If the clock is not running, then return the time when it was last - * stopped. + * Get the current time from the timer. If the clock is running it is derived from the current + * system clock the start time stored in the timer class. If the clock is not running, then + * return the time when it was last stopped. * * @return Current time value for this timer in seconds */ public synchronized double get() { if (m_running) { - return ((double) ((getMsClock() - m_startTime) + m_accumulatedTime)) / 1000.0; + return ((getMsClock() - m_startTime) + m_accumulatedTime) / 1000.0; } else { return m_accumulatedTime; } } /** - * Reset the timer by setting the time to 0. Make the timer startTime the - * current time so new requests will be relative now + * Reset the timer by setting the time to 0. Make the timer start time the current time so new + * requests will be relative now */ public synchronized void reset() { m_accumulatedTime = 0; @@ -100,8 +98,8 @@ public class HardwareTimer implements Timer.StaticInterface { } /** - * Start the timer running. Just set the running flag to true indicating - * that all time requests should be relative to the system clock. + * Start the timer running. Just set the running flag to true indicating that all time + * requests should be relative to the system clock. */ public synchronized void start() { m_startTime = getMsClock(); @@ -109,9 +107,9 @@ public class HardwareTimer implements Timer.StaticInterface { } /** - * Stop the timer. This computes the time as of now and clears the running - * flag, causing all subsequent time requests to be read from the - * accumulated time rather than looking at the system clock. + * Stop the timer. This computes the time as of now and clears the running flag, causing all + * subsequent time requests to be read from the accumulated time rather than looking at the + * system clock. */ public synchronized void stop() { final double temp = get(); @@ -120,10 +118,9 @@ public class HardwareTimer implements Timer.StaticInterface { } /** - * Check if the period specified has passed and if it has, advance the start - * time by that period. This is useful to decide if it's time to do periodic - * work without drifting later by the time it took to get around to - * checking. + * Check if the period specified has passed and if it has, advance the start time by that + * period. This is useful to decide if it's time to do periodic work without drifting later by + * the time it took to get around to checking. * * @param period The period to check for (in seconds). * @return If the period has passed. diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/package.html b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/package.html index 54d1ca6a71..7696bf331e 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/package.html +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/package.html @@ -1,23 +1,25 @@ - + WPI Robotics library - - -The WPI Robotics library (WPILibJ) is a set of Java classes that interfaces to the hardware in the FRC -control system and your robot. There are classes to handle sensors, motors, the driver + + +The WPI Robotics library (WPILibJ) is a set of Java classes that interfaces to the hardware in the +FRC control system and your robot. There are classes to handle sensors, motors, the driver station, and a number of other utility functions like timing and field management. The library is designed to:

  • Deal with all the low level interfacing to these components so you can concentrate on -solving this yearÕs Òrobot problemÓ. This is a philosophical decision to let you focus -on the higher-level design of your robot rather than deal with the details of the -processor and the operating system.
  • + solving this yearÕs Òrobot problemÓ. This is a philosophical decision to let you focus + on the higher-level design of your robot rather than deal with the details of the + processor and the operating system. +
  • Understand everything at all levels by making the full source code of the library -available. You can study (and modify) the algorithms used by the gyro class for -oversampling and integration of the input signal or just ask the class for the current -robot heading. You can work at any level.
  • + available. You can study (and modify) the algorithms used by the gyro class for + oversampling and integration of the input signal or just ask the class for the current + robot heading. You can work at any level. +
- - \ No newline at end of file + + diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/AxisCamera.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/AxisCamera.java index ac8ca83142..5084e62298 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/AxisCamera.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/AxisCamera.java @@ -7,10 +7,6 @@ package edu.wpi.first.wpilibj.vision; -import edu.wpi.first.wpilibj.image.ColorImage; -import edu.wpi.first.wpilibj.image.HSLImage; -import edu.wpi.first.wpilibj.image.NIVisionException; - import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStream; @@ -18,16 +14,21 @@ import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; +import edu.wpi.first.wpilibj.Timer; +import edu.wpi.first.wpilibj.image.ColorImage; +import edu.wpi.first.wpilibj.image.HSLImage; +import edu.wpi.first.wpilibj.image.NIVisionException; + import static com.ni.vision.NIVision.Image; import static com.ni.vision.NIVision.Priv_ReadJPEGString_C; -import static edu.wpi.first.wpilibj.Timer.delay; /** - * Axis M1011 network camera + * Axis M1011 network camera. */ public class AxisCamera { public enum WhiteBalance { - kAutomatic, kHold, kFixedOutdoor1, kFixedOutdoor2, kFixedIndoor, kFixedFluorescent1, kFixedFluorescent2, + kAutomatic, kHold, kFixedOutdoor1, kFixedOutdoor2, kFixedIndoor, kFixedFluorescent1, + kFixedFluorescent2, } public enum ExposureControl { @@ -53,7 +54,7 @@ public class AxisCamera { private static final String[] kRotationStrings = {"0", "180",}; - private final static int kImageBufferAllocationIncrement = 1000; + private static final int kImageBufferAllocationIncrement = 1000; private String m_cameraHost; private Socket m_cameraSocket; @@ -78,19 +79,50 @@ public class AxisCamera { private boolean m_done = false; /** - * AxisCamera constructor + * AxisCamera constructor. * * @param cameraHost The host to find the camera at, typically an IP address */ public AxisCamera(String cameraHost) { m_cameraHost = cameraHost; - m_captureThread.start(); + + /* + Thread spawned by AxisCamera constructor to receive images from cam. + */ + final Thread captureThread = new Thread(() -> { + int consecutiveErrors = 0; + + // Loop on trying to setup the camera connection. This happens in a + // background + // thread so it shouldn't effect the operation of user programs. + while (!m_done) { + String requestString = + "GET /mjpg/video.mjpg HTTP/1.1\n" + "User-Agent: HTTPStreamClient\n" + + "Connection: Keep-Alive\n" + "Cache-Control: no-cache\n" + + "Authorization: Basic RlJDOkZSQw==\n\n"; + + try { + m_cameraSocket = AxisCamera.this.createCameraSocket(requestString); + AxisCamera.this.readImagesFromCamera(); + consecutiveErrors = 0; + } catch (IOException ex) { + consecutiveErrors++; + + if (consecutiveErrors > 5) { + ex.printStackTrace(); + } + } + + Timer.delay(0.5); + } + }); + captureThread.start(); } /** - * Return true if the latest image from the camera has not been retrieved by - * calling GetImage() yet. - *$ + * Return true if the latest image from the camera has not been retrieved by calling GetImage() + * yet. + * * @return true if the image has not been retrieved yet. */ public boolean isFreshImage() { @@ -100,8 +132,7 @@ public class AxisCamera { /** * Get an image from the camera and store it in the provided image. * - * @param image The imaq image to store the result in. This must be an HSL or - * RGB image. + * @param image The imaq image to store the result in. This must be an HSL or RGB image. * @return true upon success, false on a failure */ public boolean getImage(Image image) { @@ -121,8 +152,7 @@ public class AxisCamera { /** * Get an image from the camera and store it in the provided image. * - * @param image The image to store the result in. This must be an HSL or RGB - * image + * @param image The image to store the result in. This must be an HSL or RGB image * @return true upon success, false on a failure */ public boolean getImage(ColorImage image) { @@ -130,8 +160,7 @@ public class AxisCamera { } /** - * Instantiate a new image object and fill it with the latest image from the - * camera. + * Instantiate a new image object and fill it with the latest image from the camera. * * @return a pointer to an HSLImage object */ @@ -160,6 +189,8 @@ public class AxisCamera { } /** + * The brightness. + * * @return The configured brightness of the camera images */ public int getBrightness() { @@ -183,6 +214,8 @@ public class AxisCamera { } /** + * The white balance. + * * @return The configured white balances of the camera images */ public WhiteBalance getWhiteBalance() { @@ -210,6 +243,8 @@ public class AxisCamera { } /** + * The current color level. + * * @return The configured color level of the camera images */ public int getColorLevel() { @@ -233,6 +268,8 @@ public class AxisCamera { } /** + * The current exposure control. + * * @return The configured exposure control mode of the camera */ public ExposureControl getExposureControl() { @@ -244,8 +281,8 @@ public class AxisCamera { /** * Request a change in the exposure priority of the camera. * - * @param exposurePriority Valid values are 0, 50, 100. 0 = Prioritize image - * quality 50 = None 100 = Prioritize frame rate + * @param exposurePriority Valid values are 0, 50, 100. 0 = Prioritize image quality 50 = None 100 + * = Prioritize frame rate */ public void writeExposurePriority(int exposurePriority) { if (exposurePriority != 0 && exposurePriority != 50 && exposurePriority != 100) { @@ -261,6 +298,8 @@ public class AxisCamera { } /** + * Gets the exposure priority. + * * @return The configured exposure priority of the camera */ public int getExposurePriority() { @@ -270,11 +309,10 @@ public class AxisCamera { } /** - * Write the maximum frames per second that the camera should send Write 0 to - * send as many as possible. + * Write the maximum frames per second that the camera should send Write 0 to send as many as + * possible. * - * @param maxFPS The number of frames the camera should send in a second, - * exposure permitting. + * @param maxFPS The number of frames the camera should send in a second, exposure permitting. */ public void writeMaxFPS(int maxFPS) { synchronized (m_parametersLock) { @@ -287,6 +325,8 @@ public class AxisCamera { } /** + * The max frames per second of the camera. + * * @return The configured maximum FPS of the camera */ public int getMaxFPS() { @@ -311,8 +351,10 @@ public class AxisCamera { } /** - * @return The configured resolution of the camera (not necessarily the same - * resolution as the most recent image, if it was changed recently.) + * Gets the configured resolution (not necessarily the same resolution as the most recent + * image, if it was changed recently). + * + * @return The configured resolution of the camera. */ public Resolution getResolution() { synchronized (m_parametersLock) { @@ -340,7 +382,9 @@ public class AxisCamera { } /** - * @return The configured compression level of the camera images + * Gets the configured compression level of the camera images. + * + * @return The configured compression level of the camera images. */ public int getCompression() { synchronized (m_parametersLock) { @@ -349,8 +393,8 @@ public class AxisCamera { } /** - * Write the rotation value to the camera. If you mount your camera upside - * down, use this to adjust the image for you. + * Write the motation value to the camera. If you mount your camera upside down, use this to + * adjust the image for you. * * @param rotation A value from the {@link Rotation} enum */ @@ -365,6 +409,8 @@ public class AxisCamera { } /** + * Gets the configured rotation mode of the camera. + * * @return The configured rotation mode of the camera */ public Rotation getRotation() { @@ -373,40 +419,6 @@ public class AxisCamera { } } - /** - * Thread spawned by AxisCamera constructor to receive images from cam - */ - private Thread m_captureThread = new Thread(new Runnable() { - @Override - public void run() { - int consecutiveErrors = 0; - - // Loop on trying to setup the camera connection. This happens in a - // background - // thread so it shouldn't effect the operation of user programs. - while (!m_done) { - String requestString = - "GET /mjpg/video.mjpg HTTP/1.1\n" + "User-Agent: HTTPStreamClient\n" - + "Connection: Keep-Alive\n" + "Cache-Control: no-cache\n" - + "Authorization: Basic RlJDOkZSQw==\n\n"; - - try { - m_cameraSocket = AxisCamera.this.createCameraSocket(requestString); - AxisCamera.this.readImagesFromCamera(); - consecutiveErrors = 0; - } catch (IOException e) { - consecutiveErrors++; - - if (consecutiveErrors > 5) { - e.printStackTrace(); - } - } - - delay(0.5); - } - } - }); - /** * This function actually reads the images from the camera. */ @@ -453,16 +465,14 @@ public class AxisCamera { } /** - * Send a request to the camera to set all of the parameters. This is called - * in the capture thread between each frame. This strategy avoids making lots - * of redundant HTTP requests, accounts for failed initial requests, and - * avoids blocking calls in the main thread unless necessary. - *

- * This method does nothing if no parameters have been modified since it last - * completely successfully. + * Send a request to the camera to set all of the parameters. This is called in the capture thread + * between each frame. This strategy avoids making lots of redundant HTTP requests, accounts for + * failed initial requests, and avoids blocking calls in the main thread unless necessary. * - * @return true if the stream should be restarted due to a - * parameter changing. + *

This method does nothing if no parameters have been modified since it last completely + * successfully. + * + * @return true if the stream should be restarted due to a parameter changing. */ private boolean writeParameters() { if (m_parametersDirty) { @@ -490,7 +500,7 @@ public class AxisCamera { request += "Authorization: Basic RlJDOkZSQw==\n\n"; try { - Socket socket = this.createCameraSocket(request); + Socket socket = createCameraSocket(request); socket.close(); m_parametersDirty = false; @@ -501,7 +511,7 @@ public class AxisCamera { } else { return false; } - } catch (IOException | NullPointerException e) { + } catch (IOException | NullPointerException ex) { return false; } @@ -511,11 +521,10 @@ public class AxisCamera { } /** - * Create a socket connected to camera Used to create a connection for reading - * images and setting parameters + * Create a socket connected to camera Used to create a connection for reading images and setting + * parameters * - * @param requestString The initial request string to send upon successful - * connection. + * @param requestString The initial request string to send upon successful connection. * @return The created socket */ private Socket createCameraSocket(String requestString) throws IOException { diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/USBCamera.java b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/USBCamera.java index ace3ffbed5..f40484c6ad 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/USBCamera.java +++ b/wpilibj/src/athena/java/edu/wpi/first/wpilibj/vision/USBCamera.java @@ -7,26 +7,25 @@ package edu.wpi.first.wpilibj.vision; +import com.ni.vision.NIVision; +import com.ni.vision.VisionException; + import java.nio.ByteBuffer; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.ni.vision.NIVision; -import com.ni.vision.VisionException; - -import static com.ni.vision.NIVision.Image; -import static edu.wpi.first.wpilibj.Timer.delay; +import edu.wpi.first.wpilibj.Timer; public class USBCamera { - public static String kDefaultCameraName = "cam0"; + public static final String kDefaultCameraName = "cam0"; - private static String ATTR_VIDEO_MODE = "AcquisitionAttributes::VideoMode"; - private static String ATTR_WB_MODE = "CameraAttributes::WhiteBalance::Mode"; - private static String ATTR_WB_VALUE = "CameraAttributes::WhiteBalance::Value"; - private static String ATTR_EX_MODE = "CameraAttributes::Exposure::Mode"; - private static String ATTR_EX_VALUE = "CameraAttributes::Exposure::Value"; - private static String ATTR_BR_MODE = "CameraAttributes::Brightness::Mode"; - private static String ATTR_BR_VALUE = "CameraAttributes::Brightness::Value"; + private static final String ATTR_VIDEO_MODE = "AcquisitionAttributes::VideoMode"; + private static final String ATTR_WB_MODE = "CameraAttributes::WhiteBalance::Mode"; + private static final String ATTR_WB_VALUE = "CameraAttributes::WhiteBalance::Value"; + private static final String ATTR_EX_MODE = "CameraAttributes::Exposure::Mode"; + private static final String ATTR_EX_VALUE = "CameraAttributes::Exposure::Value"; + private static final String ATTR_BR_MODE = "CameraAttributes::Brightness::Mode"; + private static final String ATTR_BR_VALUE = "CameraAttributes::Brightness::Value"; public class WhiteBalance { public static final int kFixedIndoor = 3000; @@ -38,7 +37,8 @@ public class USBCamera { private Pattern m_reMode = Pattern - .compile("(?[0-9]+)\\s*x\\s*(?[0-9]+)\\s+(?.*?)\\s+(?[0-9.]+)\\s*fps"); + .compile("(?[0-9]+)\\s*x\\s*(?[0-9]+)\\s+(?.*?)" + + "\\s+(?[0-9.]+)\\s*fps"); private String m_name = kDefaultCameraName; private int m_id = -1; @@ -63,54 +63,76 @@ public class USBCamera { openCamera(); } + /** + * Opens the camera. + */ public synchronized void openCamera() { - if (m_id != -1) + if (m_id != -1) { return; // Camera is already open + } for (int i = 0; i < 3; i++) { try { m_id = NIVision.IMAQdxOpenCamera(m_name, NIVision.IMAQdxCameraControlMode.CameraControlModeController); - } catch (VisionException e) { - if (i == 2) - throw e; - delay(2.0); + } catch (VisionException ex) { + if (i == 2) { + throw ex; + } + Timer.delay(2.0); continue; } break; } } + /** + * Closes the camera. + */ public synchronized void closeCamera() { - if (m_id == -1) + if (m_id == -1) { return; + } NIVision.IMAQdxCloseCamera(m_id); m_id = -1; } + /** + * Starts capturing images from the camera. + */ public synchronized void startCapture() { - if (m_id == -1 || m_active) + if (m_id == -1 || m_active) { return; + } NIVision.IMAQdxConfigureGrab(m_id); NIVision.IMAQdxStartAcquisition(m_id); m_active = true; } + /** + * Stops acquiring new images from the camera. + */ public synchronized void stopCapture() { - if (m_id == -1 || !m_active) + if (m_id == -1 || !m_active) { return; + } NIVision.IMAQdxStopAcquisition(m_id); NIVision.IMAQdxUnconfigureAcquisition(m_id); m_active = false; } + /** + * Updates the settings for the camera. + */ public synchronized void updateSettings() { boolean wasActive = m_active; // Stop acquistion, close and reopen camera - if (wasActive) + if (wasActive) { stopCapture(); - if (m_id != -1) + } + if (m_id != -1) { closeCamera(); + } openCamera(); // Video Mode @@ -118,44 +140,52 @@ public class USBCamera { NIVision.IMAQdxEnumItem foundMode = null; int foundFps = 1000; for (NIVision.IMAQdxEnumItem mode : enumerated.videoModeArray) { - Matcher m = m_reMode.matcher(mode.Name); - if (!m.matches()) + Matcher matcher = m_reMode.matcher(mode.Name); + if (!matcher.matches()) { continue; - if (Integer.parseInt(m.group("width")) != m_width) + } + if (Integer.parseInt(matcher.group("m_width")) != m_width) { continue; - if (Integer.parseInt(m.group("height")) != m_height) + } + if (Integer.parseInt(matcher.group("m_height")) != m_height) { continue; - double fps = Double.parseDouble(m.group("fps")); - if (fps < m_fps) + } + double fps = Double.parseDouble(matcher.group("fps")); + if (fps < m_fps) { continue; - if (fps > foundFps) + } + if (fps > foundFps) { continue; - String format = m.group("format"); + } + String format = matcher.group("format"); boolean isJpeg = format.equals("jpeg") || format.equals("JPEG"); - if ((m_useJpeg && !isJpeg) || (!m_useJpeg && isJpeg)) + if ((m_useJpeg && !isJpeg) || (!m_useJpeg && isJpeg)) { continue; + } foundMode = mode; foundFps = (int) fps; } if (foundMode != null) { System.out.println("found mode " + foundMode.Value + ": " + foundMode.Name); - if (foundMode.Value != enumerated.currentMode) + if (foundMode.Value != enumerated.currentMode) { NIVision.IMAQdxSetAttributeU32(m_id, ATTR_VIDEO_MODE, foundMode.Value); + } } // White Balance - if (m_whiteBalance == "auto") + if ("auto".equals(m_whiteBalance)) { NIVision.IMAQdxSetAttributeString(m_id, ATTR_WB_MODE, "Auto"); - else { + } else { NIVision.IMAQdxSetAttributeString(m_id, ATTR_WB_MODE, "Manual"); - if (m_whiteBalanceValue != -1) + if (m_whiteBalanceValue != -1) { NIVision.IMAQdxSetAttributeI64(m_id, ATTR_WB_VALUE, m_whiteBalanceValue); + } } // Exposure - if (m_exposure == "auto") + if ("auto".equals(m_exposure)) { NIVision.IMAQdxSetAttributeString(m_id, ATTR_EX_MODE, "AutoAperaturePriority"); - else { + } else { NIVision.IMAQdxSetAttributeString(m_id, ATTR_EX_MODE, "Manual"); if (m_exposureValue != -1) { long minv = NIVision.IMAQdxGetAttributeMinimumI64(m_id, ATTR_EX_VALUE); @@ -173,89 +203,124 @@ public class USBCamera { NIVision.IMAQdxSetAttributeI64(m_id, ATTR_BR_VALUE, val); // Restart acquisition - if (wasActive) + if (wasActive) { startCapture(); + } } + /** + * Sets the frames per second that the camera frames should be acquired at. + * + * @param fps The frames per second. + */ public synchronized void setFPS(int fps) { - if (fps != m_fps) { + if (m_fps != fps) { m_needSettingsUpdate = true; m_fps = fps; } } + /** + * Sets the size of the input of the USB camera. + * + * @param width The m_width of the camera input. + * @param height The m_height of the camera input. + */ public synchronized void setSize(int width, int height) { - if (width != m_width || height != m_height) { + if (m_width != width || m_height != height) { m_needSettingsUpdate = true; m_width = width; m_height = height; } } - /** Set the brightness, as a percentage (0-100). */ + /** + * Set the m_brightness, as a percentage (0-100). + */ public synchronized void setBrightness(int brightness) { - if (brightness > 100) + if (brightness > 100) { m_brightness = 100; - else if (brightness < 0) + } else if (brightness < 0) { m_brightness = 0; - else + } else { m_brightness = brightness; + } m_needSettingsUpdate = true; } - /** Get the brightness, as a percentage (0-100). */ + /** + * Get the m_brightness, as a percentage (0-100). + */ public synchronized int getBrightness() { return m_brightness; } - /** Set the white balance to auto. */ + /** + * Set the white balance to auto. + */ public synchronized void setWhiteBalanceAuto() { m_whiteBalance = "auto"; m_whiteBalanceValue = -1; m_needSettingsUpdate = true; } - /** Set the white balance to hold current. */ + /** + * Set the white balance to hold current. + */ public synchronized void setWhiteBalanceHoldCurrent() { m_whiteBalance = "manual"; m_whiteBalanceValue = -1; m_needSettingsUpdate = true; } - /** Set the white balance to manual, with specified color temperature. */ + /** + * Set the white balance to manual, with specified color temperature. + */ public synchronized void setWhiteBalanceManual(int value) { m_whiteBalance = "manual"; m_whiteBalanceValue = value; m_needSettingsUpdate = true; } - /** Set the exposure to auto aperature. */ + /** + * Set the m_exposure to auto aperature. + */ public synchronized void setExposureAuto() { m_exposure = "auto"; m_exposureValue = -1; m_needSettingsUpdate = true; } - /** Set the exposure to hold current. */ + /** + * Set the m_exposure to hold current. + */ public synchronized void setExposureHoldCurrent() { m_exposure = "manual"; m_exposureValue = -1; m_needSettingsUpdate = true; } - /** Set the exposure to manual, as a percentage (0-100). */ + /** + * Set the m_exposure to manual, as a percentage (0-100). + */ public synchronized void setExposureManual(int value) { m_exposure = "manual"; - if (value > 100) + if (value > 100) { m_exposureValue = 100; - else if (value < 0) + } else if (value < 0) { m_exposureValue = 0; - else + } else { m_exposureValue = value; - m_needSettingsUpdate = true; + m_needSettingsUpdate = true; + } } - public synchronized void getImage(Image image) { + /** + * Gets the image from the camera. + * + * @param image The image to store the data into + */ + public synchronized void getImage(NIVision.Image image) { if (m_needSettingsUpdate || m_useJpeg) { m_needSettingsUpdate = false; m_useJpeg = false; @@ -265,6 +330,11 @@ public class USBCamera { NIVision.IMAQdxGrab(m_id, image, 1); } + /** + * Gets the image data from the camera. + * + * @param data Where to put the data from the image + */ public synchronized void getImageData(ByteBuffer data) { if (m_needSettingsUpdate || !m_useJpeg) { m_needSettingsUpdate = false; @@ -279,28 +349,32 @@ public class USBCamera { } private static int getJpegSize(ByteBuffer data) { - if (data.get(0) != (byte) 0xff || data.get(1) != (byte) 0xd8) + if (data.get(0) != (byte) 0xff || data.get(1) != (byte) 0xd8) { throw new VisionException("invalid image"); + } int pos = 2; while (true) { try { - byte b = data.get(pos); - if (b != (byte) 0xff) + byte byteAtIndex = data.get(pos); + if (byteAtIndex != (byte) 0xff) { throw new VisionException("invalid image at pos " + pos + " (" + data.get(pos) + ")"); - b = data.get(pos + 1); - if (b == (byte) 0x01 || (b >= (byte) 0xd0 && b <= (byte) 0xd7)) // various + } + byteAtIndex = data.get(pos + 1); + if (byteAtIndex == (byte) 0x01 + || (byteAtIndex >= (byte) 0xd0 && byteAtIndex <= (byte) 0xd7)) { // various pos += 2; - else if (b == (byte) 0xd9) // EOI + } else if (byteAtIndex == (byte) 0xd9) { // EOI return pos + 2; - else if (b == (byte) 0xd8) // SOI + } else if (byteAtIndex == (byte) 0xd8) { // SOI throw new VisionException("invalid image"); - else if (b == (byte) 0xda) { // SOS + } else if (byteAtIndex == (byte) 0xda) { // SOS int len = ((data.get(pos + 2) & 0xff) << 8) | (data.get(pos + 3) & 0xff); pos += len + 2; // Find next marker. Skip over escaped and RST markers. while (data.get(pos) != (byte) 0xff || data.get(pos + 1) == (byte) 0x00 - || (data.get(pos + 1) >= (byte) 0xd0 && data.get(pos + 1) <= (byte) 0xd7)) + || (data.get(pos + 1) >= (byte) 0xd0 && data.get(pos + 1) <= (byte) 0xd7)) { pos += 1; + } } else { // various int len = ((data.get(pos + 2) & 0xff) << 8) | (data.get(pos + 3) & 0xff); pos += len + 2; diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/CircularBuffer.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/CircularBuffer.java index 719c2f5da8..6a10c81bd9 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/CircularBuffer.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/CircularBuffer.java @@ -8,24 +8,24 @@ package edu.wpi.first.wpilibj; /** - * This is a simple circular buffer so we don't need to "bucket brigade" copy - * old values. + * This is a simple circular buffer so we don't need to "bucket brigade" copy old values. */ public class CircularBuffer { private double[] m_data; private int m_front = 0; private int m_length = 0; + @SuppressWarnings("JavadocMethod") public CircularBuffer(int size) { m_data = new double[size]; - for (double i : m_data) { - i = 0.0; + for (int i = 0; i < m_data.length; i++) { + m_data[i] = 0.0; } } /** - * Push new value onto front of the buffer. The value at the back is - * overwritten if the buffer is full. + * Push new value onto front of the buffer. The value at the back is overwritten if the buffer is + * full. */ public void pushFront(double value) { if (m_data.length == 0) { @@ -42,8 +42,8 @@ public class CircularBuffer { } /** - * Push new value onto back of the buffer. The value at the front is - * overwritten if the buffer is full. + * Push new value onto back of the buffer. The value at the front is overwritten if the buffer is + * full. */ public void pushBack(double value) { if (m_data.length == 0) { @@ -91,6 +91,7 @@ public class CircularBuffer { return m_data[(m_front + m_length) % m_data.length]; } + @SuppressWarnings("JavadocMethod") public void reset() { for (double i : m_data) { i = 0.0; @@ -107,14 +108,14 @@ public class CircularBuffer { } /** - * Increment an index modulo the length of the m_data buffer + * Increment an index modulo the length of the m_data buffer. */ private int moduloInc(int index) { return (index + 1) % m_data.length; } /** - * Decrement an index modulo the length of the m_data buffer + * Decrement an index modulo the length of the m_data buffer. */ private int moduloDec(int index) { if (index == 0) { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Controller.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Controller.java index b3a840d1f9..37b55381c5 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Controller.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Controller.java @@ -1,13 +1,16 @@ -/* - * To change this template, choose Tools | Templates and open the template in - * the editor. - */ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + package edu.wpi.first.wpilibj; /** - * An interface for controllers. Controllers run control loops, the most command - * are PID controllers and there variants, but this includes anything that is - * controlling an actuator in a separate thread. + * An interface for controllers. Controllers run control loops, the most command are PID controllers + * and there variants, but this includes anything that is controlling an actuator in a separate + * thread. * * @author alex */ @@ -15,11 +18,10 @@ interface Controller { /** * Allows the control loop to run. */ - public void enable(); + void enable(); /** - * Stops the control loop from running until explicitly re-enabled by calling - * {@link #enable()}. + * Stops the control loop from running until explicitly re-enabled by calling {@link #enable()}. */ - public void disable(); + void disable(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GenericHID.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GenericHID.java index 385b8435f1..8b7fc62e56 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GenericHID.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GenericHID.java @@ -8,7 +8,7 @@ package edu.wpi.first.wpilibj; /** - * GenericHID Interface + * GenericHID Interface. */ public abstract class GenericHID { @@ -18,17 +18,18 @@ public abstract class GenericHID { public static class Hand { /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; static final int kLeft_val = 0; static final int kRight_val = 1; /** - * hand: left + * hand: left. */ public static final Hand kLeft = new Hand(kLeft_val); /** - * hand: right + * hand: right. */ public static final Hand kRight = new Hand(kRight_val); @@ -38,8 +39,8 @@ public abstract class GenericHID { } /** - * Get the x position of the HID - *$ + * Get the x position of the HID. + * * @return the x position of the HID */ public final double getX() { @@ -47,16 +48,16 @@ public abstract class GenericHID { } /** - * Get the x position of HID - *$ + * Get the x position of HID. + * * @param hand which hand, left or right * @return the x position */ public abstract double getX(Hand hand); /** - * Get the y position of the HID - *$ + * Get the y position of the HID. + * * @return the y position */ public final double getY() { @@ -64,16 +65,16 @@ public abstract class GenericHID { } /** - * Get the y position of the HID - *$ + * Get the y position of the HID. + * * @param hand which hand, left or right * @return the y position */ public abstract double getY(Hand hand); /** - * Get the z position of the HID - *$ + * Get the z position of the HID. + * * @return the z position */ public final double getZ() { @@ -81,38 +82,38 @@ public abstract class GenericHID { } /** - * Get the z position of the HID - *$ + * Get the z position of the HID. + * * @param hand which hand, left or right * @return the z position */ public abstract double getZ(Hand hand); /** - * Get the twist value - *$ + * Get the twist value. + * * @return the twist value */ public abstract double getTwist(); /** - * Get the throttle - *$ + * Get the throttle. + * * @return the throttle value */ public abstract double getThrottle(); /** - * Get the raw axis - *$ + * Get the raw axis. + * * @param which index of the axis * @return the raw value of the selected axis */ public abstract double getRawAxis(int which); /** - * Is the trigger pressed - *$ + * Is the trigger pressed. + * * @return true if pressed */ public final boolean getTrigger() { @@ -120,16 +121,16 @@ public abstract class GenericHID { } /** - * Is the trigger pressed - *$ + * Is the trigger pressed. + * * @param hand which hand * @return true if the trigger for the given hand is pressed */ public abstract boolean getTrigger(Hand hand); /** - * Is the top button pressed - *$ + * Is the top button pressed. + * * @return true if the top button is pressed */ public final boolean getTop() { @@ -137,16 +138,16 @@ public abstract class GenericHID { } /** - * Is the top button pressed - *$ + * Is the top button pressed. + * * @param hand which hand * @return true if hte top button for the given hand is pressed */ public abstract boolean getTop(Hand hand); /** - * Is the bumper pressed - *$ + * Is the bumper pressed. + * * @return true if the bumper is pressed */ public final boolean getBumper() { @@ -154,16 +155,16 @@ public abstract class GenericHID { } /** - * Is the bumper pressed - *$ + * Is the bumper pressed. + * * @param hand which hand * @return true if hte bumper is pressed */ public abstract boolean getBumper(Hand hand); /** - * Is the given button pressed - *$ + * Is the given button pressed. + * * @param button which button number * @return true if the button is pressed */ diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GyroBase.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GyroBase.java index 0b1bbf5e1d..0aef1c4526 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GyroBase.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/GyroBase.java @@ -8,57 +8,34 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.interfaces.Gyro; -import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * GyroBase is the common base class for Gyro implementations such as - * AnalogGyro. + * GyroBase is the common base class for Gyro implementations such as AnalogGyro. */ public abstract class GyroBase extends SensorBase implements Gyro, PIDSource, LiveWindowSendable { private PIDSourceType m_pidSource = PIDSourceType.kDisplacement; /** - * {@inheritDoc} - */ - public abstract void calibrate(); - - /** - * {@inheritDoc} - */ - public abstract void reset(); - - /** - * {@inheritDoc} - */ - public abstract double getAngle(); - - /** - * {@inheritDoc} - */ - public abstract double getRate(); - - /** - * Set which parameter of the gyro you are using as a process control - * variable. The Gyro class supports the rate and displacement parameters + * Set which parameter of the gyro you are using as a process control variable. The Gyro class + * supports the rate and displacement parameters * * @param pidSource An enum to select the parameter. */ + @Override public void setPIDSourceType(PIDSourceType pidSource) { m_pidSource = pidSource; } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_pidSource; } /** - * Get the output of the gyro for use with PIDControllers. May be the angle or - * rate depending on the set PIDSourceType + * Get the output of the gyro for use with PIDControllers. May be the angle or rate depending on + * the set PIDSourceType * * @return the output according to the gyro */ @@ -84,26 +61,18 @@ public abstract class GyroBase extends SensorBase implements Gyro, PIDSource, Li private ITable m_table; - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } - /** - * {@inheritDoc} - */ @Override public ITable getTable() { return m_table; } - /** - * {@inheritDoc} - */ @Override public void updateTable() { if (m_table != null) { @@ -111,15 +80,11 @@ public abstract class GyroBase extends SensorBase implements Gyro, PIDSource, Li } } - /** - * {@inheritDoc} - */ @Override - public void startLiveWindowMode() {} + public void startLiveWindowMode() { + } - /** - * {@inheritDoc} - */ @Override - public void stopLiveWindowMode() {} + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/HLUsageReporting.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/HLUsageReporting.java index 02a939802e..0db3e479be 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/HLUsageReporting.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/HLUsageReporting.java @@ -14,11 +14,13 @@ import edu.wpi.first.wpilibj.util.BaseSystemNotInitializedException; * * @author alex */ +@SuppressWarnings("JavadocMethod") public class HLUsageReporting { private static Interface impl; - public static void SetImplementation(Interface i) { - impl = i; + @SuppressWarnings("MethodName") + public static void SetImplementation(Interface implementation) { + impl = implementation; } public static void reportScheduler() { @@ -54,10 +56,13 @@ public class HLUsageReporting { } public static class Null implements Interface { - public void reportScheduler() {} + public void reportScheduler() { + } - public void reportPIDController(int num) {} + public void reportPIDController(int num) { + } - public void reportSmartDashboard() {} + public void reportSmartDashboard() { + } } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/MotorSafety.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/MotorSafety.java index 16e14b4265..69b5f50c9c 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/MotorSafety.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/MotorSafety.java @@ -8,11 +8,12 @@ package edu.wpi.first.wpilibj; /** + * Shuts off motors when their outputs aren't updated often enough. * * @author brad */ public interface MotorSafety { - public static final double DEFAULT_SAFETY_EXPIRATION = 0.1; + double DEFAULT_SAFETY_EXPIRATION = 0.1; void setExpiration(double timeout); diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/NamedSendable.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/NamedSendable.java index 0bc2e57030..6c41e8d98f 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/NamedSendable.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/NamedSendable.java @@ -9,15 +9,15 @@ package edu.wpi.first.wpilibj; /** - * The interface for sendable objects that gives the sendable a default name in - * the Smart Dashboard - * + * The interface for sendable objects that gives the sendable a default name in the Smart + * Dashboard. */ public interface NamedSendable extends Sendable { /** - * @return the name of the subtable of SmartDashboard that the Sendable object - * will use + * The name of the subtable. + * + * @return the name of the subtable of SmartDashboard that the Sendable object will use. */ - public String getName(); + String getName(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDController.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDController.java index 220cd59e1e..f3443c8555 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDController.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDController.java @@ -3,13 +3,13 @@ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ + package edu.wpi.first.wpilibj; -import java.util.TimerTask; import java.util.ArrayDeque; import java.util.Queue; +import java.util.TimerTask; -import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; @@ -18,30 +18,34 @@ import edu.wpi.first.wpilibj.util.BoundaryException; /** * Class implements a PID Control Loop. * - * Creates a separate thread which reads the given PIDSource and takes care of - * the integral calculations, as well as writing the given PIDOutput + *

Creates a separate thread which reads the given PIDSource and takes care of the integral + * calculations, as well as writing the given PIDOutput */ public class PIDController implements PIDInterface, LiveWindowSendable, Controller { public static final double kDefaultPeriod = .05; private static int instances = 0; + @SuppressWarnings("MemberName") private double m_P; // factor for "proportional" control + @SuppressWarnings("MemberName") private double m_I; // factor for "integral" control + @SuppressWarnings("MemberName") private double m_D; // factor for "derivative" control + @SuppressWarnings("MemberName") private double m_F; // factor for feedforward term private double m_maximumOutput = 1.0; // |maximum output| private double m_minimumOutput = -1.0; // |minimum output| private double m_maximumInput = 0.0; // maximum input - limit setpoint to this private double m_minimumInput = 0.0; // minimum input - limit setpoint to this - private boolean m_continuous = false; // do the endpoints wrap around? eg. - // Absolute encoder + // do the endpoints wrap around? eg. Absolute encoder + private boolean m_continuous = false; private boolean m_enabled = false; // is the pid controller enabled - private double m_prevError = 0.0; // the prior error (used to compute - // velocity) - private double m_totalError = 0.0; // the sum of the errors for use in the - // integral calc - private Tolerance m_tolerance; // the tolerance object used to check if on - // target + // the prior error (used to compute velocity) + private double m_prevError = 0.0; + // the sum of the errors for use in the integral calc + private double m_totalError = 0.0; + // the tolerance object used to check if on target + private Tolerance m_tolerance; private int m_bufLength = 1; private Queue m_buf; private double m_bufTotal = 0.0; @@ -58,14 +62,13 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll private boolean m_usingPercentTolerance; /** - * Tolerance is the type of tolerance used to specify if the PID controller is - * on target. + * Tolerance is the type of tolerance used to specify if the PID controller is on target. * - * The various implementations of this class such as PercentageTolerance and - * AbsoluteTolerance specify types of tolerance specifications to use. + *

The various implementations of this class such as PercentageTolerance and AbsoluteTolerance + * specify types of tolerance specifications to use. */ public interface Tolerance { - public boolean onTarget(); + boolean onTarget(); } /** @@ -79,28 +82,29 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } public class PercentageTolerance implements Tolerance { - double percentage; + private final double m_percentage; PercentageTolerance(double value) { - percentage = value; + m_percentage = value; } @Override public boolean onTarget() { - return isAvgErrorValid() && (Math.abs(getAvgError()) < percentage / 100 * (m_maximumInput - m_minimumInput)); + return isAvgErrorValid() && (Math.abs(getAvgError()) < m_percentage / 100 * (m_maximumInput + - m_minimumInput)); } } public class AbsoluteTolerance implements Tolerance { - double value; + private final double m_value; AbsoluteTolerance(double value) { - this.value = value; + m_value = value; } @Override public boolean onTarget() { - return isAvgErrorValid() && Math.abs(getAvgError()) < value; + return isAvgErrorValid() && Math.abs(getAvgError()) < m_value; } } @@ -123,19 +127,19 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll /** * Allocate a PID object with the given constants for P, I, D, and F - *$ - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient - * @param Kf the feed forward term + * + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient + * @param Kf the feed forward term * @param source The PIDSource object that is used to get values * @param output The PIDOutput object that is set to the output percentage - * @param period the loop time for doing calculations. This particularly - * effects calculations of the integral and differential terms. The - * default is 50ms. + * @param period the loop time for doing calculations. This particularly effects calculations of + * the integral and differential terms. The default is 50ms. */ + @SuppressWarnings("ParameterName") public PIDController(double Kp, double Ki, double Kd, double Kf, PIDSource source, - PIDOutput output, double period) { + PIDOutput output, double period) { if (source == null) { throw new NullPointerException("Null PIDSource was given"); @@ -163,58 +167,58 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll HLUsageReporting.reportPIDController(instances); m_tolerance = new NullTolerance(); - m_buf = new ArrayDeque(m_bufLength+1); + m_buf = new ArrayDeque(m_bufLength + 1); } /** * Allocate a PID object with the given constants for P, I, D and period - *$ - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient + * + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient * @param source the PIDSource object that is used to get values * @param output the PIDOutput object that is set to the output percentage - * @param period the loop time for doing calculations. This particularly - * effects calculations of the integral and differential terms. The - * default is 50ms. + * @param period the loop time for doing calculations. This particularly effects calculations of + * the integral and differential terms. The default is 50ms. */ + @SuppressWarnings("ParameterName") public PIDController(double Kp, double Ki, double Kd, PIDSource source, PIDOutput output, - double period) { + double period) { this(Kp, Ki, Kd, 0.0, source, output, period); } /** - * Allocate a PID object with the given constants for P, I, D, using a 50ms - * period. - *$ - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient + * Allocate a PID object with the given constants for P, I, D, using a 50ms period. + * + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient * @param source The PIDSource object that is used to get values * @param output The PIDOutput object that is set to the output percentage */ + @SuppressWarnings("ParameterName") public PIDController(double Kp, double Ki, double Kd, PIDSource source, PIDOutput output) { this(Kp, Ki, Kd, source, output, kDefaultPeriod); } /** - * Allocate a PID object with the given constants for P, I, D, using a 50ms - * period. - *$ - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient - * @param Kf the feed forward term + * Allocate a PID object with the given constants for P, I, D, using a 50ms period. + * + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient + * @param Kf the feed forward term * @param source The PIDSource object that is used to get values * @param output The PIDOutput object that is set to the output percentage */ + @SuppressWarnings("ParameterName") public PIDController(double Kp, double Ki, double Kd, double Kf, PIDSource source, - PIDOutput output) { + PIDOutput output) { this(Kp, Ki, Kd, Kf, source, output, kDefaultPeriod); } /** - * Free the PID object + * Free the PID object. */ public void free() { m_controlLoop.cancel(); @@ -224,14 +228,14 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll m_pidInput = null; m_controlLoop = null; } - if (this.table != null) - table.removeTableListener(listener); + if (m_table != null) { + m_table.removeTableListener(m_listener); + } } /** - * Read the input, calculate the output accordingly, and write to the output. - * This should only be called by the PIDTask and is created during - * initialization. + * Read the input, calculate the output accordingly, and write to the output. This should only be + * called by the PIDTask and is created during initialization. */ protected void calculate() { boolean enabled; @@ -251,7 +255,7 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll if (enabled) { double input; double result; - PIDOutput pidOutput = null; + final PIDOutput pidOutput; synchronized (this) { input = pidInput.pidGet(); } @@ -280,11 +284,10 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll m_totalError = m_maximumOutput / m_P; } - m_result = m_P * m_totalError + m_D * m_error + - calculateFeedForward(); + m_result = m_P * m_totalError + m_D * m_error + + calculateFeedForward(); } - } - else { + } else { if (m_I != 0) { double potentialIGain = (m_totalError + m_error) * m_I; if (potentialIGain < m_maximumOutput) { @@ -298,8 +301,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } } - m_result = m_P * m_error + m_I * m_totalError + - m_D * (m_error - m_prevError) + calculateFeedForward(); + m_result = m_P * m_error + m_I * m_totalError + + m_D * (m_error - m_prevError) + calculateFeedForward(); } m_prevError = m_error; @@ -325,25 +328,22 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Calculate the feed forward term + * Calculate the feed forward term. * - * Both of the provided feed forward calculations are velocity feed forwards. - * If a different feed forward calculation is desired, the user can override - * this function and provide his or her own. This function does no - * synchronization because the PIDController class only calls it in - * synchronized code, so be careful if calling it oneself. + *

Both of the provided feed forward calculations are velocity feed forwards. If a different + * feed forward calculation is desired, the user can override this function and provide his or + * her own. This function does no synchronization because the PIDController class only calls it + * in synchronized code, so be careful if calling it oneself. * - * If a velocity PID controller is being used, the F term should be set to 1 - * over the maximum setpoint for the output. If a position PID controller is - * being used, the F term should be set to 1 over the maximum speed for the - * output measured in setpoint units per this controller's update period (see - * the default period in this class's constructor). + *

If a velocity PID controller is being used, the F term should be set to 1 over the maximum + * setpoint for the output. If a position PID controller is being used, the F term should be set + * to 1 over the maximum speed for the output measured in setpoint units per this controller's + * update period (see the default period in this class's constructor). */ protected double calculateFeedForward() { if (m_pidInput.getPIDSourceType().equals(PIDSourceType.kRate)) { return m_F * getSetpoint(); - } - else { + } else { double temp = m_F * getDeltaSetpoint(); m_prevSetpoint = m_setpoint; m_setpointTimer.reset(); @@ -352,51 +352,53 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Set the PID Controller gain parameters. Set the proportional, integral, and - * differential coefficients. - *$ + * Set the PID Controller gain parameters. Set the proportional, integral, and differential + * coefficients. + * * @param p Proportional coefficient * @param i Integral coefficient * @param d Differential coefficient */ + @SuppressWarnings("ParameterName") public synchronized void setPID(double p, double i, double d) { m_P = p; m_I = i; m_D = d; - if (table != null) { - table.putNumber("p", p); - table.putNumber("i", i); - table.putNumber("d", d); + if (m_table != null) { + m_table.putNumber("p", p); + m_table.putNumber("i", i); + m_table.putNumber("d", d); } } /** - * Set the PID Controller gain parameters. Set the proportional, integral, and - * differential coefficients. - *$ + * Set the PID Controller gain parameters. Set the proportional, integral, and differential + * coefficients. + * * @param p Proportional coefficient * @param i Integral coefficient * @param d Differential coefficient * @param f Feed forward coefficient */ + @SuppressWarnings("ParameterName") public synchronized void setPID(double p, double i, double d, double f) { m_P = p; m_I = i; m_D = d; m_F = f; - if (table != null) { - table.putNumber("p", p); - table.putNumber("i", i); - table.putNumber("d", d); - table.putNumber("f", f); + if (m_table != null) { + m_table.putNumber("p", p); + m_table.putNumber("i", i); + m_table.putNumber("d", d); + m_table.putNumber("f", f); } } /** - * Get the Proportional coefficient - *$ + * Get the Proportional coefficient. + * * @return proportional coefficient */ public synchronized double getP() { @@ -404,8 +406,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Get the Integral coefficient - *$ + * Get the Integral coefficient. + * * @return integral coefficient */ public synchronized double getI() { @@ -413,8 +415,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Get the Differential coefficient - *$ + * Get the Differential coefficient. + * * @return differential coefficient */ public synchronized double getD() { @@ -422,8 +424,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Get the Feed forward coefficient - *$ + * Get the Feed forward coefficient. + * * @return feed forward coefficient */ public synchronized double getF() { @@ -431,9 +433,9 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Return the current PID result This is always centered on zero and - * constrained the the max and min outs - *$ + * Return the current PID result This is always centered on zero and constrained the the max and + * min outs. + * * @return the latest calculated output */ public synchronized double get() { @@ -441,24 +443,23 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Set the PID controller to consider the input to be continuous, Rather then - * using the max and min in as constraints, it considers them to be the same - * point and automatically calculates the shortest route to the setpoint. - *$ - * @param continuous Set to true turns on continuous, false turns off - * continuous + * Set the PID controller to consider the input to be continuous, Rather then using the max and + * min in as constraints, it considers them to be the same point and automatically calculates the + * shortest route to the setpoint. + * + * @param continuous Set to true turns on continuous, false turns off continuous */ public synchronized void setContinuous(boolean continuous) { m_continuous = continuous; } /** - * Set the PID controller to consider the input to be continuous, Rather then - * using the max and min in as constraints, it considers them to be the same - * point and automatically calculates the shortest route to the setpoint. + * Set the PID controller to consider the input to be continuous, Rather then using the max and + * min in as constraints, it considers them to be the same point and automatically calculates the + * shortest route to the setpoint. */ public synchronized void setContinuous() { - this.setContinuous(true); + setContinuous(true); } /** @@ -491,9 +492,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Set the setpoint for the PIDController - * Clears the queue for GetAvgError(). - *$ + * Set the setpoint for the PIDController Clears the queue for GetAvgError(). + * * @param setpoint the desired setpoint */ public synchronized void setSetpoint(double setpoint) { @@ -512,13 +512,14 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll m_buf.clear(); m_bufTotal = 0; - if (table != null) - table.putNumber("setpoint", m_setpoint); + if (m_table != null) { + m_table.putNumber("setpoint", m_setpoint); + } } /** - * Returns the current setpoint of the PIDController - *$ + * Returns the current setpoint of the PIDController. + * * @return the current setpoint */ public synchronized double getSetpoint() { @@ -526,8 +527,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Returns the change in setpoint over time of the PIDController - *$ + * Returns the change in setpoint over time of the PIDController. + * * @return the change in setpoint over time */ public synchronized double getDeltaSetpoint() { @@ -535,8 +536,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Returns the current difference of the input from the setpoint - *$ + * Returns the current difference of the input from the setpoint. + * * @return the current error */ public synchronized double getError() { @@ -545,8 +546,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Sets what type of input the PID controller will use - *$ + * Sets what type of input the PID controller will use. + * * @param pidSource the type of input */ void setPIDSourceType(PIDSourceType pidSource) { @@ -554,8 +555,8 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Returns the type of input the PID controller is using - *$ + * Returns the type of input the PID controller is using. + * * @return the PID controller input type */ PIDSourceType getPIDSourceType() { @@ -563,23 +564,24 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Returns the current difference of the error over the past few iterations. - * You can specify the number of iterations to average with - * setToleranceBuffer() (defaults to 1). getAvgError() is used for the - * onTarget() function. - *$ + * Returns the current difference of the error over the past few iterations. You can specify the + * number of iterations to average with setToleranceBuffer() (defaults to 1). getAvgError() is + * used for the onTarget() function. + * * @return the current average of the error */ public synchronized double getAvgError() { double avgError = 0; // Don't divide by zero. - if (m_buf.size() != 0) avgError = m_bufTotal / m_buf.size(); + if (m_buf.size() != 0) { + avgError = m_bufTotal / m_buf.size(); + } return avgError; } /** - * Returns whether or not any values have been collected. If no values - * have been collected, getAvgError is 0, which is invalid. + * Returns whether or not any values have been collected. If no values have been collected, + * getAvgError is 0, which is invalid. * * @return True if {@link #getAvgError()} is currently valid. */ @@ -588,12 +590,11 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Set the percentage error which is considered tolerable for use with - * OnTarget. (Input of 15.0 = 15 percent) - *$ + * Set the percentage error which is considered tolerable for use with OnTarget. (Input of 15.0 = + * 15 percent). + * * @param percent error which is tolerable - * @deprecated Use {@link #setPercentTolerance(double)} or - * {@link #setAbsoluteTolerance(double)} instead. + * @deprecated Use {@link #setPercentTolerance} or {@link #setAbsoluteTolerance} instead. */ @Deprecated public synchronized void setTolerance(double percent) { @@ -601,14 +602,13 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Set the PID tolerance using a Tolerance object. Tolerance can be specified - * as a percentage of the range or as an absolute value. The Tolerance object - * encapsulates those options in an object. Use it by creating the type of - * tolerance that you want to use: setTolerance(new + * Set the PID tolerance using a Tolerance object. Tolerance can be specified as a percentage of + * the range or as an absolute value. The Tolerance object encapsulates those options in an + * object. Use it by creating the type of tolerance that you want to use: setTolerance(new * PIDController.AbsoluteTolerance(0.1)) - *$ - * @param tolerance a tolerance object of the right type, e.g. - * PercentTolerance or AbsoluteTolerance + * + * @param tolerance a tolerance object of the right type, e.g. PercentTolerance or + * AbsoluteTolerance */ public void setTolerance(Tolerance tolerance) { m_tolerance = tolerance; @@ -616,18 +616,17 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll /** * Set the absolute error which is considered tolerable for use with OnTarget. - *$ - * @param absvalue absolute error which is tolerable in the units of the input - * object + * + * @param absvalue absolute error which is tolerable in the units of the input object */ public synchronized void setAbsoluteTolerance(double absvalue) { m_tolerance = new AbsoluteTolerance(absvalue); } /** - * Set the percentage error which is considered tolerable for use with - * OnTarget. (Input of 15.0 = 15 percent) - *$ + * Set the percentage error which is considered tolerable for use with OnTarget. (Input of 15.0 = + * 15 percent) + * * @param percentage percent error which is tolerable */ public synchronized void setPercentTolerance(double percentage) { @@ -635,12 +634,12 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Set the number of previous error samples to average for tolerancing. When - * determining whether a mechanism is on target, the user may want to use a - * rolling average of previous measurements instead of a precise position or - * velocity. This is useful for noisy sensors which return a few erroneous - * measurements when the mechanism is on target. However, the mechanism will - * not register as on target for at least the specified bufLength cycles. + * Set the number of previous error samples to average for tolerancing. When determining whether a + * mechanism is on target, the user may want to use a rolling average of previous measurements + * instead of a precise position or velocity. This is useful for noisy sensors which return a few + * erroneous measurements when the mechanism is on target. However, the mechanism will not + * register as on target for at least the specified bufLength cycles. + * * @param bufLength Number of previous cycles to average. */ public synchronized void setToleranceBuffer(int bufLength) { @@ -653,10 +652,9 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Return true if the error is within the percentage of the total input range, - * determined by setTolerance. This assumes that the maximum and minimum input - * were set using setInput. - *$ + * Return true if the error is within the percentage of the total input range, determined by + * setTolerance. This assumes that the maximum and minimum input were set using setInput. + * * @return true if the error is less than the tolerance */ public synchronized boolean onTarget() { @@ -664,28 +662,27 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll } /** - * Begin running the PIDController + * Begin running the PIDController. */ @Override public synchronized void enable() { m_enabled = true; - if (table != null) { - table.putBoolean("enabled", true); + if (m_table != null) { + m_table.putBoolean("enabled", true); } } /** - * Stop running the PIDController, this sets the output to zero before - * stopping. + * Stop running the PIDController, this sets the output to zero before stopping. */ @Override public synchronized void disable() { m_pidOutput.pidWrite(0); m_enabled = false; - if (table != null) { - table.putBoolean("enabled", false); + if (m_table != null) { + m_table.putBoolean("enabled", false); } } @@ -702,6 +699,7 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll /** * Return true if PIDController is enabled. */ + @Override public boolean isEnabled() { return m_enabled; } @@ -709,6 +707,7 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll /** * Reset the previous error,, the integral term, and disable the controller. */ + @Override public synchronized void reset() { disable(); m_prevError = 0; @@ -721,35 +720,35 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll return "PIDController"; } - private final ITableListener listener = new ITableListener() { - @Override - public void valueChanged(ITable table, String key, Object value, boolean isNew) { - if (key.equals("p") || key.equals("i") || key.equals("d") || key.equals("f")) { - if (getP() != table.getNumber("p", 0.0) || getI() != table.getNumber("i", 0.0) - || getD() != table.getNumber("d", 0.0) || getF() != table.getNumber("f", 0.0)) - setPID(table.getNumber("p", 0.0), table.getNumber("i", 0.0), table.getNumber("d", 0.0), - table.getNumber("f", 0.0)); - } else if (key.equals("setpoint")) { - if (getSetpoint() != ((Double) value).doubleValue()) - setSetpoint(((Double) value).doubleValue()); - } else if (key.equals("enabled")) { - if (isEnable() != ((Boolean) value).booleanValue()) { - if (((Boolean) value).booleanValue()) { - enable(); - } else { - disable(); - } + private final ITableListener m_listener = (table, key, value, isNew) -> { + if (key.equals("p") || key.equals("i") || key.equals("d") || key.equals("f")) { + if (getP() != table.getNumber("p", 0.0) || getI() != table.getNumber("i", 0.0) + || getD() != table.getNumber("d", 0.0) || getF() != table.getNumber("f", 0.0)) { + setPID(table.getNumber("p", 0.0), table.getNumber("i", 0.0), table.getNumber("d", 0.0), + table.getNumber("f", 0.0)); + } + } else if (key.equals("setpoint")) { + if (getSetpoint() != (Double) value) { + setSetpoint((Double) value); + } + } else if (key.equals("enabled")) { + if (isEnable() != (Boolean) value) { + if ((Boolean) value) { + enable(); + } else { + disable(); } } } }; - private ITable table; + private ITable m_table; @Override public void initTable(ITable table) { - if (this.table != null) - this.table.removeTableListener(listener); - this.table = table; + if (this.m_table != null) { + m_table.removeTableListener(m_listener); + } + m_table = table; if (table != null) { table.putNumber("p", getP()); table.putNumber("i", getI()); @@ -757,35 +756,29 @@ public class PIDController implements PIDInterface, LiveWindowSendable, Controll table.putNumber("f", getF()); table.putNumber("setpoint", getSetpoint()); table.putBoolean("enabled", isEnable()); - table.addTableListener(listener, false); + table.addTableListener(m_listener, false); } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { - return table; + return m_table; + } + + + @Override + public void updateTable() { } - /** - * {@inheritDoc} - */ - @Override - public void updateTable() {} - /** - * {@inheritDoc} - */ @Override public void startLiveWindowMode() { disable(); } - /** - * {@inheritDoc} - */ + @Override - public void stopLiveWindowMode() {} + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDInterface.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDInterface.java index 33602b0bd4..ad85c65548 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDInterface.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDInterface.java @@ -7,27 +7,29 @@ package edu.wpi.first.wpilibj; +@SuppressWarnings("SummaryJavadoc") public interface PIDInterface extends Controller { - public void setPID(double p, double i, double d); + @SuppressWarnings("ParameterName") + void setPID(double p, double i, double d); - public double getP(); + double getP(); - public double getI(); + double getI(); - public double getD(); + double getD(); - public void setSetpoint(double setpoint); + void setSetpoint(double setpoint); - public double getSetpoint(); + double getSetpoint(); - public double getError(); + double getError(); - public void enable(); + void enable(); - public void disable(); + void disable(); - public boolean isEnabled(); + boolean isEnabled(); - public void reset(); + void reset(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDOutput.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDOutput.java index 1fc28a5650..486217ab45 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDOutput.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDOutput.java @@ -9,15 +9,16 @@ package edu.wpi.first.wpilibj; /** * This interface allows PIDController to write it's results to its output. - *$ + * * @author dtjones */ +@FunctionalInterface public interface PIDOutput { /** - * Set the output to the value calculated by PIDController - *$ + * Set the output to the value calculated by PIDController. + * * @param output the value calculated by PIDController */ - public void pidWrite(double output); + void pidWrite(double output); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSource.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSource.java index 8195470c8f..8c395cc767 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSource.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSource.java @@ -6,36 +6,31 @@ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.PIDSourceType; /** - * This interface allows for PIDController to automatically read from this - * object - *$ + * This interface allows for PIDController to automatically read from this object. + * * @author dtjones */ public interface PIDSource { /** - * Set which parameter of the device you are using as a process control - * variable. + * Set which parameter of the device you are using as a process control variable. * - * @param pidSource - * An enum to select the parameter. + * @param pidSource An enum to select the parameter. */ - public void setPIDSourceType(PIDSourceType pidSource); + void setPIDSourceType(PIDSourceType pidSource); /** - * Get which parameter of the device you are using as a process control - * variable. + * Get which parameter of the device you are using as a process control variable. * * @return the currently selected PID source parameter */ - public PIDSourceType getPIDSourceType(); + PIDSourceType getPIDSourceType(); /** - * Get the result to use in PIDController - *$ + * Get the result to use in PIDController. + * * @return the result to use in PIDController */ - public double pidGet(); + double pidGet(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSourceType.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSourceType.java index 6f91ff4667..bd10cf71d4 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSourceType.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/PIDSourceType.java @@ -8,18 +8,19 @@ package edu.wpi.first.wpilibj; /** - * A description for the type of output value to provide to a PIDController + * A description for the type of output value to provide to a PIDController. */ public enum PIDSourceType { kDisplacement(0), kRate(1); /** - * The integer value representing this enumeration + * The integer value representing this enumeration. */ + @SuppressWarnings("MemberName") public final int value; - private PIDSourceType(int value) { + PIDSourceType(int value) { this.value = value; } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/RobotState.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/RobotState.java index 772cc72b55..5b9da8a353 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/RobotState.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/RobotState.java @@ -9,48 +9,50 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.util.BaseSystemNotInitializedException; +@SuppressWarnings("JavadocMethod") public class RobotState { - private static Interface impl; + private static Interface m_impl; - public static void SetImplementation(Interface i) { - impl = i; + @SuppressWarnings("MethodName") + public static void SetImplementation(Interface implementation) { + m_impl = implementation; } public static boolean isDisabled() { - if (impl != null) { - return impl.isDisabled(); + if (m_impl != null) { + return m_impl.isDisabled(); } else { throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); } } public static boolean isEnabled() { - if (impl != null) { - return impl.isEnabled(); + if (m_impl != null) { + return m_impl.isEnabled(); } else { throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); } } public static boolean isOperatorControl() { - if (impl != null) { - return impl.isOperatorControl(); + if (m_impl != null) { + return m_impl.isOperatorControl(); } else { throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); } } public static boolean isAutonomous() { - if (impl != null) { - return impl.isAutonomous(); + if (m_impl != null) { + return m_impl.isAutonomous(); } else { throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); } } public static boolean isTest() { - if (impl != null) { - return impl.isTest(); + if (m_impl != null) { + return m_impl.isTest(); } else { throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Sendable.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Sendable.java index f7801328e8..e5850ead33 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Sendable.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Sendable.java @@ -11,25 +11,28 @@ import edu.wpi.first.wpilibj.tables.ITable; /** - * The base interface for objects that can be sent over the network through - * network tables. + * The base interface for objects that can be sent over the network through network tables. */ public interface Sendable { /** - * Initializes a table for this sendable object. - *$ + * Initializes a table for this {@link Sendable} object. + * * @param subtable The table to put the values in. */ - public void initTable(ITable subtable); + void initTable(ITable subtable); /** - * @return the table that is currently associated with the sendable + * The table that is associated with this {@link Sendable}. + * + * @return the table that is currently associated with the {@link Sendable}. */ - public ITable getTable(); + ITable getTable(); /** - * @return the string representation of the named data type that will be used - * by the smart dashboard for this sendable + * The string representation of the named data type that will be used by the smart dashboard for + * this {@link Sendable}. + * + * @return The type of this {@link Sendable}. */ - public String getSmartDashboardType(); + String getSmartDashboardType(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/SensorBase.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/SensorBase.java index b7a1e643e3..3f814cbbe4 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/SensorBase.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/SensorBase.java @@ -8,60 +8,61 @@ package edu.wpi.first.wpilibj; /** - * Base class for all sensors. Stores most recent status information as well as - * containing utility functions for checking channels and error processing. + * Base class for all sensors. Stores most recent status information as well as containing utility + * functions for checking channels and error processing. */ public abstract class SensorBase { // TODO: Refactor // TODO: Move this to the HAL /** - * Ticks per microsecond + * Ticks per microsecond. */ public static final int kSystemClockTicksPerMicrosecond = 40; /** - * Number of digital channels per roboRIO + * Number of digital channels per roboRIO. */ public static final int kDigitalChannels = 26; /** - * Number of analog input channels + * Number of analog input channels. */ public static final int kAnalogInputChannels = 8; /** - * Number of analog output channels + * Number of analog output channels. */ public static final int kAnalogOutputChannels = 2; /** - * Number of solenoid channels per module + * Number of solenoid channels per module. */ public static final int kSolenoidChannels = 8; /** - * Number of solenoid modules + * Number of solenoid modules. */ public static final int kSolenoidModules = 2; /** - * Number of PWM channels per roboRIO + * Number of PWM channels per roboRIO. */ public static final int kPwmChannels = 20; /** - * Number of relay channels per roboRIO + * Number of relay channels per roboRIO. */ public static final int kRelayChannels = 4; /** - * Number of power distribution channels + * Number of power distribution channels. */ public static final int kPDPChannels = 16; /** - * Number of power distribution modules + * Number of power distribution modules. */ public static final int kPDPModules = 63; private static int m_defaultSolenoidModule = 0; /** - * Creates an instance of the sensor base and gets an FPGA handle + * Creates an instance of the sensor base and gets an FPGA handle. */ - public SensorBase() {} + public SensorBase() { + } /** * Set the default location for the Solenoid module. @@ -82,8 +83,8 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Check that the digital channel number is valid. Verify that the channel - * number is one of the legal channel numbers. Channel numbers are 1-based. + * Check that the digital channel number is valid. Verify that the channel number is one of the + * legal channel numbers. Channel numbers are 1-based. * * @param channel The channel number to check. */ @@ -94,8 +95,8 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Check that the digital channel number is valid. Verify that the channel - * number is one of the legal channel numbers. Channel numbers are 1-based. + * Check that the digital channel number is valid. Verify that the channel number is one of the + * legal channel numbers. Channel numbers are 1-based. * * @param channel The channel number to check. */ @@ -106,8 +107,8 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Check that the digital channel number is valid. Verify that the channel - * number is one of the legal channel numbers. Channel numbers are 1-based. + * Check that the digital channel number is valid. Verify that the channel number is one of the + * legal channel numbers. Channel numbers are 1-based. * * @param channel The channel number to check. */ @@ -118,8 +119,8 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Check that the analog input number is value. Verify that the analog input - * number is one of the legal channel numbers. Channel numbers are 0-based. + * Check that the analog input number is value. Verify that the analog input number is one of the + * legal channel numbers. Channel numbers are 0-based. * * @param channel The channel number to check. */ @@ -130,20 +131,20 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Check that the analog input number is value. Verify that the analog input - * number is one of the legal channel numbers. Channel numbers are 0-based. + * Check that the analog input number is value. Verify that the analog input number is one of the + * legal channel numbers. Channel numbers are 0-based. * * @param channel The channel number to check. */ protected static void checkAnalogOutputChannel(final int channel) { if (channel < 0 || channel >= kAnalogOutputChannels) { - throw new IndexOutOfBoundsException("Requested analog output channel number is out of range."); + throw new IndexOutOfBoundsException( + "Requested analog output channel number is out of range."); } } /** - * Verify that the solenoid channel number is within limits. Channel numbers - * are 1-based. + * Verify that the solenoid channel number is within limits. Channel numbers are 1-based. * * @param channel The channel number to check. */ @@ -154,8 +155,8 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Verify that the power distribution channel number is within limits. Channel - * numbers are 1-based. + * Verify that the power distribution channel number is within limits. Channel numbers are + * 1-based. * * @param channel The channel number to check. */ @@ -166,9 +167,8 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Verify that the PDP module number is within limits. module numbers are - * 0-based. - *$ + * Verify that the PDP module number is within limits. module numbers are 0-based. + * * @param module The module number to check. */ protected static void checkPDPModule(final int module) { @@ -187,7 +187,8 @@ public abstract class SensorBase { // TODO: Refactor } /** - * Free the resources used by this object + * Free the resources used by this object. */ - public void free() {} + public void free() { + } } diff --git a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SpeedController.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/SpeedController.java similarity index 86% rename from wpilibj/src/athena/java/edu/wpi/first/wpilibj/SpeedController.java rename to wpilibj/src/shared/java/edu/wpi/first/wpilibj/SpeedController.java index e886590f74..65c902f065 100644 --- a/wpilibj/src/athena/java/edu/wpi/first/wpilibj/SpeedController.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/SpeedController.java @@ -22,9 +22,9 @@ public interface SpeedController extends PIDOutput { /** * Common interface for setting the speed of a speed controller. * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending - * UpdateSyncGroup(). If 0, update immediately. + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update + * immediately. */ void set(double speed, byte syncGroup); @@ -43,22 +43,20 @@ public interface SpeedController extends PIDOutput { void setInverted(boolean isInverted); /** - * Common interface for returning if a speed controller is in the inverted - * state or not. - *$ - * @return isInverted The state of the inversion true is inverted. + * Common interface for returning if a speed controller is in the inverted state or not. * + * @return isInverted The state of the inversion true is inverted. */ boolean getInverted(); /** - * Disable the speed controller + * Disable the speed controller. */ void disable(); /** - * Stops motor movement. Motor can be moved again by calling set without having - * to re-enable the motor. + * Stops motor movement. Motor can be moved again by calling set without having to re-enable the + * motor. */ void stopMotor(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Timer.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Timer.java index b4d68b2485..77cc8ed06c 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Timer.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/Timer.java @@ -12,16 +12,18 @@ import edu.wpi.first.wpilibj.util.BaseSystemNotInitializedException; public class Timer { private static StaticInterface impl; + @SuppressWarnings("MethodName") public static void SetImplementation(StaticInterface ti) { impl = ti; } /** - * Return the system clock time in seconds. Return the time from the FPGA - * hardware clock in seconds since the FPGA started. + * Return the system clock time in seconds. Return the time from the FPGA hardware clock in + * seconds since the FPGA started. * * @return Robot running time in seconds. */ + @SuppressWarnings("AbbreviationAsWordInName") public static double getFPGATimestamp() { if (impl != null) { return impl.getFPGATimestamp(); @@ -31,14 +33,12 @@ public class Timer { } /** - * Return the approximate match time The FMS does not currently send the - * official match time to the robots This returns the time since the enable - * signal sent from the Driver Station At the beginning of autonomous, the - * time is reset to 0.0 seconds At the beginning of teleop, the time is reset - * to +15.0 seconds If the robot is disabled, this returns 0.0 seconds - * Warning: This is not an official time (so it cannot be used to argue with - * referees) - *$ + * Return the approximate match time The FMS does not currently send the official match time to + * the robots This returns the time since the enable signal sent from the Driver Station At the + * beginning of autonomous, the time is reset to 0.0 seconds At the beginning of teleop, the time + * is reset to +15.0 seconds If the robot is disabled, this returns 0.0 seconds Warning: This is + * not an official time (so it cannot be used to argue with referees). + * * @return Match time in seconds since the beginning of autonomous */ public static double getMatchTime() { @@ -50,11 +50,10 @@ public class Timer { } /** - * Pause the thread for a specified time. Pause the execution of the thread - * for a specified period of time given in seconds. Motors will continue to - * run at their last assigned values, and sensors will continue to update. - * Only the task containing the wait will pause until the wait time is - * expired. + * Pause the thread for a specified time. Pause the execution of the thread for a specified period + * of time given in seconds. Motors will continue to run at their last assigned values, and + * sensors will continue to update. Only the task containing the wait will pause until the wait + * time is expired. * * @param seconds Length of time to pause */ @@ -67,113 +66,114 @@ public class Timer { } public interface StaticInterface { + @SuppressWarnings("AbbreviationAsWordInName") double getFPGATimestamp(); double getMatchTime(); void delay(final double seconds); + @SuppressWarnings("JavadocMethod") Interface newTimer(); } - private final Interface timer; + private final Interface m_timer; + @SuppressWarnings("JavadocMethod") public Timer() { if (impl != null) { - timer = impl.newTimer(); + m_timer = impl.newTimer(); } else { throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); } } /** - * Get the current time from the timer. If the clock is running it is derived - * from the current system clock the start time stored in the timer class. If - * the clock is not running, then return the time when it was last stopped. + * Get the current time from the timer. If the clock is running it is derived from the current + * system clock the start time stored in the timer class. If the clock is not running, then return + * the time when it was last stopped. * * @return Current time value for this timer in seconds */ public double get() { - return timer.get(); + return m_timer.get(); } /** - * Reset the timer by setting the time to 0. Make the timer startTime the - * current time so new requests will be relative now + * Reset the timer by setting the time to 0. Make the timer startTime the current time so new + * requests will be relative now */ public void reset() { - timer.reset(); + m_timer.reset(); } /** - * Start the timer running. Just set the running flag to true indicating that - * all time requests should be relative to the system clock. + * Start the timer running. Just set the running flag to true indicating that all time requests + * should be relative to the system clock. */ public void start() { - timer.start(); + m_timer.start(); } /** - * Stop the timer. This computes the time as of now and clears the running - * flag, causing all subsequent time requests to be read from the accumulated - * time rather than looking at the system clock. + * Stop the timer. This computes the time as of now and clears the running flag, causing all + * subsequent time requests to be read from the accumulated time rather than looking at the system + * clock. */ public void stop() { - timer.stop(); + m_timer.stop(); } /** - * Check if the period specified has passed and if it has, advance the start - * time by that period. This is useful to decide if it's time to do periodic - * work without drifting later by the time it took to get around to checking. + * Check if the period specified has passed and if it has, advance the start time by that period. + * This is useful to decide if it's time to do periodic work without drifting later by the time it + * took to get around to checking. * * @param period The period to check for (in seconds). * @return If the period has passed. */ public boolean hasPeriodPassed(double period) { - return timer.hasPeriodPassed(period); + return m_timer.hasPeriodPassed(period); } public interface Interface { /** - * Get the current time from the timer. If the clock is running it is - * derived from the current system clock the start time stored in the timer - * class. If the clock is not running, then return the time when it was last - * stopped. + * Get the current time from the timer. If the clock is running it is derived from the current + * system clock the start time stored in the timer class. If the clock is not running, then + * return the time when it was last stopped. * * @return Current time value for this timer in seconds */ - public double get(); + double get(); /** - * Reset the timer by setting the time to 0. Make the timer startTime the - * current time so new requests will be relative now + * Reset the timer by setting the time to 0. Make the timer startTime the current time so new + * requests will be relative now */ - public void reset(); + void reset(); /** - * Start the timer running. Just set the running flag to true indicating - * that all time requests should be relative to the system clock. + * Start the timer running. Just set the running flag to true indicating that all time requests + * should be relative to the system clock. */ - public void start(); + void start(); /** - * Stop the timer. This computes the time as of now and clears the running - * flag, causing all subsequent time requests to be read from the - * accumulated time rather than looking at the system clock. + * Stop the timer. This computes the time as of now and clears the running flag, causing all + * subsequent time requests to be read from the accumulated time rather than looking at the + * system clock. */ - public void stop(); + void stop(); /** - * Check if the period specified has passed and if it has, advance the start - * time by that period. This is useful to decide if it's time to do periodic - * work without drifting later by the time it took to get around to - * checking. + * Check if the period specified has passed and if it has, advance the start time by that + * period. This is useful to decide if it's time to do periodic work without drifting later by + * the time it took to get around to checking. * * @param period The period to check for (in seconds). * @return If the period has passed. */ - public boolean hasPeriodPassed(double period); + boolean hasPeriodPassed(double period); } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Button.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Button.java index 69ae019368..7d0697d21a 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Button.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Button.java @@ -12,13 +12,12 @@ import edu.wpi.first.wpilibj.command.Command; /** * This class provides an easy way to link commands to OI inputs. * - * It is very easy to link a button to a command. For instance, you could link - * the trigger button of a joystick to a "score" command. + *

It is very easy to link a button to a command. For instance, you could link the trigger button + * of a joystick to a "score" command. * - * This class represents a subclass of Trigger that is specifically aimed at - * buttons on an operator interface as a common use case of the more generalized - * Trigger objects. This is a simple wrapper around Trigger with the method - * names renamed to fit the Button object use. + *

This class represents a subclass of Trigger that is specifically aimed at buttons on an + * operator interface as a common use case of the more generalized Trigger objects. This is a simple + * wrapper around Trigger with the method names renamed to fit the Button object use. * * @author brad */ @@ -26,7 +25,7 @@ public abstract class Button extends Trigger { /** * Starts the given command whenever the button is newly pressed. - *$ + * * @param command the command to start */ public void whenPressed(final Command command) { @@ -36,8 +35,8 @@ public abstract class Button extends Trigger { /** * Constantly starts the given command while the button is held. * - * {@link Command#start()} will be called repeatedly while the button is held, - * and will be canceled when the button is released. + * {@link Command#start()} will be called repeatedly while the button is held, and will be + * canceled when the button is released. * * @param command the command to start */ @@ -46,8 +45,8 @@ public abstract class Button extends Trigger { } /** - * Starts the command when the button is released - *$ + * Starts the command when the button is released. + * * @param command the command to start */ public void whenReleased(final Command command) { @@ -55,8 +54,8 @@ public abstract class Button extends Trigger { } /** - * Toggles the command whenever the button is pressed (on then off then on) - *$ + * Toggles the command whenever the button is pressed (on then off then on). + * * @param command the command to start */ public void toggleWhenPressed(final Command command) { @@ -64,8 +63,8 @@ public abstract class Button extends Trigger { } /** - * Cancel the command when the button is pressed - *$ + * Cancel the command when the button is pressed. + * * @param command the command to start */ public void cancelWhenPressed(final Command command) { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/InternalButton.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/InternalButton.java index d501a9515d..52bde5ba44 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/InternalButton.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/InternalButton.java @@ -8,16 +8,15 @@ package edu.wpi.first.wpilibj.buttons; /** - * This class is intended to be used within a program. The programmer can - * manually set its value. Also includes a setting for whether or not it should - * invert its value. + * This class is intended to be used within a program. The programmer can manually set its value. + * Also includes a setting for whether or not it should invert its value. * * @author Joe */ public class InternalButton extends Button { - boolean pressed; - boolean inverted; + private boolean m_pressed; + private boolean m_inverted; /** * Creates an InternalButton that is not inverted. @@ -29,22 +28,22 @@ public class InternalButton extends Button { /** * Creates an InternalButton which is inverted depending on the input. * - * @param inverted if false, then this button is pressed when set to true, - * otherwise it is pressed when set to false. + * @param inverted if false, then this button is pressed when set to true, otherwise it is pressed + * when set to false. */ public InternalButton(boolean inverted) { - this.pressed = this.inverted = inverted; + m_pressed = m_inverted = inverted; } public void setInverted(boolean inverted) { - this.inverted = inverted; + m_inverted = inverted; } public void setPressed(boolean pressed) { - this.pressed = pressed; + m_pressed = pressed; } public boolean get() { - return pressed ^ inverted; + return m_pressed ^ m_inverted; } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java index 8a7502be6a..7e5e371d7e 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java @@ -10,21 +10,21 @@ package edu.wpi.first.wpilibj.buttons; import edu.wpi.first.wpilibj.GenericHID; /** + * A {@link Button} that gets its state from a {@link GenericHID}. * * @author bradmiller */ public class JoystickButton extends Button { - GenericHID m_joystick; - int m_buttonNumber; + private final GenericHID m_joystick; + private final int m_buttonNumber; /** - * Create a joystick button for triggering commands - *$ - * @param joystick The GenericHID object that has the button (e.g. Joystick, - * KinectStick, etc) - * @param buttonNumber The button number (see - * {@link GenericHID#getRawButton(int) } + * Create a joystick button for triggering commands. + * + * @param joystick The GenericHID object that has the button (e.g. Joystick, KinectStick, + * etc) + * @param buttonNumber The button number (see {@link GenericHID#getRawButton(int) } */ public JoystickButton(GenericHID joystick, int buttonNumber) { m_joystick = joystick; @@ -32,8 +32,8 @@ public class JoystickButton extends Button { } /** - * Gets the value of the joystick button - *$ + * Gets the value of the joystick button. + * * @return The value of the joystick button */ public boolean get() { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java index 6a030c9a6f..4a875963ff 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java @@ -10,24 +10,24 @@ package edu.wpi.first.wpilibj.buttons; import edu.wpi.first.wpilibj.networktables.NetworkTable; /** - * + * A {@link Button} that uses a {@link NetworkTable} boolean field. * @author Joe */ public class NetworkButton extends Button { - NetworkTable table; - String field; + private final NetworkTable m_table; + private final String m_field; public NetworkButton(String table, String field) { this(NetworkTable.getTable(table), field); } public NetworkButton(NetworkTable table, String field) { - this.table = table; - this.field = field; + m_table = table; + m_field = field; } public boolean get() { - return table.isConnected() && table.getBoolean(field, false); + return m_table.isConnected() && m_table.getBoolean(m_field, false); } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Trigger.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Trigger.java index ed8fc3056f..c0a20d9b7f 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Trigger.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/buttons/Trigger.java @@ -15,62 +15,58 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * This class provides an easy way to link commands to inputs. * - * It is very easy to link a button to a command. For instance, you could link - * the trigger button of a joystick to a "score" command. + *

It is very easy to link a button to a command. For instance, you could link the trigger + * button of a joystick to a "score" command. * - * It is encouraged that teams write a subclass of Trigger if they want to have - * something unusual (for instance, if they want to react to the user holding a - * button while the robot is reading a certain sensor input). For this, they - * only have to write the {@link Trigger#get()} method to get the full - * functionality of the Trigger class. + *

It is encouraged that teams write a subclass of Trigger if they want to have something unusual + * (for instance, if they want to react to the user holding a button while the robot is reading a + * certain sensor input). For this, they only have to write the {@link Trigger#get()} method to get + * the full functionality of the Trigger class. * * @author Joe Grinstead */ public abstract class Trigger implements Sendable { /** - * Returns whether or not the trigger is active + * Returns whether or not the trigger is active. * - * This method will be called repeatedly a command is linked to the Trigger. + *

This method will be called repeatedly a command is linked to the Trigger. * * @return whether or not the trigger condition is active. */ public abstract boolean get(); /** - * Returns whether get() return true or the internal table for SmartDashboard - * use is pressed. - *$ - * @return whether get() return true or the internal table for SmartDashboard - * use is pressed + * Returns whether get() return true or the internal table for SmartDashboard use is pressed. + * + * @return whether get() return true or the internal table for SmartDashboard use is pressed. */ private boolean grab() { + // FIXME make is connected work? return get() - || (table != null /* && table.isConnected() */&& table.getBoolean("pressed", false));// FIXME - // make - // is - // connected - // work? + || (m_table != null /* && m_table.isConnected() */ && m_table.getBoolean("pressed", false)); + } /** * Starts the given command whenever the trigger just becomes active. - *$ + * * @param command the command to start */ public void whenActive(final Command command) { new ButtonScheduler() { - boolean pressedLast = grab(); + private boolean m_pressedLast = grab(); + @Override public void execute() { if (grab()) { - if (!pressedLast) { - pressedLast = true; + if (!m_pressedLast) { + m_pressedLast = true; command.start(); } } else { - pressedLast = false; + m_pressedLast = false; } } }.start(); @@ -79,23 +75,24 @@ public abstract class Trigger implements Sendable { /** * Constantly starts the given command while the button is held. * - * {@link Command#start()} will be called repeatedly while the trigger is - * active, and will be canceled when the trigger becomes inactive. + * {@link Command#start()} will be called repeatedly while the trigger is active, and will be + * canceled when the trigger becomes inactive. * * @param command the command to start */ public void whileActive(final Command command) { new ButtonScheduler() { - boolean pressedLast = grab(); + private boolean m_pressedLast = grab(); + @Override public void execute() { if (grab()) { - pressedLast = true; + m_pressedLast = true; command.start(); } else { - if (pressedLast) { - pressedLast = false; + if (m_pressedLast) { + m_pressedLast = false; command.cancel(); } } @@ -104,21 +101,22 @@ public abstract class Trigger implements Sendable { } /** - * Starts the command when the trigger becomes inactive - *$ + * Starts the command when the trigger becomes inactive. + * * @param command the command to start */ public void whenInactive(final Command command) { new ButtonScheduler() { - boolean pressedLast = grab(); + private boolean m_pressedLast = grab(); + @Override public void execute() { if (grab()) { - pressedLast = true; + m_pressedLast = true; } else { - if (pressedLast) { - pressedLast = false; + if (m_pressedLast) { + m_pressedLast = false; command.start(); } } @@ -127,19 +125,20 @@ public abstract class Trigger implements Sendable { } /** - * Toggles a command when the trigger becomes active - *$ + * Toggles a command when the trigger becomes active. + * * @param command the command to toggle */ public void toggleWhenActive(final Command command) { new ButtonScheduler() { - boolean pressedLast = grab(); + private boolean m_pressedLast = grab(); + @Override public void execute() { if (grab()) { - if (!pressedLast) { - pressedLast = true; + if (!m_pressedLast) { + m_pressedLast = true; if (command.isRunning()) { command.cancel(); } else { @@ -147,38 +146,39 @@ public abstract class Trigger implements Sendable { } } } else { - pressedLast = false; + m_pressedLast = false; } } }.start(); } /** - * Cancels a command when the trigger becomes active - *$ + * Cancels a command when the trigger becomes active. + * * @param command the command to cancel */ public void cancelWhenActive(final Command command) { new ButtonScheduler() { - boolean pressedLast = grab(); + private boolean m_pressedLast = grab(); + @Override public void execute() { if (grab()) { - if (!pressedLast) { - pressedLast = true; + if (!m_pressedLast) { + m_pressedLast = true; command.cancel(); } } else { - pressedLast = false; + m_pressedLast = false; } } }.start(); } /** - * An internal class of {@link Trigger}. The user should ignore this, it is - * only public to interface between packages. + * An internal class of {@link Trigger}. The user should ignore this, it is only public to + * interface between packages. */ public abstract class ButtonScheduler { public abstract void execute(); @@ -189,26 +189,26 @@ public abstract class Trigger implements Sendable { } /** - * These methods continue to return the "Button" SmartDashboard type until we - * decided to create a Trigger widget type for the dashboard. + * These methods continue to return the "Button" SmartDashboard type until we decided to create a + * Trigger widget type for the dashboard. */ + @Override public String getSmartDashboardType() { return "Button"; } - private ITable table; + private ITable m_table; + @Override public void initTable(ITable table) { - this.table = table; + m_table = table; if (table != null) { table.putBoolean("pressed", get()); } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { - return table; + return m_table; } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Command.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Command.java index 5bdf3a3901..b76fe77eb0 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Command.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Command.java @@ -7,44 +7,36 @@ package edu.wpi.first.wpilibj.command; +import java.util.Enumeration; +import java.util.NoSuchElementException; +import java.util.Vector; + import edu.wpi.first.wpilibj.NamedSendable; import edu.wpi.first.wpilibj.RobotState; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -import java.util.Enumeration; -import java.util.NoSuchElementException; /** - * The Command class is at the very core of the entire command framework. Every - * command can be started with a call to {@link Command#start() start()}. Once a - * command is started it will call {@link Command#initialize() initialize()}, - * and then will repeatedly call {@link Command#execute() execute()} until the - * {@link Command#isFinished() isFinished()} returns true. Once it does, - * {@link Command#end() end()} will be called. + * The Command class is at the very core of the entire command framework. Every command can be + * started with a call to {@link Command#start() start()}. Once a command is started it will call + * {@link Command#initialize() initialize()}, and then will repeatedly call {@link Command#execute() + * execute()} until the {@link Command#isFinished() isFinished()} returns true. Once it does, {@link + * Command#end() end()} will be called. * - *

- * However, if at any point while it is running {@link Command#cancel() - * cancel()} is called, then the command will be stopped and - * {@link Command#interrupted() interrupted()} will be called. - *

+ *

However, if at any point while it is running {@link Command#cancel() cancel()} is called, + * then the command will be stopped and {@link Command#interrupted() interrupted()} will be called. * - *

- * If a command uses a {@link Subsystem}, then it should specify that it does so - * by calling the {@link Command#requires(Subsystem) requires(...)} method in - * its constructor. Note that a Command may have multiple requirements, and - * {@link Command#requires(Subsystem) requires(...)} should be called for each - * one. - *

+ *

If a command uses a {@link Subsystem}, then it should specify that it does so by calling the + * {@link Command#requires(Subsystem) requires(...)} method in its constructor. Note that a Command + * may have multiple requirements, and {@link Command#requires(Subsystem) requires(...)} should be + * called for each one. * - *

- * If a command is running and a new command with shared requirements is - * started, then one of two things will happen. If the active command is - * interruptible, then {@link Command#cancel() cancel()} will be called and the - * command will be removed to make way for the new one. If the active command is - * not interruptible, the other one will not even be started, and the active one + *

If a command is running and a new command with shared requirements is started, then one of + * two things will happen. If the active command is interruptible, then {@link Command#cancel() + * cancel()} will be called and the command will be removed to make way for the new one. If the + * active command is not interruptible, the other one will not even be started, and the active one * will continue functioning. - *

* * @author Brad Miller * @author Joe Grinstead @@ -54,34 +46,53 @@ import java.util.NoSuchElementException; */ public abstract class Command implements NamedSendable { - /** The name of this command */ + /** + * The name of this command. + */ private String m_name; - /** The time since this command was initialized */ + /** + * The time since this command was initialized. + */ private double m_startTime = -1; /** - * The time (in seconds) before this command "times out" (or -1 if no timeout) + * The time (in seconds) before this command "times out" (or -1 if no timeout). */ private double m_timeout = -1; - /** Whether or not this command has been initialized */ + /** + * Whether or not this command has been initialized. + */ private boolean m_initialized = false; - /** The requirements (or null if no requirements) */ + /** + * The requirements (or null if no requirements). + */ private Set m_requirements; - /** Whether or not it is running */ + /** + * Whether or not it is running. + */ private boolean m_running = false; - /** Whether or not it is interruptible */ + /** + * Whether or not it is interruptible. + */ private boolean m_interruptible = true; - /** Whether or not it has been canceled */ + /** + * Whether or not it has been canceled. + */ private boolean m_canceled = false; - /** Whether or not it has been locked */ + /** + * Whether or not it has been locked. + */ private boolean m_locked = false; - /** Whether this command should run when the robot is disabled */ + /** + * Whether this command should run when the robot is disabled. + */ private boolean m_runWhenDisabled = false; - /** The {@link CommandGroup} this is in */ + /** + * The {@link CommandGroup} this is in. + */ private CommandGroup m_parent; /** - * Creates a new command. The name of this command will be set to its class - * name. + * Creates a new command. The name of this command will be set to its class name. */ public Command() { m_name = getClass().getName(); @@ -90,7 +101,7 @@ public abstract class Command implements NamedSendable { /** * Creates a new command with the given name. - *$ + * * @param name the name for this command * @throws IllegalArgumentException if name is null */ @@ -102,9 +113,9 @@ public abstract class Command implements NamedSendable { } /** - * Creates a new command with the given timeout and a default name. The - * default name is the name of the class. - *$ + * Creates a new command with the given timeout and a default name. The default name is the name + * of the class. + * * @param timeout the time (in seconds) before this command "times out" * @throws IllegalArgumentException if given a negative timeout * @see Command#isTimedOut() isTimedOut() @@ -119,11 +130,10 @@ public abstract class Command implements NamedSendable { /** * Creates a new command with the given name and timeout. - *$ - * @param name the name of the command + * + * @param name the name of the command * @param timeout the time (in seconds) before this command "times out" - * @throws IllegalArgumentException if given a negative timeout or name was - * null. + * @throws IllegalArgumentException if given a negative timeout or name was null. * @see Command#isTimedOut() isTimedOut() */ public Command(String name, double timeout) { @@ -135,9 +145,9 @@ public abstract class Command implements NamedSendable { } /** - * Returns the name of this command. If no name was specified in the - * constructor, then the default is the name of the class. - *$ + * Returns the name of this command. If no name was specified in the constructor, then the default + * is the name of the class. + * * @return the name of this command */ public String getName() { @@ -146,12 +156,12 @@ public abstract class Command implements NamedSendable { /** * Sets the timeout of this command. - *$ + * * @param seconds the timeout (in seconds) * @throws IllegalArgumentException if seconds is negative * @see Command#isTimedOut() isTimedOut() */ - protected synchronized final void setTimeout(double seconds) { + protected final synchronized void setTimeout(double seconds) { if (seconds < 0) { throw new IllegalArgumentException("Seconds must be positive. Given:" + seconds); } @@ -159,28 +169,25 @@ public abstract class Command implements NamedSendable { } /** - * Returns the time since this command was initialized (in seconds). This - * function will work even if there is no specified timeout. - *$ + * Returns the time since this command was initialized (in seconds). This function will work even + * if there is no specified timeout. + * * @return the time since this command was initialized (in seconds). */ - public synchronized final double timeSinceInitialized() { + public final synchronized double timeSinceInitialized() { return m_startTime < 0 ? 0 : Timer.getFPGATimestamp() - m_startTime; } /** - * This method specifies that the given {@link Subsystem} is used by this - * command. This method is crucial to the functioning of the Command System in - * general. + * This method specifies that the given {@link Subsystem} is used by this command. This method is + * crucial to the functioning of the Command System in general. * - *

- * Note that the recommended way to call this method is in the constructor. - *

+ *

Note that the recommended way to call this method is in the constructor. * * @param subsystem the {@link Subsystem} required - * @throws IllegalArgumentException if subsystem is null - * @throws IllegalUseOfCommandException if this command has started before or - * if it has been given to a {@link CommandGroup} + * @throws IllegalArgumentException if subsystem is null + * @throws IllegalUseOfCommandException if this command has started before or if it has been given + * to a {@link CommandGroup} * @see Subsystem */ protected synchronized void requires(Subsystem subsystem) { @@ -196,8 +203,8 @@ public abstract class Command implements NamedSendable { } /** - * Called when the command has been removed. This will call - * {@link Command#interrupted() interrupted()} or {@link Command#end() end()}. + * Called when the command has been removed. This will call {@link Command#interrupted() + * interrupted()} or {@link Command#end() end()}. */ synchronized void removed() { if (m_initialized) { @@ -212,16 +219,15 @@ public abstract class Command implements NamedSendable { m_initialized = false; m_canceled = false; m_running = false; - if (table != null) { - table.putBoolean("running", false); + if (m_table != null) { + m_table.putBoolean("running", false); } } /** * The run method is used internally to actually run the commands. - *$ - * @return whether or not the command should stay within the {@link Scheduler} - * . + * + * @return whether or not the command should stay within the {@link Scheduler}. */ synchronized boolean run() { if (!m_runWhenDisabled && m_parent == null && RobotState.isDisabled()) { @@ -242,82 +248,87 @@ public abstract class Command implements NamedSendable { } /** - * The initialize method is called the first time this Command is run after - * being started. + * The initialize method is called the first time this Command is run after being started. */ protected abstract void initialize(); - /** A shadow method called before {@link Command#initialize() initialize()} */ - void _initialize() {} + /** + * A shadow method called before {@link Command#initialize() initialize()}. + */ + @SuppressWarnings("MethodName") + void _initialize() { + } /** - * The execute method is called repeatedly until this Command either finishes - * or is canceled. + * The execute method is called repeatedly until this Command either finishes or is canceled. */ + @SuppressWarnings("MethodName") protected abstract void execute(); - /** A shadow method called before {@link Command#execute() execute()} */ - void _execute() {} + /** + * A shadow method called before {@link Command#execute() execute()}. + */ + @SuppressWarnings("MethodName") + void _execute() { + } /** - * Returns whether this command is finished. If it is, then the command will - * be removed and {@link Command#end() end()} will be called. + * Returns whether this command is finished. If it is, then the command will be removed and {@link + * Command#end() end()} will be called. + * + *

It may be useful for a team to reference the {@link Command#isTimedOut() isTimedOut()} + * method for time-sensitive commands. * - *

- * It may be useful for a team to reference the {@link Command#isTimedOut() - * isTimedOut()} method for time-sensitive commands. - *

- *$ * @return whether this command is finished. * @see Command#isTimedOut() isTimedOut() */ protected abstract boolean isFinished(); /** - * Called when the command ended peacefully. This is where you may want to - * wrap up loose ends, like shutting off a motor that was being used in the - * command. + * Called when the command ended peacefully. This is where you may want to wrap up loose ends, + * like shutting off a motor that was being used in the command. */ protected abstract void end(); - /** A shadow method called after {@link Command#end() end()}. */ - void _end() {} + /** + * A shadow method called after {@link Command#end() end()}. + */ + @SuppressWarnings("MethodName") + void _end() { + } /** - * Called when the command ends because somebody called - * {@link Command#cancel() cancel()} or another command shared the same - * requirements as this one, and booted it out. + * Called when the command ends because somebody called {@link Command#cancel() cancel()} or + * another command shared the same requirements as this one, and booted it out. * - *

- * This is where you may want to wrap up loose ends, like shutting off a motor - * that was being used in the command. - *

+ *

This is where you may want to wrap up loose ends, like shutting off a motor that was being + * used in the command. * - *

- * Generally, it is useful to simply call the {@link Command#end() end()} - * method within this method - *

+ *

Generally, it is useful to simply call the {@link Command#end() end()} method within this + * method. */ protected abstract void interrupted(); - /** A shadow method called after {@link Command#interrupted() interrupted()}. */ - void _interrupted() {} + /** + * A shadow method called after {@link Command#interrupted() interrupted()}. + */ + @SuppressWarnings("MethodName") + void _interrupted() { + } /** - * Called to indicate that the timer should start. This is called right before - * {@link Command#initialize() initialize()} is, inside the - * {@link Command#run() run()} method. + * Called to indicate that the timer should start. This is called right before {@link + * Command#initialize() initialize()} is, inside the {@link Command#run() run()} method. */ private void startTiming() { m_startTime = Timer.getFPGATimestamp(); } /** - * Returns whether or not the {@link Command#timeSinceInitialized() - * timeSinceInitialized()} method returns a number which is greater than or - * equal to the timeout for the command. If there is no timeout, this will - * always return false. - *$ + * Returns whether or not the {@link Command#timeSinceInitialized() timeSinceInitialized()} method + * returns a number which is greater than or equal to the timeout for the command. If there is no + * timeout, this will always return false. + * * @return whether the time has expired */ protected synchronized boolean isTimedOut() { @@ -325,27 +336,26 @@ public abstract class Command implements NamedSendable { } /** - * Returns the requirements (as an {@link Enumeration Enumeration} of - * {@link Subsystem Subsystems}) of this command - *$ - * @return the requirements (as an {@link Enumeration Enumeration} of - * {@link Subsystem Subsystems}) of this command + * Returns the requirements (as an {@link Enumeration Enumeration} of {@link Subsystem + * Subsystems}) of this command. + * + * @return the requirements (as an {@link Enumeration Enumeration} of {@link Subsystem + * Subsystems}) of this command */ synchronized Enumeration getRequirements() { return m_requirements == null ? emptyEnumeration : m_requirements.getElements(); } /** - * Prevents further changes from being made + * Prevents further changes from being made. */ synchronized void lockChanges() { m_locked = true; } /** - * If changes are locked, then this will throw an - * {@link IllegalUseOfCommandException}. - *$ + * If changes are locked, then this will throw an {@link IllegalUseOfCommandException}. + * * @param message the message to say (it is appended by a default message) */ synchronized void validate(String message) { @@ -357,33 +367,28 @@ public abstract class Command implements NamedSendable { /** * Sets the parent of this command. No actual change is made to the group. - *$ + * * @param parent the parent - * @throws IllegalUseOfCommandException if this {@link Command} already is - * already in a group + * @throws IllegalUseOfCommandException if this {@link Command} already is already in a group */ synchronized void setParent(CommandGroup parent) { - if (this.m_parent != null) { + if (m_parent != null) { throw new IllegalUseOfCommandException( "Can not give command to a command group after already being put in a command group"); } lockChanges(); - this.m_parent = parent; - if (table != null) { - table.putBoolean("isParented", true); + m_parent = parent; + if (m_table != null) { + m_table.putBoolean("isParented", true); } } /** - * Starts up the command. Gets the command ready to start. - *

- * Note that the command will eventually start, however it will not - * necessarily do so immediately, and may in fact be canceled before - * initialize is even called. - *

- *$ - * @throws IllegalUseOfCommandException if the command is a part of a - * CommandGroup + * Starts up the command. Gets the command ready to start.

Note that the command will + * eventually start, however it will not necessarily do so immediately, and may in fact be + * canceled before initialize is even called.

+ * + * @throws IllegalUseOfCommandException if the command is a part of a CommandGroup */ public synchronized void start() { lockChanges(); @@ -395,28 +400,26 @@ public abstract class Command implements NamedSendable { } /** - * This is used internally to mark that the command has been started. The - * lifecycle of a command is: + * This is used internally to mark that the command has been started. The lifecycle of a command + * is: * - * startRunning() is called. run() is called (multiple times potentially) - * removed() is called + *

startRunning() is called. run() is called (multiple times potentially) removed() is called. * - * It is very important that startRunning and removed be called in order or - * some assumptions of the code will be broken. + *

It is very important that startRunning and removed be called in order or some assumptions of + * the code will be broken. */ synchronized void startRunning() { m_running = true; m_startTime = -1; - if (table != null) { - table.putBoolean("running", true); + if (m_table != null) { + m_table.putBoolean("running", true); } } /** - * Returns whether or not the command is running. This may return true even if - * the command has just been canceled, as it may not have yet called - * {@link Command#interrupted()}. - *$ + * Returns whether or not the command is running. This may return true even if the command has + * just been canceled, as it may not have yet called {@link Command#interrupted()}. + * * @return whether or not the command is running */ public synchronized boolean isRunning() { @@ -424,33 +427,27 @@ public abstract class Command implements NamedSendable { } /** - * This will cancel the current command. - *

- * This will cancel the current command eventually. It can be called multiple - * times. And it can be called when the command is not running. If the command - * is running though, then the command will be marked as canceled and - * eventually removed. - *

- *

- * A command can not be canceled if it is a part of a command group, you must - * cancel the command group instead. - *

- *$ - * @throws IllegalUseOfCommandException if this command is a part of a command - * group + * This will cancel the current command.

This will cancel the current command eventually. It + * can be called multiple times. And it can be called when the command is not running. If the + * command is running though, then the command will be marked as canceled and eventually removed. + *

A command can not be canceled if it is a part of a command group, you must cancel the + * command group instead.

+ * + * @throws IllegalUseOfCommandException if this command is a part of a command group */ public synchronized void cancel() { if (m_parent != null) { - throw new IllegalUseOfCommandException("Can not manually cancel a command in a command group"); + throw new IllegalUseOfCommandException("Can not manually cancel a command in a command " + + "group"); } _cancel(); } /** - * This works like cancel(), except that it doesn't throw an exception if it - * is a part of a command group. Should only be called by the parent command - * group. + * This works like cancel(), except that it doesn't throw an exception if it is a part of a + * command group. Should only be called by the parent command group. */ + @SuppressWarnings("MethodName") synchronized void _cancel() { if (isRunning()) { m_canceled = true; @@ -459,7 +456,7 @@ public abstract class Command implements NamedSendable { /** * Returns whether or not this has been canceled. - *$ + * * @return whether or not this has been canceled */ public synchronized boolean isCanceled() { @@ -468,7 +465,7 @@ public abstract class Command implements NamedSendable { /** * Returns whether or not this command can be interrupted. - *$ + * * @return whether or not this command can be interrupted */ public synchronized boolean isInterruptible() { @@ -477,16 +474,16 @@ public abstract class Command implements NamedSendable { /** * Sets whether or not this command can be interrupted. - *$ + * * @param interruptible whether or not this command can be interrupted */ protected synchronized void setInterruptible(boolean interruptible) { - this.m_interruptible = interruptible; + m_interruptible = interruptible; } /** * Checks if the command requires the given {@link Subsystem}. - *$ + * * @param system the system * @return whether or not the subsystem is required, or false if given null */ @@ -495,44 +492,39 @@ public abstract class Command implements NamedSendable { } /** - * Returns the {@link CommandGroup} that this command is a part of. Will - * return null if this {@link Command} is not in a group. - *$ - * @return the {@link CommandGroup} that this command is a part of (or null if - * not in group) + * Returns the {@link CommandGroup} that this command is a part of. Will return null if this + * {@link Command} is not in a group. + * + * @return the {@link CommandGroup} that this command is a part of (or null if not in group) */ public synchronized CommandGroup getGroup() { return m_parent; } /** - * Sets whether or not this {@link Command} should run when the robot is - * disabled. + * Sets whether or not this {@link Command} should run when the robot is disabled. * - *

- * By default a command will not run when the robot is disabled, and will in - * fact be canceled. - *

- *$ - * @param run whether or not this command should run when the robot is - * disabled + *

By default a command will not run when the robot is disabled, and will in fact be canceled. + * + * @param run whether or not this command should run when the robot is disabled */ public void setRunWhenDisabled(boolean run) { m_runWhenDisabled = run; } /** - * Returns whether or not this {@link Command} will run when the robot is - * disabled, or if it will cancel itself. - *$ - * @return whether or not this {@link Command} will run when the robot is - * disabled, or if it will cancel itself + * Returns whether or not this {@link Command} will run when the robot is disabled, or if it will + * cancel itself. + * + * @return True if this command will run when the robot is disabled. */ public boolean willRunWhenDisabled() { return m_runWhenDisabled; } - /** An empty enumeration given whenever there are no requirements */ + /** + * An empty enumeration given whenever there are no requirements. + */ private static Enumeration emptyEnumeration = new Enumeration() { public boolean hasMoreElements() { @@ -546,9 +538,10 @@ public abstract class Command implements NamedSendable { /** * The string representation for a {@link Command} is by default its name. - *$ + * * @return the string representation of this object */ + @Override public String toString() { return getName(); } @@ -558,34 +551,32 @@ public abstract class Command implements NamedSendable { return "Command"; } - private ITableListener listener = new ITableListener() { - public void valueChanged(ITable table, String key, Object value, boolean isNew) { - if (((Boolean) value).booleanValue()) { - start(); - } else { - cancel(); - } + private final ITableListener m_listener = (table1, key, value, isNew) -> { + if (((Boolean) value).booleanValue()) { + start(); + } else { + cancel(); } }; - private ITable table; + private ITable m_table; + @Override public void initTable(ITable table) { - if (this.table != null) - this.table.removeTableListener(listener); - this.table = table; + if (m_table != null) { + m_table.removeTableListener(m_listener); + } + m_table = table; if (table != null) { table.putString("name", getName()); table.putBoolean("running", isRunning()); table.putBoolean("isParented", m_parent != null); - table.addTableListener("running", listener, false); + table.addTableListener("running", m_listener, false); } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { - return table; + return m_table; } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/CommandGroup.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/CommandGroup.java index ca9c65419e..d253580481 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/CommandGroup.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/CommandGroup.java @@ -13,25 +13,17 @@ import java.util.Vector; /** * A {@link CommandGroup} is a list of commands which are executed in sequence. * - *

- * Commands in a {@link CommandGroup} are added using the - * {@link CommandGroup#addSequential(Command) addSequential(...)} method and are - * called sequentially. {@link CommandGroup CommandGroups} are themselves - * {@link Command commands} and can be given to other {@link CommandGroup - * CommandGroups}. - *

+ *

Commands in a {@link CommandGroup} are added using the {@link + * CommandGroup#addSequential(Command) addSequential(...)} method and are called sequentially. + * {@link CommandGroup CommandGroups} are themselves {@link Command commands} and can be given to + * other {@link CommandGroup CommandGroups}.

* - *

- * {@link CommandGroup CommandGroups} will carry all of the requirements of - * their {@link Command subcommands}. Additional requirements can be specified - * by calling {@link CommandGroup#requires(Subsystem) requires(...)} normally in - * the constructor. - *

+ *

{@link CommandGroup CommandGroups} will carry all of the requirements of their {@link Command + * subcommands}. Additional requirements can be specified by calling {@link + * CommandGroup#requires(Subsystem) requires(...)} normally in the constructor.

* - *

- * CommandGroups can also execute commands in parallel, simply by adding them - * using {@link CommandGroup#addParallel(Command) addParallel(...)}. - *

+ *

CommandGroups can also execute commands in parallel, simply by adding them using {@link + * CommandGroup#addParallel(Command) addParallel(...)}.

* * @author Brad Miller * @author Joe Grinstead @@ -41,22 +33,32 @@ import java.util.Vector; */ public class CommandGroup extends Command { - /** The commands in this group (stored in entries) */ - Vector m_commands = new Vector(); - /** The active children in this group (stored in entries) */ - Vector m_children = new Vector(); - /** The current command, -1 signifies that none have been run */ - int m_currentCommandIndex = -1; + /** + * The commands in this group (stored in entries). + */ + private final Vector m_commands = new Vector(); + /* + * Intentionally package private + */ + /** + * The active children in this group (stored in entries). + */ + final Vector m_children = new Vector(); + /** + * The current command, -1 signifies that none have been run. + */ + private int m_currentCommandIndex = -1; /** - * Creates a new {@link CommandGroup CommandGroup}. The name of this command - * will be set to its class name. + * Creates a new {@link CommandGroup CommandGroup}. The name of this command will be set to its + * class name. */ - public CommandGroup() {} + public CommandGroup() { + } /** * Creates a new {@link CommandGroup CommandGroup} with the given name. - *$ + * * @param name the name for this command group * @throws IllegalArgumentException if name is null */ @@ -65,26 +67,21 @@ public class CommandGroup extends Command { } /** - * Adds a new {@link Command Command} to the group. The {@link Command - * Command} will be started after all the previously added {@link Command - * Commands}. + * Adds a new {@link Command Command} to the group. The {@link Command Command} will be started + * after all the previously added {@link Command Commands}. * - *

- * Note that any requirements the given {@link Command Command} has will be - * added to the group. For this reason, a {@link Command Command's} - * requirements can not be changed after being added to a group. - *

+ *

Note that any requirements the given {@link Command Command} has will be added to the + * group. For this reason, a {@link Command Command's} requirements can not be changed after being + * added to a group.

* - *

- * It is recommended that this method be called in the constructor. - *

+ *

It is recommended that this method be called in the constructor.

* * @param command The {@link Command Command} to be added - * @throws IllegalUseOfCommandException if the group has been started before - * or been given to another group - * @throws IllegalArgumentException if command is null + * @throws IllegalUseOfCommandException if the group has been started before or been given to + * another group + * @throws IllegalArgumentException if command is null */ - public synchronized final void addSequential(Command command) { + public final synchronized void addSequential(Command command) { validate("Can not add new command to command group"); if (command == null) { throw new IllegalArgumentException("Given null command"); @@ -93,40 +90,33 @@ public class CommandGroup extends Command { command.setParent(this); m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + for (Enumeration e = command.getRequirements(); e.hasMoreElements(); ) { requires((Subsystem) e.nextElement()); } } /** - * Adds a new {@link Command Command} to the group with a given timeout. The - * {@link Command Command} will be started after all the previously added - * commands. + * Adds a new {@link Command Command} to the group with a given timeout. The {@link Command + * Command} will be started after all the previously added commands. * - *

- * Once the {@link Command Command} is started, it will be run until it - * finishes or the time expires, whichever is sooner. Note that the given - * {@link Command Command} will have no knowledge that it is on a timer. - *

+ *

Once the {@link Command Command} is started, it will be run until it finishes or the time + * expires, whichever is sooner. Note that the given {@link Command Command} will have no + * knowledge that it is on a timer.

* - *

- * Note that any requirements the given {@link Command Command} has will be - * added to the group. For this reason, a {@link Command Command's} - * requirements can not be changed after being added to a group. - *

+ *

Note that any requirements the given {@link Command Command} has will be added to the + * group. For this reason, a {@link Command Command's} requirements can not be changed after being + * added to a group.

* - *

- * It is recommended that this method be called in the constructor. - *

+ *

It is recommended that this method be called in the constructor.

* * @param command The {@link Command Command} to be added * @param timeout The timeout (in seconds) - * @throws IllegalUseOfCommandException if the group has been started before - * or been given to another group or if the {@link Command Command} - * has been started before or been given to another group - * @throws IllegalArgumentException if command is null or timeout is negative + * @throws IllegalUseOfCommandException if the group has been started before or been given to + * another group or if the {@link Command Command} has been + * started before or been given to another group + * @throws IllegalArgumentException if command is null or timeout is negative */ - public synchronized final void addSequential(Command command, double timeout) { + public final synchronized void addSequential(Command command, double timeout) { validate("Can not add new command to command group"); if (command == null) { throw new IllegalArgumentException("Given null command"); @@ -138,40 +128,33 @@ public class CommandGroup extends Command { command.setParent(this); m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE, timeout)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + for (Enumeration e = command.getRequirements(); e.hasMoreElements(); ) { requires((Subsystem) e.nextElement()); } } /** - * Adds a new child {@link Command} to the group. The {@link Command} will be - * started after all the previously added {@link Command Commands}. + * Adds a new child {@link Command} to the group. The {@link Command} will be started after all + * the previously added {@link Command Commands}. * - *

- * Instead of waiting for the child to finish, a {@link CommandGroup} will - * have it run at the same time as the subsequent {@link Command Commands}. - * The child will run until either it finishes, a new child with conflicting - * requirements is started, or the main sequence runs a {@link Command} with - * conflicting requirements. In the latter two cases, the child will be - * canceled even if it says it can't be interrupted. - *

+ *

Instead of waiting for the child to finish, a {@link CommandGroup} will have it run at the + * same time as the subsequent {@link Command Commands}. The child will run until either it + * finishes, a new child with conflicting requirements is started, or the main sequence runs a + * {@link Command} with conflicting requirements. In the latter two cases, the child will be + * canceled even if it says it can't be interrupted.

* - *

- * Note that any requirements the given {@link Command Command} has will be - * added to the group. For this reason, a {@link Command Command's} - * requirements can not be changed after being added to a group. - *

+ *

Note that any requirements the given {@link Command Command} has will be added to the + * group. For this reason, a {@link Command Command's} requirements can not be changed after being + * added to a group.

* - *

- * It is recommended that this method be called in the constructor. - *

+ *

It is recommended that this method be called in the constructor.

* * @param command The command to be added - * @throws IllegalUseOfCommandException if the group has been started before - * or been given to another command group - * @throws IllegalArgumentException if command is null + * @throws IllegalUseOfCommandException if the group has been started before or been given to + * another command group + * @throws IllegalArgumentException if command is null */ - public synchronized final void addParallel(Command command) { + public final synchronized void addParallel(Command command) { validate("Can not add new command to command group"); if (command == null) { throw new NullPointerException("Given null command"); @@ -180,48 +163,38 @@ public class CommandGroup extends Command { command.setParent(this); m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + for (Enumeration e = command.getRequirements(); e.hasMoreElements(); ) { requires((Subsystem) e.nextElement()); } } /** - * Adds a new child {@link Command} to the group with the given timeout. The - * {@link Command} will be started after all the previously added - * {@link Command Commands}. + * Adds a new child {@link Command} to the group with the given timeout. The {@link Command} will + * be started after all the previously added {@link Command Commands}. * - *

- * Once the {@link Command Command} is started, it will run until it finishes, - * is interrupted, or the time expires, whichever is sooner. Note that the - * given {@link Command Command} will have no knowledge that it is on a timer. - *

+ *

Once the {@link Command Command} is started, it will run until it finishes, is interrupted, + * or the time expires, whichever is sooner. Note that the given {@link Command Command} will have + * no knowledge that it is on a timer.

* - *

- * Instead of waiting for the child to finish, a {@link CommandGroup} will - * have it run at the same time as the subsequent {@link Command Commands}. - * The child will run until either it finishes, the timeout expires, a new - * child with conflicting requirements is started, or the main sequence runs a - * {@link Command} with conflicting requirements. In the latter two cases, the - * child will be canceled even if it says it can't be interrupted. - *

+ *

Instead of waiting for the child to finish, a {@link CommandGroup} will have it run at the + * same time as the subsequent {@link Command Commands}. The child will run until either it + * finishes, the timeout expires, a new child with conflicting requirements is started, or the + * main sequence runs a {@link Command} with conflicting requirements. In the latter two cases, + * the child will be canceled even if it says it can't be interrupted.

* - *

- * Note that any requirements the given {@link Command Command} has will be - * added to the group. For this reason, a {@link Command Command's} - * requirements can not be changed after being added to a group. - *

+ *

Note that any requirements the given {@link Command Command} has will be added to the + * group. For this reason, a {@link Command Command's} requirements can not be changed after being + * added to a group.

* - *

- * It is recommended that this method be called in the constructor. - *

+ *

It is recommended that this method be called in the constructor.

* * @param command The command to be added * @param timeout The timeout (in seconds) - * @throws IllegalUseOfCommandException if the group has been started before - * or been given to another command group - * @throws IllegalArgumentException if command is null + * @throws IllegalUseOfCommandException if the group has been started before or been given to + * another command group + * @throws IllegalArgumentException if command is null */ - public synchronized final void addParallel(Command command, double timeout) { + public final synchronized void addParallel(Command command, double timeout) { validate("Can not add new command to command group"); if (command == null) { throw new NullPointerException("Given null command"); @@ -233,15 +206,17 @@ public class CommandGroup extends Command { command.setParent(this); m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD, timeout)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + for (Enumeration e = command.getRequirements(); e.hasMoreElements(); ) { requires((Subsystem) e.nextElement()); } } + @SuppressWarnings("MethodName") void _initialize() { m_currentCommandIndex = -1; } + @SuppressWarnings("MethodName") void _execute() { Entry entry = null; Command cmd = null; @@ -271,9 +246,9 @@ public class CommandGroup extends Command { entry = (Entry) m_commands.elementAt(m_currentCommandIndex); cmd = null; - switch (entry.state) { + switch (entry.m_state) { case Entry.IN_SEQUENCE: - cmd = entry.command; + cmd = entry.m_command; if (firstRun) { cmd.startRunning(); cancelConflicts(cmd); @@ -282,21 +257,23 @@ public class CommandGroup extends Command { break; case Entry.BRANCH_PEER: m_currentCommandIndex++; - entry.command.start(); + entry.m_command.start(); break; case Entry.BRANCH_CHILD: m_currentCommandIndex++; - cancelConflicts(entry.command); - entry.command.startRunning(); + cancelConflicts(entry.m_command); + entry.m_command.startRunning(); m_children.addElement(entry); break; + default: + break; } } // Run Children for (int i = 0; i < m_children.size(); i++) { entry = (Entry) m_children.elementAt(i); - Command child = entry.command; + Command child = entry.m_command; if (entry.isTimedOut()) { child._cancel(); } @@ -307,36 +284,36 @@ public class CommandGroup extends Command { } } + @SuppressWarnings("MethodName") void _end() { // Theoretically, we don't have to check this, but we do if teams override // the isFinished method if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) { - Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command; + Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).m_command; cmd._cancel(); cmd.removed(); } Enumeration children = m_children.elements(); while (children.hasMoreElements()) { - Command cmd = ((Entry) children.nextElement()).command; + Command cmd = ((Entry) children.nextElement()).m_command; cmd._cancel(); cmd.removed(); } m_children.removeAllElements(); } + @SuppressWarnings("MethodName") void _interrupted() { _end(); } /** - * Returns true if all the {@link Command Commands} in this group have been - * started and have finished. + * Returns true if all the {@link Command Commands} in this group have been started and have + * finished. * - *

- * Teams may override this method, although they should probably reference - * super.isFinished() if they do. - *

+ *

Teams may override this method, although they should probably reference super.isFinished() + * if they do.

* * @return whether this {@link CommandGroup} is finished */ @@ -345,22 +322,25 @@ public class CommandGroup extends Command { } // Can be overwritten by teams - protected void initialize() {} + protected void initialize() { + } // Can be overwritten by teams - protected void execute() {} + protected void execute() { + } // Can be overwritten by teams - protected void end() {} + protected void end() { + } // Can be overwritten by teams - protected void interrupted() {} + protected void interrupted() { + } /** - * Returns whether or not this group is interruptible. A command group will be - * uninterruptible if {@link CommandGroup#setInterruptible(boolean) - * setInterruptable(false)} was called or if it is currently running an - * uninterruptible command or child. + * Returns whether or not this group is interruptible. A command group will be uninterruptible if + * {@link CommandGroup#setInterruptible(boolean) setInterruptable(false)} was called or if it is + * currently running an uninterruptible command or child. * * @return whether or not this {@link CommandGroup} is interruptible. */ @@ -370,14 +350,14 @@ public class CommandGroup extends Command { } if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) { - Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command; + Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).m_command; if (!cmd.isInterruptible()) { return false; } } for (int i = 0; i < m_children.size(); i++) { - if (!((Entry) m_children.elementAt(i)).command.isInterruptible()) { + if (!((Entry) m_children.elementAt(i)).m_command.isInterruptible()) { return false; } } @@ -387,7 +367,7 @@ public class CommandGroup extends Command { private void cancelConflicts(Command command) { for (int i = 0; i < m_children.size(); i++) { - Command child = ((Entry) m_children.elementAt(i)).command; + Command child = ((Entry) m_children.elementAt(i)).m_command; Enumeration requirements = command.getRequirements(); @@ -408,28 +388,28 @@ public class CommandGroup extends Command { private static final int IN_SEQUENCE = 0; private static final int BRANCH_PEER = 1; private static final int BRANCH_CHILD = 2; - Command command; - int state; - double timeout; + private final Command m_command; + private final int m_state; + private final double m_timeout; Entry(Command command, int state) { - this.command = command; - this.state = state; - this.timeout = -1; + m_command = command; + m_state = state; + m_timeout = -1; } Entry(Command command, int state, double timeout) { - this.command = command; - this.state = state; - this.timeout = timeout; + m_command = command; + m_state = state; + m_timeout = timeout; } boolean isTimedOut() { - if (timeout == -1) { + if (m_timeout == -1) { return false; } else { - double time = command.timeSinceInitialized(); - return time == 0 ? false : time >= timeout; + double time = m_command.timeSinceInitialized(); + return time != 0 && time >= m_timeout; } } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java index dc8c54f1f0..3bf1968dd0 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java @@ -8,19 +8,15 @@ package edu.wpi.first.wpilibj.command; /** - * This exception will be thrown if a command is used illegally. There are - * several ways for this to happen. + * This exception will be thrown if a command is used illegally. There are several ways for this to + * happen. * - *

- * Basically, a command becomes "locked" after it is first started or added to a - * command group. + *

Basically, a command becomes "locked" after it is first started or added to a command group. *

* - *

- * This exception should be thrown if (after a command has been locked) its - * requirements change, it is put into multiple command groups, it is started - * from outside its command group, or it adds a new child. - *

+ *

This exception should be thrown if (after a command has been locked) its requirements change, + * it is put into multiple command groups, it is started from outside its command group, or it adds + * a new child.

* * @author Joe Grinstead */ @@ -29,12 +25,12 @@ public class IllegalUseOfCommandException extends RuntimeException { /** * Instantiates an {@link IllegalUseOfCommandException}. */ - public IllegalUseOfCommandException() {} + public IllegalUseOfCommandException() { + } /** - * Instantiates an {@link IllegalUseOfCommandException} with the given - * message. - *$ + * Instantiates an {@link IllegalUseOfCommandException} with the given message. + * * @param message the message */ public IllegalUseOfCommandException(String message) { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/LinkedListElement.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/LinkedListElement.java index 8edc8c5fb0..b26ac9972d 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/LinkedListElement.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/LinkedListElement.java @@ -8,58 +8,60 @@ package edu.wpi.first.wpilibj.command; /** + * An element that is in a LinkedList. * * @author Greg */ class LinkedListElement { - private LinkedListElement next; - private LinkedListElement previous; - private Command data; + private LinkedListElement m_next; + private LinkedListElement m_previous; + private Command m_data; - public LinkedListElement() {} + public LinkedListElement() { + } public void setData(Command newData) { - data = newData; + m_data = newData; } public Command getData() { - return data; + return m_data; } public LinkedListElement getNext() { - return next; + return m_next; } public LinkedListElement getPrevious() { - return previous; + return m_previous; } - public void add(LinkedListElement l) { - if (next == null) { - next = l; - next.previous = this; + public void add(LinkedListElement listElement) { + if (m_next == null) { + m_next = listElement; + m_next.m_previous = this; } else { - next.previous = l; - l.next = next; - l.previous = this; - next = l; + m_next.m_previous = listElement; + listElement.m_next = m_next; + listElement.m_previous = this; + m_next = listElement; } } public LinkedListElement remove() { - if (previous == null && next == null) { - - } else if (next == null) { - previous.next = null; - } else if (previous == null) { - next.previous = null; + if (m_previous == null && m_next == null) { + // no-op + } else if (m_next == null) { + m_previous.m_next = null; + } else if (m_previous == null) { + m_next.m_previous = null; } else { - next.previous = previous; - previous.next = next; + m_next.m_previous = m_previous; + m_previous.m_next = m_next; } - LinkedListElement n = next; - next = null; - previous = null; - return n; + LinkedListElement returnNext = m_next; + m_next = null; + m_previous = null; + return returnNext; } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDCommand.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDCommand.java index 9da84c7686..8f75b5e30a 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDCommand.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDCommand.java @@ -17,28 +17,28 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * This class defines a {@link Command} which interacts heavily with a PID loop. * - *

- * It provides some convenience methods to run an internal {@link PIDController} - * . It will also start and stop said {@link PIDController} when the - * {@link PIDCommand} is first initialized and ended/interrupted. - *

+ *

It provides some convenience methods to run an internal {@link PIDController} . It will also + * start and stop said {@link PIDController} when the {@link PIDCommand} is first initialized and + * ended/interrupted.

* * @author Joe Grinstead */ public abstract class PIDCommand extends Command implements Sendable { - /** The internal {@link PIDController} */ - private PIDController controller; - /** An output which calls {@link PIDCommand#usePIDOutput(double)} */ - private PIDOutput output = new PIDOutput() { - - public void pidWrite(double output) { - usePIDOutput(output); + /** + * The internal {@link PIDController}. + */ + private final PIDController m_controller; + /** + * An output which calls {@link PIDCommand#usePIDOutput(double)}. + */ + private final PIDOutput m_output = this::usePIDOutput; + /** + * A source which calls {@link PIDCommand#returnPIDInput()}. + */ + private final PIDSource m_source = new PIDSource() { + public void setPIDSourceType(PIDSourceType pidSource) { } - }; - /** A source which calls {@link PIDCommand#returnPIDInput()} */ - private PIDSource source = new PIDSource() { - public void setPIDSourceType(PIDSourceType pidSource) {} public PIDSourceType getPIDSourceType() { return PIDSourceType.kDisplacement; @@ -50,88 +50,95 @@ public abstract class PIDCommand extends Command implements Sendable { }; /** - * Instantiates a {@link PIDCommand} that will use the given p, i and d - * values. - *$ + * Instantiates a {@link PIDCommand} that will use the given p, i and d values. + * * @param name the name of the command - * @param p the proportional value - * @param i the integral value - * @param d the derivative value + * @param p the proportional value + * @param i the integral value + * @param d the derivative value */ + @SuppressWarnings("ParameterName") public PIDCommand(String name, double p, double i, double d) { super(name); - controller = new PIDController(p, i, d, source, output); + m_controller = new PIDController(p, i, d, m_source, m_output); } /** - * Instantiates a {@link PIDCommand} that will use the given p, i and d - * values. It will also space the time between PID loop calculations to be - * equal to the given period. - *$ - * @param name the name - * @param p the proportional value - * @param i the integral value - * @param d the derivative value + * Instantiates a {@link PIDCommand} that will use the given p, i and d values. It will also space + * the time between PID loop calculations to be equal to the given period. + * + * @param name the name + * @param p the proportional value + * @param i the integral value + * @param d the derivative value * @param period the time (in seconds) between calculations */ + @SuppressWarnings("ParameterName") public PIDCommand(String name, double p, double i, double d, double period) { super(name); - controller = new PIDController(p, i, d, source, output, period); + m_controller = new PIDController(p, i, d, m_source, m_output, period); } /** - * Instantiates a {@link PIDCommand} that will use the given p, i and d - * values. It will use the class name as its name. - *$ + * Instantiates a {@link PIDCommand} that will use the given p, i and d values. It will use the + * class name as its name. + * * @param p the proportional value * @param i the integral value * @param d the derivative value */ + @SuppressWarnings("ParameterName") public PIDCommand(double p, double i, double d) { - controller = new PIDController(p, i, d, source, output); + m_controller = new PIDController(p, i, d, m_source, m_output); } /** - * Instantiates a {@link PIDCommand} that will use the given p, i and d - * values. It will use the class name as its name.. It will also space the - * time between PID loop calculations to be equal to the given period. - *$ - * @param p the proportional value - * @param i the integral value - * @param d the derivative value + * Instantiates a {@link PIDCommand} that will use the given p, i and d values. It will use the + * class name as its name.. It will also space the time between PID loop calculations to be equal + * to the given period. + * + * @param p the proportional value + * @param i the integral value + * @param d the derivative value * @param period the time (in seconds) between calculations */ + @SuppressWarnings("ParameterName") public PIDCommand(double p, double i, double d, double period) { - controller = new PIDController(p, i, d, source, output, period); + m_controller = new PIDController(p, i, d, m_source, m_output, period); } /** - * Returns the {@link PIDController} used by this {@link PIDCommand}. Use this - * if you would like to fine tune the pid loop. + * Returns the {@link PIDController} used by this {@link PIDCommand}. Use this if you would like + * to fine tune the pid loop. * * @return the {@link PIDController} used by this {@link PIDCommand} */ protected PIDController getPIDController() { - return controller; + return m_controller; } + @Override + @SuppressWarnings("MethodName") void _initialize() { - controller.enable(); + m_controller.enable(); } + @Override + @SuppressWarnings("MethodName") void _end() { - controller.disable(); + m_controller.disable(); } + @Override + @SuppressWarnings("MethodName") void _interrupted() { _end(); } /** - * Adds the given value to the setpoint. If - * {@link PIDCommand#setInputRange(double, double) setInputRange(...)} was - * used, then the bounds will still be honored by this method. - *$ + * Adds the given value to the setpoint. If {@link PIDCommand#setInputRange(double, double) + * setInputRange(...)} was used, then the bounds will still be honored by this method. + * * @param deltaSetpoint the change in the setpoint */ public void setSetpointRelative(double deltaSetpoint) { @@ -139,28 +146,28 @@ public abstract class PIDCommand extends Command implements Sendable { } /** - * Sets the setpoint to the given value. If - * {@link PIDCommand#setInputRange(double, double) setInputRange(...)} was - * called, then the given setpoint will be trimmed to fit within the range. - *$ + * Sets the setpoint to the given value. If {@link PIDCommand#setInputRange(double, double) + * setInputRange(...)} was called, then the given setpoint will be trimmed to fit within the + * range. + * * @param setpoint the new setpoint */ protected void setSetpoint(double setpoint) { - controller.setSetpoint(setpoint); + m_controller.setSetpoint(setpoint); } /** * Returns the setpoint. - *$ + * * @return the setpoint */ protected double getSetpoint() { - return controller.getSetpoint(); + return m_controller.getSetpoint(); } /** - * Returns the current position - *$ + * Returns the current position. + * * @return the current position */ protected double getPosition() { @@ -174,44 +181,31 @@ public abstract class PIDCommand extends Command implements Sendable { * @param maximumInput the maximum value expected from the input and setpoint */ protected void setInputRange(double minimumInput, double maximumInput) { - controller.setInputRange(minimumInput, maximumInput); + m_controller.setInputRange(minimumInput, maximumInput); } /** * Returns the input for the pid loop. * - *

- * It returns the input for the pid loop, so if this command was based off of - * a gyro, then it should return the angle of the gyro - *

+ *

It returns the input for the pid loop, so if this command was based off of a gyro, then it + * should return the angle of the gyro. * - *

- * All subclasses of {@link PIDCommand} must override this method. - *

+ *

All subclasses of {@link PIDCommand} must override this method. * - *

- * This method will be called in a different thread then the {@link Scheduler} - * thread. - *

+ *

This method will be called in a different thread then the {@link Scheduler} thread. * * @return the value the pid loop should use as input */ protected abstract double returnPIDInput(); /** - * Uses the value that the pid loop calculated. The calculated value is the - * "output" parameter. This method is a good time to set motor values, maybe - * something along the lines of + * Uses the value that the pid loop calculated. The calculated value is the "output" parameter. + * This method is a good time to set motor values, maybe something along the lines of * driveline.tankDrive(output, -output) * - *

- * All subclasses of {@link PIDCommand} must override this method. - *

+ *

All subclasses of {@link PIDCommand} must override this method. * - *

- * This method will be called in a different thread then the {@link Scheduler} - * thread. - *

+ *

This method will be called in a different thread then the {@link Scheduler} thread. * * @param output the value the pid loop calculated */ @@ -222,7 +216,7 @@ public abstract class PIDCommand extends Command implements Sendable { } public void initTable(ITable table) { - controller.initTable(table); + m_controller.initTable(table); super.initTable(table); } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java index 2f5a5f59ea..70f527a498 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java @@ -15,32 +15,33 @@ import edu.wpi.first.wpilibj.Sendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * This class is designed to handle the case where there is a {@link Subsystem} - * which uses a single {@link PIDController} almost constantly (for instance, an - * elevator which attempts to stay at a constant height). + * This class is designed to handle the case where there is a {@link Subsystem} which uses a single + * {@link PIDController} almost constantly (for instance, an elevator which attempts to stay at a + * constant height). * - *

- * It provides some convenience methods to run an internal {@link PIDController} - * . It also allows access to the internal {@link PIDController} in order to - * give total control to the programmer. - *

+ *

It provides some convenience methods to run an internal {@link PIDController} . It also + * allows access to the internal {@link PIDController} in order to give total control to the + * programmer. * * @author Joe Grinstead */ public abstract class PIDSubsystem extends Subsystem implements Sendable { - /** The internal {@link PIDController} */ - private PIDController controller; - /** An output which calls {@link PIDCommand#usePIDOutput(double)} */ - private PIDOutput output = new PIDOutput() { + /** + * The internal {@link PIDController}. + */ + private final PIDController m_controller; + /** + * An output which calls {@link PIDCommand#usePIDOutput(double)}. + */ + private final PIDOutput m_output = this::usePIDOutput; - public void pidWrite(double output) { - usePIDOutput(output); + /** + * A source which calls {@link PIDCommand#returnPIDInput()}. + */ + private final PIDSource m_source = new PIDSource() { + public void setPIDSourceType(PIDSourceType pidSource) { } - }; - /** A source which calls {@link PIDCommand#returnPIDInput()} */ - private PIDSource source = new PIDSource() { - public void setPIDSourceType(PIDSourceType pidSource) {} public PIDSourceType getPIDSourceType() { return PIDSourceType.kDisplacement; @@ -52,107 +53,109 @@ public abstract class PIDSubsystem extends Subsystem implements Sendable { }; /** - * Instantiates a {@link PIDSubsystem} that will use the given p, i and d - * values. - *$ + * Instantiates a {@link PIDSubsystem} that will use the given p, i and d values. + * * @param name the name - * @param p the proportional value - * @param i the integral value - * @param d the derivative value + * @param p the proportional value + * @param i the integral value + * @param d the derivative value */ + @SuppressWarnings("ParameterName") public PIDSubsystem(String name, double p, double i, double d) { super(name); - controller = new PIDController(p, i, d, source, output); + m_controller = new PIDController(p, i, d, m_source, m_output); } /** - * Instantiates a {@link PIDSubsystem} that will use the given p, i and d - * values. - *$ + * Instantiates a {@link PIDSubsystem} that will use the given p, i and d values. + * * @param name the name - * @param p the proportional value - * @param i the integral value - * @param d the derivative value - * @param f the feed forward value + * @param p the proportional value + * @param i the integral value + * @param d the derivative value + * @param f the feed forward value */ + @SuppressWarnings("ParameterName") public PIDSubsystem(String name, double p, double i, double d, double f) { super(name); - controller = new PIDController(p, i, d, f, source, output); + m_controller = new PIDController(p, i, d, f, m_source, m_output); } /** - * Instantiates a {@link PIDSubsystem} that will use the given p, i and d - * values. It will also space the time between PID loop calculations to be - * equal to the given period. - *$ - * @param name the name - * @param p the proportional value - * @param i the integral value - * @param d the derivative value + * Instantiates a {@link PIDSubsystem} that will use the given p, i and d values. It will also + * space the time between PID loop calculations to be equal to the given period. + * + * @param name the name + * @param p the proportional value + * @param i the integral value + * @param d the derivative value * @param period the time (in seconds) between calculations */ + @SuppressWarnings("ParameterName") public PIDSubsystem(String name, double p, double i, double d, double f, double period) { super(name); - controller = new PIDController(p, i, d, f, source, output, period); + m_controller = new PIDController(p, i, d, f, m_source, m_output, period); } /** - * Instantiates a {@link PIDSubsystem} that will use the given p, i and d - * values. It will use the class name as its name. - *$ + * Instantiates a {@link PIDSubsystem} that will use the given p, i and d values. It will use the + * class name as its name. + * * @param p the proportional value * @param i the integral value * @param d the derivative value */ + @SuppressWarnings("ParameterName") public PIDSubsystem(double p, double i, double d) { - controller = new PIDController(p, i, d, source, output); + m_controller = new PIDController(p, i, d, m_source, m_output); } /** - * Instantiates a {@link PIDSubsystem} that will use the given p, i and d - * values. It will use the class name as its name. It will also space the time - * between PID loop calculations to be equal to the given period. - *$ - * @param p the proportional value - * @param i the integral value - * @param d the derivative value - * @param f the feed forward coefficient + * Instantiates a {@link PIDSubsystem} that will use the given p, i and d values. It will use the + * class name as its name. It will also space the time between PID loop calculations to be equal + * to the given period. + * + * @param p the proportional value + * @param i the integral value + * @param d the derivative value + * @param f the feed forward coefficient * @param period the time (in seconds) between calculations */ + @SuppressWarnings("ParameterName") public PIDSubsystem(double p, double i, double d, double period, double f) { - controller = new PIDController(p, i, d, f, source, output, period); + m_controller = new PIDController(p, i, d, f, m_source, m_output, period); } /** - * Instantiates a {@link PIDSubsystem} that will use the given p, i and d - * values. It will use the class name as its name. It will also space the time - * between PID loop calculations to be equal to the given period. - *$ - * @param p the proportional value - * @param i the integral value - * @param d the derivative value + * Instantiates a {@link PIDSubsystem} that will use the given p, i and d values. It will use the + * class name as its name. It will also space the time between PID loop calculations to be equal + * to the given period. + * + * @param p the proportional value + * @param i the integral value + * @param d the derivative value * @param period the time (in seconds) between calculations */ + @SuppressWarnings("ParameterName") public PIDSubsystem(double p, double i, double d, double period) { - controller = new PIDController(p, i, d, source, output, period); + m_controller = new PIDController(p, i, d, m_source, m_output, period); } /** - * Returns the {@link PIDController} used by this {@link PIDSubsystem}. Use - * this if you would like to fine tune the pid loop. + * Returns the {@link PIDController} used by this {@link PIDSubsystem}. Use this if you would like + * to fine tune the pid loop. * * @return the {@link PIDController} used by this {@link PIDSubsystem} */ public PIDController getPIDController() { - return controller; + return m_controller; } /** - * Adds the given value to the setpoint. If - * {@link PIDSubsystem#setInputRange(double, double) setInputRange(...)} was - * used, then the bounds will still be honored by this method. - *$ + * Adds the given value to the setpoint. If {@link PIDSubsystem#setInputRange(double, double) + * setInputRange(...)} was used, then the bounds will still be honored by this method. + * * @param deltaSetpoint the change in the setpoint */ public void setSetpointRelative(double deltaSetpoint) { @@ -160,28 +163,28 @@ public abstract class PIDSubsystem extends Subsystem implements Sendable { } /** - * Sets the setpoint to the given value. If - * {@link PIDSubsystem#setInputRange(double, double) setInputRange(...)} was - * called, then the given setpoint will be trimmed to fit within the range. - *$ + * Sets the setpoint to the given value. If {@link PIDSubsystem#setInputRange(double, double) + * setInputRange(...)} was called, then the given setpoint will be trimmed to fit within the + * range. + * * @param setpoint the new setpoint */ public void setSetpoint(double setpoint) { - controller.setSetpoint(setpoint); + m_controller.setSetpoint(setpoint); } /** * Returns the setpoint. - *$ + * * @return the setpoint */ public double getSetpoint() { - return controller.getSetpoint(); + return m_controller.getSetpoint(); } /** - * Returns the current position - *$ + * Returns the current position. + * * @return the current position */ public double getPosition() { @@ -195,7 +198,7 @@ public abstract class PIDSubsystem extends Subsystem implements Sendable { * @param maximumInput the maximum value expected from the output */ public void setInputRange(double minimumInput, double maximumInput) { - controller.setInputRange(minimumInput, maximumInput); + m_controller.setInputRange(minimumInput, maximumInput); } /** @@ -205,90 +208,86 @@ public abstract class PIDSubsystem extends Subsystem implements Sendable { * @param maximumOutput the maximum value to write to the output */ public void setOutputRange(double minimumOutput, double maximumOutput) { - controller.setOutputRange(minimumOutput, maximumOutput); + m_controller.setOutputRange(minimumOutput, maximumOutput); } /** - * Set the absolute error which is considered tolerable for use with OnTarget. - * The value is in the same range as the PIDInput values. - *$ + * Set the absolute error which is considered tolerable for use with OnTarget. The value is in the + * same range as the PIDInput values. + * * @param t the absolute tolerance */ + @SuppressWarnings("ParameterName") public void setAbsoluteTolerance(double t) { - controller.setAbsoluteTolerance(t); + m_controller.setAbsoluteTolerance(t); } /** - * Set the percentage error which is considered tolerable for use with - * OnTarget. (Value of 15.0 == 15 percent) - *$ + * Set the percentage error which is considered tolerable for use with OnTarget. (Value of 15.0 == + * 15 percent). + * * @param p the percent tolerance */ + @SuppressWarnings("ParameterName") public void setPercentTolerance(double p) { - controller.setPercentTolerance(p); + m_controller.setPercentTolerance(p); } /** - * Return true if the error is within the percentage of the total input range, - * determined by setTolerance. This assumes that the maximum and minimum input - * were set using setInput. - *$ + * Return true if the error is within the percentage of the total input range, determined by + * setTolerance. This assumes that the maximum and minimum input were set using setInput. + * * @return true if the error is less than the tolerance */ public boolean onTarget() { - return controller.onTarget(); + return m_controller.onTarget(); } /** * Returns the input for the pid loop. * - *

- * It returns the input for the pid loop, so if this Subsystem was based off - * of a gyro, then it should return the angle of the gyro - *

+ *

It returns the input for the pid loop, so if this Subsystem was based off of a gyro, then + * it should return the angle of the gyro. * - *

- * All subclasses of {@link PIDSubsystem} must override this method. - *

+ *

All subclasses of {@link PIDSubsystem} must override this method. * * @return the value the pid loop should use as input */ protected abstract double returnPIDInput(); /** - * Uses the value that the pid loop calculated. The calculated value is the - * "output" parameter. This method is a good time to set motor values, maybe - * something along the lines of - * driveline.tankDrive(output, -output) + * Uses the value that the pid loop calculated. The calculated value is the "output" parameter. + * This method is a good time to set motor values, maybe something along the lines of + * driveline.tankDrive(output, -output). * - *

- * All subclasses of {@link PIDSubsystem} must override this method. - *

+ *

All subclasses of {@link PIDSubsystem} must override this method. * * @param output the value the pid loop calculated */ protected abstract void usePIDOutput(double output); /** - * Enables the internal {@link PIDController} + * Enables the internal {@link PIDController}. */ public void enable() { - controller.enable(); + m_controller.enable(); } /** - * Disables the internal {@link PIDController} + * Disables the internal {@link PIDController}. */ public void disable() { - controller.disable(); + m_controller.disable(); } + @Override public String getSmartDashboardType() { return "PIDSubsystem"; } + @Override public void initTable(ITable table) { - controller.initTable(table); + m_controller.initTable(table); super.initTable(table); } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PrintCommand.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PrintCommand.java index 60b8c6c462..53926cefd0 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PrintCommand.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/PrintCommand.java @@ -8,39 +8,43 @@ package edu.wpi.first.wpilibj.command; /** - * A {@link PrintCommand} is a command which prints out a string when it is - * initialized, and then immediately finishes. It is useful if you want a - * {@link CommandGroup} to print out a string when it reaches a certain point. + * A {@link PrintCommand} is a command which prints out a string when it is initialized, and then + * immediately finishes. It is useful if you want a {@link CommandGroup} to print out a string when + * it reaches a certain point. * * @author Joe Grinstead */ public class PrintCommand extends Command { - /** The message to print out */ - private String message; + /** + * The message to print out. + */ + private String m_message; /** - * Instantiates a {@link PrintCommand} which will print the given message when - * it is run. - *$ + * Instantiates a {@link PrintCommand} which will print the given message when it is run. + * * @param message the message to print */ public PrintCommand(String message) { super("Print(\"" + message + "\""); - this.message = message; + m_message = message; } protected void initialize() { - System.out.println(message); + System.out.println(m_message); } - protected void execute() {} + protected void execute() { + } protected boolean isFinished() { return true; } - protected void end() {} + protected void end() { + } - protected void interrupted() {} + protected void interrupted() { + } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Scheduler.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Scheduler.java index 377b277267..c6b5faf599 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Scheduler.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Scheduler.java @@ -17,18 +17,14 @@ import edu.wpi.first.wpilibj.buttons.Trigger.ButtonScheduler; import edu.wpi.first.wpilibj.tables.ITable; /** - * The {@link Scheduler} is a singleton which holds the top-level running - * commands. It is in charge of both calling the command's {@link Command#run() - * run()} method and to make sure that there are no two commands with - * conflicting requirements running. + * The {@link Scheduler} is a singleton which holds the top-level running commands. It is in charge + * of both calling the command's {@link Command#run() run()} method and to make sure that there are + * no two commands with conflicting requirements running. * - *

- * It is fine if teams wish to take control of the {@link Scheduler} themselves, - * all that needs to be done is to call {@link Scheduler#getInstance() - * Scheduler.getInstance()}.{@link Scheduler#run() run()} often to have - * {@link Command Commands} function correctly. However, this is already done - * for you if you use the CommandBased Robot template. - *

+ *

It is fine if teams wish to take control of the {@link Scheduler} themselves, all that needs + * to be done is to call {@link Scheduler#getInstance() Scheduler.getInstance()}.{@link + * Scheduler#run() run()} often to have {@link Command Commands} function correctly. However, this + * is already done for you if you use the CommandBased Robot template.

* * @author Joe Grinstead * @see Command @@ -36,7 +32,7 @@ import edu.wpi.first.wpilibj.tables.ITable; public class Scheduler implements NamedSendable { /** - * The Singleton Instance + * The Singleton Instance. */ private static Scheduler instance; @@ -45,45 +41,44 @@ public class Scheduler implements NamedSendable { * * @return the {@link Scheduler} */ - public synchronized static Scheduler getInstance() { + public static synchronized Scheduler getInstance() { return instance == null ? instance = new Scheduler() : instance; } /** - * A hashtable of active {@link Command Commands} to their - * {@link LinkedListElement} + * A hashtable of active {@link Command Commands} to their {@link LinkedListElement}. */ - private Hashtable commandTable = new Hashtable(); + private Hashtable m_commandTable = new Hashtable(); /** - * The {@link Set} of all {@link Subsystem Subsystems} + * The {@link Set} of all {@link Subsystem Subsystems}. */ - private Set subsystems = new Set(); + private Set m_subsystems = new Set(); /** - * The first {@link Command} in the list + * The first {@link Command} in the list. */ - private LinkedListElement firstCommand; + private LinkedListElement m_firstCommand; /** - * The last {@link Command} in the list + * The last {@link Command} in the list. */ - private LinkedListElement lastCommand; + private LinkedListElement m_lastCommand; /** - * Whether or not we are currently adding a command + * Whether or not we are currently adding a command. */ - private boolean adding = false; + private boolean m_adding = false; /** - * Whether or not we are currently disabled + * Whether or not we are currently disabled. */ - private boolean disabled = false; + private boolean m_disabled = false; /** - * A list of all {@link Command Commands} which need to be added + * A list of all {@link Command Commands} which need to be added. */ - private Vector additions = new Vector(); + private Vector m_additions = new Vector(); private ITable m_table; /** - * A list of all {@link edu.wpi.first.wpilibj.buttons.Trigger.ButtonScheduler - * Buttons}. It is created lazily. + * A list of all {@link edu.wpi.first.wpilibj.buttons.Trigger.ButtonScheduler Buttons}. It is + * created lazily. */ - private Vector buttons; + private Vector m_buttons; private boolean m_runningCommandsChanged; /** @@ -94,59 +89,55 @@ public class Scheduler implements NamedSendable { } /** - * Adds the command to the {@link Scheduler}. This will not add the - * {@link Command} immediately, but will instead wait for the proper time in - * the {@link Scheduler#run()} loop before doing so. The command returns - * immediately and does nothing if given null. + * Adds the command to the {@link Scheduler}. This will not add the {@link Command} immediately, + * but will instead wait for the proper time in the {@link Scheduler#run()} loop before doing so. + * The command returns immediately and does nothing if given null. * - *

- * Adding a {@link Command} to the {@link Scheduler} involves the - * {@link Scheduler} removing any {@link Command} which has shared - * requirements. - *

+ *

Adding a {@link Command} to the {@link Scheduler} involves the {@link Scheduler} removing + * any {@link Command} which has shared requirements.

* * @param command the command to add */ public void add(Command command) { if (command != null) { - additions.addElement(command); + m_additions.addElement(command); } } /** - * Adds a button to the {@link Scheduler}. The {@link Scheduler} will poll the - * button during its {@link Scheduler#run()}. + * Adds a button to the {@link Scheduler}. The {@link Scheduler} will poll the button during its + * {@link Scheduler#run()}. * * @param button the button to add */ public void addButton(ButtonScheduler button) { - if (buttons == null) { - buttons = new Vector(); + if (m_buttons == null) { + m_buttons = new Vector(); } - buttons.addElement(button); + m_buttons.addElement(button); } /** - * Adds a command immediately to the {@link Scheduler}. This should only be - * called in the {@link Scheduler#run()} loop. Any command with conflicting - * requirements will be removed, unless it is uninterruptable. Giving - * null does nothing. + * Adds a command immediately to the {@link Scheduler}. This should only be called in the {@link + * Scheduler#run()} loop. Any command with conflicting requirements will be removed, unless it is + * uninterruptable. Giving null does nothing. * * @param command the {@link Command} to add */ + @SuppressWarnings("MethodName") private void _add(Command command) { if (command == null) { return; } // Check to make sure no adding during adding - if (adding) { + if (m_adding) { System.err.println("WARNING: Can not start command from cancel method. Ignoring:" + command); return; } // Only add if not already in - if (!commandTable.containsKey(command)) { + if (!m_commandTable.containsKey(command)) { // Check that the requirements can be had Enumeration requirements = command.getRequirements(); @@ -158,7 +149,7 @@ public class Scheduler implements NamedSendable { } // Give it the requirements - adding = true; + m_adding = true; requirements = command.getRequirements(); while (requirements.hasMoreElements()) { Subsystem lock = (Subsystem) requirements.nextElement(); @@ -168,18 +159,18 @@ public class Scheduler implements NamedSendable { } lock.setCurrentCommand(command); } - adding = false; + m_adding = false; // Add it to the list LinkedListElement element = new LinkedListElement(); element.setData(command); - if (firstCommand == null) { - firstCommand = lastCommand = element; + if (m_firstCommand == null) { + m_firstCommand = m_lastCommand = element; } else { - lastCommand.add(element); - lastCommand = element; + m_lastCommand.add(element); + m_lastCommand = element; } - commandTable.put(command, element); + m_commandTable.put(command, element); m_runningCommandsChanged = true; @@ -188,51 +179,45 @@ public class Scheduler implements NamedSendable { } /** - * Runs a single iteration of the loop. This method should be called often in - * order to have a functioning {@link Command} system. The loop has five - * stages: + * Runs a single iteration of the loop. This method should be called often in order to have a + * functioning {@link Command} system. The loop has five stages: * - *
    - *
  1. Poll the Buttons
  2. - *
  3. Execute/Remove the Commands
  4. - *
  5. Send values to SmartDashboard
  6. - *
  7. Add Commands
  8. - *
  9. Add Defaults
  10. - *
+ *
  1. Poll the Buttons
  2. Execute/Remove the Commands
  3. Send values to + * SmartDashboard
  4. Add Commands
  5. Add Defaults
*/ public void run() { m_runningCommandsChanged = false; - if (disabled) { + if (m_disabled) { return; - } // Don't run when disabled + } // Don't run when m_disabled // Get button input (going backwards preserves button priority) - if (buttons != null) { - for (int i = buttons.size() - 1; i >= 0; i--) { - ((ButtonScheduler) buttons.elementAt(i)).execute(); + if (m_buttons != null) { + for (int i = m_buttons.size() - 1; i >= 0; i--) { + ((ButtonScheduler) m_buttons.elementAt(i)).execute(); } } // Loop through the commands - LinkedListElement e = firstCommand; - while (e != null) { - Command c = e.getData(); - e = e.getNext(); - if (!c.run()) { - remove(c); + LinkedListElement element = m_firstCommand; + while (element != null) { + Command command = element.getData(); + element = element.getNext(); + if (!command.run()) { + remove(command); m_runningCommandsChanged = true; } } // Add the new things - for (int i = 0; i < additions.size(); i++) { - _add((Command) additions.elementAt(i)); + for (int i = 0; i < m_additions.size(); i++) { + _add((Command) m_additions.elementAt(i)); } - additions.removeAllElements(); + m_additions.removeAllElements(); // Add in the defaults - Enumeration locks = subsystems.getElements(); + Enumeration locks = m_subsystems.getElements(); while (locks.hasMoreElements()) { Subsystem lock = (Subsystem) locks.nextElement(); if (lock.getCurrentCommand() == null) { @@ -245,15 +230,15 @@ public class Scheduler implements NamedSendable { } /** - * Registers a {@link Subsystem} to this {@link Scheduler}, so that the - * {@link Scheduler} might know if a default {@link Command} needs to be run. - * All {@link Subsystem Subsystems} should call this. + * Registers a {@link Subsystem} to this {@link Scheduler}, so that the {@link Scheduler} might + * know if a default {@link Command} needs to be run. All {@link Subsystem Subsystems} should call + * this. * * @param system the system */ void registerSubsystem(Subsystem system) { if (system != null) { - subsystems.add(system); + m_subsystems.add(system); } } @@ -263,19 +248,19 @@ public class Scheduler implements NamedSendable { * @param command the command to remove */ void remove(Command command) { - if (command == null || !commandTable.containsKey(command)) { + if (command == null || !m_commandTable.containsKey(command)) { return; } - LinkedListElement e = (LinkedListElement) commandTable.get(command); - commandTable.remove(command); + LinkedListElement element = (LinkedListElement) m_commandTable.get(command); + m_commandTable.remove(command); - if (e.equals(lastCommand)) { - lastCommand = e.getPrevious(); + if (element.equals(m_lastCommand)) { + m_lastCommand = element.getPrevious(); } - if (e.equals(firstCommand)) { - firstCommand = e.getNext(); + if (element.equals(m_firstCommand)) { + m_firstCommand = element.getNext(); } - e.remove(); + element.remove(); Enumeration requirements = command.getRequirements(); while (requirements.hasMoreElements()) { @@ -286,12 +271,12 @@ public class Scheduler implements NamedSendable { } /** - * Removes all commands + * Removes all commands. */ public void removeAll() { // TODO: Confirm that this works with "uninteruptible" commands - while (firstCommand != null) { - remove(firstCommand.getData()); + while (m_firstCommand != null) { + remove(m_firstCommand.getData()); } } @@ -299,16 +284,17 @@ public class Scheduler implements NamedSendable { * Disable the command scheduler. */ public void disable() { - disabled = true; + m_disabled = true; } /** * Enable the command scheduler. */ public void enable() { - disabled = false; + m_disabled = false; } + @Override public String getName() { return "Scheduler"; } @@ -317,9 +303,7 @@ public class Scheduler implements NamedSendable { return "Scheduler"; } - /** - * {@inheritDoc} - */ + @Override public void initTable(ITable subtable) { m_table = subtable; @@ -333,7 +317,7 @@ public class Scheduler implements NamedSendable { // Get the commands to cancel double[] toCancel = m_table.getNumberArray("Cancel", new double[0]); if (toCancel.length > 0) { - for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { + for (LinkedListElement e = m_firstCommand; e != null; e = e.getNext()) { for (int i = 0; i < toCancel.length; i++) { if (e.getData().hashCode() == toCancel[i]) { e.getData().cancel(); @@ -345,17 +329,17 @@ public class Scheduler implements NamedSendable { if (m_runningCommandsChanged) { // Set the the running commands - int n = 0; - for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { - n++; + int number = 0; + for (LinkedListElement e = m_firstCommand; e != null; e = e.getNext()) { + number++; } - String[] commands = new String[n]; - double[] ids = new double[n]; - n = 0; - for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { - commands[n] = e.getData().getName(); - ids[n] = e.getData().hashCode(); - n++; + String[] commands = new String[number]; + double[] ids = new double[number]; + number = 0; + for (LinkedListElement e = m_firstCommand; e != null; e = e.getNext()) { + commands[number] = e.getData().getName(); + ids[number] = e.getData().hashCode(); + number++; } m_table.putStringArray("Names", commands); m_table.putNumberArray("Ids", ids); @@ -363,13 +347,12 @@ public class Scheduler implements NamedSendable { } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { return m_table; } + @Override public String getSmartDashboardType() { return "Scheduler"; } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Set.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Set.java index 7cf97e0cf7..b9df6c91db 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Set.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Set.java @@ -10,33 +10,36 @@ package edu.wpi.first.wpilibj.command; import java.util.Enumeration; import java.util.Vector; +@SuppressWarnings("all") /** * * @author Greg */ class Set { - Vector set = new Vector(); + private Vector m_set = new Vector(); - public Set() {} + public Set() { + } public void add(Object o) { - if (set.contains(o)) + if (m_set.contains(o)) { return; - set.addElement(o); + } + m_set.addElement(o); } public void add(Set s) { Enumeration stuff = s.getElements(); - for (Enumeration e = stuff; e.hasMoreElements();) { + for (Enumeration e = stuff; e.hasMoreElements(); ) { add(e.nextElement()); } } public boolean contains(Object o) { - return set.contains(o); + return m_set.contains(o); } public Enumeration getElements() { - return set.elements(); + return m_set.elements(); } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/StartCommand.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/StartCommand.java index 0b40d8cf64..2035d825e7 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/StartCommand.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/StartCommand.java @@ -8,20 +8,22 @@ package edu.wpi.first.wpilibj.command; /** - * A {@link StartCommand} will call the {@link Command#start() start()} method - * of another command when it is initialized and will finish immediately. + * A {@link StartCommand} will call the {@link Command#start() start()} method of another command + * when it is initialized and will finish immediately. * * @author Joe Grinstead */ public class StartCommand extends Command { - /** The command to fork */ + /** + * The command to fork. + */ private Command m_commandToFork; /** - * Instantiates a {@link StartCommand} which will start the given command - * whenever its {@link Command#initialize() initialize()} is called. - *$ + * Instantiates a {@link StartCommand} which will start the given command whenever its {@link + * Command#initialize() initialize()} is called. + * * @param commandToStart the {@link Command} to start */ public StartCommand(Command commandToStart) { @@ -33,13 +35,16 @@ public class StartCommand extends Command { m_commandToFork.start(); } - protected void execute() {} + protected void execute() { + } protected boolean isFinished() { return true; } - protected void end() {} + protected void end() { + } - protected void interrupted() {} + protected void interrupted() { + } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Subsystem.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Subsystem.java index 30c3a31744..ecad88eb5b 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Subsystem.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/Subsystem.java @@ -7,56 +7,54 @@ package edu.wpi.first.wpilibj.command; +import java.util.Enumeration; + import edu.wpi.first.wpilibj.NamedSendable; import edu.wpi.first.wpilibj.tables.ITable; -import java.util.Enumeration; -import java.util.Vector; /** * This class defines a major component of the robot. * - *

- * A good example of a subsystem is the driveline, or a claw if the robot has - * one. - *

+ *

A good example of a subsystem is the driveline, or a claw if the robot has one.

* - *

- * All motors should be a part of a subsystem. For instance, all the wheel - * motors should be a part of some kind of "Driveline" subsystem. - *

+ *

All motors should be a part of a subsystem. For instance, all the wheel motors should be a + * part of some kind of "Driveline" subsystem.

* - *

- * Subsystems are used within the command system as requirements for - * {@link Command}. Only one command which requires a subsystem can run at a - * time. Also, subsystems can have default commands which are started if there - * is no command running which requires this subsystem. - *

+ *

Subsystems are used within the command system as requirements for {@link Command}. Only one + * command which requires a subsystem can run at a time. Also, subsystems can have default commands + * which are started if there is no command running which requires this subsystem.

* * @author Joe Grinstead * @see Command */ public abstract class Subsystem implements NamedSendable { - /** Whether or not getDefaultCommand() was called */ - private boolean initializedDefaultCommand = false; - /** The current command */ - private Command currentCommand; - private boolean currentCommandChanged; - - /** The default command */ - private Command defaultCommand; - /** The name */ - private String name; - /** List of all subsystems created */ - private static Vector allSubsystems = new Vector(); + /** + * Whether or not getDefaultCommand() was called. + */ + private boolean m_initializedDefaultCommand = false; + /** + * The current command. + */ + private Command m_currentCommand; + private boolean m_currentCommandChanged; /** - * Creates a subsystem with the given name - *$ + * The default command. + */ + private Command m_defaultCommand; + /** + * The name. + */ + private String m_name; + + /** + * Creates a subsystem with the given name. + * * @param name the name of the subsystem */ public Subsystem(String name) { - this.name = name; + m_name = name; Scheduler.getInstance().registerSubsystem(this); } @@ -64,35 +62,31 @@ public abstract class Subsystem implements NamedSendable { * Creates a subsystem. This will set the name to the name of the class. */ public Subsystem() { - this.name = getClass().getName().substring(getClass().getName().lastIndexOf('.') + 1); + m_name = getClass().getName().substring(getClass().getName().lastIndexOf('.') + 1); Scheduler.getInstance().registerSubsystem(this); - currentCommandChanged = true; + m_currentCommandChanged = true; } /** - * Initialize the default command for a subsystem By default subsystems have - * no default command, but if they do, the default command is set with this - * method. It is called on all Subsystems by CommandBase in the users program - * after all the Subsystems are created. + * Initialize the default command for a subsystem By default subsystems have no default command, + * but if they do, the default command is set with this method. It is called on all Subsystems by + * CommandBase in the users program after all the Subsystems are created. */ protected abstract void initDefaultCommand(); /** - * Sets the default command. If this is not called or is called with null, - * then there will be no default command for the subsystem. + * Sets the default command. If this is not called or is called with null, then there will be no + * default command for the subsystem. * - *

- * WARNING: This should NOT be called in a constructor if the - * subsystem is a singleton. - *

+ *

WARNING: This should NOT be called in a constructor if the subsystem is a + * singleton.

* * @param command the default command (or null if there should be none) - * @throws IllegalUseOfCommandException if the command does not require the - * subsystem + * @throws IllegalUseOfCommandException if the command does not require the subsystem */ protected void setDefaultCommand(Command command) { if (command == null) { - defaultCommand = null; + m_defaultCommand = null; } else { boolean found = false; Enumeration requirements = command.getRequirements(); @@ -107,111 +101,112 @@ public abstract class Subsystem implements NamedSendable { if (!found) { throw new IllegalUseOfCommandException("A default command must require the subsystem"); } - defaultCommand = command; + m_defaultCommand = command; } - if (table != null) { - if (defaultCommand != null) { - table.putBoolean("hasDefault", true); - table.putString("default", defaultCommand.getName()); + if (m_table != null) { + if (m_defaultCommand != null) { + m_table.putBoolean("hasDefault", true); + m_table.putString("default", m_defaultCommand.getName()); } else { - table.putBoolean("hasDefault", false); + m_table.putBoolean("hasDefault", false); } } } /** * Returns the default command (or null if there is none). - *$ + * * @return the default command */ protected Command getDefaultCommand() { - if (!initializedDefaultCommand) { - initializedDefaultCommand = true; + if (!m_initializedDefaultCommand) { + m_initializedDefaultCommand = true; initDefaultCommand(); } - return defaultCommand; + return m_defaultCommand; } /** - * Sets the current command - *$ + * Sets the current command. + * * @param command the new current command */ void setCurrentCommand(Command command) { - currentCommand = command; - currentCommandChanged = true; + m_currentCommand = command; + m_currentCommandChanged = true; } /** - * Call this to alert Subsystem that the current command is actually the - * command. Sometimes, the {@link Subsystem} is told that it has no command - * while the {@link Scheduler} is going through the loop, only to be soon - * after given a new one. This will avoid that situation. + * Call this to alert Subsystem that the current command is actually the command. Sometimes, the + * {@link Subsystem} is told that it has no command while the {@link Scheduler} is going through + * the loop, only to be soon after given a new one. This will avoid that situation. */ void confirmCommand() { - if (currentCommandChanged) { - if (table != null) { - if (currentCommand != null) { - table.putBoolean("hasCommand", true); - table.putString("command", currentCommand.getName()); + if (m_currentCommandChanged) { + if (m_table != null) { + if (m_currentCommand != null) { + m_table.putBoolean("hasCommand", true); + m_table.putString("command", m_currentCommand.getName()); } else { - table.putBoolean("hasCommand", false); + m_table.putBoolean("hasCommand", false); } } - currentCommandChanged = false; + m_currentCommandChanged = false; } } /** * Returns the command which currently claims this subsystem. - *$ + * * @return the command which currently claims this subsystem */ public Command getCurrentCommand() { - return currentCommand; + return m_currentCommand; } + @Override public String toString() { return getName(); } /** * Returns the name of this subsystem, which is by default the class name. - *$ + * * @return the name of this subsystem */ + @Override public String getName() { - return name; + return m_name; } + @Override public String getSmartDashboardType() { return "Subsystem"; } - private ITable table; + private ITable m_table; + @Override public void initTable(ITable table) { - this.table = table; + m_table = table; if (table != null) { - if (defaultCommand != null) { + if (m_defaultCommand != null) { table.putBoolean("hasDefault", true); - table.putString("default", defaultCommand.getName()); + table.putString("default", m_defaultCommand.getName()); } else { table.putBoolean("hasDefault", false); } - if (currentCommand != null) { + if (m_currentCommand != null) { table.putBoolean("hasCommand", true); - table.putString("command", currentCommand.getName()); + table.putString("command", m_currentCommand.getName()); } else { table.putBoolean("hasCommand", false); } } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { - return table; + return m_table; } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitCommand.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitCommand.java index 207c3cd0ae..870f3cd7e5 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitCommand.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitCommand.java @@ -8,10 +8,9 @@ package edu.wpi.first.wpilibj.command; /** - * A {@link WaitCommand} will wait for a certain amount of time before - * finishing. It is useful if you want a {@link CommandGroup} to pause for a - * moment. - *$ + * A {@link WaitCommand} will wait for a certain amount of time before finishing. It is useful if + * you want a {@link CommandGroup} to pause for a moment. + * * @author Joe Grinstead * @see CommandGroup */ @@ -19,7 +18,7 @@ public class WaitCommand extends Command { /** * Instantiates a {@link WaitCommand} with the given timeout. - *$ + * * @param timeout the time the command takes to run */ public WaitCommand(double timeout) { @@ -28,23 +27,27 @@ public class WaitCommand extends Command { /** * Instantiates a {@link WaitCommand} with the given timeout. - *$ - * @param name the name of the command + * + * @param name the name of the command * @param timeout the time the command takes to run */ public WaitCommand(String name, double timeout) { super(name, timeout); } - protected void initialize() {} + protected void initialize() { + } - protected void execute() {} + protected void execute() { + } protected boolean isFinished() { return isTimedOut(); } - protected void end() {} + protected void end() { + } - protected void interrupted() {} + protected void interrupted() { + } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitForChildren.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitForChildren.java index 7cff89da8e..c004dd4c91 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitForChildren.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitForChildren.java @@ -8,28 +8,28 @@ package edu.wpi.first.wpilibj.command; /** - * This command will only finish if whatever {@link CommandGroup} it is in has - * no active children. If it is not a part of a {@link CommandGroup}, then it - * will finish immediately. If it is itself an active child, then the - * {@link CommandGroup} will never end. + * This command will only finish if whatever {@link CommandGroup} it is in has no active children. + * If it is not a part of a {@link CommandGroup}, then it will finish immediately. If it is itself + * an active child, then the {@link CommandGroup} will never end. + * + *

This class is useful for the situation where you want to allow anything running in parallel + * to finish, before continuing in the main {@link CommandGroup} sequence. * - *

- * This class is useful for the situation where you want to allow anything - * running in parallel to finish, before continuing in the main - * {@link CommandGroup} sequence. - *

- *$ * @author Joe Grinstead */ public class WaitForChildren extends Command { - protected void initialize() {} + protected void initialize() { + } - protected void execute() {} + protected void execute() { + } - protected void end() {} + protected void end() { + } - protected void interrupted() {} + protected void interrupted() { + } protected boolean isFinished() { return getGroup() == null || getGroup().m_children.isEmpty(); diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java index 062fdecdde..1b0ca864cc 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java @@ -10,11 +10,10 @@ package edu.wpi.first.wpilibj.command; import edu.wpi.first.wpilibj.Timer; /** - * WaitUntilCommand - waits until an absolute game time. This will wait until - * the game clock reaches some value, then continue to the next command. - *$ - * @author brad + * WaitUntilCommand - waits until an absolute game time. This will wait until the game clock reaches + * some value, then continue to the next command. * + * @author brad */ public class WaitUntilCommand extends Command { @@ -25,9 +24,11 @@ public class WaitUntilCommand extends Command { m_time = time; } - public void initialize() {} + public void initialize() { + } - public void execute() {} + public void execute() { + } /** * Check if we've reached the actual finish time. @@ -36,7 +37,9 @@ public class WaitUntilCommand extends Command { return Timer.getMatchTime() >= m_time; } - public void end() {} + public void end() { + } - public void interrupted() {} + public void interrupted() { + } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/Filter.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/Filter.java index 23f2993999..33d5ac0bdd 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/Filter.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/Filter.java @@ -11,7 +11,7 @@ import edu.wpi.first.wpilibj.PIDSource; import edu.wpi.first.wpilibj.PIDSourceType; /** - * Superclass for filters + * Superclass for filters. */ public abstract class Filter implements PIDSource { private PIDSource m_source; @@ -20,42 +20,33 @@ public abstract class Filter implements PIDSource { m_source = source; } - /** - * {@inheritDoc} - */ @Override public void setPIDSourceType(PIDSourceType pidSource) { m_source.setPIDSourceType(pidSource); } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return m_source.getPIDSourceType(); } - /** - * {@inheritDoc} - */ @Override public abstract double pidGet(); /** - * Returns the current filter estimate without also inserting new data as - * pidGet() would do. + * Returns the current filter estimate without also inserting new data as pidGet() would do. * * @return The current filter estimate */ public abstract double get(); /** - * Reset the filter state + * Reset the filter state. */ public abstract void reset(); /** - * Calls PIDGet() of source + * Calls PIDGet() of source. * * @return Current value of source */ diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/LinearDigitalFilter.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/LinearDigitalFilter.java index b8edc370cf..c5f93fefdb 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/LinearDigitalFilter.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/filters/LinearDigitalFilter.java @@ -7,58 +7,45 @@ package edu.wpi.first.wpilibj.filters; -import edu.wpi.first.wpilibj.filters.Filter; import edu.wpi.first.wpilibj.CircularBuffer; import edu.wpi.first.wpilibj.PIDSource; /** - * This class implements a linear, digital filter. All types of FIR and IIR - * filters are supported. Static factory methods are provided to create commonly - * used types of filters. + * This class implements a linear, digital filter. All types of FIR and IIR filters are supported. + * Static factory methods are provided to create commonly used types of filters. * - * Filters are of the form: - * y[n] = (b0*x[n] + b1*x[n-1] + ... + bP*x[n-P) - (a0*y[n-1] + a2*y[n-2] + ... + aQ*y[n-Q]) + *

Filters are of the form: y[n] = (b0*x[n] + b1*x[n-1] + ... + bP*x[n-P) - (a0*y[n-1] + + * a2*y[n-2] + ... + aQ*y[n-Q]) * - * Where: - * y[n] is the output at time "n" - * x[n] is the input at time "n" - * y[n-1] is the output from the LAST time step ("n-1") - * x[n-1] is the input from the LAST time step ("n-1") - * b0...bP are the "feedforward" (FIR) gains - * a0...aQ are the "feedback" (IIR) gains - * IMPORTANT! Note the "-" sign in front of the feedback term! This is a common - * convention in signal processing. + *

Where: y[n] is the output at time "n" x[n] is the input at time "n" y[n-1] is the output from + * the LAST time step ("n-1") x[n-1] is the input from the LAST time step ("n-1") b0...bP are the + * "feedforward" (FIR) gains a0...aQ are the "feedback" (IIR) gains IMPORTANT! Note the "-" sign in + * front of the feedback term! This is a common convention in signal processing. * - * What can linear filters do? Basically, they can filter, or diminish, the - * effects of undesirable input frequencies. High frequencies, or rapid changes, - * can be indicative of sensor noise or be otherwise undesirable. A "low pass" - * filter smooths out the signal, reducing the impact of these high frequency - * components. Likewise, a "high pass" filter gets rid of slow-moving signal - * components, letting you detect large changes more easily. + *

What can linear filters do? Basically, they can filter, or diminish, the effects of + * undesirable input frequencies. High frequencies, or rapid changes, can be indicative of sensor + * noise or be otherwise undesirable. A "low pass" filter smooths out the signal, reducing the + * impact of these high frequency components. Likewise, a "high pass" filter gets rid of + * slow-moving signal components, letting you detect large changes more easily. * - * Example FRC applications of filters: - * - Getting rid of noise from an analog sensor input (note: the roboRIO's FPGA - * can do this faster in hardware) - * - Smoothing out joystick input to prevent the wheels from slipping or the - * robot from tipping - * - Smoothing motor commands so that unnecessary strain isn't put on - * electrical or mechanical components - * - If you use clever gains, you can make a PID controller out of this class! + *

Example FRC applications of filters: - Getting rid of noise from an analog sensor input (note: + * the roboRIO's FPGA can do this faster in hardware) - Smoothing out joystick input to prevent the + * wheels from slipping or the robot from tipping - Smoothing motor commands so that unnecessary + * strain isn't put on electrical or mechanical components - If you use clever gains, you can make a + * PID controller out of this class! * - * For more on filters, I highly recommend the following articles: - * http://en.wikipedia.org/wiki/Linear_filter - * http://en.wikipedia.org/wiki/Iir_filter - * http://en.wikipedia.org/wiki/Fir_filter + *

For more on filters, I highly recommend the following articles: http://en.wikipedia + * .org/wiki/Linear_filter http://en.wikipedia.org/wiki/Iir_filter http://en.wikipedia + * .org/wiki/Fir_filter * - * Note 1: PIDGet() should be called by the user on a known, regular period. - * You can set up a Notifier to do this (look at the WPILib PIDController - * class), or do it "inline" with code in a periodic function. + *

Note 1: PIDGet() should be called by the user on a known, regular period. You can set up a + * Notifier to do this (look at the WPILib PIDController class), or do it "inline" with code in a + * periodic function. * - * Note 2: For ALL filters, gains are necessarily a function of frequency. If - * you make a filter that works well for you at, say, 100Hz, you will most - * definitely need to adjust the gains if you then want to run it at 200Hz! - * Combining this with Note 1 - the impetus is on YOU as a developer to make - * sure PIDGet() gets called at the desired, constant frequency! + *

Note 2: For ALL filters, gains are necessarily a function of frequency. If you make a filter + * that works well for you at, say, 100Hz, you will most definitely need to adjust the gains if you + * then want to run it at 200Hz! Combining this with Note 1 - the impetus is on YOU as a developer + * to make sure PIDGet() gets called at the desired, constant frequency! */ public class LinearDigitalFilter extends Filter { private CircularBuffer m_inputs; @@ -67,9 +54,9 @@ public class LinearDigitalFilter extends Filter { private double[] m_outputGains; /** - * Create a linear FIR or IIR filter + * Create a linear FIR or IIR filter. * - * @param source The PIDSource object that is used to get values + * @param source The PIDSource object that is used to get values * @param ffGains The "feed forward" or FIR gains * @param fbGains The "feed back" or IIR gains */ @@ -83,15 +70,14 @@ public class LinearDigitalFilter extends Filter { } /** - * Creates a one-pole IIR low-pass filter of the form: - * y[n] = (1-gain)*x[n] + gain*y[n-1] - * where gain = e^(-dt / T), T is the time constant in seconds + * Creates a one-pole IIR low-pass filter of the form: y[n] = (1-gain)*x[n] + gain*y[n-1] where + * gain = e^(-dt / T), T is the time constant in seconds. * - * This filter is stable for time constants greater than zero + *

This filter is stable for time constants greater than zero. * - * @param source The PIDSource object that is used to get values + * @param source The PIDSource object that is used to get values * @param timeConstant The discrete-time time constant in seconds - * @param period The period in seconds between samples taken by the user + * @param period The period in seconds between samples taken by the user */ public static LinearDigitalFilter singlePoleIIR(PIDSource source, double timeConstant, @@ -104,15 +90,14 @@ public class LinearDigitalFilter extends Filter { } /** - * Creates a first-order high-pass filter of the form: - * y[n] = gain*x[n] + (-gain)*x[n-1] + gain*y[n-1] - * where gain = e^(-dt / T), T is the time constant in seconds + * Creates a first-order high-pass filter of the form: y[n] = gain*x[n] + (-gain)*x[n-1] + + * gain*y[n-1] where gain = e^(-dt / T), T is the time constant in seconds. * - * This filter is stable for time constants greater than zero + *

This filter is stable for time constants greater than zero. * - * @param source The PIDSource object that is used to get values + * @param source The PIDSource object that is used to get values * @param timeConstant The discrete-time time constant in seconds - * @param period The period in seconds between samples taken by the user + * @param period The period in seconds between samples taken by the user */ public static LinearDigitalFilter highPass(PIDSource source, double timeConstant, @@ -125,14 +110,13 @@ public class LinearDigitalFilter extends Filter { } /** - * Creates a K-tap FIR moving average filter of the form: - * y[n] = 1/k * (x[k] + x[k-1] + ... + x[0]) + * Creates a K-tap FIR moving average filter of the form: y[n] = 1/k * (x[k] + x[k-1] + ... + + * x[0]). * - * This filter is always stable. + *

This filter is always stable. * * @param source The PIDSource object that is used to get values - * @param taps The number of samples to average over. Higher = smoother but - * slower + * @param taps The number of samples to average over. Higher = smoother but slower * @throws IllegalArgumentException if number of taps is less than 1 */ public static LinearDigitalFilter movingAverage(PIDSource source, int taps) { @@ -150,9 +134,6 @@ public class LinearDigitalFilter extends Filter { return new LinearDigitalFilter(source, ffGains, fbGains); } - /** - * {@inheritDoc} - */ @Override public double get() { double retVal = 0.0; @@ -168,17 +149,14 @@ public class LinearDigitalFilter extends Filter { return retVal; } - /** - * {@inheritDoc} - */ @Override public void reset() { - m_inputs.reset(); - m_outputs.reset(); + m_inputs.reset(); + m_outputs.reset(); } /** - * Calculates the next value of the filter + * Calculates the next value of the filter. * * @return The filtered value at this step */ diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java index 8db3a69359..03d498092b 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java @@ -8,40 +8,39 @@ package edu.wpi.first.wpilibj.interfaces; /** - * Interface for 3-axis accelerometers + * Interface for 3-axis accelerometers. */ public interface Accelerometer { - public enum Range { + enum Range { k2G, k4G, k8G, k16G } /** * Common interface for setting the measuring range of an accelerometer. * - * @param range The maximum acceleration, positive or negative, that the - * accelerometer will measure. Not all accelerometers support all - * ranges. + * @param range The maximum acceleration, positive or negative, that the accelerometer will + * measure. Not all accelerometers support all ranges. */ - public void setRange(Range range); + void setRange(Range range); /** - * Common interface for getting the x axis acceleration + * Common interface for getting the x axis acceleration. * * @return The acceleration along the x axis in g-forces */ - public double getX(); + double getX(); /** - * Common interface for getting the y axis acceleration + * Common interface for getting the y axis acceleration. * * @return The acceleration along the y axis in g-forces */ - public double getY(); + double getY(); /** - * Common interface for getting the z axis acceleration + * Common interface for getting the z axis acceleration. * * @return The acceleration along the z axis in g-forces */ - public double getZ(); + double getZ(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Gyro.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Gyro.java index 8bc4ddb634..8589395b7b 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Gyro.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Gyro.java @@ -8,51 +8,49 @@ package edu.wpi.first.wpilibj.interfaces; /** - * Interface for yaw rate gyros + * Interface for yaw rate gyros. */ public interface Gyro { /** - * Calibrate the gyro by running for a number of samples and computing the - * center value. Then use the center value as the Accumulator center value for - * subsequent measurements. It's important to make sure that the robot is not - * moving while the centering calculations are in progress, this is typically - * done when the robot is first turned on while it's sitting at rest before - * the competition starts. + * Calibrate the gyro by running for a number of samples and computing the center value. Then use + * the center value as the Accumulator center value for subsequent measurements. It's important to + * make sure that the robot is not moving while the centering calculations are in progress, this + * is typically done when the robot is first turned on while it's sitting at rest before the + * competition starts. */ - public void calibrate(); + void calibrate(); /** - * Reset the gyro. Resets the gyro to a heading of zero. This can be used if - * there is significant drift in the gyro and it needs to be recalibrated - * after it has been running. + * Reset the gyro. Resets the gyro to a heading of zero. This can be used if there is significant + * drift in the gyro and it needs to be recalibrated after it has been running. */ - public void reset(); + void reset(); /** * Return the actual angle in degrees that the robot is currently facing. * - * The angle is based on the current accumulator value corrected by the - * oversampling rate, the gyro type and the A/D calibration values. The angle - * is continuous, that is it will continue from 360 to 361 degrees. This - * allows algorithms that wouldn't want to see a discontinuity in the gyro - * output as it sweeps past from 360 to 0 on the second time around. + *

The angle is based on the current accumulator value corrected by the oversampling rate, the + * gyro type and the A/D calibration values. The angle is continuous, that is it will continue + * from 360 to 361 degrees. This allows algorithms that wouldn't want to see a discontinuity in + * the gyro output as it sweeps past from 360 to 0 on the second time around. * - * @return the current heading of the robot in degrees. This heading is based - * on integration of the returned rate from the gyro. + *

This heading is based on integration of the returned rate from the gyro. + * + * @return the current heading of the robot in degrees. */ - public double getAngle(); + double getAngle(); /** - * Return the rate of rotation of the gyro + * Return the rate of rotation of the gyro. * - * The rate is based on the most recent reading of the gyro analog value + *

The rate is based on the most recent reading of the gyro analog value * * @return the current rate in degrees per second */ - public double getRate(); + double getRate(); /** - * Free the resources used by the gyro + * Free the resources used by the gyro. */ - public void free(); + void free(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java index 9918ea2d8f..00ba917e13 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java @@ -10,7 +10,7 @@ package edu.wpi.first.wpilibj.interfaces; import edu.wpi.first.wpilibj.PIDSource; /** - * + * Interface for a Potentiometer. * @author alex */ public interface Potentiometer extends PIDSource { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java index e5a86f6f30..663b49801f 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java @@ -1,53 +1,24 @@ -/* - * To change this template, choose Tools | Templates and open the template in - * the editor. - */ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + package edu.wpi.first.wpilibj.livewindow; -import edu.wpi.first.wpilibj.command.Scheduler; -import edu.wpi.first.wpilibj.networktables.NetworkTable; -import edu.wpi.first.wpilibj.tables.ITable; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; -/** - * A LiveWindow component is a device (sensor or actuator) that should be added - * to the SmartDashboard in test mode. The components are cached until the first - * time the robot enters Test mode. This allows the components to be inserted, - * then renamed. - *$ - * @author brad - */ -class LiveWindowComponent { - - String m_subsystem; - String m_name; - boolean m_isSensor; - - public LiveWindowComponent(String subsystem, String name, boolean isSensor) { - m_subsystem = subsystem; - m_name = name; - m_isSensor = isSensor; - } - - public String getName() { - return m_name; - } - - public String getSubsystem() { - return m_subsystem; - } - - public boolean isSensor() { - return m_isSensor; - } -} +import edu.wpi.first.wpilibj.command.Scheduler; +import edu.wpi.first.wpilibj.networktables.NetworkTable; +import edu.wpi.first.wpilibj.tables.ITable; /** - * The LiveWindow class is the public interface for putting sensors and - * actuators on the LiveWindow. + * The LiveWindow class is the public interface for putting sensors and actuators on the + * LiveWindow. * * @author Alex Henning */ @@ -62,21 +33,20 @@ public class LiveWindow { private static boolean firstTime = true; /** - * Initialize all the LiveWindow elements the first time we enter LiveWindow - * mode. By holding off creating the NetworkTable entries, it allows them to - * be redefined before the first time in LiveWindow mode. This allows default - * sensor and actuator values to be created that are replaced with the custom - * names from users calling addActuator and addSensor. + * Initialize all the LiveWindow elements the first time we enter LiveWindow mode. By holding off + * creating the NetworkTable entries, it allows them to be redefined before the first time in + * LiveWindow mode. This allows default sensor and actuator values to be created that are replaced + * with the custom names from users calling addActuator and addSensor. */ private static void initializeLiveWindowComponents() { System.out.println("Initializing the components first time"); livewindowTable = NetworkTable.getTable("LiveWindow"); statusTable = livewindowTable.getSubTable("~STATUS~"); - for (Enumeration e = components.keys(); e.hasMoreElements();) { + for (Enumeration e = components.keys(); e.hasMoreElements(); ) { LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); - LiveWindowComponent c = (LiveWindowComponent) components.get(component); - String subsystem = c.getSubsystem(); - String name = c.getName(); + LiveWindowComponent liveWindowComponent = (LiveWindowComponent) components.get(component); + String subsystem = liveWindowComponent.getSubsystem(); + String name = liveWindowComponent.getName(); System.out.println("Initializing table for '" + subsystem + "' '" + name + "'"); livewindowTable.getSubTable(subsystem).putString("~TYPE~", "LW Subsystem"); ITable table = livewindowTable.getSubTable(subsystem).getSubTable(name); @@ -84,21 +54,19 @@ public class LiveWindow { table.putString("Name", name); table.putString("Subsystem", subsystem); component.initTable(table); - if (c.isSensor()) { + if (liveWindowComponent.isSensor()) { sensors.addElement(component); } } } /** - * Set the enabled state of LiveWindow. If it's being enabled, turn off the - * scheduler and remove all the commands from the queue and enable all the - * components registered for LiveWindow. If it's being disabled, stop all the - * registered components and reenable the scheduler. TODO: add code to disable - * PID loops when enabling LiveWindow. The commands should reenable the PID - * loops themselves when they get rescheduled. This prevents arms from - * starting to move around, etc. after a period of adjusting them in - * LiveWindow mode. + * Set the enabled state of LiveWindow. If it's being enabled, turn off the scheduler and remove + * all the commands from the queue and enable all the components registered for LiveWindow. If + * it's being disabled, stop all the registered components and reenable the scheduler. TODO: add + * code to disable PID loops when enabling LiveWindow. The commands should reenable the PID loops + * themselves when they get rescheduled. This prevents arms from starting to move around, etc. + * after a period of adjusting them in LiveWindow mode. */ public static void setEnabled(boolean enabled) { if (liveWindowEnabled != enabled) { @@ -110,13 +78,13 @@ public class LiveWindow { } Scheduler.getInstance().disable(); Scheduler.getInstance().removeAll(); - for (Enumeration e = components.keys(); e.hasMoreElements();) { + for (Enumeration e = components.keys(); e.hasMoreElements(); ) { LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); component.startLiveWindowMode(); } } else { System.out.println("stopping live window mode."); - for (Enumeration e = components.keys(); e.hasMoreElements();) { + for (Enumeration e = components.keys(); e.hasMoreElements(); ) { LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); component.stopLiveWindowMode(); } @@ -128,19 +96,17 @@ public class LiveWindow { } /** - * The run method is called repeatedly to keep the values refreshed on the - * screen in test mode. + * The run method is called repeatedly to keep the values refreshed on the screen in test mode. */ public static void run() { updateValues(); } /** - * Add a Sensor associated with the subsystem and with call it by the given - * name. + * Add a Sensor associated with the subsystem and with call it by the given name. * * @param subsystem The subsystem this component is part of. - * @param name The name of this component. + * @param name The name of this component. * @param component A LiveWindowSendable component that represents a sensor. */ public static void addSensor(String subsystem, String name, LiveWindowSendable component) { @@ -148,17 +114,58 @@ public class LiveWindow { } /** - * Add an Actuator associated with the subsystem and with call it by the given - * name. + * Add Sensor to LiveWindow. The components are shown with the type and channel like this: Gyro[1] + * for a gyro object connected to the first analog channel. + * + * @param moduleType A string indicating the type of the module used in the naming (above) + * @param channel The channel number the device is connected to + * @param component A reference to the object being added + */ + public static void addSensor(String moduleType, int channel, LiveWindowSendable component) { + addSensor("Ungrouped", moduleType + "[" + channel + "]", component); + if (sensors.contains(component)) { + sensors.removeElement(component); + } + sensors.addElement(component); + } + + /** + * Add an Actuator associated with the subsystem and with call it by the given name. * * @param subsystem The subsystem this component is part of. - * @param name The name of this component. + * @param name The name of this component. * @param component A LiveWindowSendable component that represents a actuator. */ public static void addActuator(String subsystem, String name, LiveWindowSendable component) { components.put(component, new LiveWindowComponent(subsystem, name, false)); } + /** + * Add Actuator to LiveWindow. The components are shown with the module type, slot and channel + * like this: Servo[1,2] for a servo object connected to the first digital module and PWM port 2. + * + * @param moduleType A string that defines the module name in the label for the value + * @param channel The channel number the device is plugged into (usually PWM) + * @param component The reference to the object being added + */ + public static void addActuator(String moduleType, int channel, LiveWindowSendable component) { + addActuator("Ungrouped", moduleType + "[" + channel + "]", component); + } + + /** + * Add Actuator to LiveWindow. The components are shown with the module type, slot and channel + * like this: Servo[1,2] for a servo object connected to the first digital module and PWM port 2. + * + * @param moduleType A string that defines the module name in the label for the value + * @param moduleNumber The number of the particular module type + * @param channel The channel number the device is plugged into (usually PWM) + * @param component The reference to the object being added + */ + public static void addActuator(String moduleType, int moduleNumber, int channel, + LiveWindowSendable component) { + addActuator("Ungrouped", moduleType + "[" + moduleNumber + "," + channel + "]", component); + } + /** * Puts all sensor values on the live window. */ @@ -171,52 +178,4 @@ public class LiveWindow { // TODO: Add actuators? // TODO: Add better rate limiting. } - - /** - * Add Sensor to LiveWindow. The components are shown with the type and - * channel like this: Gyro[1] for a gyro object connected to the first analog - * channel. - * - * @param moduleType A string indicating the type of the module used in the - * naming (above) - * @param channel The channel number the device is connected to - * @param component A reference to the object being added - */ - public static void addSensor(String moduleType, int channel, LiveWindowSendable component) { - addSensor("Ungrouped", moduleType + "[" + channel + "]", component); - if (sensors.contains(component)) { - sensors.removeElement(component); - } - sensors.addElement(component); - } - - /** - * Add Actuator to LiveWindow. The components are shown with the module type, - * slot and channel like this: Servo[1,2] for a servo object connected to the - * first digital module and PWM port 2. - * - * @param moduleType A string that defines the module name in the label for - * the value - * @param channel The channel number the device is plugged into (usually PWM) - * @param component The reference to the object being added - */ - public static void addActuator(String moduleType, int channel, LiveWindowSendable component) { - addActuator("Ungrouped", moduleType + "[" + channel + "]", component); - } - - /** - * Add Actuator to LiveWindow. The components are shown with the module type, - * slot and channel like this: Servo[1,2] for a servo object connected to the - * first digital module and PWM port 2. - * - * @param moduleType A string that defines the module name in the label for - * the value - * @param moduleNumber The number of the particular module type - * @param channel The channel number the device is plugged into (usually PWM) - * @param component The reference to the object being added - */ - public static void addActuator(String moduleType, int moduleNumber, int channel, - LiveWindowSendable component) { - addActuator("Ungrouped", moduleType + "[" + moduleNumber + "," + channel + "]", component); - } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindowComponent.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindowComponent.java new file mode 100644 index 0000000000..e00fe91ce0 --- /dev/null +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindowComponent.java @@ -0,0 +1,36 @@ +package edu.wpi.first.wpilibj.livewindow; + +/** + * A LiveWindow component is a device (sensor or actuator) that should be added to the + * SmartDashboard in test mode. The components are cached until the first time the robot enters Test + * mode. This allows the components to be inserted, then renamed. + * + * @author brad + */ +/* + * This class is intentionally package private. + */ +class LiveWindowComponent { + + String m_subsystem; + String m_name; + boolean m_isSensor; + + public LiveWindowComponent(String subsystem, String name, boolean isSensor) { + m_subsystem = subsystem; + m_name = name; + m_isSensor = isSensor; + } + + public String getName() { + return m_name; + } + + public String getSubsystem() { + return m_subsystem; + } + + public boolean isSensor() { + return m_isSensor; + } +} diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java index 4a46fe8c66..1828247d68 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java @@ -1,7 +1,10 @@ -/* - * To change this template, choose Tools | Templates and open the template in - * the editor. - */ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + package edu.wpi.first.wpilibj.livewindow; import edu.wpi.first.wpilibj.Sendable; @@ -15,16 +18,16 @@ public interface LiveWindowSendable extends Sendable { /** * Update the table for this sendable object with the latest values. */ - public void updateTable(); + void updateTable(); /** - * Start having this sendable object automatically respond to value changes - * reflect the value on the table. + * Start having this sendable object automatically respond to value changes reflect the value on + * the table. */ - public void startLiveWindowMode(); + void startLiveWindowMode(); /** * Stop having this sendable object automatically respond to value changes. */ - public void stopLiveWindowMode(); + void stopLiveWindowMode(); } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java index 68e2d59d3a..34ddff50d0 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java @@ -7,143 +7,139 @@ package edu.wpi.first.wpilibj.smartdashboard; +import java.util.ArrayList; + import edu.wpi.first.wpilibj.Sendable; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.tables.ITable; -import java.util.ArrayList; - /** - * The {@link SendableChooser} class is a useful tool for presenting a selection - * of options to the {@link SmartDashboard}. + * The {@link SendableChooser} class is a useful tool for presenting a selection of options to the + * {@link SmartDashboard}. * - *

- * For instance, you may wish to be able to select between multiple autonomous - * modes. You can do this by putting every possible {@link Command} you want to - * run as an autonomous into a {@link SendableChooser} and then put it into the - * {@link SmartDashboard} to have a list of options appear on the laptop. Once - * autonomous starts, simply ask the {@link SendableChooser} what the selected + *

For instance, you may wish to be able to select between multiple autonomous modes. You can do + * this by putting every possible {@link Command} you want to run as an autonomous into a {@link + * SendableChooser} and then put it into the {@link SmartDashboard} to have a list of options appear + * on the laptop. Once autonomous starts, simply ask the {@link SendableChooser} what the selected * value is. - *

* * @author Joe Grinstead */ public class SendableChooser implements Sendable { /** - * The key for the default value + * The key for the default value. */ private static final String DEFAULT = "default"; /** - * The key for the selected option + * The key for the selected option. */ private static final String SELECTED = "selected"; /** - * The key for the option array + * The key for the option array. */ private static final String OPTIONS = "options"; /** - * A table linking strings to the objects the represent + * A table linking strings to the objects the represent. */ - private ArrayList choices = new ArrayList(); - private ArrayList values = new ArrayList(); - private String defaultChoice = null; - private Object defaultValue = null; + private final ArrayList m_choices = new ArrayList<>(); + private final ArrayList m_values = new ArrayList<>(); + private String m_defaultChoice = null; + private Object m_defaultValue = null; /** * Instantiates a {@link SendableChooser}. */ - public SendableChooser() {} + public SendableChooser() { + } /** - * Adds the given object to the list of options. On the {@link SmartDashboard} - * on the desktop, the object will appear as the given name. + * Adds the given object to the list of options. On the {@link SmartDashboard} on the desktop, the + * object will appear as the given name. * - * @param name the name of the option + * @param name the name of the option * @param object the option */ public void addObject(String name, Object object) { // if we don't have a default, set the default automatically - if (defaultChoice == null) { + if (m_defaultChoice == null) { addDefault(name, object); return; } - for (int i = 0; i < choices.size(); ++i) { - if (choices.get(i).equals(name)) { - choices.set(i, name); - values.set(i, object); + for (int i = 0; i < m_choices.size(); ++i) { + if (m_choices.get(i).equals(name)) { + m_choices.set(i, name); + m_values.set(i, object); return; } } // not found - choices.add(name); - values.add(object); + m_choices.add(name); + m_values.add(object); - if (table != null) { - table.putStringArray(OPTIONS, choices.toArray(new String[0])); + if (m_table != null) { + m_table.putStringArray(OPTIONS, m_choices.toArray(new String[0])); } } /** - * Add the given object to the list of options and marks it as the default. - * Functionally, this is very close to - * {@link SendableChooser#addObject(java.lang.String, java.lang.Object) - * addObject(...)} except that it will use this as the default option if none - * other is explicitly selected. + * Add the given object to the list of options and marks it as the default. Functionally, this is + * very close to {@link SendableChooser#addObject(java.lang.String, java.lang.Object) + * addObject(...)} except that it will use this as the default option if none other is explicitly + * selected. * - * @param name the name of the option + * @param name the name of the option * @param object the option */ public void addDefault(String name, Object object) { if (name == null) { throw new NullPointerException("Name cannot be null"); } - defaultChoice = name; - defaultValue = object; - if (table != null) { - table.putString(DEFAULT, defaultChoice); + m_defaultChoice = name; + m_defaultValue = object; + if (m_table != null) { + m_table.putString(DEFAULT, m_defaultChoice); } addObject(name, object); } /** - * Returns the selected option. If there is none selected, it will return the - * default. If there is none selected and no default, then it will return - * {@code null}. + * Returns the selected option. If there is none selected, it will return the default. If there is + * none selected and no default, then it will return {@code null}. * * @return the option selected */ public Object getSelected() { - String selected = table.getString(SELECTED, null); - for (int i = 0; i < values.size(); ++i) { - if (choices.get(i).equals(selected)) { - return values.get(i); + String selected = m_table.getString(SELECTED, null); + for (int i = 0; i < m_values.size(); ++i) { + if (m_choices.get(i).equals(selected)) { + return m_values.get(i); } } - return defaultValue; + return m_defaultValue; } + @Override public String getSmartDashboardType() { return "String Chooser"; } - private ITable table; + private ITable m_table; + @Override public void initTable(ITable table) { - this.table = table; + m_table = table; if (table != null) { - table.putStringArray(OPTIONS, choices.toArray(new String[0])); - if (defaultChoice != null) { - table.putString(DEFAULT, defaultChoice); + table.putStringArray(OPTIONS, m_choices.toArray(new String[0])); + if (m_defaultChoice != null) { + table.putString(DEFAULT, m_defaultChoice); } } } - /** - * {@inheritDoc} - */ + @Override public ITable getTable() { - return table; + return m_table; } } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java index 64586ea92f..61cc21eb11 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java @@ -7,34 +7,34 @@ package edu.wpi.first.wpilibj.smartdashboard; +import java.util.Hashtable; +import java.util.NoSuchElementException; + +import edu.wpi.first.wpilibj.HLUsageReporting; import edu.wpi.first.wpilibj.NamedSendable; import edu.wpi.first.wpilibj.Sendable; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.networktables.NetworkTableKeyNotDefined; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.TableKeyNotDefinedException; -import edu.wpi.first.wpilibj.HLUsageReporting; -import java.util.Hashtable; -import java.util.NoSuchElementException; /** - * The {@link SmartDashboard} class is the bridge between robot programs and the - * SmartDashboard on the laptop. + * The {@link SmartDashboard} class is the bridge between robot programs and the SmartDashboard on + * the laptop. * - *

- * When a value is put into the SmartDashboard here, it pops up on the - * SmartDashboard on the laptop. Users can put values into and get values from - * the SmartDashboard - *

+ *

When a value is put into the SmartDashboard here, it pops up on the SmartDashboard on the + * laptop. Users can put values into and get values from the SmartDashboard. * * @author Joe Grinstead */ public class SmartDashboard { - /** The {@link NetworkTable} used by {@link SmartDashboard} */ + /** + * The {@link NetworkTable} used by {@link SmartDashboard}. + */ private static final NetworkTable table = NetworkTable.getTable("SmartDashboard"); /** - * A table linking tables in the SmartDashboard to the - * {@link SmartDashboardData} objects they came from. + * A table linking tables in the SmartDashboard to the {@link Sendable} objects they + * came from. */ private static final Hashtable tablesToData = new Hashtable(); @@ -43,13 +43,12 @@ public class SmartDashboard { } /** - * Maps the specified key to the specified value in this table. The key can - * not be null. The value can be retrieved by calling the get method with a - * key that is equal to the original key. - *$ - * @param key the key + * Maps the specified key to the specified value in this table. The key can not be null. The value + * can be retrieved by calling the get method with a key that is equal to the original key. + * + * @param key the key * @param data the value - * @throws IllegalArgumentException if key is null + * @throws IllegalArgumentException If key is null */ public static void putData(String key, Sendable data) { ITable dataTable = table.getSubTable(key); @@ -60,14 +59,14 @@ public class SmartDashboard { // TODO should we reimplement NamedSendable? + /** - * Maps the specified key (where the key is the name of the - * {@link NamedSendable} SmartDashboardNamedData to the specified value in - * this table. The value can be retrieved by calling the get method with a key - * that is equal to the original key. - *$ + * Maps the specified key (where the key is the name of the {@link NamedSendable} + * SmartDashboardNamedData to the specified value in this table. The value can be retrieved by + * calling the get method with a key that is equal to the original key. + * * @param value the value - * @throws IllegalArgumentException if key is null + * @throws IllegalArgumentException If key is null */ public static void putData(NamedSendable value) { putData(value.getName(), value); @@ -75,11 +74,11 @@ public class SmartDashboard { /** * Returns the value at the specified key. - *$ + * * @param key the key * @return the value * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the key is null + * @throws IllegalArgumentException if the key is null */ public static Sendable getData(String key) { ITable subtable = table.getSubTable(key); @@ -92,11 +91,10 @@ public class SmartDashboard { } /** - * Maps the specified key to the specified value in this table. The key can - * not be null. The value can be retrieved by calling the get method with a - * key that is equal to the original key. - *$ - * @param key the key + * Maps the specified key to the specified value in this table. The key can not be null. The value + * can be retrieved by calling the get method with a key that is equal to the original key. + * + * @param key the key * @param value the value * @throws IllegalArgumentException if key is null */ @@ -106,13 +104,12 @@ public class SmartDashboard { /** * Returns the value at the specified key. - *$ + * * @param key the key * @return the value * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a - * boolean - * @throws IllegalArgumentException if the key is null + * @throws IllegalArgumentException if the value mapped to by the key is not a boolean + * @throws IllegalArgumentException if the key is null */ public static boolean getBoolean(String key) throws TableKeyNotDefinedException { return table.getBoolean(key); @@ -120,12 +117,11 @@ public class SmartDashboard { /** * Returns the value at the specified key. - *$ - * @param key the key + * + * @param key the key * @param defaultValue returned if the key doesn't exist * @return the value - * @throws IllegalArgumentException if the value mapped to by the key is not a - * boolean + * @throws IllegalArgumentException if the value mapped to by the key is not a boolean * @throws IllegalArgumentException if the key is null */ public static boolean getBoolean(String key, boolean defaultValue) { @@ -133,11 +129,10 @@ public class SmartDashboard { } /** - * Maps the specified key to the specified value in this table. The key can - * not be null. The value can be retrieved by calling the get method with a - * key that is equal to the original key. - *$ - * @param key the key + * Maps the specified key to the specified value in this table. The key can not be null. The value + * can be retrieved by calling the get method with a key that is equal to the original key. + * + * @param key the key * @param value the value * @throws IllegalArgumentException if key is null */ @@ -147,14 +142,12 @@ public class SmartDashboard { /** * Returns the value at the specified key. - *$ + * * @param key the key * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the - * key - * @throws IllegalArgumentException if the value mapped to by the key is not a - * double - * @throws IllegalArgumentException if the key is null + * @throws TableKeyNotDefinedException if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not a double + * @throws IllegalArgumentException if the key is null */ public static double getNumber(String key) throws TableKeyNotDefinedException { return table.getNumber(key); @@ -162,25 +155,24 @@ public class SmartDashboard { /** * Returns the value at the specified key. - *$ - * @param key the key + * + * @param key the key * @param defaultValue the value returned if the key is undefined * @return the value * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a - * double - * @throws IllegalArgumentException if the key is null + * @throws IllegalArgumentException if the value mapped to by the key is not a double + * @throws IllegalArgumentException if the key is null */ public static double getNumber(String key, double defaultValue) { return table.getNumber(key, defaultValue); } /** - * Maps the specified key to the specified value in this table. Neither the - * key nor the value can be null. The value can be retrieved by calling the - * get method with a key that is equal to the original key. - *$ - * @param key the key + * Maps the specified key to the specified value in this table. Neither the key nor the value can + * be null. The value can be retrieved by calling the get method with a key that is equal to the + * original key. + * + * @param key the key * @param value the value * @throws IllegalArgumentException if key or value is null */ @@ -190,13 +182,12 @@ public class SmartDashboard { /** * Returns the value at the specified key. - *$ + * * @param key the key * @return the value * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a - * string - * @throws IllegalArgumentException if the key is null + * @throws IllegalArgumentException if the value mapped to by the key is not a string + * @throws IllegalArgumentException if the key is null */ public static String getString(String key) throws TableKeyNotDefinedException { return table.getString(key); @@ -204,14 +195,13 @@ public class SmartDashboard { /** * Returns the value at the specified key. - *$ - * @param key the key + * + * @param key the key * @param defaultValue The value returned if the key is undefined * @return the value * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a - * string - * @throws IllegalArgumentException if the key is null + * @throws IllegalArgumentException if the value mapped to by the key is not a string + * @throws IllegalArgumentException if the key is null */ public static String getString(String key, String defaultValue) { return table.getString(key, defaultValue); @@ -222,17 +212,17 @@ public class SmartDashboard { /* * Deprecated Methods */ + /** * Maps the specified key to the specified value in this table. * - * The key can not be null. The value can be retrieved by calling the get - * method with a key that is equal to the original key. + *

The key can not be null. The value can be retrieved by calling the get method with a key + * that is equal to the original key. * - * @deprecated Use {@link #putNumber(java.lang.String, double) putNumber - * method} instead - * @param key the key + * @param key the key * @param value the value * @throws IllegalArgumentException if key is null + * @deprecated Use {@link #putNumber(java.lang.String, double) putNumber method} instead */ public static void putInt(String key, int value) { table.putNumber(key, value); @@ -241,14 +231,12 @@ public class SmartDashboard { /** * Returns the value at the specified key. * - * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead * @param key the key * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the - * key - * @throws IllegalArgumentException if the value mapped to by the key is not - * an int - * @throws IllegalArgumentException if the key is null + * @throws TableKeyNotDefinedException if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not an int + * @throws IllegalArgumentException if the key is null + * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead */ public static int getInt(String key) throws TableKeyNotDefinedException { return (int) table.getNumber(key); @@ -257,16 +245,13 @@ public class SmartDashboard { /** * Returns the value at the specified key. * - * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} - * instead - * @param key the key + * @param key the key * @param defaultValue the value returned if the key is undefined * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the - * key - * @throws IllegalArgumentException if the value mapped to by the key is not - * an int - * @throws IllegalArgumentException if the key is null + * @throws TableKeyNotDefinedException if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not an int + * @throws IllegalArgumentException if the key is null + * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} instead */ public static int getInt(String key, int defaultValue) throws TableKeyNotDefinedException { try { @@ -279,14 +264,13 @@ public class SmartDashboard { /** * Maps the specified key to the specified value in this table. * - * The key can not be null. The value can be retrieved by calling the get - * method with a key that is equal to the original key. + *

The key can not be null. The value can be retrieved by calling the get method with a key + * that is equal to the original key. * - * @deprecated Use{@link #putNumber(java.lang.String, double) putNumber} - * instead - * @param key the key + * @param key the key * @param value the value * @throws IllegalArgumentException if key is null + * @deprecated Use{@link #putNumber(java.lang.String, double) putNumber} instead */ public static void putDouble(String key, double value) { table.putNumber(key, value); @@ -295,14 +279,12 @@ public class SmartDashboard { /** * Returns the value at the specified key. * - * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead * @param key the key * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the - * key - * @throws IllegalArgumentException if the value mapped to by the key is not a - * double - * @throws IllegalArgumentException if the key is null + * @throws TableKeyNotDefinedException if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not a double + * @throws IllegalArgumentException if the key is null + * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead */ public static double getDouble(String key) throws TableKeyNotDefinedException { return table.getNumber(key); @@ -311,16 +293,12 @@ public class SmartDashboard { /** * Returns the value at the specified key. * - * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} - * instead. - * @param key the key + * @param key the key * @param defaultValue the value returned if the key is undefined * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the - * key - * @throws IllegalArgumentException if the value mapped to by the key is not a - * double + * @throws IllegalArgumentException if the value mapped to by the key is not a double * @throws IllegalArgumentException if the key is null + * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} instead. */ public static double getDouble(String key, double defaultValue) { return table.getNumber(key, defaultValue); diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/AllocationException.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/AllocationException.java index 07ecd1012a..a06266e4a5 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/AllocationException.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/AllocationException.java @@ -8,15 +8,15 @@ package edu.wpi.first.wpilibj.util; /** - * Exception indicating that the resource is already allocated - *$ + * Exception indicating that the resource is already allocated. + * * @author dtjones */ public class AllocationException extends RuntimeException { /** - * Create a new AllocationException - *$ + * Create a new AllocationException. + * * @param msg the message to attach to the exception */ public AllocationException(String msg) { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java index c6801d810d..815b0b1ccf 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java @@ -9,15 +9,15 @@ package edu.wpi.first.wpilibj.util; /** - * Thrown if there is an error caused by a basic system or setting not being - * properly initialized before being used. - *$ + * Thrown if there is an error caused by a basic system or setting not being properly initialized + * before being used. + * * @author Jonathan Leitschuh */ public class BaseSystemNotInitializedException extends RuntimeException { /** - * Create a new BaseSystemNotInitializedException - *$ + * Create a new BaseSystemNotInitializedException. + * * @param message the message to attach to the exception */ public BaseSystemNotInitializedException(String message) { @@ -25,16 +25,14 @@ public class BaseSystemNotInitializedException extends RuntimeException { } /** - * Create a new BaseSystemNotInitializedException using the offending class - * that was not set and the class that was affected. - *$ + * Create a new BaseSystemNotInitializedException using the offending class that was not set and + * the class that was affected. + * * @param offender The class or interface that was not properly initialized. - * @param affected The class that was was affected by this missing - * initialization. + * @param affected The class that was was affected by this missing initialization. */ public BaseSystemNotInitializedException(Class offender, Class affected) { super("The " + offender.getSimpleName() + " for the " + affected.getSimpleName() + " was never set."); } - } diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BoundaryException.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BoundaryException.java index e1d1c16213..4b908d2d63 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BoundaryException.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/BoundaryException.java @@ -8,16 +8,15 @@ package edu.wpi.first.wpilibj.util; /** - * This exception represents an error in which a lower limit was set as higher - * than an upper limit. - *$ + * This exception represents an error in which a lower limit was set as higher than an upper limit. + * * @author dtjones */ public class BoundaryException extends RuntimeException { /** - * Create a new exception with the given message - *$ + * Create a new exception with the given message. + * * @param message the message to attach to the exception */ public BoundaryException(String message) { @@ -25,23 +24,24 @@ public class BoundaryException extends RuntimeException { } /** - * Make sure that the given value is between the upper and lower bounds, and - * throw an exception if they are not. - *$ + * Make sure that the given value is between the upper and lower bounds, and throw an exception if + * they are not. + * * @param value The value to check. * @param lower The minimum acceptable value. * @param upper The maximum acceptable value. */ public static void assertWithinBounds(double value, double lower, double upper) { - if (value < lower || value > upper) + if (value < lower || value > upper) { throw new BoundaryException("Value must be between " + lower + " and " + upper + ", " + value + " given"); + } } /** - * Returns the message for a boundary exception. Used to keep the message - * consistent across all boundary exceptions. - *$ + * Returns the message for a boundary exception. Used to keep the message consistent across all + * boundary exceptions. + * * @param value The given value * @param lower The lower limit * @param upper The upper limit diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java index 3d8c74d751..d931e09d97 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java @@ -8,16 +8,16 @@ package edu.wpi.first.wpilibj.util; /** - * Exception indicating that the resource is already allocated This is meant to - * be thrown by the resource class - *$ + * Exception indicating that the resource is already allocated This is meant to be thrown by the + * resource class. + * * @author dtjones */ public class CheckedAllocationException extends Exception { /** - * Create a new CheckedAllocationException - *$ + * Create a new CheckedAllocationException. + * * @param msg the message to attach to the exception */ public CheckedAllocationException(String msg) { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/SortedVector.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/SortedVector.java index aa56232baa..1cc4b72deb 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/SortedVector.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/SortedVector.java @@ -10,6 +10,7 @@ package edu.wpi.first.wpilibj.util; import java.util.Vector; /** + * A vector that is sorted. * * @author dtjones */ @@ -18,34 +19,36 @@ public class SortedVector extends Vector { /** * Interface used to determine the order to place sorted objects. */ - public static interface Comparator { + public interface Comparator { /** * Compare the given two objects. - *$ + * + *

Should return -1, 0, or 1 if the first object is less than, equal to, or greater than the + * second, respectively. + * * @param object1 First object to compare * @param object2 Second object to compare - * @return -1, 0, or 1 if the first object is less than, equal to, or - * greater than the second, respectively + * @return -1, 0, or 1. */ - public int compare(Object object1, Object object2); + int compare(Object object1, Object object2); } - Comparator comparator; + private final Comparator m_comparator; /** * Create a new sorted vector and use the given comparator to determine order. - *$ - * @param comparator The comparator to use to determine what order to place - * the elements in this vector. + * + * @param comparator The comparator to use to determine what order to place the elements in this + * vector. */ public SortedVector(Comparator comparator) { - this.comparator = comparator; + m_comparator = comparator; } /** * Adds an element in the Vector, sorted from greatest to least. - *$ + * * @param element The element to add to the Vector */ public void addElement(Object element) { @@ -53,7 +56,7 @@ public class SortedVector extends Vector { int lowBound = 0; while (highBound - lowBound > 0) { int index = (highBound + lowBound) / 2; - int result = comparator.compare(element, elementAt(index)); + int result = m_comparator.compare(element, elementAt(index)); if (result < 0) { lowBound = index + 1; } else if (result > 0) { diff --git a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java index f9996e532b..f98ff2303a 100644 --- a/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java +++ b/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java @@ -8,28 +8,28 @@ package edu.wpi.first.wpilibj.util; /** - * Exception for bad status codes from the chip object - *$ + * Exception for bad status codes from the chip object. + * * @author Brian */ public final class UncleanStatusException extends IllegalStateException { - private final int statusCode; + private final int m_statusCode; /** - * Create a new UncleanStatusException - *$ - * @param status the status code that caused the exception + * Create a new UncleanStatusException. + * + * @param status the status code that caused the exception * @param message A message describing the exception */ public UncleanStatusException(int status, String message) { super(message); - statusCode = status; + m_statusCode = status; } /** - * Create a new UncleanStatusException - *$ + * Create a new UncleanStatusException. + * * @param status the status code that caused the exception */ public UncleanStatusException(int status) { @@ -37,8 +37,8 @@ public final class UncleanStatusException extends IllegalStateException { } /** - * Create a new UncleanStatusException - *$ + * Create a new UncleanStatusException. + * * @param message a message describing the exception */ public UncleanStatusException(String message) { @@ -46,18 +46,18 @@ public final class UncleanStatusException extends IllegalStateException { } /** - * Create a new UncleanStatusException + * Create a new UncleanStatusException. */ public UncleanStatusException() { this(-1, "Status code was non-zero"); } /** - * Create a new UncleanStatusException - *$ + * Create a new UncleanStatusException. + * * @return the status code that caused the exception */ public int getStatus() { - return statusCode; + return m_statusCode; } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogGyro.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogGyro.java index 31ca2d9ddb..7c390d101a 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogGyro.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogGyro.java @@ -7,191 +7,183 @@ package edu.wpi.first.wpilibj; +import edu.wpi.first.wpilibj.GyroBase; import edu.wpi.first.wpilibj.interfaces.Gyro; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.simulation.SimGyro; -import edu.wpi.first.wpilibj.GyroBase; import edu.wpi.first.wpilibj.tables.ITable; /** - * Use a rate gyro to return the robots heading relative to a starting position. - * The AnalogGyro class tracks the robots heading based on the starting position. As - * the robot rotates the new heading is computed by integrating the rate of - * rotation returned by the sensor. When the class is instantiated, it does a - * short calibration routine where it samples the gyro while at rest to - * determine the default offset. This is subtracted from each sample to - * determine the heading. + * Use a rate gyro to return the robots heading relative to a starting position. The AnalogGyro + * class tracks the robots heading based on the starting position. As the robot rotates the new + * heading is computed by integrating the rate of rotation returned by the sensor. When the class is + * instantiated, it does a short calibration routine where it samples the gyro while at rest to + * determine the default offset. This is subtracted from each sample to determine the heading. */ public class AnalogGyro extends GyroBase implements Gyro, PIDSource, LiveWindowSendable { - private PIDSourceType m_pidSource; - private SimGyro impl; + private PIDSourceType m_pidSource; + private SimGyro impl; - /** - * Initialize the gyro. Calibrate the gyro by running for a number of - * samples and computing the center value for this part. Then use the center - * value as the Accumulator center value for subsequent measurements. It's - * important to make sure that the robot is not moving while the centering - * calculations are in progress, this is typically done when the robot is - * first turned on while it's sitting at rest before the competition starts. - */ - private void initGyro(int channel) { - impl = new SimGyro("simulator/analog/"+channel); + /** + * Initialize the gyro. Calibrate the gyro by running for a number of samples and computing the + * center value for this part. Then use the center value as the Accumulator center value for + * subsequent measurements. It's important to make sure that the robot is not moving while the + * centering calculations are in progress, this is typically done when the robot is first turned + * on while it's sitting at rest before the competition starts. + */ + private void initGyro(int channel) { + impl = new SimGyro("simulator/analog/" + channel); - reset(); - setPIDSourceType(PIDSourceType.kDisplacement); + reset(); + setPIDSourceType(PIDSourceType.kDisplacement); - LiveWindow.addSensor("AnalogGyro", channel, this); - } + LiveWindow.addSensor("AnalogGyro", channel, this); + } - /** - * AnalogGyro constructor with only a channel. - * - * @param channel - * The analog channel the gyro is connected to. - */ - public AnalogGyro(int channel) { - initGyro(channel); - } + /** + * AnalogGyro constructor with only a channel. + * + * @param channel The analog channel the gyro is connected to. + */ + public AnalogGyro(int channel) { + initGyro(channel); + } - /** - * {@inherit_doc} - */ - public void calibrate(){ - reset(); - } + /** + * {@inherit_doc} + */ + public void calibrate() { + reset(); + } - /** - * AnalogGyro constructor with a precreated analog channel object. Use this - * constructor when the analog channel needs to be shared. There is no - * reference counting when an AnalogChannel is passed to the gyro. - * - * @param channel - * The AnalogChannel object that the gyro is connected to. - */ - // Not Supported: public AnalogGyro(AnalogChannel channel) { + /** + * AnalogGyro constructor with a precreated analog channel object. Use this + * constructor when the analog channel needs to be shared. There is no + * reference counting when an AnalogChannel is passed to the gyro. + * + * @param channel + * The AnalogChannel object that the gyro is connected to. + */ + // Not Supported: public AnalogGyro(AnalogChannel channel) { - /** - * Reset the gyro. Resets the gyro to a heading of zero. This can be used if - * there is significant drift in the gyro and it needs to be recalibrated - * after it has been running. - */ - public void reset() { - impl.reset(); - } + /** + * Reset the gyro. Resets the gyro to a heading of zero. This can be used if there is significant + * drift in the gyro and it needs to be recalibrated after it has been running. + */ + public void reset() { + impl.reset(); + } - /** - * Delete (free) the accumulator and the analog components used for the - * gyro. - */ - public void free() { - } + /** + * Delete (free) the accumulator and the analog components used for the gyro. + */ + public void free() { + } - /** - * Return the actual angle in degrees that the robot is currently facing. - * - * The angle is based on the current accumulator value corrected by the - * oversampling rate, the gyro type and the A/D calibration values. The - * angle is continuous, that is can go beyond 360 degrees. This make - * algorithms that wouldn't want to see a discontinuity in the gyro output - * as it sweeps past 0 on the second time around. - * - * @return the current heading of the robot in degrees. This heading is - * based on integration of the returned rate from the gyro. - */ - public double getAngle() { - return impl.getAngle(); - } + /** + * Return the actual angle in degrees that the robot is currently facing. + * + * The angle is based on the current accumulator value corrected by the oversampling rate, the + * gyro type and the A/D calibration values. The angle is continuous, that is can go beyond 360 + * degrees. This make algorithms that wouldn't want to see a discontinuity in the gyro output as + * it sweeps past 0 on the second time around. + * + * @return the current heading of the robot in degrees. This heading is based on integration of + * the returned rate from the gyro. + */ + public double getAngle() { + return impl.getAngle(); + } - /** - * Return the rate of rotation of the gyro - * - * The rate is based on the most recent reading of the gyro analog value - * - * @return the current rate in degrees per second - */ - public double getRate() { - return impl.getVelocity(); - } + /** + * Return the rate of rotation of the gyro + * + * The rate is based on the most recent reading of the gyro analog value + * + * @return the current rate in degrees per second + */ + public double getRate() { + return impl.getVelocity(); + } - /** - * Set which parameter of the encoder you are using as a process control - * variable. The AnalogGyro class supports the rate and angle parameters - * - * @param pidSource - * An enum to select the parameter. - */ - public void setPIDSourceType(PIDSourceType pidSource) { - m_pidSource = pidSource; - } + /** + * Set which parameter of the encoder you are using as a process control variable. The AnalogGyro + * class supports the rate and angle parameters + * + * @param pidSource An enum to select the parameter. + */ + public void setPIDSourceType(PIDSourceType pidSource) { + m_pidSource = pidSource; + } - /** - * {@inheritDoc} - */ - public PIDSourceType getPIDSourceType() { - return m_pidSource; + /** + * {@inheritDoc} + */ + public PIDSourceType getPIDSourceType() { + return m_pidSource; + } + + /** + * Get the angle of the gyro for use with PIDControllers + * + * @return the current angle according to the gyro + */ + public double pidGet() { + switch (m_pidSource) { + case kRate: + return getRate(); + case kDisplacement: + return getAngle(); + default: + return 0.0; } + } - /** - * Get the angle of the gyro for use with PIDControllers - * - * @return the current angle according to the gyro - */ - public double pidGet() { - switch (m_pidSource) { - case kRate: - return getRate(); - case kDisplacement: - return getAngle(); - default: - return 0.0; - } - } + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "AnalogGyro"; + } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "AnalogGyro"; - } + private ITable m_table; - private ITable m_table; + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", getAngle()); + } + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", getAngle()); - } - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - } - - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogInput.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogInput.java index a663a3f0cc..a969ec1deb 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogInput.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogInput.java @@ -15,79 +15,72 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * Analog channel class. * - * Each analog channel is read from hardware as a 12-bit number representing - * -10V to 10V. + * Each analog channel is read from hardware as a 12-bit number representing -10V to 10V. * - * Connected to each analog channel is an averaging and oversampling engine. - * This engine accumulates the specified ( by setAverageBits() and - * setOversampleBits() ) number of samples before returning a new value. This is - * not a sliding window average. The only difference between the oversampled - * samples and the averaged samples is that the oversampled samples are simply - * accumulated effectively increasing the resolution, while the averaged samples - * are divided by the number of samples to retain the resolution, but get more - * stable values. + * Connected to each analog channel is an averaging and oversampling engine. This engine accumulates + * the specified ( by setAverageBits() and setOversampleBits() ) number of samples before returning + * a new value. This is not a sliding window average. The only difference between the oversampled + * samples and the averaged samples is that the oversampled samples are simply accumulated + * effectively increasing the resolution, while the averaged samples are divided by the number of + * samples to retain the resolution, but get more stable values. */ public class AnalogInput extends SensorBase implements PIDSource, - LiveWindowSendable { + LiveWindowSendable { - private SimFloatInput m_impl; - private int m_channel; + private SimFloatInput m_impl; + private int m_channel; protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement; - /** - * Construct an analog channel. - * - * @param channel - * The channel number to represent. - */ - public AnalogInput(final int channel) { - m_channel = channel; - m_impl = new SimFloatInput("simulator/analog/"+channel); + /** + * Construct an analog channel. + * + * @param channel The channel number to represent. + */ + public AnalogInput(final int channel) { + m_channel = channel; + m_impl = new SimFloatInput("simulator/analog/" + channel); - LiveWindow.addSensor("AnalogInput", channel, this); - } + LiveWindow.addSensor("AnalogInput", channel, this); + } - /** - * Channel destructor. - */ - public void free() { - m_channel = 0; - } + /** + * Channel destructor. + */ + public void free() { + m_channel = 0; + } - /** - * Get a scaled sample straight from this channel on the module. The value - * is scaled to units of Volts using the calibrated scaling data from - * getLSBWeight() and getOffset(). - * - * @return A scaled sample straight from this channel on the module. - */ - public double getVoltage() { - return m_impl.get(); - } + /** + * Get a scaled sample straight from this channel on the module. The value is scaled to units of + * Volts using the calibrated scaling data from getLSBWeight() and getOffset(). + * + * @return A scaled sample straight from this channel on the module. + */ + public double getVoltage() { + return m_impl.get(); + } - /** - * Get a scaled sample from the output of the oversample and average engine - * for this channel. The value is scaled to units of Volts using the - * calibrated scaling data from getLSBWeight() and getOffset(). Using - * oversampling will cause this value to be higher resolution, but it will - * update more slowly. Using averaging will cause this value to be more - * stable, but it will update more slowly. - * - * @return A scaled sample from the output of the oversample and average - * engine for this channel. - */ - public double getAverageVoltage() { - return getVoltage(); - } + /** + * Get a scaled sample from the output of the oversample and average engine for this channel. The + * value is scaled to units of Volts using the calibrated scaling data from getLSBWeight() and + * getOffset(). Using oversampling will cause this value to be higher resolution, but it will + * update more slowly. Using averaging will cause this value to be more stable, but it will update + * more slowly. + * + * @return A scaled sample from the output of the oversample and average engine for this channel. + */ + public double getAverageVoltage() { + return getVoltage(); + } - /** - * Get the channel number. - * - * @return The channel number. - */ - public int getChannel() { - return m_channel; - } + /** + * Get the channel number. + * + * @return The channel number. + */ + public int getChannel() { + return m_channel; + } /** * {@inheritDoc} @@ -103,59 +96,57 @@ public class AnalogInput extends SensorBase implements PIDSource, return m_pidSource; } - /** - * Get the average value for use with PIDController - * - * @return the average value - */ - public double pidGet() { - return getAverageVoltage(); - } + /** + * Get the average value for use with PIDController + * + * @return the average value + */ + public double pidGet() { + return getAverageVoltage(); + } - /** - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Analog Input"; - } + /** + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Analog Input"; + } - private ITable m_table; + private ITable m_table; - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", getAverageVoltage()); - } - } + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", getAverageVoltage()); + } + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * Analog Channels don't have to do anything special when entering the - * LiveWindow. {@inheritDoc} - */ - public void startLiveWindowMode() { - } + /** + * Analog Channels don't have to do anything special when entering the LiveWindow. {@inheritDoc} + */ + public void startLiveWindowMode() { + } - /** - * Analog Channels don't have to do anything special when exiting the - * LiveWindow. {@inheritDoc} - */ - public void stopLiveWindowMode() { - } + /** + * Analog Channels don't have to do anything special when exiting the LiveWindow. {@inheritDoc} + */ + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java index 4e7e0d94e4..2212845ae6 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java @@ -6,135 +6,128 @@ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; + import edu.wpi.first.wpilibj.interfaces.Potentiometer; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class for reading analog potentiometers. Analog potentiometers read - * in an analog voltage that corresponds to a position. Usually the - * position is either degrees or meters. However, if no conversion is - * given it remains volts. + * Class for reading analog potentiometers. Analog potentiometers read in an analog voltage that + * corresponds to a position. Usually the position is either degrees or meters. However, if no + * conversion is given it remains volts. * * @author Alex Henning */ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { - private double m_scale, m_offset; - private AnalogInput m_analog_input; - private boolean m_init_analog_input; + private double m_scale, m_offset; + private AnalogInput m_analog_input; + private boolean m_init_analog_input; protected PIDSourceType m_pidSource = PIDSourceType.kDisplacement; - /** - * Common initialization code called by all constructors. - * @param input The {@link AnalogInput} this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful unit. - * @param offset The offset to add to the scaled value for controlling the zero value - */ - private void initPot(final AnalogInput input, double scale, double offset) { - this.m_scale = scale; - this.m_offset = offset; - m_analog_input = input; - } + /** + * Common initialization code called by all constructors. + * + * @param input The {@link AnalogInput} this potentiometer is plugged into. + * @param scale The scaling to multiply the voltage by to get a meaningful unit. + * @param offset The offset to add to the scaled value for controlling the zero value + */ + private void initPot(final AnalogInput input, double scale, double offset) { + this.m_scale = scale; + this.m_offset = offset; + m_analog_input = input; + } - /** - * AnalogPotentiometer constructor. - * - * Use the scaling and offset values so that the output produces - * meaningful values. I.E: you have a 270 degree potentiometer and - * you want the output to be degrees with the halfway point as 0 - * degrees. The scale value is 270.0(degrees)/5.0(volts) and the - * offset is -135.0 since the halfway point after scaling is 135 - * degrees. - * - * @param channel The analog channel this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful unit. - * @param offset The offset to add to the scaled value for controlling the zero value - */ - public AnalogPotentiometer(final int channel, double scale, double offset) { - AnalogInput input = new AnalogInput(channel); - m_init_analog_input = true; - initPot(input, scale, offset); - } + /** + * AnalogPotentiometer constructor. + * + * Use the scaling and offset values so that the output produces meaningful values. I.E: you have + * a 270 degree potentiometer and you want the output to be degrees with the halfway point as 0 + * degrees. The scale value is 270.0(degrees)/5.0(volts) and the offset is -135.0 since the + * halfway point after scaling is 135 degrees. + * + * @param channel The analog channel this potentiometer is plugged into. + * @param scale The scaling to multiply the voltage by to get a meaningful unit. + * @param offset The offset to add to the scaled value for controlling the zero value + */ + public AnalogPotentiometer(final int channel, double scale, double offset) { + AnalogInput input = new AnalogInput(channel); + m_init_analog_input = true; + initPot(input, scale, offset); + } - /** - * AnalogPotentiometer constructor. - * - * Use the scaling and offset values so that the output produces - * meaningful values. I.E: you have a 270 degree potentiometer and - * you want the output to be degrees with the halfway point as 0 - * degrees. The scale value is 270.0(degrees)/5.0(volts) and the - * offset is -135.0 since the halfway point after scaling is 135 - * degrees. - * - * @param input The {@link AnalogInput} this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful unit. - * @param offset The offset to add to the scaled value for controlling the zero value - */ - public AnalogPotentiometer(final AnalogInput input, double scale, double offset) { - m_init_analog_input = false; - initPot(input, scale, offset); - } + /** + * AnalogPotentiometer constructor. + * + * Use the scaling and offset values so that the output produces meaningful values. I.E: you have + * a 270 degree potentiometer and you want the output to be degrees with the halfway point as 0 + * degrees. The scale value is 270.0(degrees)/5.0(volts) and the offset is -135.0 since the + * halfway point after scaling is 135 degrees. + * + * @param input The {@link AnalogInput} this potentiometer is plugged into. + * @param scale The scaling to multiply the voltage by to get a meaningful unit. + * @param offset The offset to add to the scaled value for controlling the zero value + */ + public AnalogPotentiometer(final AnalogInput input, double scale, double offset) { + m_init_analog_input = false; + initPot(input, scale, offset); + } - /** - * AnalogPotentiometer constructor. - * - * Use the scaling and offset values so that the output produces - * meaningful values. I.E: you have a 270 degree potentiometer and - * you want the output to be degrees with the halfway point as 0 - * degrees. The scale value is 270.0(degrees)/5.0(volts) and the - * offset is -135.0 since the halfway point after scaling is 135 - * degrees. - * - * @param channel The analog channel this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful unit. - */ - public AnalogPotentiometer(final int channel, double scale) { - this(channel, scale, 0); - } + /** + * AnalogPotentiometer constructor. + * + * Use the scaling and offset values so that the output produces meaningful values. I.E: you have + * a 270 degree potentiometer and you want the output to be degrees with the halfway point as 0 + * degrees. The scale value is 270.0(degrees)/5.0(volts) and the offset is -135.0 since the + * halfway point after scaling is 135 degrees. + * + * @param channel The analog channel this potentiometer is plugged into. + * @param scale The scaling to multiply the voltage by to get a meaningful unit. + */ + public AnalogPotentiometer(final int channel, double scale) { + this(channel, scale, 0); + } - /** - * AnalogPotentiometer constructor. - * - * Use the scaling and offset values so that the output produces - * meaningful values. I.E: you have a 270 degree potentiometer and - * you want the output to be degrees with the halfway point as 0 - * degrees. The scale value is 270.0(degrees)/5.0(volts) and the - * offset is -135.0 since the halfway point after scaling is 135 - * degrees. - * - * @param input The {@link AnalogInput} this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful unit. - */ - public AnalogPotentiometer(final AnalogInput input, double scale) { - this(input, scale, 0); - } + /** + * AnalogPotentiometer constructor. + * + * Use the scaling and offset values so that the output produces meaningful values. I.E: you have + * a 270 degree potentiometer and you want the output to be degrees with the halfway point as 0 + * degrees. The scale value is 270.0(degrees)/5.0(volts) and the offset is -135.0 since the + * halfway point after scaling is 135 degrees. + * + * @param input The {@link AnalogInput} this potentiometer is plugged into. + * @param scale The scaling to multiply the voltage by to get a meaningful unit. + */ + public AnalogPotentiometer(final AnalogInput input, double scale) { + this(input, scale, 0); + } - /** - * AnalogPotentiometer constructor. - * - * @param channel The analog channel this potentiometer is plugged into. - */ - public AnalogPotentiometer(final int channel) { - this(channel, 1, 0); - } + /** + * AnalogPotentiometer constructor. + * + * @param channel The analog channel this potentiometer is plugged into. + */ + public AnalogPotentiometer(final int channel) { + this(channel, 1, 0); + } - /** - * AnalogPotentiometer constructor. - * - * @param input The {@link AnalogInput} this potentiometer is plugged into. - */ - public AnalogPotentiometer(final AnalogInput input) { - this(input, 1, 0); - } + /** + * AnalogPotentiometer constructor. + * + * @param input The {@link AnalogInput} this potentiometer is plugged into. + */ + public AnalogPotentiometer(final AnalogInput input) { + this(input, 1, 0); + } - /** - * Get the current reading of the potentiomere. - * - * @return The current position of the potentiometer. - */ - public double get() { - return m_analog_input.getVoltage() * m_scale + m_offset; - } + /** + * Get the current reading of the potentiomere. + * + * @return The current position of the potentiometer. + */ + public double get() { + return m_analog_input.getVoltage() * m_scale + m_offset; + } /** * {@inheritDoc} @@ -150,65 +143,66 @@ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { return m_pidSource; } - /** - * Implement the PIDSource interface. - * - * @return The current reading. - */ - public double pidGet() { - return get(); + /** + * Implement the PIDSource interface. + * + * @return The current reading. + */ + public double pidGet() { + return get(); + } + + + /** + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Analog Input"; + } + + private ITable m_table; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); } + } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType(){ - return "Analog Input"; + public void free() { + if (m_init_analog_input) { + m_analog_input.free(); + m_analog_input = null; + m_init_analog_input = false; } - private ITable m_table; + } - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * Analog Channels don't have to do anything special when entering the LiveWindow. {@inheritDoc} + */ + public void startLiveWindowMode() { + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } - - /** - * {@inheritDoc} - */ - public ITable getTable(){ - return m_table; - } - - public void free(){ - if(m_init_analog_input){ - m_analog_input.free(); - m_analog_input = null; - m_init_analog_input = false; - } - } - - /** - * Analog Channels don't have to do anything special when entering the LiveWindow. - * {@inheritDoc} - */ - public void startLiveWindowMode() {} - - /** - * Analog Channels don't have to do anything special when exiting the LiveWindow. - * {@inheritDoc} - */ - public void stopLiveWindowMode() {} + /** + * Analog Channels don't have to do anything special when exiting the LiveWindow. {@inheritDoc} + */ + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/CounterBase.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/CounterBase.java index 3bd860633b..a7493a0e9d 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/CounterBase.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/CounterBase.java @@ -8,74 +8,79 @@ package edu.wpi.first.wpilibj; /** - * Interface for counting the number of ticks on a digital input channel. - * Encoders, Gear tooth sensors, and counters should all subclass this so it can be used to - * build more advanced classes for control and driving. + * Interface for counting the number of ticks on a digital input channel. Encoders, Gear tooth + * sensors, and counters should all subclass this so it can be used to build more advanced classes + * for control and driving. * - * All counters will immediately start counting - reset() them if you need them - * to be zeroed before use. + * All counters will immediately start counting - reset() them if you need them to be zeroed before + * use. */ public interface CounterBase { + /** + * The number of edges for the counterbase to increment or decrement on + */ + public enum EncodingType { /** - * The number of edges for the counterbase to increment or decrement on + * Count only the rising edge */ - public enum EncodingType { - /** - * Count only the rising edge - */ - k1X(0), - /** - * Count both the rising and falling edge - */ - k2X(1), - /** - * Count rising and falling on both channels - */ - k4X(2); + k1X(0), + /** + * Count both the rising and falling edge + */ + k2X(1), + /** + * Count rising and falling on both channels + */ + k4X(2); - /** - * The integer value representing this enumeration - */ - public final int value; + /** + * The integer value representing this enumeration + */ + public final int value; - private EncodingType(int value) { - this.value = value; - } + private EncodingType(int value) { + this.value = value; } + } - /** - * Get the count - * @return the count - */ - int get(); + /** + * Get the count + * + * @return the count + */ + int get(); - /** - * Reset the count to zero - */ - void reset(); + /** + * Reset the count to zero + */ + void reset(); - /** - * Get the time between the last two edges counted - * @return the time beteween the last two ticks in seconds - */ - double getPeriod(); + /** + * Get the time between the last two edges counted + * + * @return the time beteween the last two ticks in seconds + */ + double getPeriod(); - /** - * Set the maximum time between edges to be considered stalled - * @param maxPeriod the maximum period in seconds - */ - void setMaxPeriod(double maxPeriod); + /** + * Set the maximum time between edges to be considered stalled + * + * @param maxPeriod the maximum period in seconds + */ + void setMaxPeriod(double maxPeriod); - /** - * Determine if the counter is not moving - * @return true if the counter has not changed for the max period - */ - boolean getStopped(); + /** + * Determine if the counter is not moving + * + * @return true if the counter has not changed for the max period + */ + boolean getStopped(); - /** - * Determine which direction the counter is going - * @return true for one direction, false for the other - */ - boolean getDirection(); + /** + * Determine which direction the counter is going + * + * @return true for one direction, false for the other + */ + boolean getDirection(); } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DigitalInput.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DigitalInput.java index 3235ac717c..69a2910a9e 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DigitalInput.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DigitalInput.java @@ -12,93 +12,90 @@ import edu.wpi.first.wpilibj.simulation.SimDigitalInput; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class to read a digital input. This class will read digital inputs and return - * the current value on the channel. Other devices such as encoders, gear tooth - * sensors, etc. that are implemented elsewhere will automatically allocate - * digital inputs and outputs as required. This class is only for devices like - * switches etc. that aren't implemented anywhere else. + * Class to read a digital input. This class will read digital inputs and return the current value + * on the channel. Other devices such as encoders, gear tooth sensors, etc. that are implemented + * elsewhere will automatically allocate digital inputs and outputs as required. This class is only + * for devices like switches etc. that aren't implemented anywhere else. */ public class DigitalInput implements LiveWindowSendable { - private SimDigitalInput impl; - private int m_channel; + private SimDigitalInput impl; + private int m_channel; - /** - * Create an instance of a Digital Input class. Creates a digital input - * given a channel. - * - * @param channel - * the port for the digital input - */ - public DigitalInput(int channel) { - impl = new SimDigitalInput("simulator/dio/"+channel); - m_channel = channel; - } + /** + * Create an instance of a Digital Input class. Creates a digital input given a channel. + * + * @param channel the port for the digital input + */ + public DigitalInput(int channel) { + impl = new SimDigitalInput("simulator/dio/" + channel); + m_channel = channel; + } - /** - * Get the value from a digital input channel. Retrieve the value of a - * single digital input channel from the FPGA. - * - * @return the stats of the digital input - */ - public boolean get() { - return impl.get(); - } + /** + * Get the value from a digital input channel. Retrieve the value of a single digital input + * channel from the FPGA. + * + * @return the stats of the digital input + */ + public boolean get() { + return impl.get(); + } - /** - * Get the channel of the digital input - * - * @return The GPIO channel number that this object represents. - */ - public int getChannel() { - return m_channel; - } + /** + * Get the channel of the digital input + * + * @return The GPIO channel number that this object represents. + */ + public int getChannel() { + return m_channel; + } - public boolean getAnalogTriggerForRouting() { - return false; - } + public boolean getAnalogTriggerForRouting() { + return false; + } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Digital Input"; - } + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Digital Input"; + } - private ITable m_table; + private ITable m_table; - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putBoolean("Value", get()); - } - } + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putBoolean("Value", get()); + } + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + } - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DoubleSolenoid.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DoubleSolenoid.java index 691a74ae1a..9845cad28d 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DoubleSolenoid.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DoubleSolenoid.java @@ -7,180 +7,181 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; -import edu.wpi.first.wpilibj.simulation.SimEncoder; import edu.wpi.first.wpilibj.simulation.SimSpeedController; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -import edu.wpi.first.wpilibj.util.AllocationException; -import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * DoubleSolenoid class for running 2 channels of high voltage Digital Output. * - * The DoubleSolenoid class is typically used for pneumatics solenoids that - * have two positions controlled by two separate channels. + * The DoubleSolenoid class is typically used for pneumatics solenoids that have two positions + * controlled by two separate channels. */ public class DoubleSolenoid implements LiveWindowSendable { - /** - * Possible values for a DoubleSolenoid - */ - public static class Value { + /** + * Possible values for a DoubleSolenoid + */ + public static class Value { - public final int value; - public static final int kOff_val = 0; - public static final int kForward_val = 1; - public static final int kReverse_val = 2; - public static final Value kOff = new Value(kOff_val); - public static final Value kForward = new Value(kForward_val); - public static final Value kReverse = new Value(kReverse_val); + public final int value; + public static final int kOff_val = 0; + public static final int kForward_val = 1; + public static final int kReverse_val = 2; + public static final Value kOff = new Value(kOff_val); + public static final Value kForward = new Value(kForward_val); + public static final Value kReverse = new Value(kReverse_val); - private Value(int value) { - this.value = value; - } + private Value(int value) { + this.value = value; } - - private int m_forwardChannel; ///< The forward channel on the module to control. - private int m_reverseChannel; ///< The reverse channel on the module to control. - private int m_moduleNumber; - private boolean m_reverseDirection; - private SimSpeedController m_impl; - private Value m_value; + } - /** - * Common function to implement constructor behavior. - */ - private synchronized void initSolenoid(int moduleNumber, int forwardChannel, int reverseChannel) { - m_forwardChannel = forwardChannel; - m_reverseChannel = reverseChannel; - m_moduleNumber = moduleNumber; + private int m_forwardChannel; ///< The forward channel on the module to control. + private int m_reverseChannel; ///< The reverse channel on the module to control. + private int m_moduleNumber; + private boolean m_reverseDirection; + private SimSpeedController m_impl; + private Value m_value; + + /** + * Common function to implement constructor behavior. + */ + private synchronized void initSolenoid(int moduleNumber, int forwardChannel, int reverseChannel) { + m_forwardChannel = forwardChannel; + m_reverseChannel = reverseChannel; + m_moduleNumber = moduleNumber; // LiveWindow.addActuator("DoubleSolenoid", m_moduleNumber, m_forwardChannel, this); - - if (reverseChannel < forwardChannel) { // Swap ports - int channel = forwardChannel; - forwardChannel = reverseChannel; - reverseChannel = channel; - m_reverseDirection = true; - } - m_impl = new SimSpeedController("simulator/pneumatic/"+moduleNumber+"/"+forwardChannel+"/"+moduleNumber+"/"+reverseChannel); - } - /** - * Constructor. - * - * @param forwardChannel The forward channel on the module to control. - * @param reverseChannel The reverse channel on the module to control. - */ - public DoubleSolenoid(final int forwardChannel, final int reverseChannel) { - initSolenoid(1, forwardChannel, reverseChannel); + if (reverseChannel < forwardChannel) { // Swap ports + int channel = forwardChannel; + forwardChannel = reverseChannel; + reverseChannel = channel; + m_reverseDirection = true; } + m_impl = new SimSpeedController("simulator/pneumatic/" + moduleNumber + "/" + forwardChannel + + "/" + moduleNumber + "/" + reverseChannel); + } - /** - * Constructor. - * - * @param moduleNumber The module number of the solenoid module to use. - * @param forwardChannel The forward channel on the module to control. - * @param reverseChannel The reverse channel on the module to control. - */ - public DoubleSolenoid(final int moduleNumber, final int forwardChannel, final int reverseChannel) { - initSolenoid(moduleNumber, forwardChannel, reverseChannel); + /** + * Constructor. + * + * @param forwardChannel The forward channel on the module to control. + * @param reverseChannel The reverse channel on the module to control. + */ + public DoubleSolenoid(final int forwardChannel, final int reverseChannel) { + initSolenoid(1, forwardChannel, reverseChannel); + } + + /** + * Constructor. + * + * @param moduleNumber The module number of the solenoid module to use. + * @param forwardChannel The forward channel on the module to control. + * @param reverseChannel The reverse channel on the module to control. + */ + public DoubleSolenoid(final int moduleNumber, final int forwardChannel, final int + reverseChannel) { + initSolenoid(moduleNumber, forwardChannel, reverseChannel); + } + + /** + * Destructor. + */ + public synchronized void free() { + } + + /** + * Set the value of a solenoid. + * + * @param value Move the solenoid to forward, reverse, or don't move it. + */ + public void set(final Value value) { + m_value = value; + switch (value.value) { + case Value.kOff_val: + m_impl.set(0); + break; + case Value.kForward_val: + m_impl.set(m_reverseDirection ? -1 : 1); + break; + case Value.kReverse_val: + m_impl.set(m_reverseDirection ? 1 : -1); + break; } + } - /** - * Destructor. - */ - public synchronized void free() {} + /** + * Read the current value of the solenoid. + * + * @return The current value of the solenoid. + */ + public Value get() { + return m_value; + } - /** - * Set the value of a solenoid. - * - * @param value Move the solenoid to forward, reverse, or don't move it. - */ - public void set(final Value value) { - m_value = value; - switch (value.value) { - case Value.kOff_val: - m_impl.set(0); - break; - case Value.kForward_val: - m_impl.set(m_reverseDirection ? -1 : 1); - break; - case Value.kReverse_val: - m_impl.set(m_reverseDirection ? 1 : -1); - break; - } + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Double Solenoid"; + } + + private ITable m_table; + private ITableListener m_table_listener; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + //TODO: this is bad + m_table.putString("Value", (get() == Value.kForward ? "Forward" : (get() == Value.kReverse + ? "Reverse" : "Off"))); } + } - /** - * Read the current value of the solenoid. - * - * @return The current value of the solenoid. - */ - public Value get() { - return m_value; - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + set(Value.kOff); // Stop for safety + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + //TODO: this is bad also + if (value.toString().equals("Reverse")) + set(Value.kReverse); + else if (value.toString().equals("Forward")) + set(Value.kForward); + else + set(Value.kOff); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Double Solenoid"; - } - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - //TODO: this is bad - m_table.putString("Value", (get() == Value.kForward ? "Forward" : (get() == Value.kReverse ? "Reverse" : "Off"))); - } - } - - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - set(Value.kOff); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - //TODO: this is bad also - if (value.toString().equals("Reverse")) - set(Value.kReverse); - else if (value.toString().equals("Forward")) - set(Value.kForward); - else - set(Value.kOff); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } - - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - set(Value.kOff); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + set(Value.kOff); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DriverStation.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DriverStation.java index fa34e34418..f5832a3008 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DriverStation.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/DriverStation.java @@ -7,328 +7,354 @@ package edu.wpi.first.wpilibj; +import org.gazebosim.transport.SubscriberCallback; + import edu.wpi.first.wpilibj.simulation.MainNode; import gazebo.msgs.GzDriverStation; import gazebo.msgs.GzDriverStation.DriverStation.State; import gazebo.msgs.GzJoystick.Joystick; -import org.gazebosim.transport.SubscriberCallback; - /** * Provide access to the network communication data to / from the Driver Station. */ public class DriverStation implements RobotState.Interface { - /** - * Slot for the analog module to read the battery - */ - public static final int kBatterySlot = 1; - /** - * Analog channel to read the battery - */ - public static final int kBatteryChannel = 7; - /** - * Number of Joystick Ports - */ - public static final int kJoystickPorts = 6; - /** - * Number of Joystick Axes - */ - public static final int kJoystickAxes = 6; - /** - * Convert from raw values to volts - */ - public static final double kDSAnalogInScaling = 5.0 / 1023.0; + /** + * Slot for the analog module to read the battery + */ + public static final int kBatterySlot = 1; + /** + * Analog channel to read the battery + */ + public static final int kBatteryChannel = 7; + /** + * Number of Joystick Ports + */ + public static final int kJoystickPorts = 6; + /** + * Number of Joystick Axes + */ + public static final int kJoystickAxes = 6; + /** + * Convert from raw values to volts + */ + public static final double kDSAnalogInScaling = 5.0 / 1023.0; + + /** + * The robot alliance that the robot is a part of + */ + public static class Alliance { /** - * The robot alliance that the robot is a part of + * The integer value representing this enumeration. */ - public static class Alliance { - - /** The integer value representing this enumeration. */ - public final int value; - /** The Alliance name. */ - public final String name; - public static final int kRed_val = 0; - public static final int kBlue_val = 1; - public static final int kInvalid_val = 2; - /** alliance: Red */ - public static final Alliance kRed = new Alliance(kRed_val, "Red"); - /** alliance: Blue */ - public static final Alliance kBlue = new Alliance(kBlue_val, "Blue"); - /** alliance: Invalid */ - public static final Alliance kInvalid = new Alliance(kInvalid_val, "invalid"); - - private Alliance(int value, String name) { - this.value = value; - this.name = name; - } - } /* Alliance */ - - - private static DriverStation instance = new DriverStation(); - private final Object m_dataSem; - private boolean m_userInDisabled = false; - private boolean m_userInAutonomous = false; - private boolean m_userInTeleop = false; - private boolean m_userInTest = false; - private boolean m_newControlData; - private GzDriverStation.DriverStation state; - private Joystick joysticks[] = new Joystick[6]; - + public final int value; /** - * Gets an instance of the DriverStation - * - * @return The DriverStation. + * The Alliance name. */ - public static DriverStation getInstance() { - return DriverStation.instance; + public final String name; + public static final int kRed_val = 0; + public static final int kBlue_val = 1; + public static final int kInvalid_val = 2; + /** + * alliance: Red + */ + public static final Alliance kRed = new Alliance(kRed_val, "Red"); + /** + * alliance: Blue + */ + public static final Alliance kBlue = new Alliance(kBlue_val, "Blue"); + /** + * alliance: Invalid + */ + public static final Alliance kInvalid = new Alliance(kInvalid_val, "invalid"); + + private Alliance(int value, String name) { + this.value = value; + this.name = name; } + } /* Alliance */ - /** - * DriverStation constructor. - * - * The single DriverStation instance is created statically with the - * instance static member variable. - */ - protected DriverStation() { - m_dataSem = new Object(); - MainNode.subscribe("ds/state", GzDriverStation.DriverStation.getDefaultInstance(), - new SubscriberCallback() { - @Override public void callback(GzDriverStation.DriverStation msg) { - state = msg; - m_newControlData = true; - synchronized (m_dataSem) { - m_dataSem.notifyAll(); - } - } - } - ); + private static DriverStation instance = new DriverStation(); + private final Object m_dataSem; + private boolean m_userInDisabled = false; + private boolean m_userInAutonomous = false; + private boolean m_userInTeleop = false; + private boolean m_userInTest = false; + private boolean m_newControlData; + private GzDriverStation.DriverStation state; + private Joystick joysticks[] = new Joystick[6]; - for (int i = 0; i < 6; i++) { - final int j = i; - MainNode.subscribe("ds/joysticks/"+i, Joystick.getDefaultInstance(), - new SubscriberCallback() { - @Override public void callback(Joystick msg) { - synchronized (m_dataSem) { - joysticks[j] = msg; - } - } - } - ); - } - } + /** + * Gets an instance of the DriverStation + * + * @return The DriverStation. + */ + public static DriverStation getInstance() { + return DriverStation.instance; + } - /** - * Wait for new data from the driver station. - */ - public void waitForData() { - waitForData(0); - } + /** + * DriverStation constructor. + * + * The single DriverStation instance is created statically with the instance static member + * variable. + */ + protected DriverStation() { + m_dataSem = new Object(); - /** - * Wait for new data or for timeout, which ever comes first. If timeout is - * 0, wait for new data only. - * - * @param timeout The maximum time in milliseconds to wait. - */ - public void waitForData(long timeout) { - synchronized (m_dataSem) { - try { - m_dataSem.wait(timeout); - } catch (InterruptedException ex) { + MainNode.subscribe("ds/state", GzDriverStation.DriverStation.getDefaultInstance(), + new SubscriberCallback() { + @Override + public void callback(GzDriverStation.DriverStation msg) { + state = msg; + m_newControlData = true; + synchronized (m_dataSem) { + m_dataSem.notifyAll(); } + } } - } + ); - /** - * Read the battery voltage. - * - * @return The battery voltage. - */ - public double getBatteryVoltage() { - return 12.0; // 12 volts all the time! + for (int i = 0; i < 6; i++) { + final int j = i; + MainNode.subscribe("ds/joysticks/" + i, Joystick.getDefaultInstance(), + new SubscriberCallback() { + @Override + public void callback(Joystick msg) { + synchronized (m_dataSem) { + joysticks[j] = msg; + } + } + } + ); } + } - /** - * Get the value of the axis on a joystick. - * This depends on the mapping of the joystick connected to the specified port. - * - * @param stick The joystick to read. - * @param axis The analog axis value to read from the joystick. - * @return The value of the axis on the joystick. - */ - public double getStickAxis(int stick, int axis) { - if (stick < 0 || stick >= joysticks.length || joysticks[stick] == null) { - return 0.0; - } - if (axis < 0 || axis >= kJoystickAxes || axis >= joysticks[stick].getAxesCount()) { - return 0.0; - } - return joysticks[stick].getAxes(axis); - } + /** + * Wait for new data from the driver station. + */ + public void waitForData() { + waitForData(0); + } - /** - * The state of the buttons on the joystick. - * 12 buttons (4 msb are unused) from the joystick. - * - * @param stick The joystick to read. - * @return The state of the buttons on the joystick. - */ - public boolean getStickButton(int stick, int button) { - if (stick < 0 || stick >= joysticks.length || joysticks[stick] == null) { - return false; - } - if (button < 1 || button > joysticks[stick].getButtonsCount()) { - return false; - } - return joysticks[stick].getButtons(button - 1); + /** + * Wait for new data or for timeout, which ever comes first. If timeout is 0, wait for new data + * only. + * + * @param timeout The maximum time in milliseconds to wait. + */ + public void waitForData(long timeout) { + synchronized (m_dataSem) { + try { + m_dataSem.wait(timeout); + } catch (InterruptedException ex) { + } } + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be enabled. - * - * @return True if the robot is enabled, false otherwise. - */ - public boolean isEnabled() { - return state != null ? state.getEnabled() : false; - } + /** + * Read the battery voltage. + * + * @return The battery voltage. + */ + public double getBatteryVoltage() { + return 12.0; // 12 volts all the time! + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be disabled. - * - * @return True if the robot should be disabled, false otherwise. - */ - public boolean isDisabled() { - return !isEnabled(); + /** + * Get the value of the axis on a joystick. This depends on the mapping of the joystick connected + * to the specified port. + * + * @param stick The joystick to read. + * @param axis The analog axis value to read from the joystick. + * @return The value of the axis on the joystick. + */ + public double getStickAxis(int stick, int axis) { + if (stick < 0 || stick >= joysticks.length || joysticks[stick] == null) { + return 0.0; } + if (axis < 0 || axis >= kJoystickAxes || axis >= joysticks[stick].getAxesCount()) { + return 0.0; + } + return joysticks[stick].getAxes(axis); + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be running in autonomous mode. - * - * @return True if autonomous mode should be enabled, false otherwise. - */ - public boolean isAutonomous() { - return state != null ? state.getState() == State.AUTO : false; + /** + * The state of the buttons on the joystick. 12 buttons (4 msb are unused) from the joystick. + * + * @param stick The joystick to read. + * @return The state of the buttons on the joystick. + */ + public boolean getStickButton(int stick, int button) { + if (stick < 0 || stick >= joysticks.length || joysticks[stick] == null) { + return false; } + if (button < 1 || button > joysticks[stick].getButtonsCount()) { + return false; + } + return joysticks[stick].getButtons(button - 1); + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be running in test mode. - * @return True if test mode should be enabled, false otherwise. - */ - public boolean isTest() { - return state != null ? state.getState() == State.TEST : false; - } + /** + * Gets a value indicating whether the Driver Station requires the robot to be enabled. + * + * @return True if the robot is enabled, false otherwise. + */ + public boolean isEnabled() { + return state != null ? state.getEnabled() : false; + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be running in operator-controlled mode. - * - * @return True if operator-controlled mode should be enabled, false otherwise. - */ - public boolean isOperatorControl() { - return !(isAutonomous() || isTest()); - } + /** + * Gets a value indicating whether the Driver Station requires the robot to be disabled. + * + * @return True if the robot should be disabled, false otherwise. + */ + public boolean isDisabled() { + return !isEnabled(); + } - /** - * Has a new control packet from the driver station arrived since the last time this function was called? - * @return True if the control data has been updated since the last call. - */ - public synchronized boolean isNewControlData() { - boolean result = m_newControlData; - m_newControlData = false; - return result; - } + /** + * Gets a value indicating whether the Driver Station requires the robot to be running in + * autonomous mode. + * + * @return True if autonomous mode should be enabled, false otherwise. + */ + public boolean isAutonomous() { + return state != null ? state.getState() == State.AUTO : false; + } - /** - * Get the current alliance from the FMS - * @return the current alliance - */ - public Alliance getAlliance() { - switch ('I') { // TODO: Always invalid - case 'R': - return Alliance.kRed; - case 'B': - return Alliance.kBlue; - default: - return Alliance.kInvalid; - } - } + /** + * Gets a value indicating whether the Driver Station requires the robot to be running in test + * mode. + * + * @return True if test mode should be enabled, false otherwise. + */ + public boolean isTest() { + return state != null ? state.getState() == State.TEST : false; + } - /** - * Gets the location of the team's driver station controls. - * - * @return the location of the team's driver station controls: 1, 2, or 3 - */ - public int getLocation() { - return -1; // TODO: always -1 - } + /** + * Gets a value indicating whether the Driver Station requires the robot to be running in + * operator-controlled mode. + * + * @return True if operator-controlled mode should be enabled, false otherwise. + */ + public boolean isOperatorControl() { + return !(isAutonomous() || isTest()); + } - /** - * Return the team number that the Driver Station is configured for - * @return The team number - */ - public int getTeamNumber() { - return 348; // TODO - } + /** + * Has a new control packet from the driver station arrived since the last time this function was + * called? + * + * @return True if the control data has been updated since the last call. + */ + public synchronized boolean isNewControlData() { + boolean result = m_newControlData; + m_newControlData = false; + return result; + } - /** - * Is the driver station attached to a Field Management System? - * Note: This does not work with the Blue DS. - * @return True if the robot is competing on a field being controlled by a Field Management System - */ - public boolean isFMSAttached() { - return false; + /** + * Get the current alliance from the FMS + * + * @return the current alliance + */ + public Alliance getAlliance() { + switch ('I') { // TODO: Always invalid + case 'R': + return Alliance.kRed; + case 'B': + return Alliance.kBlue; + default: + return Alliance.kInvalid; } - - /** - * Report error to Driver Station. - * Also prints error to System.err - * Optionally appends Stack trace to error message - * @param printTrace If true, append stack trace to error string - */ - public static void reportError(String error, boolean printTrace) { - String errorString = error; - if(printTrace) { - errorString += " at "; - StackTraceElement[] traces = Thread.currentThread().getStackTrace(); - for (int i=2; i Timer.getFPGATimestamp(); } /** - * Check if this motor has exceeded its timeout. This method is called - * periodically to determine if this motor has exceeded its timeout value. If - * it has, the stop method is called, and the motor is shut down until its - * value is updated again. + * Check if this motor has exceeded its timeout. This method is called periodically to determine + * if this motor has exceeded its timeout value. If it has, the stop method is called, and the + * motor is shut down until its value is updated again. */ public void check() { if (!m_enabled || RobotState.isDisabled() || RobotState.isTest()) return; if (m_stopTime < Timer.getFPGATimestamp()) { - DriverStation.reportError(m_safeObject.getDescription() + "... Output not updated often enough.", false); + DriverStation.reportError(m_safeObject.getDescription() + "... Output not updated often " + + "enough.", false); m_safeObject.stopMotor(); } } /** - * Enable/disable motor safety for this device Turn on and off the motor - * safety option for this PWM object. - *$ + * Enable/disable motor safety for this device Turn on and off the motor safety option for this + * PWM object. + * * @param enabled True if motor safety is enforced for this object */ public void setSafetyEnabled(boolean enabled) { @@ -109,9 +105,9 @@ public class MotorSafetyHelper { } /** - * Return the state of the motor safety enabled flag Return if the motor - * safety is currently enabled for this devicce. - *$ + * Return the state of the motor safety enabled flag Return if the motor safety is currently + * enabled for this devicce. + * * @return True if motor safety is enforced for this device */ public boolean isSafetyEnabled() { @@ -119,8 +115,8 @@ public class MotorSafetyHelper { } /** - * Check the motors to see if any have timed out. This static method is called - * periodically to poll all the motors and stop any that have timed out. + * Check the motors to see if any have timed out. This static method is called periodically to + * poll all the motors and stop any that have timed out. */ // TODO: these should be synchronized with the setting methods in case it's // called from a different thread diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Preferences.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Preferences.java index da90b2d631..7073a6aa78 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Preferences.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Preferences.java @@ -21,804 +21,779 @@ import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; /** - * The preferences class provides a relatively simple way to save important - * values to the RoboRIO to access the next time the RoboRIO is booted. + * The preferences class provides a relatively simple way to save important values to the RoboRIO to + * access the next time the RoboRIO is booted. * - *

This class loads and saves from a file inside the RoboRIO. The user can not - * access the file directly, but may modify values at specific fields which will - * then be saved to the file when {@link Preferences#save() save()} is - * called.

+ *

This class loads and saves from a file inside the RoboRIO. The user can not access the file + * directly, but may modify values at specific fields which will then be saved to the file when + * {@link Preferences#save() save()} is called.

* *

This class is thread safe.

* - *

This will also interact with {@link NetworkTable} by creating a table - * called "Preferences" with all the key-value pairs. To save using - * {@link NetworkTable}, simply set the boolean at position ~S A V E~ to true. - * Also, if the value of any variable is " in the {@link NetworkTable}, then - * that represents non-existence in the {@link Preferences} table

+ *

This will also interact with {@link NetworkTable} by creating a table called "Preferences" + * with all the key-value pairs. To save using {@link NetworkTable}, simply set the boolean at + * position ~S A V E~ to true. Also, if the value of any variable is " in the {@link NetworkTable}, + * then that represents non-existence in the {@link Preferences} table

* * @author Joe Grinstead */ public class Preferences { - /** - * The Preferences table name - */ - private static final String TABLE_NAME = "Preferences"; - /** - * The value of the save field - */ - private static final String SAVE_FIELD = "~S A V E~"; - /** - * The file to save to - */ - private static final String FILE_NAME = "wpilib-preferences.ini"; - /** - * The characters to put between a field and value - */ - private static final byte[] VALUE_PREFIX = {'=', '\"'}; - /** - * The characters to put after the value - */ - private static final byte[] VALUE_SUFFIX = {'\"', '\n'}; - /** - * The newline character - */ - private static final byte[] NEW_LINE = {'\n'}; - /** - * The singleton instance - */ - private static Preferences instance; + /** + * The Preferences table name + */ + private static final String TABLE_NAME = "Preferences"; + /** + * The value of the save field + */ + private static final String SAVE_FIELD = "~S A V E~"; + /** + * The file to save to + */ + private static final String FILE_NAME = "wpilib-preferences.ini"; + /** + * The characters to put between a field and value + */ + private static final byte[] VALUE_PREFIX = {'=', '\"'}; + /** + * The characters to put after the value + */ + private static final byte[] VALUE_SUFFIX = {'\"', '\n'}; + /** + * The newline character + */ + private static final byte[] NEW_LINE = {'\n'}; + /** + * The singleton instance + */ + private static Preferences instance; - /** - * Returns the preferences instance. - * - * @return the preferences instance - */ - public synchronized static Preferences getInstance() { - if (instance == null) { - instance = new Preferences(); + /** + * Returns the preferences instance. + * + * @return the preferences instance + */ + public synchronized static Preferences getInstance() { + if (instance == null) { + instance = new Preferences(); + } + return instance; + } + + /** + * The semaphore for beginning reads and writes to the file + */ + private final Object fileLock = new Object(); + /** + * The semaphore for reading from the table + */ + private final Object lock = new Object(); + /** + * The actual values (String->String) + */ + private Hashtable values; + /** + * The keys in the order they were read from the file + */ + private Vector keys; + /** + * The comments that were in the file sorted by which key they appeared over (String->Comment) + */ + private Hashtable comments; + /** + * The comment at the end of the file + */ + private Comment endComment; + + /** + * Creates a preference class that will automatically read the file in a different thread. Any + * call to its methods will be blocked until the thread is finished reading. + */ + private Preferences() { + values = new Hashtable(); + keys = new Vector(); + + // We synchronized on fileLock and then wait + // for it to know that the reading thread has started + synchronized (fileLock) { + new Thread() { + public void run() { + read(); } - return instance; + }.start(); + try { + fileLock.wait(); + } catch (InterruptedException ex) { + } } - /** - * The semaphore for beginning reads and writes to the file - */ - private final Object fileLock = new Object(); - /** - * The semaphore for reading from the table - */ - private final Object lock = new Object(); - /** - * The actual values (String->String) - */ - private Hashtable values; - /** - * The keys in the order they were read from the file - */ - private Vector keys; - /** - * The comments that were in the file sorted by which key they appeared over - * (String->Comment) - */ - private Hashtable comments; - /** - * The comment at the end of the file - */ - private Comment endComment; + } - /** - * Creates a preference class that will automatically read the file in a - * different thread. Any call to its methods will be blocked until the - * thread is finished reading. - */ - private Preferences() { - values = new Hashtable(); - keys = new Vector(); + /** + * @return a vector of the keys + */ + public Vector getKeys() { + synchronized (lock) { + return keys; + } + } - // We synchronized on fileLock and then wait - // for it to know that the reading thread has started - synchronized (fileLock) { - new Thread() { - public void run() { - read(); - } - } .start(); - try { - fileLock.wait(); - } catch (InterruptedException ex) { - } + /** + * Puts the given value into the given key position + * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains an illegal character + */ + private void put(String key, String value) { + synchronized (lock) { + if (key == null) { + throw new NullPointerException(); + } + ImproperPreferenceKeyException.confirmString(key); + if (values.put(key, value) == null) { + keys.addElement(key); + } + NetworkTable.getTable(TABLE_NAME).putString(key, value); + } + } + + /** + * Puts the given string into the preferences table. + * + *

The value may not have quotation marks, nor may the key have any whitespace nor an equals + * sign

+ * + *

This will NOT save the value to memory between power cycles, to do that you must call + * {@link Preferences#save() save()} (which must be used with care). at some point after calling + * this.

+ * + * @param key the key + * @param value the value + * @throws NullPointerException if value is null + * @throws IllegalArgumentException if value contains a quotation mark + * @throws ImproperPreferenceKeyException if the key contains any whitespace or an equals sign + */ + public void putString(String key, String value) { + if (value == null) { + throw new NullPointerException(); + } + if (value.indexOf('"') != -1) { + throw new IllegalArgumentException("Can not put string:" + value + " because it contains " + + "quotation marks"); + } + put(key, value); + } + + /** + * Puts the given int into the preferences table. + * + *

The key may not have any whitespace nor an equals sign

+ * + *

This will NOT save the value to memory between power cycles, to do that you must call + * {@link Preferences#save() save()} (which must be used with care) at some point after calling + * this.

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace or an equals sign + */ + public void putInt(String key, int value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given double into the preferences table. + * + *

The key may not have any whitespace nor an equals sign

+ * + *

This will NOT save the value to memory between power cycles, to do that you must call + * {@link Preferences#save() save()} (which must be used with care) at some point after calling + * this.

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace or an equals sign + */ + public void putDouble(String key, double value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given float into the preferences table. + * + *

The key may not have any whitespace nor an equals sign

+ * + *

This will NOT save the value to memory between power cycles, to do that you must call + * {@link Preferences#save() save()} (which must be used with care) at some point after calling + * this.

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace or an equals sign + */ + public void putFloat(String key, float value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given boolean into the preferences table. + * + *

The key may not have any whitespace nor an equals sign

+ * + *

This will NOT save the value to memory between power cycles, to do that you must call + * {@link Preferences#save() save()} (which must be used with care) at some point after calling + * this.

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace or an equals sign + */ + public void putBoolean(String key, boolean value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given long into the preferences table. + * + *

The key may not have any whitespace nor an equals sign

+ * + *

This will NOT save the value to memory between power cycles, to do that you must call + * {@link Preferences#save() save()} (which must be used with care) at some point after calling + * this.

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace or an equals sign + */ + public void putLong(String key, long value) { + put(key, String.valueOf(value)); + } + + /** + * Returns the value at the given key. + * + * @param key the key + * @return the value (or null if none exists) + * @throws NullPointerException if the key is null + */ + private String get(String key) { + synchronized (lock) { + if (key == null) { + throw new NullPointerException(); + } + return (String) values.get(key); + } + } + + /** + * Returns whether or not there is a key with the given name. + * + * @param key the key + * @return if there is a value at the given key + * @throws NullPointerException if key is null + */ + public boolean containsKey(String key) { + return get(key) != null; + } + + /** + * Remove a preference + * + * @param key the key + * @throws NullPointerException if key is null + */ + public void remove(String key) { + synchronized (lock) { + if (key == null) { + throw new NullPointerException(); + } + values.remove(key); + keys.removeElement(key); + } + } + + /** + * Returns the string at the given key. If this table does not have a value for that position, + * then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws NullPointerException if the key is null + */ + public String getString(String key, String backup) { + String value = get(key); + return value == null ? backup : value; + } + + /** + * Returns the int at the given key. If this table does not have a value for that position, then + * the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be converted to an int + */ + public int getInt(String key, int backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "int"); + } + } + } + + /** + * Returns the double at the given key. If this table does not have a value for that position, + * then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be converted to an double + */ + public double getDouble(String key, double backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + try { + return Double.parseDouble(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "double"); + } + } + } + + /** + * Returns the boolean at the given key. If this table does not have a value for that position, + * then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be converted to a boolean + */ + public boolean getBoolean(String key, boolean backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + if (value.equalsIgnoreCase("true")) { + return true; + } else if (value.equalsIgnoreCase("false")) { + return false; + } else { + throw new IncompatibleTypeException(value, "boolean"); + } + } + } + + /** + * Returns the float at the given key. If this table does not have a value for that position, then + * the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be converted to a float + */ + public float getFloat(String key, float backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + try { + return Float.parseFloat(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "float"); + } + } + } + + /** + * Returns the long at the given key. If this table does not have a value for that position, then + * the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be converted to a long + */ + public long getLong(String key, long backup) { + String value = get(key); + if (value == null) { + put(key, String.valueOf(backup)); + return backup; + } else { + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "long"); + } + } + } + + /** + * Saves the preferences to a file on the RoboRIO. + * + *

This should NOT be called often. Too many writes can damage the RoboRIO's flash + * memory. While it is ok to save once or twice a match, this should never be called every run of + * {@link IterativeRobot#teleopPeriodic()}.

+ * + *

The actual writing of the file is done in a separate thread. However, any call to a get or + * put method will wait until the table is fully saved before continuing.

+ */ + public void save() { + synchronized (fileLock) { + new Thread() { + public void run() { + write(); } + }.start(); + try { + fileLock.wait(); + } catch (InterruptedException ex) { + } } + } - /** - * @return a vector of the keys - */ - public Vector getKeys() { - synchronized (lock) { - return keys; - } - } + /** + * Internal method that actually writes the table to a file. This is called in its own thread when + * {@link Preferences#save() save()} is called. + */ + private void write() { + synchronized (lock) { + synchronized (fileLock) { + fileLock.notifyAll(); + } - /** - * Puts the given value into the given key position - * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains an illegal - * character - */ - private void put(String key, String value) { - synchronized (lock) { - if (key == null) { - throw new NullPointerException(); - } - ImproperPreferenceKeyException.confirmString(key); - if (values.put(key, value) == null) { - keys.addElement(key); - } - NetworkTable.getTable(TABLE_NAME).putString(key, value); - } - } + File file = null; + FileOutputStream output = null; + try { + file = new File(FILE_NAME); - /** - * Puts the given string into the preferences table. - * - *

The value may not have quotation marks, nor may the key have any - * whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care). at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws NullPointerException if value is null - * @throws IllegalArgumentException if value contains a quotation mark - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putString(String key, String value) { - if (value == null) { - throw new NullPointerException(); - } - if (value.indexOf('"') != -1) { - throw new IllegalArgumentException("Can not put string:" + value + " because it contains quotation marks"); - } - put(key, value); - } + if (file.exists()) + file.delete(); - /** - * Puts the given int into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putInt(String key, int value) { - put(key, String.valueOf(value)); - } + file.createNewFile(); - /** - * Puts the given double into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putDouble(String key, double value) { - put(key, String.valueOf(value)); - } + output = new FileOutputStream(file); - /** - * Puts the given float into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putFloat(String key, float value) { - put(key, String.valueOf(value)); - } - - /** - * Puts the given boolean into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putBoolean(String key, boolean value) { - put(key, String.valueOf(value)); - } - - /** - * Puts the given long into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putLong(String key, long value) { - put(key, String.valueOf(value)); - } - - /** - * Returns the value at the given key. - * - * @param key the key - * @return the value (or null if none exists) - * @throws NullPointerException if the key is null - */ - private String get(String key) { - synchronized (lock) { - if (key == null) { - throw new NullPointerException(); - } - return (String) values.get(key); - } - } - - /** - * Returns whether or not there is a key with the given name. - * - * @param key the key - * @return if there is a value at the given key - * @throws NullPointerException if key is null - */ - public boolean containsKey(String key) { - return get(key) != null; - } - - /** - * Remove a preference - * - * @param key the key - * @throws NullPointerException if key is null - */ - public void remove(String key) { - synchronized (lock) { - if (key == null) { - throw new NullPointerException(); - } - values.remove(key); - keys.removeElement(key); - } - } - - /** - * Returns the string at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws NullPointerException if the key is null - */ - public String getString(String key, String backup) { - String value = get(key); - return value == null ? backup : value; - } - - /** - * Returns the int at the given key. If this table does not have a value for - * that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to an int - */ - public int getInt(String key, int backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "int"); - } - } - } - - /** - * Returns the double at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to an double - */ - public double getDouble(String key, double backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - try { - return Double.parseDouble(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "double"); - } - } - } - - /** - * Returns the boolean at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to a boolean - */ - public boolean getBoolean(String key, boolean backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - if (value.equalsIgnoreCase("true")) { - return true; - } else if (value.equalsIgnoreCase("false")) { - return false; - } else { - throw new IncompatibleTypeException(value, "boolean"); - } - } - } - - /** - * Returns the float at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to a float - */ - public float getFloat(String key, float backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - try { - return Float.parseFloat(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "float"); - } - } - } - - /** - * Returns the long at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to a long - */ - public long getLong(String key, long backup) { - String value = get(key); - if (value == null) { - put(key, String.valueOf(backup)); - return backup; - } else { - try { - return Long.parseLong(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "long"); - } - } - } - - /** - * Saves the preferences to a file on the RoboRIO. - * - *

This should NOT be called often. Too many writes can damage the - * RoboRIO's flash memory. While it is ok to save once or twice a match, this - * should never be called every run of - * {@link IterativeRobot#teleopPeriodic()}.

- * - *

The actual writing of the file is done in a separate thread. However, - * any call to a get or put method will wait until the table is fully saved - * before continuing.

- */ - public void save() { - synchronized (fileLock) { - new Thread() { - public void run() { - write(); - } - } .start(); - try { - fileLock.wait(); - } catch (InterruptedException ex) { - } - } - } - - /** - * Internal method that actually writes the table to a file. This is called - * in its own thread when {@link Preferences#save() save()} is called. - */ - private void write() { - synchronized (lock) { - synchronized (fileLock) { - fileLock.notifyAll(); - } - - File file = null; - FileOutputStream output = null; - try { - file = new File(FILE_NAME); - - if (file.exists()) - file.delete(); - - file.createNewFile(); - - output = new FileOutputStream(file); - - for (int i = 0; i < keys.size(); i++) { - String key = (String) keys.elementAt(i); - String value = (String) values.get(key); - - if (comments != null) { - Comment comment = (Comment) comments.get(key); - if (comment != null) { - comment.write(output); - } - } - - output.write(key.getBytes()); - output.write(VALUE_PREFIX); - output.write(value.getBytes()); - output.write(VALUE_SUFFIX); - } - - if (endComment != null) { - endComment.write(output); - } - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (output != null) { - try { - output.close(); - } catch (IOException ex) { - } - } - NetworkTable.getTable(TABLE_NAME).putBoolean(SAVE_FIELD, false); - } - } - } - - /** - * The internal method to read from a file. This will be called in its own - * thread when the preferences singleton is first created. - */ - private void read() { - class EndOfStreamException extends Exception { - } - - class Reader { - - InputStream stream; - - Reader(InputStream stream) { - this.stream = stream; - } - - public char read() throws IOException, EndOfStreamException { - int input = stream.read(); - if (input == -1) { - throw new EndOfStreamException(); - } else { - // Check for carriage returns - return input == '\r' ? '\n' : (char) input; - } - } - - char readWithoutWhitespace() throws IOException, EndOfStreamException { - while (true) { - char value = read(); - switch (value) { - case ' ': - case '\t': - continue; - default: - return value; - } - } - } - } - - synchronized (lock) { - synchronized (fileLock) { - fileLock.notifyAll(); - } - - Comment comment = null; - - - - File file = null; - FileInputStream input = null; - try { - file = new File(FILE_NAME); - - if (file.exists()) { - input = new FileInputStream(file); - Reader reader = new Reader(input); - - StringBuffer buffer; - - while (true) { - char value = reader.readWithoutWhitespace(); - - if (value == '\n' || value == ';') { - if (comment == null) { - comment = new Comment(); - } - - if (value == '\n') { - comment.addBytes(NEW_LINE); - } else { - buffer = new StringBuffer(30); - for (; value != '\n'; value = reader.read()) { - buffer.append(value); - } - buffer.append('\n'); - comment.addBytes(buffer.toString().getBytes()); - } - } else { - buffer = new StringBuffer(30); - for (; value != '='; value = reader.readWithoutWhitespace()) { - buffer.append(value); - } - String name = buffer.toString(); - buffer = new StringBuffer(30); - - boolean shouldBreak = false; - - value = reader.readWithoutWhitespace(); - if (value == '"') { - for (value = reader.read(); value != '"'; value = reader.read()) { - buffer.append(value); - } - // Clear the line - while (reader.read() != '\n'); - } else { - try { - for (; value != '\n'; value = reader.readWithoutWhitespace()) { - buffer.append(value); - } - } catch (EndOfStreamException e) { - shouldBreak = true; - } - } - - String result = buffer.toString(); - - keys.addElement(name); - values.put(name, result); - NetworkTable.getTable(TABLE_NAME).putString(name, result); - - if (comment != null) { - if (comments == null) { - comments = new Hashtable(); - } - comments.put(name, comment); - comment = null; - } - - - if (shouldBreak) { - break; - } - } - } - } - } catch (IOException ex) { - ex.printStackTrace(); - } catch (EndOfStreamException ex) { - System.out.println("Done Reading"); - } - - if (input != null) { - try { - input.close(); - } catch (IOException ex) { - } - } + for (int i = 0; i < keys.size(); i++) { + String key = (String) keys.elementAt(i); + String value = (String) values.get(key); + if (comments != null) { + Comment comment = (Comment) comments.get(key); if (comment != null) { - endComment = comment; + comment.write(output); } + } + + output.write(key.getBytes()); + output.write(VALUE_PREFIX); + output.write(value.getBytes()); + output.write(VALUE_SUFFIX); } + if (endComment != null) { + endComment.write(output); + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (output != null) { + try { + output.close(); + } catch (IOException ex) { + } + } NetworkTable.getTable(TABLE_NAME).putBoolean(SAVE_FIELD, false); - // TODO: Verify that this works even though it changes with subtables. - // Should work since preferences shouldn't have subtables. - NetworkTable.getTable(TABLE_NAME).addTableListener(new ITableListener() { - public void valueChanged(ITable source, String key, Object value, boolean isNew) { - if (key.equals(SAVE_FIELD)) { - if (((Boolean) value).booleanValue()) { - save(); - } - } else { - synchronized (lock) { - if (!ImproperPreferenceKeyException.isAcceptable(key) || value.toString().indexOf('"') != -1) { - if (values.contains(key) || keys.contains(key)) { - values.remove(key); - keys.removeElement(key); - NetworkTable.getTable(TABLE_NAME).putString(key, "\""); - } - } else { - if (values.put(key, value.toString()) == null) { - keys.addElement(key); - } - } - } + } + } + } + + /** + * The internal method to read from a file. This will be called in its own thread when the + * preferences singleton is first created. + */ + private void read() { + class EndOfStreamException extends Exception { + } + + class Reader { + + InputStream stream; + + Reader(InputStream stream) { + this.stream = stream; + } + + public char read() throws IOException, EndOfStreamException { + int input = stream.read(); + if (input == -1) { + throw new EndOfStreamException(); + } else { + // Check for carriage returns + return input == '\r' ? '\n' : (char) input; + } + } + + char readWithoutWhitespace() throws IOException, EndOfStreamException { + while (true) { + char value = read(); + switch (value) { + case ' ': + case '\t': + continue; + default: + return value; + } + } + } + } + + synchronized (lock) { + synchronized (fileLock) { + fileLock.notifyAll(); + } + + Comment comment = null; + + + File file = null; + FileInputStream input = null; + try { + file = new File(FILE_NAME); + + if (file.exists()) { + input = new FileInputStream(file); + Reader reader = new Reader(input); + + StringBuffer buffer; + + while (true) { + char value = reader.readWithoutWhitespace(); + + if (value == '\n' || value == ';') { + if (comment == null) { + comment = new Comment(); + } + + if (value == '\n') { + comment.addBytes(NEW_LINE); + } else { + buffer = new StringBuffer(30); + for (; value != '\n'; value = reader.read()) { + buffer.append(value); } + buffer.append('\n'); + comment.addBytes(buffer.toString().getBytes()); + } + } else { + buffer = new StringBuffer(30); + for (; value != '='; value = reader.readWithoutWhitespace()) { + buffer.append(value); + } + String name = buffer.toString(); + buffer = new StringBuffer(30); + + boolean shouldBreak = false; + + value = reader.readWithoutWhitespace(); + if (value == '"') { + for (value = reader.read(); value != '"'; value = reader.read()) { + buffer.append(value); + } + // Clear the line + while (reader.read() != '\n') ; + } else { + try { + for (; value != '\n'; value = reader.readWithoutWhitespace()) { + buffer.append(value); + } + } catch (EndOfStreamException e) { + shouldBreak = true; + } + } + + String result = buffer.toString(); + + keys.addElement(name); + values.put(name, result); + NetworkTable.getTable(TABLE_NAME).putString(name, result); + + if (comment != null) { + if (comments == null) { + comments = new Hashtable(); + } + comments.put(name, comment); + comment = null; + } + + + if (shouldBreak) { + break; + } } - }); + } + } + } catch (IOException ex) { + ex.printStackTrace(); + } catch (EndOfStreamException ex) { + System.out.println("Done Reading"); + } + + if (input != null) { + try { + input.close(); + } catch (IOException ex) { + } + } + + if (comment != null) { + endComment = comment; + } + } + + NetworkTable.getTable(TABLE_NAME).putBoolean(SAVE_FIELD, false); + // TODO: Verify that this works even though it changes with subtables. + // Should work since preferences shouldn't have subtables. + NetworkTable.getTable(TABLE_NAME).addTableListener(new ITableListener() { + public void valueChanged(ITable source, String key, Object value, boolean isNew) { + if (key.equals(SAVE_FIELD)) { + if (((Boolean) value).booleanValue()) { + save(); + } + } else { + synchronized (lock) { + if (!ImproperPreferenceKeyException.isAcceptable(key) || value.toString().indexOf + ('"') != -1) { + if (values.contains(key) || keys.contains(key)) { + values.remove(key); + keys.removeElement(key); + NetworkTable.getTable(TABLE_NAME).putString(key, "\""); + } + } else { + if (values.put(key, value.toString()) == null) { + keys.addElement(key); + } + } + } + } + } + }); + } + + /** + * A class representing some comment lines in the ini file. This is used so that if a programmer + * ever directly modifies the ini file, then his/her comments will still be there after {@link + * Preferences#save() save()} is called. + */ + private static class Comment { + + /** + * A vector of byte arrays. Each array represents a line to write + */ + private Vector bytes = new Vector(); + + /** + * Appends the given bytes to the comment. + * + * @param bytes the bytes to add + */ + private void addBytes(byte[] bytes) { + this.bytes.addElement(bytes); } /** - * A class representing some comment lines in the ini file. This is used so - * that if a programmer ever directly modifies the ini file, then his/her - * comments will still be there after {@link Preferences#save() save()} is - * called. + * Writes this comment to the given stream + * + * @param stream the stream to write to + * @throws IOException if the stream has a problem */ - private static class Comment { + private void write(OutputStream stream) throws IOException { + for (int i = 0; i < bytes.size(); i++) { + stream.write((byte[]) bytes.elementAt(i)); + } + } + } - /** - * A vector of byte arrays. Each array represents a line to write - */ - private Vector bytes = new Vector(); + /** + * This exception is thrown if the a value requested cannot be converted to the requested type. + */ + public static class IncompatibleTypeException extends RuntimeException { - /** - * Appends the given bytes to the comment. - * - * @param bytes the bytes to add - */ - private void addBytes(byte[] bytes) { - this.bytes.addElement(bytes); - } + /** + * Creates an exception with a description based on the input + * + * @param value the value that can not be converted + * @param type the type that the value can not be converted to + */ + public IncompatibleTypeException(String value, String type) { + super("Cannot convert \"" + value + "\" into " + type); + } + } - /** - * Writes this comment to the given stream - * - * @param stream the stream to write to - * @throws IOException if the stream has a problem - */ - private void write(OutputStream stream) throws IOException { - for (int i = 0; i < bytes.size(); i++) { - stream.write((byte[]) bytes.elementAt(i)); - } - } + /** + * Should be thrown if a string can not be used as a key in the preferences file. This happens if + * the string contains a new line, a space, a tab, or an equals sign. + */ + public static class ImproperPreferenceKeyException extends RuntimeException { + + /** + * Instantiates an exception with a descriptive message based on the input. + * + * @param value the illegal key + * @param letter the specific character that made it illegal + */ + public ImproperPreferenceKeyException(String value, char letter) { + super("Preference key \"" + + value + "\" is not allowed to contain letter with ASCII code:" + (byte) letter); } /** - * This exception is thrown if the a value requested cannot be converted to - * the requested type. + * Tests if the given string is ok to use as a key in the preference table. If not, then a + * {@link ImproperPreferenceKeyException} will be thrown. + * + * @param value the value to test */ - public static class IncompatibleTypeException extends RuntimeException { - - /** - * Creates an exception with a description based on the input - * - * @param value the value that can not be converted - * @param type the type that the value can not be converted to - */ - public IncompatibleTypeException(String value, String type) { - super("Cannot convert \"" + value + "\" into " + type); + public static void confirmString(String value) { + for (int i = 0; i < value.length(); i++) { + char letter = value.charAt(i); + switch (letter) { + case '=': + case '\n': + case '\r': + case ' ': + case '\t': + throw new ImproperPreferenceKeyException(value, letter); } + } } /** - * Should be thrown if a string can not be used as a key in the preferences - * file. This happens if the string contains a new line, a space, a tab, or - * an equals sign. + * Returns whether or not the given string is ok to use in the preference table. */ - public static class ImproperPreferenceKeyException extends RuntimeException { - - /** - * Instantiates an exception with a descriptive message based on the - * input. - * - * @param value the illegal key - * @param letter the specific character that made it illegal - */ - public ImproperPreferenceKeyException(String value, char letter) { - super("Preference key \"" - + value + "\" is not allowed to contain letter with ASCII code:" + (byte) letter); - } - - /** - * Tests if the given string is ok to use as a key in the preference - * table. If not, then a {@link ImproperPreferenceKeyException} will be - * thrown. - * - * @param value the value to test - */ - public static void confirmString(String value) { - for (int i = 0; i < value.length(); i++) { - char letter = value.charAt(i); - switch (letter) { - case '=': - case '\n': - case '\r': - case ' ': - case '\t': - throw new ImproperPreferenceKeyException(value, letter); - } - } - } - - /** - * Returns whether or not the given string is ok to use in the - * preference table. - * - * @param value - * @return - */ - public static boolean isAcceptable(String value) { - for (int i = 0; i < value.length(); i++) { - char letter = value.charAt(i); - switch (letter) { - case '=': - case '\n': - case '\r': - case ' ': - case '\t': - return false; - } - } - return true; + public static boolean isAcceptable(String value) { + for (int i = 0; i < value.length(); i++) { + char letter = value.charAt(i); + switch (letter) { + case '=': + case '\n': + case '\r': + case ' ': + case '\t': + return false; } + } + return true; } + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Relay.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Relay.java index 178cd07d69..ac8b169383 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Relay.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Relay.java @@ -14,242 +14,236 @@ import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; /** - * Class for VEX Robotics Spike style relay outputs. Relays are intended to be - * connected to Spikes or similar relays. The relay channels controls a pair of - * pins that are either both off, one on, the other on, or both on. This - * translates into two Spike outputs at 0v, one at 12v and one at 0v, one at 0v - * and the other at 12v, or two Spike outputs at 12V. This allows off, full - * forward, or full reverse control of motors without variable speed. It also - * allows the two channels (forward and reverse) to be used independently for - * something that does not care about voltage polarity (like a solenoid). + * Class for VEX Robotics Spike style relay outputs. Relays are intended to be connected to Spikes + * or similar relays. The relay channels controls a pair of pins that are either both off, one on, + * the other on, or both on. This translates into two Spike outputs at 0v, one at 12v and one at 0v, + * one at 0v and the other at 12v, or two Spike outputs at 12V. This allows off, full forward, or + * full reverse control of motors without variable speed. It also allows the two channels (forward + * and reverse) to be used independently for something that does not care about voltage polarity + * (like a solenoid). */ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable { - private MotorSafetyHelper m_safetyHelper; - /** - * This class represents errors in trying to set relay values contradictory - * to the direction to which the relay is set. - */ - public class InvalidValueException extends RuntimeException { + private MotorSafetyHelper m_safetyHelper; - /** - * Create a new exception with the given message - * - * @param message - * the message to pass with the exception - */ - public InvalidValueException(String message) { - super(message); - } - } + /** + * This class represents errors in trying to set relay values contradictory to the direction to + * which the relay is set. + */ + public class InvalidValueException extends RuntimeException { - /** - * The state to drive a Relay to. - */ - public static class Value { + /** + * Create a new exception with the given message + * + * @param message the message to pass with the exception + */ + public InvalidValueException(String message) { + super(message); + } + } - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kOff_val = 0; - static final int kOn_val = 1; - static final int kForward_val = 2; - static final int kReverse_val = 3; - /** - * value: off - */ - public static final Value kOff = new Value(kOff_val); - /** - * value: on for relays with defined direction - */ - public static final Value kOn = new Value(kOn_val); - /** - * value: forward - */ - public static final Value kForward = new Value(kForward_val); - /** - * value: reverse - */ - public static final Value kReverse = new Value(kReverse_val); + /** + * The state to drive a Relay to. + */ + public static class Value { - private Value(int value) { - this.value = value; - } - } + /** + * The integer value representing this enumeration + */ + public final int value; + static final int kOff_val = 0; + static final int kOn_val = 1; + static final int kForward_val = 2; + static final int kReverse_val = 3; + /** + * value: off + */ + public static final Value kOff = new Value(kOff_val); + /** + * value: on for relays with defined direction + */ + public static final Value kOn = new Value(kOn_val); + /** + * value: forward + */ + public static final Value kForward = new Value(kForward_val); + /** + * value: reverse + */ + public static final Value kReverse = new Value(kReverse_val); - /** - * The Direction(s) that a relay is configured to operate in. - */ - public static class Direction { + private Value(int value) { + this.value = value; + } + } - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kBoth_val = 0; - static final int kForward_val = 1; - static final int kReverse_val = 2; - /** - * direction: both directions are valid - */ - public static final Direction kBoth = new Direction(kBoth_val); - /** - * direction: Only forward is valid - */ - public static final Direction kForward = new Direction(kForward_val); - /** - * direction: only reverse is valid - */ - public static final Direction kReverse = new Direction(kReverse_val); + /** + * The Direction(s) that a relay is configured to operate in. + */ + public static class Direction { - private Direction(int value) { - this.value = value; - } - } + /** + * The integer value representing this enumeration + */ + public final int value; + static final int kBoth_val = 0; + static final int kForward_val = 1; + static final int kReverse_val = 2; + /** + * direction: both directions are valid + */ + public static final Direction kBoth = new Direction(kBoth_val); + /** + * direction: Only forward is valid + */ + public static final Direction kForward = new Direction(kForward_val); + /** + * direction: only reverse is valid + */ + public static final Direction kReverse = new Direction(kReverse_val); - private int m_channel; - private Direction m_direction; - private SimSpeedController impl; - private boolean go_pos, go_neg; + private Direction(int value) { + this.value = value; + } + } - /** - * Common relay initialization method. This code is common to all Relay - * constructors and initializes the relay and reserves all resources that - * need to be locked. Initially the relay is set to both lines at 0v. - */ - private void initRelay() { - SensorBase.checkRelayChannel(m_channel); - impl = new SimSpeedController("simulator/relay/" + m_channel); + private int m_channel; + private Direction m_direction; + private SimSpeedController impl; + private boolean go_pos, go_neg; - m_safetyHelper = new MotorSafetyHelper(this); - m_safetyHelper.setSafetyEnabled(false); + /** + * Common relay initialization method. This code is common to all Relay constructors and + * initializes the relay and reserves all resources that need to be locked. Initially the relay is + * set to both lines at 0v. + */ + private void initRelay() { + SensorBase.checkRelayChannel(m_channel); + impl = new SimSpeedController("simulator/relay/" + m_channel); - LiveWindow.addActuator("Relay", m_channel, this); - } + m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper.setSafetyEnabled(false); - /** - * Relay constructor given a channel. - * - * @param channel - * The channel number for this relay. - * @param direction - * The direction that the Relay object will control. - */ - public Relay(final int channel, Direction direction) { - if (direction == null) - throw new NullPointerException("Null Direction was given"); - m_channel = channel; - m_direction = direction; - initRelay(); - } + LiveWindow.addActuator("Relay", m_channel, this); + } - /** - * Relay constructor given a channel, allowing both directions. - * - * @param channel - * The channel number for this relay. - */ - public Relay(final int channel) { - m_channel = channel; - m_direction = Direction.kBoth; - initRelay(); - } + /** + * Relay constructor given a channel. + * + * @param channel The channel number for this relay. + * @param direction The direction that the Relay object will control. + */ + public Relay(final int channel, Direction direction) { + if (direction == null) + throw new NullPointerException("Null Direction was given"); + m_channel = channel; + m_direction = direction; + initRelay(); + } - public void free() { - impl.set(0); - } + /** + * Relay constructor given a channel, allowing both directions. + * + * @param channel The channel number for this relay. + */ + public Relay(final int channel) { + m_channel = channel; + m_direction = Direction.kBoth; + initRelay(); + } - /** - * Set the relay state. - * - * Valid values depend on which directions of the relay are controlled by - * the object. - * - * When set to kBothDirections, the relay can be set to any of the four - * states: 0v-0v, 12v-0v, 0v-12v, 12v-12v - * - * When set to kForwardOnly or kReverseOnly, you can specify the constant - * for the direction or you can simply specify kOff_val and kOn_val. Using - * only kOff_val and kOn_val is recommended. - * - * @param value - * The state to set the relay. - */ - public void set(Value value) { - switch (value.value) { - case Value.kOff_val: - if (m_direction == Direction.kBoth - || m_direction == Direction.kForward) { - go_pos = false; - } - if (m_direction == Direction.kBoth - || m_direction == Direction.kReverse) { - go_neg = false; - } - break; - case Value.kOn_val: - if (m_direction == Direction.kBoth - || m_direction == Direction.kForward) { - go_pos = true; - } - if (m_direction == Direction.kBoth - || m_direction == Direction.kReverse) { - go_neg = true; - } - break; - case Value.kForward_val: - if (m_direction == Direction.kReverse) - throw new InvalidValueException( - "A relay configured for reverse cannot be set to forward"); - if (m_direction == Direction.kBoth - || m_direction == Direction.kForward) { + public void free() { + impl.set(0); + } - go_pos = true; - } - if (m_direction == Direction.kBoth) { - go_neg = false; - } - break; - case Value.kReverse_val: - if (m_direction == Direction.kForward) - throw new InvalidValueException( - "A relay configured for forward cannot be set to reverse"); - if (m_direction == Direction.kBoth) { - go_pos = false; - } - if (m_direction == Direction.kBoth - || m_direction == Direction.kReverse) { - go_neg = true; - } - break; - default: - // Cannot hit this, limited by Value enum - } - impl.set((go_pos ? 1 : 0) + (go_neg ? -1 : 0)); - } + /** + * Set the relay state. + * + * Valid values depend on which directions of the relay are controlled by the object. + * + * When set to kBothDirections, the relay can be set to any of the four states: 0v-0v, 12v-0v, + * 0v-12v, 12v-12v + * + * When set to kForwardOnly or kReverseOnly, you can specify the constant for the direction or you + * can simply specify kOff_val and kOn_val. Using only kOff_val and kOn_val is recommended. + * + * @param value The state to set the relay. + */ + public void set(Value value) { + switch (value.value) { + case Value.kOff_val: + if (m_direction == Direction.kBoth + || m_direction == Direction.kForward) { + go_pos = false; + } + if (m_direction == Direction.kBoth + || m_direction == Direction.kReverse) { + go_neg = false; + } + break; + case Value.kOn_val: + if (m_direction == Direction.kBoth + || m_direction == Direction.kForward) { + go_pos = true; + } + if (m_direction == Direction.kBoth + || m_direction == Direction.kReverse) { + go_neg = true; + } + break; + case Value.kForward_val: + if (m_direction == Direction.kReverse) + throw new InvalidValueException( + "A relay configured for reverse cannot be set to forward"); + if (m_direction == Direction.kBoth + || m_direction == Direction.kForward) { - /** - * Get the Relay State - * - * Gets the current state of the relay. - * - * When set to kForwardOnly or kReverseOnly, value is returned as kOn/kOff - * not kForward/kReverse (per the recommendation in Set) - * - * @return The current state of the relay as a Relay::Value - */ - public Value get() { - // TODO: Don't assume that the go_pos and go_neg fields are correct? - if ((go_pos || m_direction == Direction.kReverse) && (go_neg || m_direction == Direction.kForward)) { - return Value.kOn; - } else if (go_pos) { - return Value.kForward; - } else if (go_neg) { - return Value.kReverse; - } else { - return Value.kOff; - } - } + go_pos = true; + } + if (m_direction == Direction.kBoth) { + go_neg = false; + } + break; + case Value.kReverse_val: + if (m_direction == Direction.kForward) + throw new InvalidValueException( + "A relay configured for forward cannot be set to reverse"); + if (m_direction == Direction.kBoth) { + go_pos = false; + } + if (m_direction == Direction.kBoth + || m_direction == Direction.kReverse) { + go_neg = true; + } + break; + default: + // Cannot hit this, limited by Value enum + } + impl.set((go_pos ? 1 : 0) + (go_neg ? -1 : 0)); + } + + /** + * Get the Relay State + * + * Gets the current state of the relay. + * + * When set to kForwardOnly or kReverseOnly, value is returned as kOn/kOff not kForward/kReverse + * (per the recommendation in Set) + * + * @return The current state of the relay as a Relay::Value + */ + public Value get() { + // TODO: Don't assume that the go_pos and go_neg fields are correct? + if ((go_pos || m_direction == Direction.kReverse) && (go_neg || m_direction == Direction + .kForward)) { + return Value.kOn; + } else if (go_pos) { + return Value.kForward; + } else if (go_neg) { + return Value.kReverse; + } else { + return Value.kOff; + } + } /** * Get the channel number. @@ -295,98 +289,96 @@ public class Relay extends SensorBase implements MotorSafety, LiveWindowSendable return "Relay ID " + getChannel(); } - /** - * Set the Relay Direction - * - * Changes which values the relay can be set to depending on which direction - * is used - * - * Valid inputs are kBothDirections, kForwardOnly, and kReverseOnly - * - * @param direction - * The direction for the relay to operate in - */ - public void setDirection(Direction direction) { - if (direction == null) - throw new NullPointerException("Null Direction was given"); - if (m_direction == direction) { - return; - } + /** + * Set the Relay Direction + * + * Changes which values the relay can be set to depending on which direction is used + * + * Valid inputs are kBothDirections, kForwardOnly, and kReverseOnly + * + * @param direction The direction for the relay to operate in + */ + public void setDirection(Direction direction) { + if (direction == null) + throw new NullPointerException("Null Direction was given"); + if (m_direction == direction) { + return; + } - free(); + free(); - m_direction = direction; + m_direction = direction; - // initRelay(); // NOTE: not needed in simulation - } + // initRelay(); // NOTE: not needed in simulation + } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Relay"; - } + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Relay"; + } - private ITable m_table; - private ITableListener m_table_listener; + private ITable m_table; + private ITableListener m_table_listener; - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - if (get() == Value.kOn) { - m_table.putString("Value", "On"); - } else if (get() == Value.kForward) { - m_table.putString("Value", "Forward"); - } else if (get() == Value.kReverse) { - m_table.putString("Value", "Reverse"); - } else { - m_table.putString("Value", "Off"); - } - } - } + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + if (get() == Value.kOn) { + m_table.putString("Value", "On"); + } else if (get() == Value.kForward) { + m_table.putString("Value", "Forward"); + } else if (get() == Value.kReverse) { + m_table.putString("Value", "Reverse"); + } else { + m_table.putString("Value", "Off"); + } + } + } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, - boolean bln) { - String val = ((String) value); - if (val.equals("Off")) { - set(Value.kOff); - } else if (val.equals("Forward")) { - set(Value.kForward); - } else if (val.equals("Reverse")) { - set(Value.kReverse); - } - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, + boolean bln) { + String val = ((String) value); + if (val.equals("Off")) { + set(Value.kOff); + } else if (val.equals("Forward")) { + set(Value.kForward); + } else if (val.equals("Reverse")) { + set(Value.kReverse); + } + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotBase.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotBase.java index 7b2c350c62..191e7a8cf9 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotBase.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotBase.java @@ -12,201 +12,212 @@ import java.net.URL; import java.util.Enumeration; import java.util.jar.Manifest; -import edu.wpi.first.wpilibj.simulation.MainNode; import edu.wpi.first.wpilibj.internal.SimTimer; import edu.wpi.first.wpilibj.networktables.NetworkTable; +import edu.wpi.first.wpilibj.simulation.MainNode; /** - * Implement a Robot Program framework. - * The RobotBase class is intended to be subclassed by a user creating a robot program. - * Overridden autonomous() and operatorControl() methods are called at the appropriate time - * as the match proceeds. In the current implementation, the Autonomous code will run to - * completion before the OperatorControl code could start. In the future the Autonomous code + * Implement a Robot Program framework. The RobotBase class is intended to be subclassed by a user + * creating a robot program. Overridden autonomous() and operatorControl() methods are called at the + * appropriate time as the match proceeds. In the current implementation, the Autonomous code will + * run to completion before the OperatorControl code could start. In the future the Autonomous code * might be spawned as a task, then killed at the end of the Autonomous period. */ public abstract class RobotBase { - /** - * The VxWorks priority that robot code should work at (so Java code should run at) - */ - public static final int ROBOT_TASK_PRIORITY = 101; + /** + * The VxWorks priority that robot code should work at (so Java code should run at) + */ + public static final int ROBOT_TASK_PRIORITY = 101; - /** - * Boolean System property. If true (default), send System.err messages to the driver station. - */ - public final static String ERRORS_TO_DRIVERSTATION_PROP = "first.driverstation.senderrors"; + /** + * Boolean System property. If true (default), send System.err messages to the driver station. + */ + public final static String ERRORS_TO_DRIVERSTATION_PROP = "first.driverstation.senderrors"; - protected final DriverStation m_ds; + protected final DriverStation m_ds; - /** - * Constructor for a generic robot program. - * User code should be placed in the constructor that runs before the Autonomous or Operator - * Control period starts. The constructor will run to completion before Autonomous is entered. - * - * This must be used to ensure that the communications code starts. In the future it would be - * nice to put this code into it's own task that loads on boot so ensure that it runs. - */ - protected RobotBase() { - // TODO: StartCAPI(); - // TODO: See if the next line is necessary - // Resource.RestartProgram(); + /** + * Constructor for a generic robot program. User code should be placed in the constructor that + * runs before the Autonomous or Operator Control period starts. The constructor will run to + * completion before Autonomous is entered. + * + * This must be used to ensure that the communications code starts. In the future it would be nice + * to put this code into it's own task that loads on boot so ensure that it runs. + */ + protected RobotBase() { + // TODO: StartCAPI(); + // TODO: See if the next line is necessary + // Resource.RestartProgram(); // if (getBooleanProperty(ERRORS_TO_DRIVERSTATION_PROP, true)) { // Utility.sendErrorStreamToDriverStation(true); // } - NetworkTable.setServerMode();//must be before b - m_ds = DriverStation.getInstance(); - NetworkTable.getTable(""); // forces network tables to initialize - NetworkTable.getTable("LiveWindow").getSubTable("~STATUS~").putBoolean("LW Enabled", false); + NetworkTable.setServerMode();//must be before b + m_ds = DriverStation.getInstance(); + NetworkTable.getTable(""); // forces network tables to initialize + NetworkTable.getTable("LiveWindow").getSubTable("~STATUS~").putBoolean("LW Enabled", false); + } + + /** + * Free the resources for a RobotBase class. + */ + public void free() { + } + + /** + * @return If the robot is running in simulation. + */ + public static boolean isSimulation() { + return true; + } + + /** + * @return If the robot is running in the real world. + */ + public static boolean isReal() { + return false; + } + + /** + * Determine if the Robot is currently disabled. + * + * @return True if the Robot is currently disabled by the field controls. + */ + public boolean isDisabled() { + return m_ds.isDisabled(); + } + + /** + * Determine if the Robot is currently enabled. + * + * @return True if the Robot is currently enabled by the field controls. + */ + public boolean isEnabled() { + return m_ds.isEnabled(); + } + + /** + * Determine if the robot is currently in Autonomous mode. + * + * @return True if the robot is currently operating Autonomously as determined by the field + * controls. + */ + public boolean isAutonomous() { + return m_ds.isAutonomous(); + } + + /** + * Determine if the robot is currently in Test mode + * + * @return True if the robot is currently operating in Test mode as determined by the driver + * station. + */ + public boolean isTest() { + return m_ds.isTest(); + } + + /** + * Determine if the robot is currently in Operator Control mode. + * + * @return True if the robot is currently operating in Tele-Op mode as determined by the field + * controls. + */ + public boolean isOperatorControl() { + return m_ds.isOperatorControl(); + } + + /** + * Indicates if new data is available from the driver station. + * + * @return Has new data arrived over the network since the last time this function was called? + */ + public boolean isNewDataAvailable() { + return m_ds.isNewControlData(); + } + + /** + * Provide an alternate "main loop" via startCompetition(). + */ + public abstract void startCompetition(); + + public static boolean getBooleanProperty(String name, boolean defaultValue) { + String propVal = System.getProperty(name); + if (propVal == null) { + return defaultValue; + } + if (propVal.equalsIgnoreCase("false")) { + return false; + } else if (propVal.equalsIgnoreCase("true")) { + return true; + } else { + throw new IllegalStateException(propVal); + } + } + + /** + * Starting point for the applications. Starts the OtaServer and then runs the robot. + */ + public static void main(String args[]) { // TODO: expose main to teams? + boolean errorOnExit = false; + + try { + MainNode.openGazeboConnection(); + } catch (Throwable e) { + System.err.println("Could not connect to Gazebo."); + e.printStackTrace(); + System.exit(1); + return; } - /** - * Free the resources for a RobotBase class. - */ - public void free() { + // Set some implementations so that the static methods work properly + Timer.SetImplementation(new SimTimer()); + RobotState.SetImplementation(DriverStation.getInstance()); + HLUsageReporting.SetImplementation(new HLUsageReporting.Null()); // No reporting + + String robotName = ""; + Enumeration resources = null; + try { + resources = RobotBase.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); + } catch (IOException e) { + e.printStackTrace(); } - /** - * @return If the robot is running in simulation. - */ - public static boolean isSimulation() { - return true; - } + System.out.println("resources = |" + resources + "|"); - /** - * @return If the robot is running in the real world. - */ - public static boolean isReal() { - return false; - } - - /** - * Determine if the Robot is currently disabled. - * @return True if the Robot is currently disabled by the field controls. - */ - public boolean isDisabled() { - return m_ds.isDisabled(); - } - - /** - * Determine if the Robot is currently enabled. - * @return True if the Robot is currently enabled by the field controls. - */ - public boolean isEnabled() { - return m_ds.isEnabled(); - } - - /** - * Determine if the robot is currently in Autonomous mode. - * @return True if the robot is currently operating Autonomously as determined by the field controls. - */ - public boolean isAutonomous() { - return m_ds.isAutonomous(); - } - - /** - * Determine if the robot is currently in Test mode - * @return True if the robot is currently operating in Test mode as determined by the driver station. - */ - public boolean isTest() { - return m_ds.isTest(); - } - - /** - * Determine if the robot is currently in Operator Control mode. - * @return True if the robot is currently operating in Tele-Op mode as determined by the field controls. - */ - public boolean isOperatorControl() { - return m_ds.isOperatorControl(); - } - - /** - * Indicates if new data is available from the driver station. - * @return Has new data arrived over the network since the last time this function was called? - */ - public boolean isNewDataAvailable() { - return m_ds.isNewControlData(); - } - - /** - * Provide an alternate "main loop" via startCompetition(). - */ - public abstract void startCompetition(); - - public static boolean getBooleanProperty(String name, boolean defaultValue) { - String propVal = System.getProperty(name); - if (propVal == null) { - return defaultValue; - } - if (propVal.equalsIgnoreCase("false")) { - return false; - } else if (propVal.equalsIgnoreCase("true")) { - return true; - } else { - throw new IllegalStateException(propVal); + while (resources != null && resources.hasMoreElements()) { + try { + Manifest manifest = new Manifest(resources.nextElement().openStream()); + if (manifest.getMainAttributes().getValue("Robot-Class") != null) { + robotName = manifest.getMainAttributes().getValue("Robot-Class"); } + } catch (IOException e) { + e.printStackTrace(); + } } - /** - * Starting point for the applications. Starts the OtaServer and then runs - * the robot. - * @throws javax.microedition.midlet.MIDletStateChangeException - */ - public static void main(String args[]) { // TODO: expose main to teams? - boolean errorOnExit = false; - - try { - MainNode.openGazeboConnection(); - } catch (Throwable e) { - System.err.println("Could not connect to Gazebo."); - e.printStackTrace(); - System.exit(1); - return; - } - - // Set some implementations so that the static methods work properly - Timer.SetImplementation(new SimTimer()); - RobotState.SetImplementation(DriverStation.getInstance()); - HLUsageReporting.SetImplementation(new HLUsageReporting.Null()); // No reporting - - String robotName = ""; - Enumeration resources = null; - try { - resources = RobotBase.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); - } catch (IOException e) {e.printStackTrace();} - - System.out.println("resources = |"+ resources +"|"); - - while (resources != null && resources.hasMoreElements()) { - try { - Manifest manifest = new Manifest(resources.nextElement().openStream()); - if (manifest.getMainAttributes().getValue("Robot-Class") != null){ - robotName = manifest.getMainAttributes().getValue("Robot-Class"); - } - } catch (IOException e) {e.printStackTrace();} - } - - RobotBase robot; - try { - robot = (RobotBase) Class.forName(robotName).newInstance(); - } catch (InstantiationException|IllegalAccessException|ClassNotFoundException e) { - System.err.println("WARNING: Robots don't quit!"); - System.err.println("ERROR: Could not instantiate robot "+robotName+"!"); - return; - } - - try { - robot.startCompetition(); - } catch (Throwable t) { - t.printStackTrace(); - errorOnExit = true; - } finally { - // startCompetition never returns unless exception occurs.... - System.err.println("WARNING: Robots don't quit!"); - if (errorOnExit) { - System.err.println("---> The startCompetition() method (or methods called by it) should have handled the exception above."); - } else { - System.err.println("---> Unexpected return from startCompetition() method."); - } - } + RobotBase robot; + try { + robot = (RobotBase) Class.forName(robotName).newInstance(); + } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { + System.err.println("WARNING: Robots don't quit!"); + System.err.println("ERROR: Could not instantiate robot " + robotName + "!"); + return; } + + try { + robot.startCompetition(); + } catch (Throwable t) { + t.printStackTrace(); + errorOnExit = true; + } finally { + // startCompetition never returns unless exception occurs.... + System.err.println("WARNING: Robots don't quit!"); + if (errorOnExit) { + System.err.println("---> The startCompetition() method (or methods called by it) should " + + "have handled the exception above."); + } else { + System.err.println("---> Unexpected return from startCompetition() method."); + } + } + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotDrive.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotDrive.java index a159ad5dbf..4f8716fe39 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotDrive.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/RobotDrive.java @@ -9,712 +9,742 @@ package edu.wpi.first.wpilibj; /** - * Utility class for handling Robot drive based on a definition of the motor configuration. - * The robot drive class handles basic driving for a robot. Currently, 2 and 4 motor standard - * drive trains are supported. In the future other drive types like swerve and meccanum might - * be implemented. Motor channel numbers are passed supplied on creation of the class. Those are - * used for either the drive function (intended for hand created drive code, such as autonomous) - * or with the Tank/Arcade functions intended to be used for Operator Control driving. + * Utility class for handling Robot drive based on a definition of the motor configuration. The + * robot drive class handles basic driving for a robot. Currently, 2 and 4 motor standard drive + * trains are supported. In the future other drive types like swerve and meccanum might be + * implemented. Motor channel numbers are passed supplied on creation of the class. Those are used + * for either the drive function (intended for hand created drive code, such as autonomous) or with + * the Tank/Arcade functions intended to be used for Operator Control driving. */ public class RobotDrive implements MotorSafety { - protected MotorSafetyHelper m_safetyHelper; + protected MotorSafetyHelper m_safetyHelper; + + /** + * The location of a motor on the robot for the purpose of driving + */ + public static class MotorType { /** - * The location of a motor on the robot for the purpose of driving + * The integer value representing this enumeration */ - public static class MotorType { - - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kFrontLeft_val = 0; - static final int kFrontRight_val = 1; - static final int kRearLeft_val = 2; - static final int kRearRight_val = 3; - /** - * motortype: front left - */ - public static final MotorType kFrontLeft = new MotorType(kFrontLeft_val); - /** - * motortype: front right - */ - public static final MotorType kFrontRight = new MotorType(kFrontRight_val); - /** - * motortype: rear left - */ - public static final MotorType kRearLeft = new MotorType(kRearLeft_val); - /** - * motortype: rear right - */ - public static final MotorType kRearRight = new MotorType(kRearRight_val); - - private MotorType(int value) { - this.value = value; - } - } - public static final double kDefaultExpirationTime = 0.1; - public static final double kDefaultSensitivity = 0.5; - public static final double kDefaultMaxOutput = 1.0; - protected static final int kMaxNumberOfMotors = 4; - protected final int m_invertedMotors[] = new int[4]; - protected double m_sensitivity; - protected double m_maxOutput; - protected SpeedController m_frontLeftMotor; - protected SpeedController m_frontRightMotor; - protected SpeedController m_rearLeftMotor; - protected SpeedController m_rearRightMotor; - protected boolean m_allocatedSpeedControllers; - protected boolean m_isCANInitialized = false;//TODO: fix can - protected static boolean kArcadeRatioCurve_Reported = false; - protected static boolean kTank_Reported = false; - protected static boolean kArcadeStandard_Reported = false; - protected static boolean kMecanumCartesian_Reported = false; - protected static boolean kMecanumPolar_Reported = false; - - /** Constructor for RobotDrive with 2 motors specified with channel numbers. - * Set up parameters for a two wheel drive system where the - * left and right motor pwm channels are specified in the call. - * This call assumes Jaguars for controlling the motors. - * @param leftMotorChannel The PWM channel number that drives the left motor. - * @param rightMotorChannel The PWM channel number that drives the right motor. - */ - public RobotDrive(final int leftMotorChannel, final int rightMotorChannel) { - m_sensitivity = kDefaultSensitivity; - m_maxOutput = kDefaultMaxOutput; - m_frontLeftMotor = null; - m_rearLeftMotor = new Jaguar(leftMotorChannel); - m_frontRightMotor = null; - m_rearRightMotor = new Jaguar(rightMotorChannel); - for (int i = 0; i < kMaxNumberOfMotors; i++) { - m_invertedMotors[i] = 1; - } - m_allocatedSpeedControllers = true; - setupMotorSafety(); - drive(0, 0); - } - + public final int value; + static final int kFrontLeft_val = 0; + static final int kFrontRight_val = 1; + static final int kRearLeft_val = 2; + static final int kRearRight_val = 3; /** - * Constructor for RobotDrive with 4 motors specified with channel numbers. - * Set up parameters for a four wheel drive system where all four motor - * pwm channels are specified in the call. - * This call assumes Jaguars for controlling the motors. - * @param frontLeftMotor Front left motor channel number - * @param rearLeftMotor Rear Left motor channel number - * @param frontRightMotor Front right motor channel number - * @param rearRightMotor Rear Right motor channel number + * motortype: front left */ - public RobotDrive(final int frontLeftMotor, final int rearLeftMotor, - final int frontRightMotor, final int rearRightMotor) { - m_sensitivity = kDefaultSensitivity; - m_maxOutput = kDefaultMaxOutput; - m_rearLeftMotor = new Jaguar(rearLeftMotor); - m_rearRightMotor = new Jaguar(rearRightMotor); - m_frontLeftMotor = new Jaguar(frontLeftMotor); - m_frontRightMotor = new Jaguar(frontRightMotor); - for (int i = 0; i < kMaxNumberOfMotors; i++) { - m_invertedMotors[i] = 1; - } - m_allocatedSpeedControllers = true; - setupMotorSafety(); - drive(0, 0); - } - + public static final MotorType kFrontLeft = new MotorType(kFrontLeft_val); /** - * Constructor for RobotDrive with 2 motors specified as SpeedController objects. - * The SpeedController version of the constructor enables programs to use the RobotDrive classes with - * subclasses of the SpeedController objects, for example, versions with ramping or reshaping of - * the curve to suit motor bias or dead-band elimination. - * @param leftMotor The left SpeedController object used to drive the robot. - * @param rightMotor the right SpeedController object used to drive the robot. + * motortype: front right */ - public RobotDrive(SpeedController leftMotor, SpeedController rightMotor) { - if (leftMotor == null || rightMotor == null) { - m_rearLeftMotor = m_rearRightMotor = null; - throw new NullPointerException("Null motor provided"); - } - m_frontLeftMotor = null; - m_rearLeftMotor = leftMotor; - m_frontRightMotor = null; - m_rearRightMotor = rightMotor; - m_sensitivity = kDefaultSensitivity; - m_maxOutput = kDefaultMaxOutput; - for (int i = 0; i < kMaxNumberOfMotors; i++) { - m_invertedMotors[i] = 1; - } - m_allocatedSpeedControllers = false; - setupMotorSafety(); - drive(0, 0); - } - + public static final MotorType kFrontRight = new MotorType(kFrontRight_val); /** - * Constructor for RobotDrive with 4 motors specified as SpeedController objects. - * Speed controller input version of RobotDrive (see previous comments). - * @param rearLeftMotor The back left SpeedController object used to drive the robot. - * @param frontLeftMotor The front left SpeedController object used to drive the robot - * @param rearRightMotor The back right SpeedController object used to drive the robot. - * @param frontRightMotor The front right SpeedController object used to drive the robot. + * motortype: rear left */ - public RobotDrive(SpeedController frontLeftMotor, SpeedController rearLeftMotor, - SpeedController frontRightMotor, SpeedController rearRightMotor) { - if (frontLeftMotor == null || rearLeftMotor == null || frontRightMotor == null || rearRightMotor == null) { - m_frontLeftMotor = m_rearLeftMotor = m_frontRightMotor = m_rearRightMotor = null; - throw new NullPointerException("Null motor provided"); - } - m_frontLeftMotor = frontLeftMotor; - m_rearLeftMotor = rearLeftMotor; - m_frontRightMotor = frontRightMotor; - m_rearRightMotor = rearRightMotor; - m_sensitivity = kDefaultSensitivity; - m_maxOutput = kDefaultMaxOutput; - for (int i = 0; i < kMaxNumberOfMotors; i++) { - m_invertedMotors[i] = 1; - } - m_allocatedSpeedControllers = false; - setupMotorSafety(); - drive(0, 0); - } - + public static final MotorType kRearLeft = new MotorType(kRearLeft_val); /** - * Drive the motors at "outputMagnitude" and "curve". - * Both outputMagnitude and curve are -1.0 to +1.0 values, where 0.0 - * represents stopped and not turning. curve < 0 will turn left and curve > 0 - * will turn right. - * - * The algorithm for steering provides a constant turn radius for any normal - * speed range, both forward and backward. Increasing m_sensitivity causes - * sharper turns for fixed values of curve. - * - * This function will most likely be used in an autonomous routine. - * - * @param outputMagnitude The speed setting for the outside wheel in a turn, - * forward or backwards, +1 to -1. - * @param curve The rate of turn, constant for different forward speeds. Set - * curve < 0 for left turn or curve > 0 for right turn. - * Set curve = e^(-r/w) to get a turn radius r for wheelbase w of your robot. - * Conversely, turn radius r = -ln(curve)*w for a given value of curve and - * wheelbase w. + * motortype: rear right */ - public void drive(double outputMagnitude, double curve) { - double leftOutput, rightOutput; + public static final MotorType kRearRight = new MotorType(kRearRight_val); - if(!kArcadeRatioCurve_Reported) { - kArcadeRatioCurve_Reported = true; - } - if (curve < 0) { - double value = Math.log(-curve); - double ratio = (value - m_sensitivity) / (value + m_sensitivity); - if (ratio == 0) { - ratio = .0000000001; - } - leftOutput = outputMagnitude / ratio; - rightOutput = outputMagnitude; - } else if (curve > 0) { - double value = Math.log(curve); - double ratio = (value - m_sensitivity) / (value + m_sensitivity); - if (ratio == 0) { - ratio = .0000000001; - } - leftOutput = outputMagnitude; - rightOutput = outputMagnitude / ratio; - } else { - leftOutput = outputMagnitude; - rightOutput = outputMagnitude; - } - setLeftRightMotorOutputs(leftOutput, rightOutput); + private MotorType(int value) { + this.value = value; + } + } + + public static final double kDefaultExpirationTime = 0.1; + public static final double kDefaultSensitivity = 0.5; + public static final double kDefaultMaxOutput = 1.0; + protected static final int kMaxNumberOfMotors = 4; + protected final int m_invertedMotors[] = new int[4]; + protected double m_sensitivity; + protected double m_maxOutput; + protected SpeedController m_frontLeftMotor; + protected SpeedController m_frontRightMotor; + protected SpeedController m_rearLeftMotor; + protected SpeedController m_rearRightMotor; + protected boolean m_allocatedSpeedControllers; + protected boolean m_isCANInitialized = false;//TODO: fix can + protected static boolean kArcadeRatioCurve_Reported = false; + protected static boolean kTank_Reported = false; + protected static boolean kArcadeStandard_Reported = false; + protected static boolean kMecanumCartesian_Reported = false; + protected static boolean kMecanumPolar_Reported = false; + + /** + * Constructor for RobotDrive with 2 motors specified with channel numbers. Set up parameters for + * a two wheel drive system where the left and right motor pwm channels are specified in the call. + * This call assumes Jaguars for controlling the motors. + * + * @param leftMotorChannel The PWM channel number that drives the left motor. + * @param rightMotorChannel The PWM channel number that drives the right motor. + */ + public RobotDrive(final int leftMotorChannel, final int rightMotorChannel) { + m_sensitivity = kDefaultSensitivity; + m_maxOutput = kDefaultMaxOutput; + m_frontLeftMotor = null; + m_rearLeftMotor = new Jaguar(leftMotorChannel); + m_frontRightMotor = null; + m_rearRightMotor = new Jaguar(rightMotorChannel); + for (int i = 0; i < kMaxNumberOfMotors; i++) { + m_invertedMotors[i] = 1; + } + m_allocatedSpeedControllers = true; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Constructor for RobotDrive with 4 motors specified with channel numbers. Set up parameters for + * a four wheel drive system where all four motor pwm channels are specified in the call. This + * call assumes Jaguars for controlling the motors. + * + * @param frontLeftMotor Front left motor channel number + * @param rearLeftMotor Rear Left motor channel number + * @param frontRightMotor Front right motor channel number + * @param rearRightMotor Rear Right motor channel number + */ + public RobotDrive(final int frontLeftMotor, final int rearLeftMotor, + final int frontRightMotor, final int rearRightMotor) { + m_sensitivity = kDefaultSensitivity; + m_maxOutput = kDefaultMaxOutput; + m_rearLeftMotor = new Jaguar(rearLeftMotor); + m_rearRightMotor = new Jaguar(rearRightMotor); + m_frontLeftMotor = new Jaguar(frontLeftMotor); + m_frontRightMotor = new Jaguar(frontRightMotor); + for (int i = 0; i < kMaxNumberOfMotors; i++) { + m_invertedMotors[i] = 1; + } + m_allocatedSpeedControllers = true; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Constructor for RobotDrive with 2 motors specified as SpeedController objects. The + * SpeedController version of the constructor enables programs to use the RobotDrive classes with + * subclasses of the SpeedController objects, for example, versions with ramping or reshaping of + * the curve to suit motor bias or dead-band elimination. + * + * @param leftMotor The left SpeedController object used to drive the robot. + * @param rightMotor the right SpeedController object used to drive the robot. + */ + public RobotDrive(SpeedController leftMotor, SpeedController rightMotor) { + if (leftMotor == null || rightMotor == null) { + m_rearLeftMotor = m_rearRightMotor = null; + throw new NullPointerException("Null motor provided"); + } + m_frontLeftMotor = null; + m_rearLeftMotor = leftMotor; + m_frontRightMotor = null; + m_rearRightMotor = rightMotor; + m_sensitivity = kDefaultSensitivity; + m_maxOutput = kDefaultMaxOutput; + for (int i = 0; i < kMaxNumberOfMotors; i++) { + m_invertedMotors[i] = 1; + } + m_allocatedSpeedControllers = false; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Constructor for RobotDrive with 4 motors specified as SpeedController objects. Speed controller + * input version of RobotDrive (see previous comments). + * + * @param rearLeftMotor The back left SpeedController object used to drive the robot. + * @param frontLeftMotor The front left SpeedController object used to drive the robot + * @param rearRightMotor The back right SpeedController object used to drive the robot. + * @param frontRightMotor The front right SpeedController object used to drive the robot. + */ + public RobotDrive(SpeedController frontLeftMotor, SpeedController rearLeftMotor, + SpeedController frontRightMotor, SpeedController rearRightMotor) { + if (frontLeftMotor == null || rearLeftMotor == null || frontRightMotor == null || + rearRightMotor == null) { + m_frontLeftMotor = m_rearLeftMotor = m_frontRightMotor = m_rearRightMotor = null; + throw new NullPointerException("Null motor provided"); + } + m_frontLeftMotor = frontLeftMotor; + m_rearLeftMotor = rearLeftMotor; + m_frontRightMotor = frontRightMotor; + m_rearRightMotor = rearRightMotor; + m_sensitivity = kDefaultSensitivity; + m_maxOutput = kDefaultMaxOutput; + for (int i = 0; i < kMaxNumberOfMotors; i++) { + m_invertedMotors[i] = 1; + } + m_allocatedSpeedControllers = false; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Drive the motors at "outputMagnitude" and "curve". Both outputMagnitude and curve are -1.0 to + * +1.0 values, where 0.0 represents stopped and not turning. curve < 0 will turn left and curve > + * 0 will turn right. + * + * The algorithm for steering provides a constant turn radius for any normal speed range, both + * forward and backward. Increasing m_sensitivity causes sharper turns for fixed values of curve. + * + * This function will most likely be used in an autonomous routine. + * + * @param outputMagnitude The speed setting for the outside wheel in a turn, forward or backwards, + * +1 to -1. + * @param curve The rate of turn, constant for different forward speeds. Set curve < 0 + * for left turn or curve > 0 for right turn. Set curve = e^(-r/w) to get a + * turn radius r for wheelbase w of your robot. Conversely, turn radius r = + * -ln(curve)*w for a given value of curve and wheelbase w. + */ + public void drive(double outputMagnitude, double curve) { + double leftOutput, rightOutput; + + if (!kArcadeRatioCurve_Reported) { + kArcadeRatioCurve_Reported = true; + } + if (curve < 0) { + double value = Math.log(-curve); + double ratio = (value - m_sensitivity) / (value + m_sensitivity); + if (ratio == 0) { + ratio = .0000000001; + } + leftOutput = outputMagnitude / ratio; + rightOutput = outputMagnitude; + } else if (curve > 0) { + double value = Math.log(curve); + double ratio = (value - m_sensitivity) / (value + m_sensitivity); + if (ratio == 0) { + ratio = .0000000001; + } + leftOutput = outputMagnitude; + rightOutput = outputMagnitude / ratio; + } else { + leftOutput = outputMagnitude; + rightOutput = outputMagnitude; + } + setLeftRightMotorOutputs(leftOutput, rightOutput); + } + + /** + * Provide tank steering using the stored robot configuration. drive the robot using two joystick + * inputs. The Y-axis will be selected from each Joystick object. + * + * @param leftStick The joystick to control the left side of the robot. + * @param rightStick The joystick to control the right side of the robot. + */ + public void tankDrive(GenericHID leftStick, GenericHID rightStick) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getY(), rightStick.getY(), true); + } + + /** + * Provide tank steering using the stored robot configuration. drive the robot using two joystick + * inputs. The Y-axis will be selected from each Joystick object. + * + * @param leftStick The joystick to control the left side of the robot. + * @param rightStick The joystick to control the right side of the robot. + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds + */ + public void tankDrive(GenericHID leftStick, GenericHID rightStick, boolean squaredInputs) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getY(), rightStick.getY(), squaredInputs); + } + + /** + * Provide tank steering using the stored robot configuration. This function lets you pick the + * axis to be used on each Joystick object for the left and right sides of the robot. + * + * @param leftStick The Joystick object to use for the left side of the robot. + * @param leftAxis The axis to select on the left side Joystick object. + * @param rightStick The Joystick object to use for the right side of the robot. + * @param rightAxis The axis to select on the right side Joystick object. + */ + public void tankDrive(GenericHID leftStick, final int leftAxis, + GenericHID rightStick, final int rightAxis) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), true); + } + + /** + * Provide tank steering using the stored robot configuration. This function lets you pick the + * axis to be used on each Joystick object for the left and right sides of the robot. + * + * @param leftStick The Joystick object to use for the left side of the robot. + * @param leftAxis The axis to select on the left side Joystick object. + * @param rightStick The Joystick object to use for the right side of the robot. + * @param rightAxis The axis to select on the right side Joystick object. + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds + */ + public void tankDrive(GenericHID leftStick, final int leftAxis, + GenericHID rightStick, final int rightAxis, boolean squaredInputs) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), squaredInputs); + } + + /** + * Provide tank steering using the stored robot configuration. This function lets you directly + * provide joystick values from any source. + * + * @param leftValue The value of the left stick. + * @param rightValue The value of the right stick. + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds + */ + public void tankDrive(double leftValue, double rightValue, boolean squaredInputs) { + + if (!kTank_Reported) { + kTank_Reported = true; } - /** - * Provide tank steering using the stored robot configuration. - * drive the robot using two joystick inputs. The Y-axis will be selected from - * each Joystick object. - * @param leftStick The joystick to control the left side of the robot. - * @param rightStick The joystick to control the right side of the robot. - */ - public void tankDrive(GenericHID leftStick, GenericHID rightStick) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getY(), rightStick.getY(), true); + // square the inputs (while preserving the sign) to increase fine control while permitting + // full power + leftValue = limit(leftValue); + rightValue = limit(rightValue); + if (squaredInputs) { + if (leftValue >= 0.0) { + leftValue = (leftValue * leftValue); + } else { + leftValue = -(leftValue * leftValue); + } + if (rightValue >= 0.0) { + rightValue = (rightValue * rightValue); + } else { + rightValue = -(rightValue * rightValue); + } + } + setLeftRightMotorOutputs(leftValue, rightValue); + } + + /** + * Provide tank steering using the stored robot configuration. This function lets you directly + * provide joystick values from any source. + * + * @param leftValue The value of the left stick. + * @param rightValue The value of the right stick. + */ + public void tankDrive(double leftValue, double rightValue) { + tankDrive(leftValue, rightValue, true); + } + + /** + * Arcade drive implements single stick driving. Given a single Joystick, the class assumes the Y + * axis for the move value and the X axis for the rotate value. (Should add more information here + * regarding the way that arcade drive works.) + * + * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be + * selected for forwards/backwards and the X-axis will be selected for + * rotation rate. + * @param squaredInputs If true, the sensitivity will be decreased for small values + */ + public void arcadeDrive(GenericHID stick, boolean squaredInputs) { + // simply call the full-featured arcadeDrive with the appropriate values + arcadeDrive(stick.getY(), stick.getX(), squaredInputs); + } + + /** + * Arcade drive implements single stick driving. Given a single Joystick, the class assumes the Y + * axis for the move value and the X axis for the rotate value. (Should add more information here + * regarding the way that arcade drive works.) + * + * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected + * for forwards/backwards and the X-axis will be selected for rotation rate. + */ + public void arcadeDrive(GenericHID stick) { + this.arcadeDrive(stick, true); + } + + /** + * Arcade drive implements single stick driving. Given two joystick instances and two axis, + * compute the values to send to either two or four motors. + * + * @param moveStick The Joystick object that represents the forward/backward direction + * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically + * Y_AXIS) + * @param rotateStick The Joystick object that represents the rotation value + * @param rotateAxis The axis on the rotation object to use for the rotate right/left + * (typically X_AXIS) + * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds + */ + public void arcadeDrive(GenericHID moveStick, final int moveAxis, + GenericHID rotateStick, final int rotateAxis, + boolean squaredInputs) { + double moveValue = moveStick.getRawAxis(moveAxis); + double rotateValue = rotateStick.getRawAxis(rotateAxis); + + arcadeDrive(moveValue, rotateValue, squaredInputs); + } + + /** + * Arcade drive implements single stick driving. Given two joystick instances and two axis, + * compute the values to send to either two or four motors. + * + * @param moveStick The Joystick object that represents the forward/backward direction + * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically + * Y_AXIS) + * @param rotateStick The Joystick object that represents the rotation value + * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically + * X_AXIS) + */ + public void arcadeDrive(GenericHID moveStick, final int moveAxis, + GenericHID rotateStick, final int rotateAxis) { + this.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true); + } + + /** + * Arcade drive implements single stick driving. This function lets you directly provide joystick + * values from any source. + * + * @param moveValue The value to use for forwards/backwards + * @param rotateValue The value to use for the rotate right/left + * @param squaredInputs If set, decreases the sensitivity at low speeds + */ + public void arcadeDrive(double moveValue, double rotateValue, boolean squaredInputs) { + // local variables to hold the computed PWM values for the motors + if (!kArcadeStandard_Reported) { + kArcadeStandard_Reported = true; } - /** - * Provide tank steering using the stored robot configuration. - * drive the robot using two joystick inputs. The Y-axis will be selected from - * each Joystick object. - * @param leftStick The joystick to control the left side of the robot. - * @param rightStick The joystick to control the right side of the robot. - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void tankDrive(GenericHID leftStick, GenericHID rightStick, boolean squaredInputs) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getY(), rightStick.getY(), squaredInputs); + double leftMotorSpeed; + double rightMotorSpeed; + + moveValue = limit(moveValue); + rotateValue = limit(rotateValue); + + if (squaredInputs) { + // square the inputs (while preserving the sign) to increase fine control while permitting + // full power + if (moveValue >= 0.0) { + moveValue = (moveValue * moveValue); + } else { + moveValue = -(moveValue * moveValue); + } + if (rotateValue >= 0.0) { + rotateValue = (rotateValue * rotateValue); + } else { + rotateValue = -(rotateValue * rotateValue); + } } - /** - * Provide tank steering using the stored robot configuration. - * This function lets you pick the axis to be used on each Joystick object for the left - * and right sides of the robot. - * @param leftStick The Joystick object to use for the left side of the robot. - * @param leftAxis The axis to select on the left side Joystick object. - * @param rightStick The Joystick object to use for the right side of the robot. - * @param rightAxis The axis to select on the right side Joystick object. - */ - public void tankDrive(GenericHID leftStick, final int leftAxis, - GenericHID rightStick, final int rightAxis) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), true); + if (moveValue > 0.0) { + if (rotateValue > 0.0) { + leftMotorSpeed = moveValue - rotateValue; + rightMotorSpeed = Math.max(moveValue, rotateValue); + } else { + leftMotorSpeed = Math.max(moveValue, -rotateValue); + rightMotorSpeed = moveValue + rotateValue; + } + } else { + if (rotateValue > 0.0) { + leftMotorSpeed = -Math.max(-moveValue, rotateValue); + rightMotorSpeed = moveValue + rotateValue; + } else { + leftMotorSpeed = moveValue - rotateValue; + rightMotorSpeed = -Math.max(-moveValue, -rotateValue); + } } - /** - * Provide tank steering using the stored robot configuration. - * This function lets you pick the axis to be used on each Joystick object for the left - * and right sides of the robot. - * @param leftStick The Joystick object to use for the left side of the robot. - * @param leftAxis The axis to select on the left side Joystick object. - * @param rightStick The Joystick object to use for the right side of the robot. - * @param rightAxis The axis to select on the right side Joystick object. - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void tankDrive(GenericHID leftStick, final int leftAxis, - GenericHID rightStick, final int rightAxis, boolean squaredInputs) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), squaredInputs); + setLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed); + } + + /** + * Arcade drive implements single stick driving. This function lets you directly provide joystick + * values from any source. + * + * @param moveValue The value to use for fowards/backwards + * @param rotateValue The value to use for the rotate right/left + */ + public void arcadeDrive(double moveValue, double rotateValue) { + this.arcadeDrive(moveValue, rotateValue, true); + } + + /** + * Drive method for Mecanum wheeled robots. + * + * A method for driving with Mecanum wheeled robots. There are 4 wheels on the robot, arranged so + * that the front and back wheels are toed in 45 degrees. When looking at the wheels from the top, + * the roller axles should form an X across the robot. + * + * This is designed to be directly driven by joystick axes. + * + * @param x The speed that the robot should drive in the X direction. [-1.0..1.0] + * @param y The speed that the robot should drive in the Y direction. This input is + * inverted to match the forward == -1.0 that joysticks produce. [-1.0..1.0] + * @param rotation The rate of rotation for the robot that is completely independent of the + * translation. [-1.0..1.0] + * @param gyroAngle The current angle reading from the gyro. Use this to implement field-oriented + * controls. + */ + public void mecanumDrive_Cartesian(double x, double y, double rotation, double gyroAngle) { + if (!kMecanumCartesian_Reported) { + kMecanumCartesian_Reported = true; + } + double xIn = x; + double yIn = y; + // Negate y for the joystick. + yIn = -yIn; + // Compenstate for gyro angle. + double rotated[] = rotateVector(xIn, yIn, gyroAngle); + xIn = rotated[0]; + yIn = rotated[1]; + + double wheelSpeeds[] = new double[kMaxNumberOfMotors]; + wheelSpeeds[MotorType.kFrontLeft_val] = xIn + yIn + rotation; + wheelSpeeds[MotorType.kFrontRight_val] = -xIn + yIn - rotation; + wheelSpeeds[MotorType.kRearLeft_val] = -xIn + yIn + rotation; + wheelSpeeds[MotorType.kRearRight_val] = xIn + yIn - rotation; + + normalize(wheelSpeeds); + + byte syncGroup = (byte) 0x80; + + m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_invertedMotors[MotorType + .kFrontLeft_val] * m_maxOutput, syncGroup); + m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_invertedMotors[MotorType + .kFrontRight_val] * m_maxOutput, syncGroup); + m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_invertedMotors[MotorType + .kRearLeft_val] * m_maxOutput, syncGroup); + m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_invertedMotors[MotorType + .kRearRight_val] * m_maxOutput, syncGroup); + + if (m_safetyHelper != null) m_safetyHelper.feed(); + } + + /** + * Drive method for Mecanum wheeled robots. + * + * A method for driving with Mecanum wheeled robots. There are 4 wheels on the robot, arranged so + * that the front and back wheels are toed in 45 degrees. When looking at the wheels from the top, + * the roller axles should form an X across the robot. + * + * @param magnitude The speed that the robot should drive in a given direction. + * @param direction The direction the robot should drive in degrees. The direction and maginitute + * are independent of the rotation rate. + * @param rotation The rate of rotation for the robot that is completely independent of the + * magnitute or direction. [-1.0..1.0] + */ + public void mecanumDrive_Polar(double magnitude, double direction, double rotation) { + if (!kMecanumPolar_Reported) { + kMecanumPolar_Reported = true; + } + double frontLeftSpeed, rearLeftSpeed, frontRightSpeed, rearRightSpeed; + // Normalized for full power along the Cartesian axes. + magnitude = limit(magnitude) * Math.sqrt(2.0); + // The rollers are at 45 degree angles. + double dirInRad = (direction + 45.0) * 3.14159 / 180.0; + double cosD = Math.cos(dirInRad); + double sinD = Math.sin(dirInRad); + + double wheelSpeeds[] = new double[kMaxNumberOfMotors]; + wheelSpeeds[MotorType.kFrontLeft_val] = (sinD * magnitude + rotation); + wheelSpeeds[MotorType.kFrontRight_val] = (cosD * magnitude - rotation); + wheelSpeeds[MotorType.kRearLeft_val] = (cosD * magnitude + rotation); + wheelSpeeds[MotorType.kRearRight_val] = (sinD * magnitude - rotation); + + normalize(wheelSpeeds); + + byte syncGroup = (byte) 0x80; + + m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_invertedMotors[MotorType + .kFrontLeft_val] * m_maxOutput, syncGroup); + m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_invertedMotors[MotorType + .kFrontRight_val] * m_maxOutput, syncGroup); + m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_invertedMotors[MotorType + .kRearLeft_val] * m_maxOutput, syncGroup); + m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_invertedMotors[MotorType + .kRearRight_val] * m_maxOutput, syncGroup); + + if (m_safetyHelper != null) m_safetyHelper.feed(); + } + + /** + * Holonomic Drive method for Mecanum wheeled robots. + * + * This is an alias to mecanumDrive_Polar() for backward compatability + * + * @param magnitude The speed that the robot should drive in a given direction. [-1.0..1.0] + * @param direction The direction the robot should drive. The direction and maginitute are + * independent of the rotation rate. + * @param rotation The rate of rotation for the robot that is completely independent of the + * magnitute or direction. [-1.0..1.0] + */ + void holonomicDrive(float magnitude, float direction, float rotation) { + mecanumDrive_Polar(magnitude, direction, rotation); + } + + /** + * Set the speed of the right and left motors. This is used once an appropriate drive setup + * function is called such as twoWheelDrive(). The motors are set to "leftSpeed" and "rightSpeed" + * and includes flipping the direction of one side for opposing motors. + * + * @param leftOutput The speed to send to the left side of the robot. + * @param rightOutput The speed to send to the right side of the robot. + */ + public void setLeftRightMotorOutputs(double leftOutput, double rightOutput) { + if (m_rearLeftMotor == null || m_rearRightMotor == null) { + throw new NullPointerException("Null motor provided"); } - /** - * Provide tank steering using the stored robot configuration. - * This function lets you directly provide joystick values from any source. - * @param leftValue The value of the left stick. - * @param rightValue The value of the right stick. - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void tankDrive(double leftValue, double rightValue, boolean squaredInputs) { + byte syncGroup = (byte) 0x80; - if(!kTank_Reported) { - kTank_Reported = true; - } - - // square the inputs (while preserving the sign) to increase fine control while permitting full power - leftValue = limit(leftValue); - rightValue = limit(rightValue); - if(squaredInputs) { - if (leftValue >= 0.0) { - leftValue = (leftValue * leftValue); - } else { - leftValue = -(leftValue * leftValue); - } - if (rightValue >= 0.0) { - rightValue = (rightValue * rightValue); - } else { - rightValue = -(rightValue * rightValue); - } - } - setLeftRightMotorOutputs(leftValue, rightValue); + if (m_frontLeftMotor != null) { + m_frontLeftMotor.set(limit(leftOutput) * m_invertedMotors[MotorType.kFrontLeft_val] * + m_maxOutput, syncGroup); } + m_rearLeftMotor.set(limit(leftOutput) * m_invertedMotors[MotorType.kRearLeft_val] * + m_maxOutput, syncGroup); - /** - * Provide tank steering using the stored robot configuration. - * This function lets you directly provide joystick values from any source. - * @param leftValue The value of the left stick. - * @param rightValue The value of the right stick. - */ - public void tankDrive(double leftValue, double rightValue) { - tankDrive(leftValue, rightValue, true); + if (m_frontRightMotor != null) { + m_frontRightMotor.set(-limit(rightOutput) * m_invertedMotors[MotorType.kFrontRight_val] * + m_maxOutput, syncGroup); } + m_rearRightMotor.set(-limit(rightOutput) * m_invertedMotors[MotorType.kRearRight_val] * + m_maxOutput, syncGroup); - /** - * Arcade drive implements single stick driving. - * Given a single Joystick, the class assumes the Y axis for the move value and the X axis - * for the rotate value. - * (Should add more information here regarding the way that arcade drive works.) - * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected - * for forwards/backwards and the X-axis will be selected for rotation rate. - * @param squaredInputs If true, the sensitivity will be decreased for small values - */ - public void arcadeDrive(GenericHID stick, boolean squaredInputs) { - // simply call the full-featured arcadeDrive with the appropriate values - arcadeDrive(stick.getY(), stick.getX(), squaredInputs); + if (m_safetyHelper != null) m_safetyHelper.feed(); + } + + /** + * Limit motor values to the -1.0 to +1.0 range. + */ + protected static double limit(double num) { + if (num > 1.0) { + return 1.0; } - - /** - * Arcade drive implements single stick driving. - * Given a single Joystick, the class assumes the Y axis for the move value and the X axis - * for the rotate value. - * (Should add more information here regarding the way that arcade drive works.) - * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected - * for forwards/backwards and the X-axis will be selected for rotation rate. - */ - public void arcadeDrive(GenericHID stick) { - this.arcadeDrive(stick, true); + if (num < -1.0) { + return -1.0; } + return num; + } - /** - * Arcade drive implements single stick driving. - * Given two joystick instances and two axis, compute the values to send to either two - * or four motors. - * @param moveStick The Joystick object that represents the forward/backward direction - * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically Y_AXIS) - * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void arcadeDrive(GenericHID moveStick, final int moveAxis, - GenericHID rotateStick, final int rotateAxis, - boolean squaredInputs) { - double moveValue = moveStick.getRawAxis(moveAxis); - double rotateValue = rotateStick.getRawAxis(rotateAxis); - - arcadeDrive(moveValue, rotateValue, squaredInputs); + /** + * Normalize all wheel speeds if the magnitude of any wheel is greater than 1.0. + */ + protected static void normalize(double wheelSpeeds[]) { + double maxMagnitude = Math.abs(wheelSpeeds[0]); + int i; + for (i = 1; i < kMaxNumberOfMotors; i++) { + double temp = Math.abs(wheelSpeeds[i]); + if (maxMagnitude < temp) maxMagnitude = temp; } - - /** - * Arcade drive implements single stick driving. - * Given two joystick instances and two axis, compute the values to send to either two - * or four motors. - * @param moveStick The Joystick object that represents the forward/backward direction - * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically Y_AXIS) - * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) - */ - public void arcadeDrive(GenericHID moveStick, final int moveAxis, - GenericHID rotateStick, final int rotateAxis) { - this.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true); + if (maxMagnitude > 1.0) { + for (i = 0; i < kMaxNumberOfMotors; i++) { + wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude; + } } + } - /** - * Arcade drive implements single stick driving. - * This function lets you directly provide joystick values from any source. - * @param moveValue The value to use for forwards/backwards - * @param rotateValue The value to use for the rotate right/left - * @param squaredInputs If set, decreases the sensitivity at low speeds - */ - public void arcadeDrive(double moveValue, double rotateValue, boolean squaredInputs) { - // local variables to hold the computed PWM values for the motors - if(!kArcadeStandard_Reported) { - kArcadeStandard_Reported = true; - } + /** + * Rotate a vector in Cartesian space. + */ + protected static double[] rotateVector(double x, double y, double angle) { + double cosA = Math.cos(angle * (3.14159 / 180.0)); + double sinA = Math.sin(angle * (3.14159 / 180.0)); + double out[] = new double[2]; + out[0] = x * cosA - y * sinA; + out[1] = x * sinA + y * cosA; + return out; + } - double leftMotorSpeed; - double rightMotorSpeed; + /** + * Invert a motor direction. This is used when a motor should run in the opposite direction as the + * drive code would normally run it. Motors that are direct drive would be inverted, the drive + * code assumes that the motors are geared with one reversal. + * + * @param motor The motor index to invert. + * @param isInverted True if the motor should be inverted when operated. + */ + public void setInvertedMotor(MotorType motor, boolean isInverted) { + m_invertedMotors[motor.value] = isInverted ? -1 : 1; + } - moveValue = limit(moveValue); - rotateValue = limit(rotateValue); + /** + * Set the turning sensitivity. + * + * This only impacts the drive() entry-point. + * + * @param sensitivity Effectively sets the turning sensitivity (or turn radius for a given value) + */ + public void setSensitivity(double sensitivity) { + m_sensitivity = sensitivity; + } - if (squaredInputs) { - // square the inputs (while preserving the sign) to increase fine control while permitting full power - if (moveValue >= 0.0) { - moveValue = (moveValue * moveValue); - } else { - moveValue = -(moveValue * moveValue); - } - if (rotateValue >= 0.0) { - rotateValue = (rotateValue * rotateValue); - } else { - rotateValue = -(rotateValue * rotateValue); - } - } + /** + * Configure the scaling factor for using RobotDrive with motor controllers in a mode other than + * PercentVbus. + * + * @param maxOutput Multiplied with the output percentage computed by the drive functions. + */ + public void setMaxOutput(double maxOutput) { + m_maxOutput = maxOutput; + } - if (moveValue > 0.0) { - if (rotateValue > 0.0) { - leftMotorSpeed = moveValue - rotateValue; - rightMotorSpeed = Math.max(moveValue, rotateValue); - } else { - leftMotorSpeed = Math.max(moveValue, -rotateValue); - rightMotorSpeed = moveValue + rotateValue; - } - } else { - if (rotateValue > 0.0) { - leftMotorSpeed = -Math.max(-moveValue, rotateValue); - rightMotorSpeed = moveValue + rotateValue; - } else { - leftMotorSpeed = moveValue - rotateValue; - rightMotorSpeed = -Math.max(-moveValue, -rotateValue); - } - } - setLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed); + /** + * Free the speed controllers if they were allocated locally + */ + public void free() { + } + + public void setExpiration(double timeout) { + m_safetyHelper.setExpiration(timeout); + } + + public double getExpiration() { + return m_safetyHelper.getExpiration(); + } + + public boolean isAlive() { + return m_safetyHelper.isAlive(); + } + + public boolean isSafetyEnabled() { + return m_safetyHelper.isSafetyEnabled(); + } + + public void setSafetyEnabled(boolean enabled) { + m_safetyHelper.setSafetyEnabled(enabled); + } + + public String getDescription() { + return "Robot Drive"; + } + + public void stopMotor() { + if (m_frontLeftMotor != null) { + m_frontLeftMotor.set(0.0); } - - /** - * Arcade drive implements single stick driving. - * This function lets you directly provide joystick values from any source. - * @param moveValue The value to use for fowards/backwards - * @param rotateValue The value to use for the rotate right/left - */ - public void arcadeDrive(double moveValue, double rotateValue) { - this.arcadeDrive(moveValue, rotateValue, true); + if (m_frontRightMotor != null) { + m_frontRightMotor.set(0.0); } - - /** - * Drive method for Mecanum wheeled robots. - * - * A method for driving with Mecanum wheeled robots. There are 4 wheels - * on the robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X across the robot. - * - * This is designed to be directly driven by joystick axes. - * - * @param x The speed that the robot should drive in the X direction. [-1.0..1.0] - * @param y The speed that the robot should drive in the Y direction. - * This input is inverted to match the forward == -1.0 that joysticks produce. [-1.0..1.0] - * @param rotation The rate of rotation for the robot that is completely independent of - * the translation. [-1.0..1.0] - * @param gyroAngle The current angle reading from the gyro. Use this to implement field-oriented controls. - */ - public void mecanumDrive_Cartesian(double x, double y, double rotation, double gyroAngle) { - if(!kMecanumCartesian_Reported) { - kMecanumCartesian_Reported = true; - } - double xIn = x; - double yIn = y; - // Negate y for the joystick. - yIn = -yIn; - // Compenstate for gyro angle. - double rotated[] = rotateVector(xIn, yIn, gyroAngle); - xIn = rotated[0]; - yIn = rotated[1]; - - double wheelSpeeds[] = new double[kMaxNumberOfMotors]; - wheelSpeeds[MotorType.kFrontLeft_val] = xIn + yIn + rotation; - wheelSpeeds[MotorType.kFrontRight_val] = -xIn + yIn - rotation; - wheelSpeeds[MotorType.kRearLeft_val] = -xIn + yIn + rotation; - wheelSpeeds[MotorType.kRearRight_val] = xIn + yIn - rotation; - - normalize(wheelSpeeds); - - byte syncGroup = (byte)0x80; - - m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_invertedMotors[MotorType.kFrontLeft_val] * m_maxOutput, syncGroup); - m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_invertedMotors[MotorType.kFrontRight_val] * m_maxOutput, syncGroup); - m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_invertedMotors[MotorType.kRearLeft_val] * m_maxOutput, syncGroup); - m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_invertedMotors[MotorType.kRearRight_val] * m_maxOutput, syncGroup); - - if (m_safetyHelper != null) m_safetyHelper.feed(); + if (m_rearLeftMotor != null) { + m_rearLeftMotor.set(0.0); } - - /** - * Drive method for Mecanum wheeled robots. - * - * A method for driving with Mecanum wheeled robots. There are 4 wheels - * on the robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X across the robot. - * - * @param magnitude The speed that the robot should drive in a given direction. - * @param direction The direction the robot should drive in degrees. The direction and maginitute are - * independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely independent of - * the magnitute or direction. [-1.0..1.0] - */ - public void mecanumDrive_Polar(double magnitude, double direction, double rotation) { - if(!kMecanumPolar_Reported) { - kMecanumPolar_Reported = true; - } - double frontLeftSpeed, rearLeftSpeed, frontRightSpeed, rearRightSpeed; - // Normalized for full power along the Cartesian axes. - magnitude = limit(magnitude) * Math.sqrt(2.0); - // The rollers are at 45 degree angles. - double dirInRad = (direction + 45.0) * 3.14159 / 180.0; - double cosD = Math.cos(dirInRad); - double sinD = Math.sin(dirInRad); - - double wheelSpeeds[] = new double[kMaxNumberOfMotors]; - wheelSpeeds[MotorType.kFrontLeft_val] = (sinD * magnitude + rotation); - wheelSpeeds[MotorType.kFrontRight_val] = (cosD * magnitude - rotation); - wheelSpeeds[MotorType.kRearLeft_val] = (cosD * magnitude + rotation); - wheelSpeeds[MotorType.kRearRight_val] = (sinD * magnitude - rotation); - - normalize(wheelSpeeds); - - byte syncGroup = (byte)0x80; - - m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_invertedMotors[MotorType.kFrontLeft_val] * m_maxOutput, syncGroup); - m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_invertedMotors[MotorType.kFrontRight_val] * m_maxOutput, syncGroup); - m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_invertedMotors[MotorType.kRearLeft_val] * m_maxOutput, syncGroup); - m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_invertedMotors[MotorType.kRearRight_val] * m_maxOutput, syncGroup); - - if (m_safetyHelper != null) m_safetyHelper.feed(); + if (m_rearRightMotor != null) { + m_rearRightMotor.set(0.0); } + } - /** - * Holonomic Drive method for Mecanum wheeled robots. - * - * This is an alias to mecanumDrive_Polar() for backward compatability - * - * @param magnitude The speed that the robot should drive in a given direction. [-1.0..1.0] - * @param direction The direction the robot should drive. The direction and maginitute are - * independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely independent of - * the magnitute or direction. [-1.0..1.0] - */ - void holonomicDrive(float magnitude, float direction, float rotation) { - mecanumDrive_Polar(magnitude, direction, rotation); - } + private void setupMotorSafety() { + m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper.setExpiration(kDefaultExpirationTime); + m_safetyHelper.setSafetyEnabled(true); + } - /** Set the speed of the right and left motors. - * This is used once an appropriate drive setup function is called such as - * twoWheelDrive(). The motors are set to "leftSpeed" and "rightSpeed" - * and includes flipping the direction of one side for opposing motors. - * @param leftOutput The speed to send to the left side of the robot. - * @param rightOutput The speed to send to the right side of the robot. - */ - public void setLeftRightMotorOutputs(double leftOutput, double rightOutput) { - if (m_rearLeftMotor == null || m_rearRightMotor == null) { - throw new NullPointerException("Null motor provided"); - } - - byte syncGroup = (byte)0x80; - - if (m_frontLeftMotor != null) { - m_frontLeftMotor.set(limit(leftOutput) * m_invertedMotors[MotorType.kFrontLeft_val] * m_maxOutput, syncGroup); - } - m_rearLeftMotor.set(limit(leftOutput) * m_invertedMotors[MotorType.kRearLeft_val] * m_maxOutput, syncGroup); - - if (m_frontRightMotor != null) { - m_frontRightMotor.set(-limit(rightOutput) * m_invertedMotors[MotorType.kFrontRight_val] * m_maxOutput, syncGroup); - } - m_rearRightMotor.set(-limit(rightOutput) * m_invertedMotors[MotorType.kRearRight_val] * m_maxOutput, syncGroup); - - if (m_safetyHelper != null) m_safetyHelper.feed(); - } - - /** - * Limit motor values to the -1.0 to +1.0 range. - */ - protected static double limit(double num) { - if (num > 1.0) { - return 1.0; - } - if (num < -1.0) { - return -1.0; - } - return num; - } - - /** - * Normalize all wheel speeds if the magnitude of any wheel is greater than 1.0. - */ - protected static void normalize(double wheelSpeeds[]) { - double maxMagnitude = Math.abs(wheelSpeeds[0]); - int i; - for (i=1; i 1.0) { - for (i=0; i + * + * By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value
By default {@value + * #kDefaultMinServoPWM} ms is used as the minPWM value
+ * + * @param channel The PWM channel to which the servo is attached. 0-9 are on-board, 10-19 are on + * the MXP port + */ + public Servo(final int channel) { + this.channel = channel; + initServo(); + } + + private double getServoAngleRange() { + return kMaxServoAngle - kMinServoAngle; + } + + /** + * Set the servo position. + * + * Servo values range from -1.0 to 1.0 corresponding to the range of full left to full right. + * + * @param value Position from -1.0 to 1.0. + */ + public void set(double value) { + impl.set(value); + } + + /** + * Get the servo position. + * + * Servo values range from -1.0 to 1.0 corresponding to the range of full left to full right. + * + * @return Position from -1.0 to 1.0. + */ + public double get() { + return impl.get(); + } + + /** + * Disable the speed controller + */ + public void disable() { + impl.set(0); + } + + /** + * Set the servo angle. + * + * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to + * test). + * + * Servo angles that are out of the supported range of the servo simply "saturate" in that + * direction In other words, if the servo has a range of (X degrees to Y degrees) than angles of + * less than X result in an angle of X being set and angles of more than Y degrees result in an + * angle of Y being set. + * + * @param degrees The angle in degrees to set the servo. + */ + public void setAngle(double degrees) { + if (degrees < kMinServoAngle) { + degrees = kMinServoAngle; + } else if (degrees > kMaxServoAngle) { + degrees = kMaxServoAngle; } - /** - * Set the PWM value. - * - * @deprecated - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - impl.set(speed, syncGroup); + set((degrees - kMinServoAngle) / getServoAngleRange()); + } + + /** + * Get the servo angle. + * + * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to + * test). + * + * @return The angle in degrees to which the servo is set. + */ + public double getAngle() { + return impl.get() * getServoAngleRange() + kMinServoAngle; + } + + /** + * {@inheritDoc} + */ + @Override + public ITable getTable() { + return m_table; + } + + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Servo"; + } + + private ITable m_table; + private ITableListener m_table_listener; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); } + } - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - impl.pidWrite(output); - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Double) value).doubleValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * Constructor.
- * - * By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value
- * By default {@value #kDefaultMinServoPWM} ms is used as the minPWM value
- * - * @param channel The PWM channel to which the servo is attached. 0-9 are on-board, 10-19 are on the MXP port - */ - public Servo(final int channel) { - this.channel = channel; - initServo(); - } - - private double getServoAngleRange() { - return kMaxServoAngle - kMinServoAngle; - } - - /** - * Set the servo position. - * - * Servo values range from -1.0 to 1.0 corresponding to the range of full left to full right. - * - * @param value Position from -1.0 to 1.0. - */ - public void set(double value) { - impl.set(value); - } - - /** - * Get the servo position. - * - * Servo values range from -1.0 to 1.0 corresponding to the range of full left to full right. - * - * @return Position from -1.0 to 1.0. - */ - public double get() { - return impl.get(); - } - - /** - * Disable the speed controller - */ - public void disable() { - impl.set(0); - } - - /** - * Set the servo angle. - * - * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to test). - * - * Servo angles that are out of the supported range of the servo simply "saturate" in that direction - * In other words, if the servo has a range of (X degrees to Y degrees) than angles of less than X - * result in an angle of X being set and angles of more than Y degrees result in an angle of Y being set. - * - * @param degrees The angle in degrees to set the servo. - */ - public void setAngle(double degrees) { - if (degrees < kMinServoAngle) { - degrees = kMinServoAngle; - } else if (degrees > kMaxServoAngle) { - degrees = kMaxServoAngle; - } - - set((degrees - kMinServoAngle) / getServoAngleRange()); - } - - /** - * Get the servo angle. - * - * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to test). - * @return The angle in degrees to which the servo is set. - */ - public double getAngle() { - return impl.get() * getServoAngleRange() + kMinServoAngle; - } - - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } - - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Servo"; - } - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } - - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Double) value).doubleValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } - - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Solenoid.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Solenoid.java index cc8e7974f9..fe4314fed2 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Solenoid.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Solenoid.java @@ -16,126 +16,128 @@ import edu.wpi.first.wpilibj.tables.ITableListener; /** * Solenoid class for running high voltage Digital Output. * - * The Solenoid class is typically used for pneumatics solenoids, but could be used - * for any device within the current spec of the PCM. + * The Solenoid class is typically used for pneumatics solenoids, but could be used for any device + * within the current spec of the PCM. */ public class Solenoid implements LiveWindowSendable { - private int m_moduleNumber, m_channel; ///< The channel on the module to control. - private boolean m_value; - private SimSpeedController m_impl; + private int m_moduleNumber, m_channel; ///< The channel on the module to control. + private boolean m_value; + private SimSpeedController m_impl; - /** - * Common function to implement constructor behavior. - */ - private synchronized void initSolenoid(int slot, int channel) { - m_moduleNumber = slot; - m_channel = channel; - m_impl = new SimSpeedController("simulator/pneumatic/"+slot+"/"+channel); - - LiveWindow.addActuator("Solenoid", m_moduleNumber, m_channel, this); + /** + * Common function to implement constructor behavior. + */ + private synchronized void initSolenoid(int slot, int channel) { + m_moduleNumber = slot; + m_channel = channel; + m_impl = new SimSpeedController("simulator/pneumatic/" + slot + "/" + channel); + + LiveWindow.addActuator("Solenoid", m_moduleNumber, m_channel, this); + } + + /** + * Constructor. + * + * @param channel The channel on the module to control. + */ + public Solenoid(final int channel) { + initSolenoid(1, channel); + } + + /** + * Constructor. + * + * @param moduleNumber The module number of the solenoid module to use. + * @param channel The channel on the module to control. + */ + public Solenoid(final int moduleNumber, final int channel) { + initSolenoid(moduleNumber, channel); + } + + /** + * Destructor. + */ + public synchronized void free() { + } + + /** + * Set the value of a solenoid. + * + * @param on Turn the solenoid output off or on. + */ + public void set(boolean on) { + m_value = on; + if (on) { + m_impl.set(1); + } else { + m_impl.set(-1); } + } - /** - * Constructor. - * - * @param channel The channel on the module to control. - */ - public Solenoid(final int channel) { - initSolenoid(1, channel); - } - - /** - * Constructor. - * - * @param moduleNumber The module number of the solenoid module to use. - * @param channel The channel on the module to control. - */ - public Solenoid(final int moduleNumber, final int channel) { - initSolenoid(moduleNumber, channel); - } - - /** - * Destructor. - */ - public synchronized void free() {} - - /** - * Set the value of a solenoid. - * - * @param on Turn the solenoid output off or on. - */ - public void set(boolean on) { - m_value = on; - if (on) { - m_impl.set(1); - } else { - m_impl.set(-1); - } - } - - /** - * Read the current value of the solenoid. - * - * @return The current value of the solenoid. - */ - public boolean get() { - return m_value; - } - - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Solenoid"; - } - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putBoolean("Value", get()); - } + /** + * Read the current value of the solenoid. + * + * @return The current value of the solenoid. + */ + public boolean get() { + return m_value; + } + + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Solenoid"; + } + + private ITable m_table; + private ITableListener m_table_listener; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putBoolean("Value", get()); } + } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - set(false); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Boolean) value).booleanValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + set(false); // Stop for safety + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Boolean) value).booleanValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - set(false); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + set(false); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/SpeedController.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/SpeedController.java index 60cef1beab..17402abe1a 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/SpeedController.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/SpeedController.java @@ -12,30 +12,31 @@ package edu.wpi.first.wpilibj; */ public interface SpeedController extends PIDOutput { - /** - * Common interface for getting the current set speed of a speed controller. - * - * @return The current set speed. Value is between -1.0 and 1.0. - */ - double get(); + /** + * Common interface for getting the current set speed of a speed controller. + * + * @return The current set speed. Value is between -1.0 and 1.0. + */ + double get(); - /** - * Common interface for setting the speed of a speed controller. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - void set(double speed, byte syncGroup); + /** + * Common interface for setting the speed of a speed controller. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, + * update immediately. + */ + void set(double speed, byte syncGroup); - /** - * Common interface for setting the speed of a speed controller. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - */ - void set(double speed); + /** + * Common interface for setting the speed of a speed controller. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + */ + void set(double speed); - /** - * Disable the speed controller - */ - void disable(); + /** + * Disable the speed controller + */ + void disable(); } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Talon.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Talon.java index 75bffdb9aa..2b21aa2fdd 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Talon.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Talon.java @@ -7,203 +7,184 @@ package edu.wpi.first.wpilibj; +import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.simulation.SimSpeedController; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * CTRE Talon Speed Controller + * CTRE Talon Speed Controller. */ public class Talon implements SpeedController, PIDOutput, MotorSafety, LiveWindowSendable { - private int channel; - private SimSpeedController impl; + private int m_channel; + private SimSpeedController m_impl; - /** - * Common initialization code called by all constructors. - * - * Note that the Talon uses the following bounds for PWM values. These values should work reasonably well for - * most controllers, but if users experience issues such as asymmetric behavior around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the Talon User Manual available from CTRE. - * - * - 2.037ms = full "forward" - * - 1.539ms = the "high end" of the deadband range - * - 1.513ms = center of the deadband range (off) - * - 1.487ms = the "low end" of the deadband range - * - .989ms = full "reverse" - */ - private void initTalon(final int channel) { - this.channel = channel; - impl = new SimSpeedController("simulator/pwm/"+channel); + /** + * Common initialization code called by all constructors. + * + *

Note that the Talon uses the following bounds for PWM values. These values should work + * reasonably well for most controllers, but if users experience issues such as asymmetric + * behavior around the deadband or inability to saturate the controller in either direction, + * calibration is recommended. The calibration procedure can be found in the Talon User Manual + * available from CTRE. + * + *

- 2.037ms = full "forward" - 1.539ms = the "high end" of the deadband range - 1.513ms = + * center of the deadband range (off) - 1.487ms = the "low end" of the deadband range - .989ms = + * full "reverse" + */ + private void initTalon(final int channel) { + this.m_channel = channel; + m_impl = new SimSpeedController("simulator/pwm/" + channel); - m_safetyHelper = new MotorSafetyHelper(this); - m_safetyHelper.setExpiration(0.0); - m_safetyHelper.setSafetyEnabled(false); + m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper.setExpiration(0.0); + m_safetyHelper.setSafetyEnabled(false); - LiveWindow.addActuator("Talon", channel, this); + LiveWindow.addActuator("Talon", channel, this); + } + + /** + * Constructor. + * + * @param channel The PWM channel that the Talon is attached to. + */ + public Talon(final int channel) { + initTalon(channel); + } + + /** + * Set the PWM value. + * + *

The PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, + * update immediately. + * @deprecated For compatibility with CANJaguar + */ + public void set(double speed, byte syncGroup) { + m_impl.set(speed, syncGroup); + } + + /** + * Set the PWM value. + * + *

The PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + public void set(double speed) { + m_impl.set(speed); + } + + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + public double get() { + return m_impl.get(); + } + + /** + * Disable the speed controller. + */ + public void disable() { + m_impl.set(0); + } + + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + public void pidWrite(double output) { + m_impl.pidWrite(output); + } + + //// MotorSafety Methods + private MotorSafetyHelper m_safetyHelper; + + @Override + public void setExpiration(double timeout) { + m_safetyHelper.setExpiration(timeout); + } + + @Override + public double getExpiration() { + return m_safetyHelper.getExpiration(); + } + + @Override + public boolean isAlive() { + return m_safetyHelper.isAlive(); + } + + @Override + public void stopMotor() { + disable(); + } + + @Override + public void setSafetyEnabled(boolean enabled) { + m_safetyHelper.setSafetyEnabled(enabled); + } + + @Override + public boolean isSafetyEnabled() { + return m_safetyHelper.isSafetyEnabled(); + } + + @Override + public String getDescription() { + return "PWM " + m_channel + " on module 1"; + } + + //// LiveWindow Methods + private ITable m_table; + private ITableListener m_tableListener; + + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + @Override + public ITable getTable() { + return m_table; + } + + @Override + public String getSmartDashboardType() { + return "Speed Controller"; + } + + @Override + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); } + } - /** - * Constructor. - * - * @param channel The PWM channel that the Talon is attached to. - */ - public Talon(final int channel) { - initTalon(channel); - } + @Override + public void startLiveWindowMode() { + set(0.0); // Stop for safety + m_tableListener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Double) value).doubleValue()); + } + }; + m_table.addTableListener("Value", m_tableListener, true); + } - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - impl.set(speed, syncGroup); - } - - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - public void set(double speed) { - impl.set(speed); - } - - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - public double get() { - return impl.get(); - } - - /** - * Disable the speed controller - */ - public void disable() { - impl.set(0); - } - - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - impl.pidWrite(output); - } - - //// MotorSafety Methods - private MotorSafetyHelper m_safetyHelper; - - @Override - public void setExpiration(double timeout) { - m_safetyHelper.setExpiration(timeout); - } - - @Override - public double getExpiration() { - return m_safetyHelper.getExpiration(); - } - - @Override - public boolean isAlive() { - return m_safetyHelper.isAlive(); - } - - @Override - public void stopMotor() { - disable(); - } - - @Override - public void setSafetyEnabled(boolean enabled) { - m_safetyHelper.setSafetyEnabled(enabled); - } - - @Override - public boolean isSafetyEnabled() { - return m_safetyHelper.isSafetyEnabled(); - } - - @Override - public String getDescription() { - return "PWM "+channel+" on module 1"; - } - - //// LiveWindow Methods - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - @Override - public String getSmartDashboardType() { - return "Speed Controller"; - } - - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - set(0.0); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Double) value).doubleValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } - - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - set(0); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + @Override + public void stopLiveWindowMode() { + set(0); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_tableListener); + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Victor.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Victor.java index 84a8cfad8c..a1e794577d 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Victor.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/Victor.java @@ -7,206 +7,187 @@ package edu.wpi.first.wpilibj; +import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.simulation.SimSpeedController; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * VEX Robotics Victor Speed Controller + * VEX Robotics Victor Speed Controller. */ public class Victor implements SpeedController, PIDOutput, MotorSafety, LiveWindowSendable { - private int channel; - private SimSpeedController impl; + private int m_channel; + private SimSpeedController m_impl; - /** - * Common initialization code called by all constructors. - * - * Note that the Victor uses the following bounds for PWM values. These values were determined - * empirically and optimized for the Victor 888. These values should work reasonably well for - * Victor 884 controllers also but if users experience issues such as asymmetric behavior around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the Victor 884 User Manual available from VEX Robotics: - * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf - * - * - 2.027ms = full "forward" - * - 1.525ms = the "high end" of the deadband range - * - 1.507ms = center of the deadband range (off) - * - 1.49ms = the "low end" of the deadband range - * - 1.026ms = full "reverse" - */ - private void initVictor(final int channel) { - this.channel = channel; - impl = new SimSpeedController("simulator/pwm/"+channel); - - m_safetyHelper = new MotorSafetyHelper(this); - m_safetyHelper.setExpiration(0.0); - m_safetyHelper.setSafetyEnabled(false); - - LiveWindow.addActuator("Victor", channel, this); - // UsageReporting.report(tResourceType.kResourceType_Talon, getChannel(), getModuleNumber()-1); + /** + * Common initialization code called by all constructors. + * + *

Note that the Victor uses the following bounds for PWM values. These values were determined + * empirically and optimized for the Victor 888. These values should work reasonably well for + * Victor 884 controllers also but if users experience issues such as asymmetric behavior around + * the deadband or inability to saturate the controller in either direction, calibration is + * recommended. The calibration procedure can be found in the Victor 884 User Manual available + * from VEX Robotics: http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf + * + *

- 2.027ms = full "forward" - 1.525ms = the "high end" of the deadband range - 1.507ms = center + * of the deadband range (off) - 1.49ms = the "low end" of the deadband range - 1.026ms = full + * "reverse" + */ + private void initVictor(final int channel) { + this.m_channel = channel; + m_impl = new SimSpeedController("simulator/pwm/" + channel); + + m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper.setExpiration(0.0); + m_safetyHelper.setSafetyEnabled(false); + + LiveWindow.addActuator("Victor", channel, this); + // UsageReporting.report(tResourceType.kResourceType_Talon, getChannel(), getModuleNumber()-1); + } + + /** + * Constructor. + * + * @param channel The PWM channel that the Victor is attached to. + */ + public Victor(final int channel) { + initVictor(channel); + } + + /** + * Set the PWM value. + * + *

The PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, + * update immediately. + * @deprecated For compatibility with CANJaguar. + */ + public void set(double speed, byte syncGroup) { + m_impl.set(speed, syncGroup); + } + + /** + * Set the PWM value. + * + *

The PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + public void set(double speed) { + m_impl.set(speed); + } + + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + public double get() { + return m_impl.get(); + } + + /** + * Disable the speed controller. + */ + public void disable() { + m_impl.set(0); + } + + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + public void pidWrite(double output) { + m_impl.pidWrite(output); + } + + //// MotorSafety Methods + private MotorSafetyHelper m_safetyHelper; + + @Override + public void setExpiration(double timeout) { + m_safetyHelper.setExpiration(timeout); + } + + @Override + public double getExpiration() { + return m_safetyHelper.getExpiration(); + } + + @Override + public boolean isAlive() { + return m_safetyHelper.isAlive(); + } + + @Override + public void stopMotor() { + disable(); + } + + @Override + public void setSafetyEnabled(boolean enabled) { + m_safetyHelper.setSafetyEnabled(enabled); + } + + @Override + public boolean isSafetyEnabled() { + return m_safetyHelper.isSafetyEnabled(); + } + + @Override + public String getDescription() { + return "PWM " + m_channel + " on module 1"; + } + + //// LiveWindow Methods + private ITable m_table; + private ITableListener m_tableListener; + + + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + @Override + public ITable getTable() { + return m_table; + } + + @Override + public String getSmartDashboardType() { + return "Speed Controller"; + } + + @Override + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); } + } - /** - * Constructor. - * - * @param channel The PWM channel that the Victor is attached to. - */ - public Victor(final int channel) { - initVictor(channel); - } + @Override + public void startLiveWindowMode() { + set(0.0); // Stop for safety + m_tableListener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Double) value).doubleValue()); + } + }; + m_table.addTableListener("Value", m_tableListener, true); + } - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - impl.set(speed, syncGroup); - } - - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - public void set(double speed) { - impl.set(speed); - } - - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - public double get() { - return impl.get(); - } - - /** - * Disable the speed controller - */ - public void disable() { - impl.set(0); - } - - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - impl.pidWrite(output); - } - - //// MotorSafety Methods - private MotorSafetyHelper m_safetyHelper; - - @Override - public void setExpiration(double timeout) { - m_safetyHelper.setExpiration(timeout); - } - - @Override - public double getExpiration() { - return m_safetyHelper.getExpiration(); - } - - @Override - public boolean isAlive() { - return m_safetyHelper.isAlive(); - } - - @Override - public void stopMotor() { - disable(); - } - - @Override - public void setSafetyEnabled(boolean enabled) { - m_safetyHelper.setSafetyEnabled(enabled); - } - - @Override - public boolean isSafetyEnabled() { - return m_safetyHelper.isSafetyEnabled(); - } - - @Override - public String getDescription() { - return "PWM "+channel+" on module 1"; - } - - //// LiveWindow Methods - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - @Override - public String getSmartDashboardType() { - return "Speed Controller"; - } - - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - set(0.0); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Double) value).doubleValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } - - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - set(0); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + @Override + public void stopLiveWindowMode() { + set(0); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_tableListener); + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/command/Scheduler.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/command/Scheduler.java index 7754b19352..b1639302d3 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/command/Scheduler.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/command/Scheduler.java @@ -8,7 +8,9 @@ package edu.wpi.first.wpilibj.command; import java.util.Enumeration; +import java.util.HashSet; import java.util.Hashtable; +import java.util.Set; import java.util.Vector; import edu.wpi.first.wpilibj.NamedSendable; @@ -18,351 +20,344 @@ import edu.wpi.first.wpilibj.networktables2.type.StringArray; import edu.wpi.first.wpilibj.tables.ITable; /** - * The {@link Scheduler} is a singleton which holds the top-level running - * commands. It is in charge of both calling the command's - * {@link Command#run() run()} method and to make sure that there are no two - * commands with conflicting requirements running. + * The {@link Scheduler} is a singleton which holds the top-level running commands. It is in charge + * of both calling the command's {@link Command#run() run()} method and to make sure that there are + * no two commands with conflicting requirements running. * - *

It is fine if teams wish to take control of the {@link Scheduler} - * themselves, all that needs to be done is to call - * {@link Scheduler#getInstance() Scheduler.getInstance()}.{@link Scheduler#run() run()} - * often to have {@link Command Commands} function correctly. However, this is - * already done for you if you use the CommandBased Robot template.

+ *

It is fine if teams wish to take control of the {@link Scheduler} themselves, all that needs + * to be done is to call {@link Scheduler#getInstance() Scheduler.getInstance()}.{@link + * Scheduler#run() run()} often to have {@link Command Commands} function correctly. However, this + * is already done for you if you use the CommandBased Robot template.

* * @author Joe Grinstead * @see Command */ public class Scheduler implements NamedSendable { - /** - * The Singleton Instance - */ - private static Scheduler instance; + /** + * The Singleton Instance. + */ + private static Scheduler instance; - /** - * Returns the {@link Scheduler}, creating it if one does not exist. - * - * @return the {@link Scheduler} - */ - public synchronized static Scheduler getInstance() { - return instance == null ? instance = new Scheduler() : instance; + /** + * Returns the {@link Scheduler}, creating it if one does not exist. + * + * @return the {@link Scheduler} + */ + public static synchronized Scheduler getInstance() { + return instance == null ? instance = new Scheduler() : instance; + } + + /** + * A hashtable of active {@link Command Commands} to their {@link LinkedListElement}. + */ + private Hashtable m_commandTable = new Hashtable(); + /** + * The {@link Set} of all {@link Subsystem Subsystems}. + */ + private Set m_subsystems = new HashSet<>(); + /** + * The first {@link Command} in the list. + */ + private LinkedListElement m_firstCommand; + /** + * The last {@link Command} in the list. + */ + private LinkedListElement m_lastCommand; + /** + * Whether or not we are currently adding a command. + */ + private boolean m_adding = false; + /** + * Whether or not we are currently disabled. + */ + private boolean m_disabled = false; + /** + * A list of all {@link Command Commands} which need to be added. + */ + private Vector m_additions = new Vector(); + private ITable m_table; + /** + * A list of all {@link edu.wpi.first.wpilibj.buttons.Trigger.ButtonScheduler Buttons}. It is + * created lazily. + */ + private Vector m_buttons; + private boolean m_runningCommandsChanged; + + /** + * Instantiates a {@link Scheduler}. + */ + private Scheduler() { + } + + /** + * Adds the command to the {@link Scheduler}. This will not add the {@link Command} immediately, + * but will instead wait for the proper time in the {@link Scheduler#run()} loop before doing so. + * The command returns immediately and does nothing if given null. + * + *

Adding a {@link Command} to the {@link Scheduler} involves the {@link Scheduler} removing + * any {@link Command} which has shared requirements.

+ * + * @param command the command to add + */ + public void add(Command command) { + if (command != null) { + m_additions.addElement(command); } - /** - * A hashtable of active {@link Command Commands} to their - * {@link LinkedListElement} - */ - private Hashtable commandTable = new Hashtable(); - /** - * The {@link Set} of all {@link Subsystem Subsystems} - */ - private Set subsystems = new Set(); - /** - * The first {@link Command} in the list - */ - private LinkedListElement firstCommand; - /** - * The last {@link Command} in the list - */ - private LinkedListElement lastCommand; - /** - * Whether or not we are currently adding a command - */ - private boolean adding = false; - /** - * Whether or not we are currently disabled - */ - private boolean disabled = false; - /** - * A list of all {@link Command Commands} which need to be added - */ - private Vector additions = new Vector(); - private ITable m_table; - /** - * A list of all - * {@link edu.wpi.first.wpilibj.buttons.Trigger.ButtonScheduler Buttons}. It - * is created lazily. - */ - private Vector buttons; - private boolean m_runningCommandsChanged; + } - /** - * Instantiates a {@link Scheduler}. - */ - private Scheduler() { + /** + * Adds a button to the {@link Scheduler}. The {@link Scheduler} will poll the button during its + * {@link Scheduler#run()}. + * + * @param button the button to add + */ + public void addButton(ButtonScheduler button) { + if (m_buttons == null) { + m_buttons = new Vector(); + } + m_buttons.addElement(button); + } + + /** + * Adds a command immediately to the {@link Scheduler}. This should only be called in the {@link + * Scheduler#run()} loop. Any command with conflicting requirements will be removed, unless it is + * uninterruptable. Giving null does nothing. + * + * @param command the {@link Command} to add + */ + @SuppressWarnings("MethodName") + private void _add(Command command) { + if (command == null) { + return; } - /** - * Adds the command to the {@link Scheduler}. This will not add the - * {@link Command} immediately, but will instead wait for the proper time in - * the {@link Scheduler#run()} loop before doing so. The command returns - * immediately and does nothing if given null. - * - *

Adding a {@link Command} to the {@link Scheduler} involves the - * {@link Scheduler} removing any {@link Command} which has shared - * requirements.

- * - * @param command the command to add - */ - public void add(Command command) { - if (command != null) { - additions.addElement(command); - } + // Check to make sure no adding during adding + if (m_adding) { + System.err.println("WARNING: Can not start command from cancel method. Ignoring:" + command); + return; } - /** - * Adds a button to the {@link Scheduler}. The {@link Scheduler} will poll - * the button during its {@link Scheduler#run()}. - * - * @param button the button to add - */ - public void addButton(ButtonScheduler button) { - if (buttons == null) { - buttons = new Vector(); + // Only add if not already in + if (!m_commandTable.containsKey(command)) { + + // Check that the requirements can be had + Enumeration requirements = command.getRequirements(); + while (requirements.hasMoreElements()) { + Subsystem lock = (Subsystem) requirements.nextElement(); + if (lock.getCurrentCommand() != null && !lock.getCurrentCommand().isInterruptible()) { + return; } - buttons.addElement(button); + } + + // Give it the requirements + m_adding = true; + requirements = command.getRequirements(); + while (requirements.hasMoreElements()) { + Subsystem lock = (Subsystem) requirements.nextElement(); + if (lock.getCurrentCommand() != null) { + lock.getCurrentCommand().cancel(); + remove(lock.getCurrentCommand()); + } + lock.setCurrentCommand(command); + } + m_adding = false; + + // Add it to the list + LinkedListElement element = new LinkedListElement(); + element.setData(command); + if (m_firstCommand == null) { + m_firstCommand = m_lastCommand = element; + } else { + m_lastCommand.add(element); + m_lastCommand = element; + } + m_commandTable.put(command, element); + + m_runningCommandsChanged = true; + + command.startRunning(); + } + } + + /** + * Runs a single iteration of the loop. This method should be called often in order to have a + * functioning {@link Command} system. The loop has five stages: + * + *
  1. Poll the Buttons
  2. Execute/Remove the Commands
  3. Send values to + * SmartDashboard
  4. Add Commands
  5. Add Defaults
+ */ + public void run() { + + m_runningCommandsChanged = false; + + if (m_disabled) { + return; + } // Don't run when disabled + + // Get button input (going backwards preserves button priority) + if (m_buttons != null) { + for (int i = m_buttons.size() - 1; i >= 0; i--) { + ((ButtonScheduler) m_buttons.elementAt(i)).execute(); + } + } + // Loop through the commands + LinkedListElement linkedListElement = m_firstCommand; + while (linkedListElement != null) { + Command command = linkedListElement.getData(); + linkedListElement = linkedListElement.getNext(); + if (!command.run()) { + remove(command); + m_runningCommandsChanged = true; + } } - /** - * Adds a command immediately to the {@link Scheduler}. This should only be - * called in the {@link Scheduler#run()} loop. Any command with conflicting - * requirements will be removed, unless it is uninterruptable. Giving - * null does nothing. - * - * @param command the {@link Command} to add - */ - private void _add(Command command) { - if (command == null) { - return; - } + // Add the new things + for (int i = 0; i < m_additions.size(); i++) { + _add((Command) m_additions.elementAt(i)); + } + m_additions.removeAllElements(); - // Check to make sure no adding during adding - if (adding) { - System.err.println("WARNING: Can not start command from cancel method. Ignoring:" + command); - return; - } + // Add in the defaults + Enumeration locks = new Vector<>(m_subsystems).elements(); + while (locks.hasMoreElements()) { + Subsystem lock = (Subsystem) locks.nextElement(); + if (lock.getCurrentCommand() == null) { + _add(lock.getDefaultCommand()); + } + lock.confirmCommand(); + } - // Only add if not already in - if (!commandTable.containsKey(command)) { + updateTable(); + } - // Check that the requirements can be had - Enumeration requirements = command.getRequirements(); - while (requirements.hasMoreElements()) { - Subsystem lock = (Subsystem) requirements.nextElement(); - if (lock.getCurrentCommand() != null && !lock.getCurrentCommand().isInterruptible()) { - return; - } + /** + * Registers a {@link Subsystem} to this {@link Scheduler}, so that the {@link Scheduler} might + * know if a default {@link Command} needs to be run. All {@link Subsystem Subsystems} should call + * this. + * + * @param system the system + */ + void registerSubsystem(Subsystem system) { + if (system != null) { + m_subsystems.add(system); + } + } + + /** + * Removes the {@link Command} from the {@link Scheduler}. + * + * @param command the command to remove + */ + void remove(Command command) { + if (command == null || !m_commandTable.containsKey(command)) { + return; + } + LinkedListElement linkedListElement = (LinkedListElement) m_commandTable.get(command); + m_commandTable.remove(command); + + if (linkedListElement.equals(m_lastCommand)) { + m_lastCommand = linkedListElement.getPrevious(); + } + if (linkedListElement.equals(m_firstCommand)) { + m_firstCommand = linkedListElement.getNext(); + } + linkedListElement.remove(); + + Enumeration requirements = command.getRequirements(); + while (requirements.hasMoreElements()) { + ((Subsystem) requirements.nextElement()).setCurrentCommand(null); + } + + command.removed(); + } + + /** + * Removes all commands. + */ + public void removeAll() { + // TODO: Confirm that this works with "uninteruptible" commands + while (m_firstCommand != null) { + remove(m_firstCommand.getData()); + } + } + + /** + * Disable the command scheduler. + */ + public void disable() { + m_disabled = true; + } + + /** + * Enable the command scheduler. + */ + public void enable() { + m_disabled = false; + } + + @Override + public String getName() { + return "Scheduler"; + } + + public String getType() { + return "Scheduler"; + } + + private StringArray m_commands; + private NumberArray m_ids; + private NumberArray m_toCancel; + + @Override + public void initTable(ITable subtable) { + m_table = subtable; + m_commands = new StringArray(); + m_ids = new NumberArray(); + m_toCancel = new NumberArray(); + + m_table.putValue("Names", m_commands); + m_table.putValue("Ids", m_ids); + m_table.putValue("Cancel", m_toCancel); + } + + private void updateTable() { + if (m_table != null) { + // Get the commands to cancel + m_table.retrieveValue("Cancel", m_toCancel); + if (m_toCancel.size() > 0) { + for (LinkedListElement e = m_firstCommand; e != null; e = e.getNext()) { + for (int i = 0; i < m_toCancel.size(); i++) { + if (e.getData().hashCode() == m_toCancel.get(i)) { + e.getData().cancel(); } - - // Give it the requirements - adding = true; - requirements = command.getRequirements(); - while (requirements.hasMoreElements()) { - Subsystem lock = (Subsystem) requirements.nextElement(); - if (lock.getCurrentCommand() != null) { - lock.getCurrentCommand().cancel(); - remove(lock.getCurrentCommand()); - } - lock.setCurrentCommand(command); - } - adding = false; - - // Add it to the list - LinkedListElement element = new LinkedListElement(); - element.setData(command); - if (firstCommand == null) { - firstCommand = lastCommand = element; - } else { - lastCommand.add(element); - lastCommand = element; - } - commandTable.put(command, element); - - m_runningCommandsChanged = true; - - command.startRunning(); + } } - } + m_toCancel.setSize(0); + m_table.putValue("Cancel", m_toCancel); + } - /** - * Runs a single iteration of the loop. This method should be called often - * in order to have a functioning {@link Command} system. The loop has five - * stages: - * - *
  1. Poll the Buttons
  2. Execute/Remove the Commands
  3. - *
  4. Send values to SmartDashboard
  5. Add Commands
  6. Add - * Defaults
- */ - public void run() { - - m_runningCommandsChanged = false; - - if (disabled) { - return; - } // Don't run when disabled - - // Get button input (going backwards preserves button priority) - if (buttons != null) { - for (int i = buttons.size() - 1; i >= 0; i--) { - ((ButtonScheduler) buttons.elementAt(i)).execute(); - } + if (m_runningCommandsChanged) { + m_commands.setSize(0); + m_ids.setSize(0); + // Set the the running commands + for (LinkedListElement e = m_firstCommand; e != null; e = e.getNext()) { + m_commands.add(e.getData().getName()); + m_ids.add(e.getData().hashCode()); } - // Loop through the commands - LinkedListElement e = firstCommand; - while (e != null) { - Command c = e.getData(); - e = e.getNext(); - if (!c.run()) { - remove(c); - m_runningCommandsChanged = true; - } - } - - // Add the new things - for (int i = 0; i < additions.size(); i++) { - _add((Command) additions.elementAt(i)); - } - additions.removeAllElements(); - - // Add in the defaults - Enumeration locks = subsystems.getElements(); - while (locks.hasMoreElements()) { - Subsystem lock = (Subsystem) locks.nextElement(); - if (lock.getCurrentCommand() == null) { - _add(lock.getDefaultCommand()); - } - lock.confirmCommand(); - } - - updateTable(); + m_table.putValue("Names", m_commands); + m_table.putValue("Ids", m_ids); + } } + } - /** - * Registers a {@link Subsystem} to this {@link Scheduler}, so that the - * {@link Scheduler} might know if a default {@link Command} needs to be - * run. All {@link Subsystem Subsystems} should call this. - * - * @param system the system - */ - void registerSubsystem(Subsystem system) { - if (system != null) { - subsystems.add(system); - } - } + @Override + public ITable getTable() { + return m_table; + } - /** - * Removes the {@link Command} from the {@link Scheduler}. - * - * @param command the command to remove - */ - void remove(Command command) { - if (command == null || !commandTable.containsKey(command)) { - return; - } - LinkedListElement e = (LinkedListElement) commandTable.get(command); - commandTable.remove(command); - - if (e.equals(lastCommand)) { - lastCommand = e.getPrevious(); - } - if (e.equals(firstCommand)) { - firstCommand = e.getNext(); - } - e.remove(); - - Enumeration requirements = command.getRequirements(); - while (requirements.hasMoreElements()) { - ((Subsystem) requirements.nextElement()).setCurrentCommand(null); - } - - command.removed(); - } - - /** - * Removes all commands - */ - public void removeAll() { - // TODO: Confirm that this works with "uninteruptible" commands - while (firstCommand != null) { - remove(firstCommand.getData()); - } - } - - /** - * Disable the command scheduler. - */ - public void disable() { - disabled = true; - } - - /** - * Enable the command scheduler. - */ - public void enable() { - disabled = false; - } - - public String getName() { - return "Scheduler"; - } - - public String getType() { - return "Scheduler"; - } - private StringArray commands; - private NumberArray ids, toCancel; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - commands = new StringArray(); - ids = new NumberArray(); - toCancel = new NumberArray(); - - m_table.putValue("Names", commands); - m_table.putValue("Ids", ids); - m_table.putValue("Cancel", toCancel); - } - - private void updateTable() { - if (m_table != null) { - // Get the commands to cancel - m_table.retrieveValue("Cancel", toCancel); - if (toCancel.size() > 0) { - for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { - for (int i = 0; i < toCancel.size(); i++) { - if (e.getData().hashCode() == toCancel.get(i)) { - e.getData().cancel(); - } - } - } - toCancel.setSize(0); - m_table.putValue("Cancel", toCancel); - } - - if (m_runningCommandsChanged) { - commands.setSize(0); - ids.setSize(0); - // Set the the running commands - for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { - commands.add(e.getData().getName()); - ids.add(e.getData().hashCode()); - } - m_table.putValue("Names", commands); - m_table.putValue("Ids", ids); - } - } - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - public String getSmartDashboardType() { - return "Scheduler"; - } + @Override + public String getSmartDashboardType() { + return "Scheduler"; + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/internal/SimTimer.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/internal/SimTimer.java index a3d9352453..4850ec1ff1 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/internal/SimTimer.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/internal/SimTimer.java @@ -15,157 +15,156 @@ import edu.wpi.first.wpilibj.simulation.MainNode; import gazebo.msgs.GzFloat64.Float64; /** - * Timer objects measure accumulated time in milliseconds. - * The timer object functions like a stopwatch. It can be started, stopped, and cleared. When the - * timer is running its value counts up in milliseconds. When stopped, the timer holds the current - * value. The implementation simply records the time when started and subtracts the current time - * whenever the value is requested. + * Timer objects measure accumulated time in milliseconds. The timer object functions like a + * stopwatch. It can be started, stopped, and cleared. When the timer is running its value counts up + * in milliseconds. When stopped, the timer holds the current value. The implementation simply + * records the time when started and subtracts the current time whenever the value is requested. */ public class SimTimer implements Timer.StaticInterface { - private double m_startTime; - private double m_accumulatedTime; - private boolean m_running; - private static double simTime; - private static Object time_notifier = new Object(); - static { - MainNode.subscribe("time", Msgs.Float64(), - new SubscriberCallback() { - @Override - public void callback(Float64 msg) { - simTime = msg.getData(); - synchronized(time_notifier) { time_notifier.notifyAll(); } // Ew, this is nested too deep... Refactor? - } - } - ); - } + private double m_startTime; + private double m_accumulatedTime; + private boolean m_running; + private static double simTime; + private static Object time_notifier = new Object(); - /** - * Pause the thread for a specified time. Pause the execution of the - * thread for a specified period of time given in seconds. Motors will - * continue to run at their last assigned values, and sensors will continue - * to update. Only the task containing the wait will pause until the wait - * time is expired. - * - * @param seconds Length of time to pause - */ - public void delay(final double seconds) { - final double start = simTime; - - while ((simTime - start) < seconds) { - synchronized(time_notifier) { - try { - time_notifier.wait(); // Block until time progresses - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - - /** - * Return the system clock time in seconds. Return the time from the - * FPGA hardware clock in seconds since the FPGA started. - * - * @return Robot running time in seconds. - */ - public double getFPGATimestamp() { - return simTime; - } - - @Override - public double getMatchTime() { - return simTime; - } - - @Override - public Timer.Interface newTimer() { - return new TimerImpl(); - } - - class TimerImpl implements Timer.Interface { - /** - * Create a new timer object. - * Create a new timer object and reset the time to zero. The timer is initially not running and - * must be started. - */ - public TimerImpl() { - reset(); - } - - /** - * Return the system clock time in milliseconds. Return the time from the - * FPGA hardware clock in milliseconds since the FPGA started. - * - * @deprecated Use getFPGATimestamp instead. - * @return Robot running time in milliseconds. - */ - private double getMsClock() { - return (simTime * 1e3); - } - - /** - * Get the current time from the timer. If the clock is running it is derived from - * the current system clock the start time stored in the timer class. If the clock - * is not running, then return the time when it was last stopped. - * - * @return Current time value for this timer in seconds - */ - public synchronized double get() { - if (m_running) { - return ((double) ((getMsClock() - m_startTime) + m_accumulatedTime)) / 1000.0; - } else { - return m_accumulatedTime; - } - } - - /** - * Reset the timer by setting the time to 0. - * Make the timer startTime the current time so new requests will be relative now - */ - public synchronized void reset() { - m_accumulatedTime = 0; - m_startTime = getMsClock(); - } - - /** - * Start the timer running. - * Just set the running flag to true indicating that all time requests should be - * relative to the system clock. - */ - public synchronized void start() { - m_startTime = getMsClock(); - m_running = true; - } - - /** - * Stop the timer. - * This computes the time as of now and clears the running flag, causing all - * subsequent time requests to be read from the accumulated time rather than - * looking at the system clock. - */ - public synchronized void stop() { - final double temp = get(); - m_accumulatedTime = temp; - m_running = false; - } - - /** - * Check if the period specified has passed and if it has, advance the start - * time by that period. This is useful to decide if it's time to do periodic - * work without drifting later by the time it took to get around to checking. - * - * @param period The period to check for (in seconds). - * @return If the period has passed. - */ - public synchronized boolean hasPeriodPassed(double period) { - if (get() > period) { - // Advance the start time by the period. - // Don't set it to the current time... we want to avoid drift. - m_startTime += period; - return true; - } - return false; + static { + MainNode.subscribe("time", Msgs.Float64(), + new SubscriberCallback() { + @Override + public void callback(Float64 msg) { + simTime = msg.getData(); + synchronized (time_notifier) { + time_notifier.notifyAll(); + } // Ew, this is nested too deep... Refactor? + } } + ); + } + + /** + * Pause the thread for a specified time. Pause the execution of the thread for a specified period + * of time given in seconds. Motors will continue to run at their last assigned values, and + * sensors will continue to update. Only the task containing the wait will pause until the wait + * time is expired. + * + * @param seconds Length of time to pause + */ + public void delay(final double seconds) { + final double start = simTime; + + while ((simTime - start) < seconds) { + synchronized (time_notifier) { + try { + time_notifier.wait(); // Block until time progresses + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } } + } + + /** + * Return the system clock time in seconds. Return the time from the FPGA hardware clock in + * seconds since the FPGA started. + * + * @return Robot running time in seconds. + */ + @SuppressWarnings("AbbreviationAsWordInName") + public double getFPGATimestamp() { + return simTime; + } + + @Override + public double getMatchTime() { + return simTime; + } + + @Override + public Timer.Interface newTimer() { + return new TimerImpl(); + } + + class TimerImpl implements Timer.Interface { + /** + * Create a new timer object. Create a new timer object and reset the time to zero. The timer is + * initially not running and must be started. + */ + public TimerImpl() { + reset(); + } + + /** + * Return the system clock time in milliseconds. Return the time from the FPGA hardware clock in + * milliseconds since the FPGA started. + * + * @return Robot running time in milliseconds. + * @deprecated Use getFPGATimestamp instead. + */ + private double getMsClock() { + return (simTime * 1e3); + } + + /** + * Get the current time from the timer. If the clock is running it is derived from the current + * system clock the start time stored in the timer class. If the clock is not running, then + * return the time when it was last stopped. + * + * @return Current time value for this timer in seconds + */ + public synchronized double get() { + if (m_running) { + return ((double) ((getMsClock() - m_startTime) + m_accumulatedTime)) / 1000.0; + } else { + return m_accumulatedTime; + } + } + + /** + * Reset the timer by setting the time to 0. Make the timer startTime the current time so new + * requests will be relative now + */ + public synchronized void reset() { + m_accumulatedTime = 0; + m_startTime = getMsClock(); + } + + /** + * Start the timer running. Just set the running flag to true indicating that all time requests + * should be relative to the system clock. + */ + public synchronized void start() { + m_startTime = getMsClock(); + m_running = true; + } + + /** + * Stop the timer. This computes the time as of now and clears the running flag, causing all + * subsequent time requests to be read from the accumulated time rather than looking at the + * system clock. + */ + public synchronized void stop() { + final double temp = get(); + m_accumulatedTime = temp; + m_running = false; + } + + /** + * Check if the period specified has passed and if it has, advance the start time by that + * period. This is useful to decide if it's time to do periodic work without drifting later by + * the time it took to get around to checking. + * + * @param period The period to check for (in seconds). + * @return If the period has passed. + */ + public synchronized boolean hasPeriodPassed(double period) { + if (get() > period) { + // Advance the start time by the period. + // Don't set it to the current time... we want to avoid drift. + m_startTime += period; + return true; + } + return false; + } + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/MainNode.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/MainNode.java index 98db62a1b6..cb7ee90639 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/MainNode.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/MainNode.java @@ -7,44 +7,50 @@ package edu.wpi.first.wpilibj.simulation; -import java.io.IOException; -import java.util.logging.Logger; +import com.google.protobuf.Message; import org.gazebosim.transport.Node; import org.gazebosim.transport.Publisher; import org.gazebosim.transport.Subscriber; import org.gazebosim.transport.SubscriberCallback; -import com.google.protobuf.Message; +import java.io.IOException; +import java.util.logging.Logger; public class MainNode { - private MainNode() { - } + private MainNode() { + } - private static final Logger LOG = Logger.getLogger("Simulation MainNode"); - private static Node mainNode; + private static final Logger LOG = Logger.getLogger("Simulation MainNode"); + private static Node m_mainNode; - public static synchronized void openGazeboConnection() throws IOException, InterruptedException { - if (mainNode != null) { - LOG.warning("MainNode.openGazeboConnection() was already called!"); - return; - } - mainNode = new Node("frc"); - mainNode.waitForConnection(); - } + @SuppressWarnings("JavadocMethod") + public static synchronized void openGazeboConnection() throws IOException, InterruptedException { + if (m_mainNode != null) { + LOG.warning("MainNode.openGazeboConnection() was already called!"); + return; + } + m_mainNode = new Node("frc"); + m_mainNode.waitForConnection(); + } - public static Publisher advertise(String topic, T defaultMessage) { - if (mainNode == null) { - throw new IllegalStateException("MainNode.openGazeboConnection() should have already been called by RobotBase.main()!"); - } - return mainNode.advertise(topic, defaultMessage); - } + @SuppressWarnings("JavadocMethod") + public static Publisher advertise(String topic, T defaultMessage) { + if (m_mainNode == null) { + throw new IllegalStateException("MainNode.openGazeboConnection() should have already been " + + "called by RobotBase.main()!"); + } + return m_mainNode.advertise(topic, defaultMessage); + } - public static Subscriber subscribe(String topic, T defaultMessage, SubscriberCallback cb) { - if (mainNode == null) { - throw new IllegalStateException("MainNode.openGazeboConnection() should have already been called by RobotBase.main()!"); - } - return mainNode.subscribe(topic, defaultMessage, cb); - } + @SuppressWarnings("JavadocMethod") + public static Subscriber subscribe(String topic, T defaultMessage, + SubscriberCallback cb) { + if (m_mainNode == null) { + throw new IllegalStateException("MainNode.openGazeboConnection() should have already been " + + "called by RobotBase.main()!"); + } + return m_mainNode.subscribe(topic, defaultMessage, cb); + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimDigitalInput.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimDigitalInput.java index 5d2b286a1a..86cc6a8fe5 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimDigitalInput.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimDigitalInput.java @@ -7,25 +7,27 @@ package edu.wpi.first.wpilibj.simulation; -import gazebo.msgs.GzBool.Bool; - import org.gazebosim.transport.Msgs; import org.gazebosim.transport.SubscriberCallback; -public class SimDigitalInput { - private boolean value; - - public SimDigitalInput(String topic) { - MainNode.subscribe(topic, Msgs.Bool(), - new SubscriberCallback() { - @Override public void callback(Bool msg) { - value = msg.getData(); - } - } - ); - } +import gazebo.msgs.GzBool.Bool; - public boolean get() { - return value; - } +public class SimDigitalInput { + private boolean m_value; + + @SuppressWarnings("JavadocMethod") + public SimDigitalInput(String topic) { + MainNode.subscribe(topic, Msgs.Bool(), + new SubscriberCallback() { + @Override + public void callback(Bool msg) { + m_value = msg.getData(); + } + } + ); + } + + public boolean get() { + return m_value; + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimEncoder.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimEncoder.java index 4c7ff873ab..f0b5d47055 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimEncoder.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimEncoder.java @@ -15,61 +15,65 @@ import gazebo.msgs.GzFloat64.Float64; import gazebo.msgs.GzString; public class SimEncoder { - private double position, velocity; - private Publisher command_pub; - - public SimEncoder(String topic) { - command_pub = MainNode.advertise(topic+"/control", Msgs.String()); + private double m_position; + private double m_velocity; + private Publisher m_commandPub; - MainNode.subscribe(topic+"/position", Msgs.Float64(), - new SubscriberCallback() { - @Override public void callback(Float64 msg) { - position = msg.getData(); - } - } - ); + @SuppressWarnings("JavadocMethod") + public SimEncoder(String topic) { + m_commandPub = MainNode.advertise(topic + "/control", Msgs.String()); - MainNode.subscribe(topic+"/velocity", Msgs.Float64(), - new SubscriberCallback() { - @Override public void callback(Float64 msg) { - velocity = msg.getData(); - } - } - ); + MainNode.subscribe(topic + "/position", Msgs.Float64(), + new SubscriberCallback() { + @Override + public void callback(Float64 msg) { + m_position = msg.getData(); + } + } + ); - try { - if (command_pub.waitForConnection(5000)) { // Wait up to five seconds. - System.out.println("Initialized " + topic); - } else { - System.err.println("Failed to initialize " + topic + ": does the encoder exist?"); - } - } catch (InterruptedException ex) { - ex.printStackTrace(); // TODO: Better way to handle this? - Thread.currentThread().interrupt(); - } - } - - public void reset() { - sendCommand("reset"); - } + MainNode.subscribe(topic + "/velocity", Msgs.Float64(), + new SubscriberCallback() { + @Override + public void callback(Float64 msg) { + m_velocity = msg.getData(); + } + } + ); - public void start() { - sendCommand("start"); - } + try { + if (m_commandPub.waitForConnection(5000)) { // Wait up to five seconds. + System.out.println("Initialized " + topic); + } else { + System.err.println("Failed to initialize " + topic + ": does the encoder exist?"); + } + } catch (InterruptedException ex) { + ex.printStackTrace(); // TODO: Better way to handle this? + Thread.currentThread().interrupt(); + } + } - public void stop() { - sendCommand("stop"); - } + public void reset() { + sendCommand("reset"); + } - private void sendCommand(String cmd) { - command_pub.publish(Msgs.String(cmd)); - } + public void start() { + sendCommand("start"); + } - public double getPosition() { - return position; - } + public void stop() { + sendCommand("stop"); + } - public double getVelocity() { - return velocity; - } + private void sendCommand(String cmd) { + m_commandPub.publish(Msgs.String(cmd)); + } + + public double getPosition() { + return m_position; + } + + public double getVelocity() { + return m_velocity; + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimFloatInput.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimFloatInput.java index 5c51f3c441..74dd46deda 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimFloatInput.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimFloatInput.java @@ -14,19 +14,21 @@ import org.gazebosim.transport.SubscriberCallback; import gazebo.msgs.GzFloat64.Float64; public class SimFloatInput { - private double value; - - public SimFloatInput(String topic) { - MainNode.subscribe(topic, Msgs.Float64(), - new SubscriberCallback() { - @Override public void callback(Float64 msg) { - value = msg.getData(); - } - } - ); - } + private double m_value; - public double get() { - return value; - } + @SuppressWarnings("JavadocMethod") + public SimFloatInput(String topic) { + MainNode.subscribe(topic, Msgs.Float64(), + new SubscriberCallback() { + @Override + public void callback(Float64 msg) { + m_value = msg.getData(); + } + } + ); + } + + public double get() { + return m_value; + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimGyro.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimGyro.java index c6d4b1f2a7..13a9012c62 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimGyro.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimGyro.java @@ -7,51 +7,55 @@ package edu.wpi.first.wpilibj.simulation; -import gazebo.msgs.GzFloat64.Float64; -import gazebo.msgs.GzString; - import org.gazebosim.transport.Msgs; import org.gazebosim.transport.Publisher; import org.gazebosim.transport.SubscriberCallback; +import gazebo.msgs.GzFloat64.Float64; +import gazebo.msgs.GzString; + public class SimGyro { - private double position, velocity; - private Publisher command_pub; - - public SimGyro(String topic) { - command_pub = MainNode.advertise(topic+"/control", Msgs.String()); - command_pub.setLatchMode(true); + private double m_position; + private double m_velocity; + private Publisher m_commandPub; - MainNode.subscribe(topic+"/position", Msgs.Float64(), - new SubscriberCallback() { - @Override public void callback(Float64 msg) { - position = msg.getData(); - } - } - ); - - MainNode.subscribe(topic+"/velocity", Msgs.Float64(), - new SubscriberCallback() { - @Override public void callback(Float64 msg) { - velocity = msg.getData(); - } - } - ); - } - - public void reset() { - sendCommand("reset"); - } + @SuppressWarnings("JavadocMethod") + public SimGyro(String topic) { + m_commandPub = MainNode.advertise(topic + "/control", Msgs.String()); + m_commandPub.setLatchMode(true); - private void sendCommand(String cmd) { - command_pub.publish(Msgs.String(cmd)); - } + MainNode.subscribe(topic + "/position", Msgs.Float64(), + new SubscriberCallback() { + @Override + public void callback(Float64 msg) { + m_position = msg.getData(); + } + } + ); - public double getAngle() { - return position; - } + MainNode.subscribe(topic + "/velocity", Msgs.Float64(), + new SubscriberCallback() { + @Override + public void callback(Float64 msg) { + m_velocity = msg.getData(); + } + } + ); + } - public double getVelocity() { - return velocity; - } + public void reset() { + sendCommand("reset"); + } + + private void sendCommand(String cmd) { + m_commandPub.publish(Msgs.String(cmd)); + } + + public double getAngle() { + return m_position; + } + + public double getVelocity() { + return m_velocity; + } } diff --git a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimSpeedController.java b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimSpeedController.java index 3039022a09..2c90836b6a 100644 --- a/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimSpeedController.java +++ b/wpilibj/src/sim/java/edu/wpi/first/wpilibj/simulation/SimSpeedController.java @@ -7,74 +7,74 @@ package edu.wpi.first.wpilibj.simulation; -import gazebo.msgs.GzFloat64.Float64; - import org.gazebosim.transport.Msgs; import org.gazebosim.transport.Publisher; +import gazebo.msgs.GzFloat64.Float64; + public class SimSpeedController { - private Publisher pub; - private double speed; + private Publisher m_pub; + private double m_speed; - /** - * Constructor that assumes the default digital module. - * - * @param channel The PWM channel on the digital module that the Victor is attached to. - */ - public SimSpeedController(String topic) { - pub = MainNode.advertise(topic, Msgs.Float64()); - } + /** + * Constructor that assumes the default digital module. + * + * @param topic The topic to publish the to. + */ + public SimSpeedController(String topic) { + m_pub = MainNode.advertise(topic, Msgs.Float64()); + } - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - set(speed); - } + /** + * Set the PWM value. + * + *

he PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, + * update immediately. + * @deprecated For compatibility with CANJaguar + */ + public void set(double speed, byte syncGroup) { + set(speed); + } - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - public void set(double speed) { - pub.publish(Msgs.Float64(speed)); - } + /** + * Set the PWM value. + * + *

The PWM value is set using a range of -1.0 to 1.0, appropriately scaling the value for the + * FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + public void set(double speed) { + m_pub.publish(Msgs.Float64(speed)); + } - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - public double get() { - return speed; - } - - /** - * Disable the speed controller - */ - public void disable() { - set(0); - } + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + public double get() { + return m_speed; + } - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - set(output); - } + /** + * Disable the speed controller. + */ + public void disable() { + set(0); + } + + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + public void pidWrite(double output) { + set(output); + } } diff --git a/wpilibjIntegrationTests/README.html b/wpilibjIntegrationTests/README.html index 9c26b77411..dc9d154fc1 100644 --- a/wpilibjIntegrationTests/README.html +++ b/wpilibjIntegrationTests/README.html @@ -1,4 +1,8 @@ -README

TO LOAD & RUN INTEGRATION TESTS

-

See: allwpilib/test-scripts

\ No newline at end of file + + + + README +

TO LOAD & RUN INTEGRATION TESTS

+

See: allwpilib/test-scripts

+ diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java index 98222b8c3a..5b35232049 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java @@ -7,6 +7,15 @@ package edu.wpi.first.wpilibj; +import org.junit.After; +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import edu.wpi.first.wpilibj.test.AbstractComsSetup; + import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; @@ -14,51 +23,39 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -import org.junit.After; -import org.junit.Test; - -import edu.wpi.first.wpilibj.test.AbstractComsSetup; - /** - * This class should not be run as a test explicitly. Instead it should be - * extended by tests that use the InterruptableSensorBase + * This class should not be run as a test explicitly. Instead it should be extended by tests that + * use the InterruptableSensorBase. * * @author jonathanleitschuh - * */ public abstract class AbstractInterruptTest extends AbstractComsSetup { - private InterruptableSensorBase interruptable = null; + private InterruptableSensorBase m_interruptable = null; private InterruptableSensorBase getInterruptable() { - if (interruptable == null) { - interruptable = giveInterruptableSensorBase(); + if (m_interruptable == null) { + m_interruptable = giveInterruptableSensorBase(); } - return interruptable; + return m_interruptable; } @After public void interruptTeardown() { - if (interruptable != null) { + if (m_interruptable != null) { freeInterruptableSensorBase(); - interruptable = null; + m_interruptable = null; } } /** - * Give the interruptible sensor base that interrupts can be attached to. - *$ - * @return + * Give the interruptable sensor base that interrupts can be attached to. */ abstract InterruptableSensorBase giveInterruptableSensorBase(); /** - * Cleans up the interruptible sensor base. This is only called if - * {@link #giveInterruptableSensorBase()} is called. + * Cleans up the interruptable sensor base. This is only called if {@link + * #giveInterruptableSensorBase()} is called. */ abstract void freeInterruptableSensorBase(); @@ -74,50 +71,54 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { private class InterruptCounter { - private final AtomicInteger count = new AtomicInteger(); + private final AtomicInteger m_count = new AtomicInteger(); void increment() { - count.addAndGet(1); + m_count.addAndGet(1); } int getCount() { - return count.get(); + return m_count.get(); } - }; + } private class TestInterruptHandlerFunction extends InterruptHandlerFunction { - protected final AtomicBoolean exceptionThrown = new AtomicBoolean(false); - /** Stores the time that the interrupt fires */ - final AtomicLong interruptFireTime = new AtomicLong(); - /** Stores if the interrupt has completed at least once */ - final AtomicBoolean interruptComplete = new AtomicBoolean(false); - protected Exception ex; - final InterruptCounter counter; + protected final AtomicBoolean m_exceptionThrown = new AtomicBoolean(false); + /** + * Stores the time that the interrupt fires. + */ + final AtomicLong m_interruptFireTime = new AtomicLong(); + /** + * Stores if the interrupt has completed at least once. + */ + final AtomicBoolean m_interruptComplete = new AtomicBoolean(false); + protected Exception m_ex; + final InterruptCounter m_counter; TestInterruptHandlerFunction(InterruptCounter counter) { - this.counter = counter; + m_counter = counter; } @Override public void interruptFired(int interruptAssertedMask, InterruptCounter param) { - interruptFireTime.set(Utility.getFPGATime()); - counter.increment(); + m_interruptFireTime.set(Utility.getFPGATime()); + m_counter.increment(); try { // This won't cause the test to fail - assertSame(counter, param); + assertSame(m_counter, param); } catch (Exception ex) { // So we must throw the exception within the test - exceptionThrown.set(true); - this.ex = ex; + m_exceptionThrown.set(true); + m_ex = ex; } - interruptComplete.set(true); - }; + m_interruptComplete.set(true); + } @Override public InterruptCounter overridableParameter() { - return counter; + return m_counter; } - }; + } @Test(timeout = 1000) public void testSingleInterruptsTriggering() throws Exception { @@ -137,7 +138,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { setInterruptHigh(); // Delay until the interrupt is complete - while (!function.interruptComplete.get()) { + while (!function.m_interruptComplete.get()) { Timer.delay(.005); } @@ -145,14 +146,15 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { // Then assertEquals("The interrupt did not fire the expected number of times", 1, counter.getCount()); // If the test within the interrupt failed - if (function.exceptionThrown.get()) { - throw function.ex; + if (function.m_exceptionThrown.get()) { + throw function.m_ex; } final long range = 10000; // in microseconds assertThat( "The interrupt did not fire within the expected time period (values in milliseconds)", - function.interruptFireTime.get(), - both(greaterThan(interruptTriggerTime - range)).and(lessThan(interruptTriggerTime + range))); + function.m_interruptFireTime.get(), + both(greaterThan(interruptTriggerTime - range)).and(lessThan(interruptTriggerTime + + range))); assertThat( "The readRisingTimestamp() did not return the correct value (values in seconds)", getInterruptable().readRisingTimestamp(), @@ -175,7 +177,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { setInterruptLow(); setInterruptHigh(); // Wait for the interrupt to complete before moving on - while (!function.interruptComplete.getAndSet(false)) { + while (!function.m_interruptComplete.getAndSet(false)) { Timer.delay(.005); } } @@ -184,7 +186,9 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { counter.getCount()); } - /** The timeout length for this test in seconds */ + /** + * The timeout length for this test in seconds. + */ private static final int synchronousTimeout = 5; @Test(timeout = (long) (synchronousTimeout * 1e3)) @@ -193,13 +197,10 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { getInterruptable().requestInterrupts(); final double synchronousDelay = synchronousTimeout / 2.; - Runnable r = new Runnable() { - @Override - public void run() { - Timer.delay(synchronousDelay); - setInterruptLow(); - setInterruptHigh(); - } + final Runnable runnable = () -> { + Timer.delay(synchronousDelay); + setInterruptLow(); + setInterruptHigh(); }; // When @@ -207,7 +208,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { // Note: the long time value is used because doubles can flip if the robot // is left running for long enough final long startTimeStamp = Utility.getFPGATime(); - new Thread(r).start(); + new Thread(runnable).start(); // Delay for twice as long as the timeout so the test should fail first getInterruptable().waitForInterrupt(synchronousTimeout * 2); final long stopTimeStamp = Utility.getFPGATime(); @@ -225,9 +226,11 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { getInterruptable().requestInterrupts(); //Don't fire interrupt. Expect it to timeout. - InterruptableSensorBase.WaitResult result = getInterruptable().waitForInterrupt(synchronousTimeout / 2); + InterruptableSensorBase.WaitResult result = getInterruptable() + .waitForInterrupt(synchronousTimeout / 2); - assertEquals("The interrupt did not time out correctly.", result, InterruptableSensorBase.WaitResult.kTimeout); + assertEquals("The interrupt did not time out correctly.", result, InterruptableSensorBase + .WaitResult.kTimeout); } @Test(timeout = (long) (synchronousTimeout * 1e3)) @@ -236,20 +239,19 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { getInterruptable().requestInterrupts(); final double synchronousDelay = synchronousTimeout / 2.; - Runnable r = new Runnable() { - @Override - public void run() { - Timer.delay(synchronousDelay); - setInterruptLow(); - setInterruptHigh(); - } + final Runnable runnable = () -> { + Timer.delay(synchronousDelay); + setInterruptLow(); + setInterruptHigh(); }; - new Thread(r).start(); + new Thread(runnable).start(); // Delay for twice as long as the timeout so the test should fail first - InterruptableSensorBase.WaitResult result = getInterruptable().waitForInterrupt(synchronousTimeout * 2); + InterruptableSensorBase.WaitResult result = getInterruptable() + .waitForInterrupt(synchronousTimeout * 2); - assertEquals("The interrupt did not fire on the rising edge.", result, InterruptableSensorBase.WaitResult.kRisingEdge); + assertEquals("The interrupt did not fire on the rising edge.", result, + InterruptableSensorBase.WaitResult.kRisingEdge); } @Test(timeout = (long) (synchronousTimeout * 1e3)) @@ -259,20 +261,19 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { getInterruptable().setUpSourceEdge(false, true); final double synchronousDelay = synchronousTimeout / 2.; - Runnable r = new Runnable() { - @Override - public void run() { - Timer.delay(synchronousDelay); - setInterruptHigh(); - setInterruptLow(); - } + final Runnable runnable = () -> { + Timer.delay(synchronousDelay); + setInterruptHigh(); + setInterruptLow(); }; - new Thread(r).start(); + new Thread(runnable).start(); // Delay for twice as long as the timeout so the test should fail first - InterruptableSensorBase.WaitResult result = getInterruptable().waitForInterrupt(synchronousTimeout * 2); + InterruptableSensorBase.WaitResult result = getInterruptable() + .waitForInterrupt(synchronousTimeout * 2); - assertEquals("The interrupt did not fire on the falling edge.", result, InterruptableSensorBase.WaitResult.kFallingEdge); + assertEquals("The interrupt did not fire on the falling edge.", result, + InterruptableSensorBase.WaitResult.kFallingEdge); } @@ -290,7 +291,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup { setInterruptLow(); setInterruptHigh(); // Wait for the interrupt to complete before moving on - while (!function.interruptComplete.getAndSet(false)) { + while (!function.m_interruptComplete.getAndSet(false)) { Timer.delay(.005); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java index c1707911a6..6a17831b86 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java @@ -7,25 +7,25 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.logging.Logger; - -import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.AnalogTriggerOutput.AnalogTriggerType; import edu.wpi.first.wpilibj.fixtures.AnalogCrossConnectFixture; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** - * @author jonathanleitschuh + * Test that covers the {@link AnalogCrossConnectFixture}. * + * @author jonathanleitschuh */ public class AnalogCrossConnectTest extends AbstractInterruptTest { private static final Logger logger = Logger.getLogger(AnalogCrossConnectTest.class.getName()); @@ -40,36 +40,22 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest { } - /** - * @throws java.lang.Exception - */ @BeforeClass public static void setUpBeforeClass() throws Exception { analogIO = TestBench.getAnalogCrossConnectFixture(); } - /** - * @throws java.lang.Exception - */ @AfterClass public static void tearDownAfterClass() throws Exception { analogIO.teardown(); analogIO = null; } - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { analogIO.setup(); } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} @Test public void testAnalogOuput() { @@ -155,43 +141,44 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest { analogIO.getInput().getAccumulatorCount(); } - private AnalogTrigger interruptTrigger; - private AnalogTriggerOutput interruptTriggerOutput; + private AnalogTrigger m_interruptTrigger; + private AnalogTriggerOutput m_interruptTriggerOutput; /* * (non-Javadoc) - *$ + * * @see * edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase() */ @Override InterruptableSensorBase giveInterruptableSensorBase() { - interruptTrigger = new AnalogTrigger(analogIO.getInput()); - interruptTrigger.setLimitsVoltage(2.0f, 3.0f); - interruptTriggerOutput = new AnalogTriggerOutput(interruptTrigger, AnalogTriggerType.kState); - return interruptTriggerOutput; + m_interruptTrigger = new AnalogTrigger(analogIO.getInput()); + m_interruptTrigger.setLimitsVoltage(2.0f, 3.0f); + m_interruptTriggerOutput = new AnalogTriggerOutput(m_interruptTrigger, + AnalogTriggerType.kState); + return m_interruptTriggerOutput; } /* * (non-Javadoc) - *$ + * * @see * edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase() */ @Override void freeInterruptableSensorBase() { - interruptTriggerOutput.cancelInterrupts(); - interruptTriggerOutput.free(); - interruptTriggerOutput = null; - interruptTrigger.free(); - interruptTrigger = null; + m_interruptTriggerOutput.cancelInterrupts(); + m_interruptTriggerOutput.free(); + m_interruptTriggerOutput = null; + m_interruptTrigger.free(); + m_interruptTrigger = null; } /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh() */ @Override @@ -202,7 +189,7 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow() */ @Override diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java index e67d34a652..7e4d61019e 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java @@ -7,50 +7,45 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; - -import java.util.logging.Logger; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.AnalogCrossConnectFixture; import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertEquals; + /** - * @author jonathanleitschuh + * Tests the {@link AnalogPotentiometer}. * + * @author jonathanleitschuh */ public class AnalogPotentiometerTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(AnalogPotentiometerTest.class.getName()); - private AnalogCrossConnectFixture analogIO; - private FakePotentiometerSource potSource; - private AnalogPotentiometer pot; + private AnalogCrossConnectFixture m_analogIO; + private FakePotentiometerSource m_potSource; + private AnalogPotentiometer m_pot; private static final double DOUBLE_COMPARISON_DELTA = 2.0; - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { - analogIO = TestBench.getAnalogCrossConnectFixture(); - potSource = new FakePotentiometerSource(analogIO.getOutput(), 360); - pot = new AnalogPotentiometer(analogIO.getInput(), 360.0, 0); + m_analogIO = TestBench.getAnalogCrossConnectFixture(); + m_potSource = new FakePotentiometerSource(m_analogIO.getOutput(), 360); + m_pot = new AnalogPotentiometer(m_analogIO.getInput(), 360.0, 0); } - /** - * @throws java.lang.Exception - */ @After public void tearDown() throws Exception { - potSource.reset(); - pot.free(); - analogIO.teardown(); + m_potSource.reset(); + m_pot.free(); + m_analogIO.teardown(); } @Override @@ -60,16 +55,16 @@ public class AnalogPotentiometerTest extends AbstractComsSetup { @Test public void testInitialSettings() { - assertEquals(0, pot.get(), DOUBLE_COMPARISON_DELTA); + assertEquals(0, m_pot.get(), DOUBLE_COMPARISON_DELTA); } @Test public void testRangeValues() { for (double i = 0.0; i < 360.0; i = i + 1.0) { - potSource.setAngle(i); - potSource.setMaxVoltage(ControllerPower.getVoltage5V()); + m_potSource.setAngle(i); + m_potSource.setMaxVoltage(ControllerPower.getVoltage5V()); Timer.delay(.02); - assertEquals(i, pot.get(), DOUBLE_COMPARISON_DELTA); + assertEquals(i, m_pot.get(), DOUBLE_COMPARISON_DELTA); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java index c8b2e5d4a2..c3fb6c3c0a 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java @@ -7,21 +7,21 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Arrays; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.interfaces.Accelerometer; import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertEquals; + @RunWith(Parameterized.class) public class BuiltInAccelerometerTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(BuiltInAccelerometerTest.class.getName()); @@ -46,7 +46,7 @@ public class BuiltInAccelerometerTest extends AbstractComsSetup { */ @Parameters public static Collection generateData() { - return Arrays.asList(new Accelerometer.Range[][] { {Accelerometer.Range.k2G}, + return Arrays.asList(new Accelerometer.Range[][]{{Accelerometer.Range.k2G}, {Accelerometer.Range.k4G}, {Accelerometer.Range.k8G},}); } @@ -56,8 +56,8 @@ public class BuiltInAccelerometerTest extends AbstractComsSetup { } /** - * There's not much we can automatically test with the on-board accelerometer, - * but checking for gravity is probably good enough to tell that it's working. + * There's not much we can automatically test with the on-board accelerometer, but checking for + * gravity is probably good enough to tell that it's working. */ @Test public void testAccelerometer() { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java index af52f0cfb9..4bbd0719a6 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java @@ -7,19 +7,17 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertTrue; - -import java.util.logging.Logger; - import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.SampleFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; -import edu.wpi.first.wpilibj.hal.CanTalonJNI; +import static org.junit.Assert.assertTrue; /** * Basic test (borrowed straight from SampleTest) for running the CAN TalonSRX. @@ -27,7 +25,7 @@ import edu.wpi.first.wpilibj.hal.CanTalonJNI; public class CANTalonTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(SampleTest.class.getName()); - static SampleFixture fixture = new SampleFixture(); + static SampleFixture m_fixture = new SampleFixture(); protected Logger getClassLogger() { return logger; @@ -36,19 +34,19 @@ public class CANTalonTest extends AbstractComsSetup { @BeforeClass public static void classSetup() { // Set up the fixture before the test is created - fixture.setup(); + m_fixture.setup(); } @Before public void setUp() { // Reset the fixture elements before every test - fixture.reset(); + m_fixture.reset(); } @AfterClass public static void tearDown() { // Clean up the fixture after the test - fixture.teardown(); + m_fixture.teardown(); } private String errorMessage(double actual, double expected) { @@ -84,9 +82,10 @@ public class CANTalonTest extends AbstractComsSetup { } @Test - public void SetGetPID() { + public void setGetPID() { CANTalon talon = new CANTalon(0); talon.changeControlMode(CANTalon.TalonControlMode.Position); + @SuppressWarnings({"LocalVariableName", "MultipleVariableDeclarations"}) double p = 0.05, i = 0.098, d = 1.23; talon.setPID(p, i, d); assertTrue(errorMessage(talon.getP(), p), Math.abs(p - talon.getP()) < 1e-5); @@ -109,6 +108,7 @@ public class CANTalonTest extends AbstractComsSetup { talon.changeControlMode(CANTalon.TalonControlMode.Position); talon.setFeedbackDevice(CANTalon.FeedbackDevice.AnalogPot); Timer.delay(0.2); + @SuppressWarnings({"LocalVariableName", "MultipleVariableDeclarations"}) double p = 1.0, i = 0.0, d = 0.00; talon.setPID(p, i, d); talon.set(100); @@ -137,20 +137,20 @@ public class CANTalonTest extends AbstractComsSetup { CANTalon talon = new CANTalon(0); talon.clearStickyFaults(); - assertTrue(talon.getFaultOverTemp()==0); - assertTrue(talon.getFaultUnderVoltage()==0); - assertTrue(talon.getFaultForLim()==0); - assertTrue(talon.getFaultRevLim()==0); - assertTrue(talon.getFaultHardwareFailure()==0); - assertTrue(talon.getFaultForSoftLim()==0); - assertTrue(talon.getFaultRevSoftLim()==0); + assertTrue(talon.getFaultOverTemp() == 0); + assertTrue(talon.getFaultUnderVoltage() == 0); + assertTrue(talon.getFaultForLim() == 0); + assertTrue(talon.getFaultRevLim() == 0); + assertTrue(talon.getFaultHardwareFailure() == 0); + assertTrue(talon.getFaultForSoftLim() == 0); + assertTrue(talon.getFaultRevSoftLim() == 0); - assertTrue(talon.getStickyFaultOverTemp()==0); -// assertTrue(talon.getStickyFaultUnderVoltage()==0); - assertTrue(talon.getStickyFaultForLim()==0); - assertTrue(talon.getStickyFaultRevLim()==0); - assertTrue(talon.getStickyFaultForSoftLim()==0); - assertTrue(talon.getStickyFaultRevSoftLim()==0); + assertTrue(talon.getStickyFaultOverTemp() == 0); + // assertTrue(talon.getStickyFaultUnderVoltage()==0); + assertTrue(talon.getStickyFaultForLim() == 0); + assertTrue(talon.getStickyFaultRevLim() == 0); + assertTrue(talon.getStickyFaultForSoftLim() == 0); + assertTrue(talon.getStickyFaultRevSoftLim() == 0); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CircularBufferTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CircularBufferTest.java index 3d5a3aa4c3..e44c14e9fe 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CircularBufferTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CircularBufferTest.java @@ -7,34 +7,33 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.Test; - -import edu.wpi.first.wpilibj.CircularBuffer; import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertEquals; + public class CircularBufferTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(CircularBufferTest.class.getName()); - private double[] values = {751.848, 766.366, 342.657, 234.252, 716.126, - 132.344, 445.697, 22.727, 421.125, 799.913}; - private double[] pushFrontOut = {799.913, 421.125, 22.727, 445.697, 132.344, - 716.126, 234.252, 342.657}; - private double[] pushBackOut = {342.657, 234.252, 716.126, 132.344, 445.697, - 22.727, 421.125, 799.913}; + private double[] m_values = {751.848, 766.366, 342.657, 234.252, 716.126, + 132.344, 445.697, 22.727, 421.125, 799.913}; + private double[] m_pushFrontOut = {799.913, 421.125, 22.727, 445.697, 132.344, + 716.126, 234.252, 342.657}; + private double[] m_pushBackOut = {342.657, 234.252, 716.126, 132.344, 445.697, + 22.727, 421.125, 799.913}; @Test public void pushFrontTest() { CircularBuffer queue = new CircularBuffer(8); - for (double value : values) { + for (double value : m_values) { queue.pushFront(value); } - for (int i = 0; i < pushFrontOut.length; i++) { - assertEquals(pushFrontOut[i], queue.get(i), 0.00005); + for (int i = 0; i < m_pushFrontOut.length; i++) { + assertEquals(m_pushFrontOut[i], queue.get(i), 0.00005); } } @@ -42,12 +41,12 @@ public class CircularBufferTest extends AbstractComsSetup { public void pushBackTest() { CircularBuffer queue = new CircularBuffer(8); - for (double value : values) { + for (double value : m_values) { queue.pushBack(value); } - for (int i = 0; i < pushBackOut.length; i++) { - assertEquals(pushBackOut[i], queue.get(i), 0.00005); + for (int i = 0; i < m_pushBackOut.length; i++) { + assertEquals(m_pushBackOut[i], queue.get(i), 0.00005); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java index d967d09520..44da0385b8 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java @@ -7,11 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; @@ -20,23 +15,28 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.FakeCounterFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** - * Tests to see if the Counter is working properly - *$ - * @author Jonathan Leitschuh + * Tests to see if the Counter is working properly. * + * @author Jonathan Leitschuh */ @RunWith(Parameterized.class) public class CounterTest extends AbstractComsSetup { private static FakeCounterFixture counter = null; private static final Logger logger = Logger.getLogger(CounterTest.class.getName()); - Integer input; - Integer output; + Integer m_input; + Integer m_output; @Override protected Logger getClassLogger() { @@ -44,29 +44,29 @@ public class CounterTest extends AbstractComsSetup { } /** - * Constructs a Counter Test with the given inputs - *$ - * @param input The input Port + * Constructs a Counter Test with the given inputs. + * + * @param input The input Port * @param output The output Port */ public CounterTest(Integer input, Integer output) { assert input != null; assert output != null; - this.input = input; - this.output = output; + m_input = input; + m_output = output; // System.out.println("Counter Test: Input: " + input + " Output: " + // output); - if (counter != null) + if (counter != null) { counter.teardown(); + } counter = new FakeCounterFixture(input, output); } /** - * Test data generator. This method is called the the JUnit parameterized test - * runner and returns a Collection of Arrays. For each Array in the - * Collection, each array element corresponds to a parameter in the - * constructor. + * Test data generator. This method is called the the JUnit parameterized test runner and returns + * a Collection of Arrays. For each Array in the Collection, each array element corresponds to a + * parameter in the constructor. */ @Parameters public static Collection generateData() { @@ -79,48 +79,39 @@ public class CounterTest extends AbstractComsSetup { } - - /** - * @throws java.lang.Exception - */ @BeforeClass - public static void setUpBeforeClass() throws Exception {} + public static void setUpBeforeClass() throws Exception { + } - /** - * @throws java.lang.Exception - */ @AfterClass public static void tearDownAfterClass() throws Exception { counter.teardown(); counter = null; } - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { counter.setup(); } /** - * Tests the default state of the counter immediately after reset + * Tests the default state of the counter immediately after reset. */ @Test public void testDefault() { - assertTrue("Counter did not reset to 0", counter.getCounter().get() == 0); + assertEquals("Counter did not reset to 0", 0, counter.getCounter().get()); } @Test(timeout = 5000) public void testCount() { - int goal = 100; + final int goal = 100; counter.getFakeCounterSource().setCount(goal); counter.getFakeCounterSource().execute(); - int count = counter.getCounter().get(); + final int count = counter.getCounter().get(); - assertTrue("Fake Counter, Input: " + input + ", Output: " + output + ", did not return " + goal - + " instead got: " + count, count == goal); + assertTrue("Fake Counter, Input: " + m_input + ", Output: " + m_output + ", did not return " + + goal + " instead got: " + count, count == goal); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java index a4d3771fbb..71dad68cde 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java @@ -7,12 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.After; import org.junit.AfterClass; import org.junit.Test; @@ -20,12 +14,18 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.DIOCrossConnectFixture; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** - * Tests to see if the Digital ports are working properly - *$ + * Tests to see if the Digital ports are working properly. + * * @author jonathanleitschuh */ @RunWith(Parameterized.class) @@ -40,14 +40,12 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { } /** - * Default constructor for the DIOCrossConnectTest This test is parameterized - * in order to allow it to be tested using a variety of different input/output - * pairs without duplicate code.
- * This class takes Integer port values instead of DigitalClasses because it - * would force them to be instantiated at the same time which could (untested) - * cause port binding errors. - *$ - * @param input The port for the input wire + * Default constructor for the DIOCrossConnectTest This test is parameterized in order to allow it + * to be tested using a variety of different input/output pairs without duplicate code.
This + * class takes Integer port values instead of DigitalClasses because it would force them to be + * instantiated at the same time which could (untested) cause port binding errors. + * + * @param input The port for the input wire * @param output The port for the output wire */ public DIOCrossConnectTest(Integer input, Integer output) { @@ -58,12 +56,10 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { } - /** - * Test data generator. This method is called the the JUnit parameterized test - * runner and returns a Collection of Arrays. For each Array in the - * Collection, each array element corresponds to a parameter in the - * constructor. + * Test data generator. This method is called the the JUnit parameterized test runner and returns + * a Collection of Arrays. For each Array in the Collection, each array element corresponds to a + * parameter in the constructor. */ @Parameters(name = "{index}: Input Port: {0} Output Port: {1}") public static Collection generateData() { @@ -87,7 +83,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { } /** - * Tests to see if the DIO can create and recognize a high value + * Tests to see if the DIO can create and recognize a high value. */ @Test public void testSetHigh() { @@ -98,7 +94,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { } /** - * Tests to see if the DIO can create and recognize a low value + * Tests to see if the DIO can create and recognize a low value. */ @Test public void testSetLow() { @@ -112,7 +108,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { * Tests to see if the DIO PWM functionality works. */ @Test - public void testDIOPWM() { + public void testDIOpulseWidthModulation() { dio.getOutput().set(false); assertFalse("DIO Not Low after no delay", dio.getInput().get()); //Set frequency to 2.0 Hz @@ -126,24 +122,24 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { //TODO: Add return value from WaitForInterrupt dio.getInput().waitForInterrupt(3.0, true); Timer.delay(0.5); - boolean firstCycle = dio.getInput().get(); + final boolean firstCycle = dio.getInput().get(); Timer.delay(0.5); - boolean secondCycle = dio.getInput().get(); + final boolean secondCycle = dio.getInput().get(); Timer.delay(0.5); - boolean thirdCycle = dio.getInput().get(); + final boolean thirdCycle = dio.getInput().get(); Timer.delay(0.5); - boolean forthCycle = dio.getInput().get(); + final boolean forthCycle = dio.getInput().get(); Timer.delay(0.5); - boolean fifthCycle = dio.getInput().get(); + final boolean fifthCycle = dio.getInput().get(); Timer.delay(0.5); - boolean sixthCycle = dio.getInput().get(); + final boolean sixthCycle = dio.getInput().get(); Timer.delay(0.5); - boolean seventhCycle = dio.getInput().get(); + final boolean seventhCycle = dio.getInput().get(); dio.getOutput().disablePWM(); Timer.delay(0.5); - boolean firstAfterStop = dio.getInput().get(); + final boolean firstAfterStop = dio.getInput().get(); Timer.delay(0.5); - boolean secondAfterStop = dio.getInput().get(); + final boolean secondAfterStop = dio.getInput().get(); assertFalse("DIO Not Low after first delay", firstCycle); assertTrue("DIO Not High after second delay", secondCycle); @@ -158,7 +154,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { /* * (non-Javadoc) - *$ + * * @see * edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase() */ @@ -169,7 +165,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { /* * (non-Javadoc) - *$ + * * @see * edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase() */ @@ -180,7 +176,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh() */ @Override @@ -190,7 +186,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow() */ @Override diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilterTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilterTest.java index 43a0b428e8..64ede88e7b 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilterTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilterTest.java @@ -7,18 +7,13 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.Test; - import edu.wpi.first.wpilibj.test.AbstractComsSetup; -import edu.wpi.first.wpilibj.DigitalInput; -import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.Counter; -import edu.wpi.first.wpilibj.DigitalGlitchFilter; +import static org.junit.Assert.assertEquals; /** * Test for the DigitalGlitchFilter class. @@ -27,38 +22,37 @@ import edu.wpi.first.wpilibj.DigitalGlitchFilter; */ public class DigitalGlitchFilterTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger( - DigitalGlitchFilterTest.class.getName()); + DigitalGlitchFilterTest.class.getName()); protected Logger getClassLogger() { return logger; } /** - * This is a test to make sure that filters can be created and are consistent. - * This assumes that the FPGA implementation to actually implement the filter - * has been tested. It does validate that we are successfully able to set and - * get the active filters for ports and makes sure that the FPGA filter is - * changed correctly, and does the same for the period. + * This is a test to make sure that filters can be created and are consistent. This assumes that + * the FPGA implementation to actually implement the filter has been tested. It does validate + * that we are successfully able to set and get the active filters for ports and makes sure that + * the FPGA filter is changed correctly, and does the same for the period. */ @Test public void testDigitalGlitchFilterBasic() { - DigitalInput input1 = new DigitalInput(1); - DigitalInput input2 = new DigitalInput(2); - DigitalInput input3 = new DigitalInput(3); - DigitalInput input4 = new DigitalInput(4); - Encoder encoder5 = new Encoder(5, 6); - Counter counter7 = new Counter(7); + final DigitalInput input1 = new DigitalInput(1); + final DigitalInput input2 = new DigitalInput(2); + final DigitalInput input3 = new DigitalInput(3); + final DigitalInput input4 = new DigitalInput(4); + final Encoder encoder5 = new Encoder(5, 6); + final Counter counter7 = new Counter(7); - DigitalGlitchFilter filter1 = new DigitalGlitchFilter(); + final DigitalGlitchFilter filter1 = new DigitalGlitchFilter(); filter1.add(input1); filter1.setPeriodNanoSeconds(4200); - DigitalGlitchFilter filter2 = new DigitalGlitchFilter(); + final DigitalGlitchFilter filter2 = new DigitalGlitchFilter(); filter2.add(input2); filter2.add(input3); filter2.setPeriodNanoSeconds(97100); - DigitalGlitchFilter filter3 = new DigitalGlitchFilter(); + final DigitalGlitchFilter filter3 = new DigitalGlitchFilter(); filter3.add(input4); filter3.add(encoder5); filter3.add(counter7); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java index fe0e36a3ac..e3d78ef7ce 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java @@ -7,11 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -20,27 +15,31 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.FakeEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertTrue; + /** - * Test to see if the FPGA properly recognizes a mock Encoder input - *$ - * @author Jonathan Leitschuh + * Test to see if the FPGA properly recognizes a mock Encoder input. * + * @author Jonathan Leitschuh */ @RunWith(Parameterized.class) public class EncoderTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(EncoderTest.class.getName()); private static FakeEncoderFixture encoder = null; - private final boolean flip; // Does this test need to flip the inputs - private final int inputA; - private final int inputB; - private final int outputA; - private final int outputB; + private final boolean m_flip; // Does this test need to flip the inputs + private final int m_inputA; + private final int m_inputB; + private final int m_outputA; + private final int m_outputB; @Override protected Logger getClassLogger() { @@ -48,10 +47,9 @@ public class EncoderTest extends AbstractComsSetup { } /** - * Test data generator. This method is called the the JUnit parameterized test - * runner and returns a Collection of Arrays. For each Array in the - * Collection, each array element corresponds to a parameter in the - * constructor. + * Test data generator. This method is called the the JUnit parametrized test runner and returns + * a Collection of Arrays. For each Array in the Collection, each array element corresponds to a + * parameter in the constructor. */ @Parameters public static Collection generateData() { @@ -59,32 +57,29 @@ public class EncoderTest extends AbstractComsSetup { } /** - * Constructs a parameterized Encoder Test - *$ - * @param inputA The port number for inputA + * Constructs a parametrized Encoder Test. + * + * @param inputA The port number for inputA * @param outputA The port number for outputA - * @param inputB The port number for inputB + * @param inputB The port number for inputB * @param outputB The port number for outputB - * @param flip whether or not these set of values require the encoder to be - * reversed (0 or 1) + * @param flip whether or not these set of values require the encoder to be reversed (0 or 1) */ public EncoderTest(int inputA, int outputA, int inputB, int outputB, int flip) { - this.inputA = inputA; - this.inputB = inputB; - this.outputA = outputA; - this.outputB = outputB; + m_inputA = inputA; + m_inputB = inputB; + m_outputA = outputA; + m_outputB = outputB; // If the encoder from a previous test is allocated then we must free its // members - if (encoder != null) + if (encoder != null) { encoder.teardown(); - this.flip = flip == 0; + } + m_flip = flip == 0; encoder = new FakeEncoderFixture(inputA, outputA, inputB, outputB); } - /** - * @throws java.lang.Exception - */ @AfterClass public static void tearDownAfterClass() throws Exception { encoder.teardown(); @@ -92,9 +87,7 @@ public class EncoderTest extends AbstractComsSetup { } /** - * Sets up the test and verifies that the test was reset to the default state - *$ - * @throws java.lang.Exception + * Sets up the test and verifies that the test was reset to the default state. */ @Before public void setUp() throws Exception { @@ -102,16 +95,13 @@ public class EncoderTest extends AbstractComsSetup { testDefaultState(); } - /** - * @throws java.lang.Exception - */ @After public void tearDown() throws Exception { encoder.reset(); } /** - * Tests to see if Encoders initialize to zero + * Tests to see if Encoders initialize to zero. */ @Test public void testDefaultState() { @@ -120,13 +110,13 @@ public class EncoderTest extends AbstractComsSetup { } /** - * Tests to see if Encoders can count up sucsessfully + * Tests to see if Encoders can count up successfully. */ @Test public void testCountUp() { int goal = 100; encoder.getFakeEncoderSource().setCount(goal); - encoder.getFakeEncoderSource().setForward(flip); + encoder.getFakeEncoderSource().setForward(m_flip); encoder.getFakeEncoderSource().execute(); int value = encoder.getEncoder().get(); assertTrue(errorMessage(goal, value), value == goal); @@ -134,13 +124,13 @@ public class EncoderTest extends AbstractComsSetup { } /** - * Tests to see if Encoders can count down sucsessfully + * Tests to see if Encoders can count down successfully. */ @Test public void testCountDown() { int goal = -100; encoder.getFakeEncoderSource().setCount(goal); // Goal has to be positive - encoder.getFakeEncoderSource().setForward(!flip); + encoder.getFakeEncoderSource().setForward(!m_flip); encoder.getFakeEncoderSource().execute(); int value = encoder.getEncoder().get(); assertTrue(errorMessage(goal, value), value == goal); @@ -148,16 +138,14 @@ public class EncoderTest extends AbstractComsSetup { } /** - * Creates a simple message with the error that was encounterd for the - * Encoders - *$ - * @param goal The goal that was trying to be reached + * Creates a simple message with the error that was encountered for the Encoders. + * + * @param goal The goal that was trying to be reached * @param trueValue The actual value that was reached by the test - * @return A fully constructed message with data about where and why the the - * test failed + * @return A fully constructed message with data about where and why the the test failed. */ private String errorMessage(int goal, int trueValue) { - return "Encoder ({In,Out}): {" + inputA + ", " + outputA + "},{" + inputB + ", " + outputB - + "} Returned: " + trueValue + ", Wanted: " + goal; + return "Encoder ({In,Out}): {" + m_inputA + ", " + m_outputA + "},{" + m_inputB + ", " + + m_outputB + "} Returned: " + trueValue + ", Wanted: " + goal; } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterNoiseTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterNoiseTest.java index 12312cb583..f571342487 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterNoiseTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterNoiseTest.java @@ -7,12 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -21,10 +15,16 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Arrays; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.FilterNoiseFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertTrue; + @RunWith(Parameterized.class) public class FilterNoiseTest extends AbstractComsSetup { @@ -37,18 +37,24 @@ public class FilterNoiseTest extends AbstractComsSetup { return logger; } + /** + * Constructs the FilterNoiseTest. + * + * @param mef The fixture under test. + */ public FilterNoiseTest(FilterNoiseFixture mef) { logger.fine("Constructor with: " + mef.getType()); - if (me != null && !me.equals(mef)) + if (me != null && !me.equals(mef)) { me.teardown(); + } me = mef; } @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { - return Arrays.asList(new FilterNoiseFixture[][] { - {TestBench.getInstance().getSinglePoleIIRNoiseFixture()}, - {TestBench.getInstance().getMovAvgNoiseFixture()}}); + return Arrays.asList(new FilterNoiseFixture[][]{ + {TestBench.getInstance().getSinglePoleIIRNoiseFixture()}, + {TestBench.getInstance().getMovAvgNoiseFixture()}}); } @Before @@ -69,11 +75,10 @@ public class FilterNoiseTest extends AbstractComsSetup { } /** - * Test if the filter reduces the noise produced by a signal generator + * Test if the filter reduces the noise produced by a signal generator. */ @Test public void testNoiseReduce() { - double theoryData = 0.0; double noiseGenError = 0.0; double filterError = 0.0; @@ -81,11 +86,12 @@ public class FilterNoiseTest extends AbstractComsSetup { noise.reset(); for (double t = 0; t < TestBench.kFilterTime; t += TestBench.kFilterStep) { - theoryData = noise.getData(t); + final double theoryData = noise.getData(t); filterError += Math.abs(me.getFilter().pidGet() - theoryData); noiseGenError += Math.abs(noise.get() - theoryData); } - assertTrue(me.getType() + " should have reduced noise accumulation from " + noiseGenError + " but failed. The filter error was " + filterError, noiseGenError > filterError); + assertTrue(me.getType() + " should have reduced noise accumulation from " + noiseGenError + + " but failed. The filter error was " + filterError, noiseGenError > filterError); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterOutputTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterOutputTest.java index 6aed5a723f..2affc83b4b 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterOutputTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/FilterOutputTest.java @@ -7,12 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -21,16 +15,22 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Arrays; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.FilterOutputFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertEquals; + @RunWith(Parameterized.class) public class FilterOutputTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(FilterOutputTest.class.getName()); - private double expectedOutput; + private double m_expectedOutput; private static FilterOutputFixture me = null; @@ -39,20 +39,26 @@ public class FilterOutputTest extends AbstractComsSetup { return logger; } + /** + * Constructs a filter output test. + * + * @param mef The fixture under test. + */ public FilterOutputTest(FilterOutputFixture mef) { logger.fine("Constructor with: " + mef.getType()); - if (me != null && !me.equals(mef)) + if (me != null && !me.equals(mef)) { me.teardown(); + } me = mef; - expectedOutput = me.getExpectedOutput(); + m_expectedOutput = me.getExpectedOutput(); } @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { - return Arrays.asList(new FilterOutputFixture[][] { - {TestBench.getInstance().getSinglePoleIIROutputFixture()}, - {TestBench.getInstance().getHighPassOutputFixture()}, - {TestBench.getInstance().getMovAvgOutputFixture()}}); + return Arrays.asList(new FilterOutputFixture[][]{ + {TestBench.getInstance().getSinglePoleIIROutputFixture()}, + {TestBench.getInstance().getHighPassOutputFixture()}, + {TestBench.getInstance().getMovAvgOutputFixture()}}); } @Before @@ -73,7 +79,7 @@ public class FilterOutputTest extends AbstractComsSetup { } /** - * Test if the filter produces consistent output for a given data set + * Test if the filter produces consistent output for a given data set. */ @Test public void testOutput() { @@ -84,6 +90,6 @@ public class FilterOutputTest extends AbstractComsSetup { filterOutput = me.getFilter().pidGet(); } - assertEquals(me.getType() + " output was incorrect.", expectedOutput, filterOutput, 0.00005); + assertEquals(me.getType() + " output was incorrect.", m_expectedOutput, filterOutput, 0.00005); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java index c878a64d31..d2ca6b8522 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java @@ -7,25 +7,28 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; - -import java.util.logging.Logger; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.TiltPanCameraFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertEquals; + +/** + * Tests that the {@link TiltPanCameraFixture}. + */ public class GyroTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(GyroTest.class.getName()); public static final double TEST_ANGLE = 90.0; - private TiltPanCameraFixture tpcam; + private TiltPanCameraFixture m_tpcam; @Override protected Logger getClassLogger() { @@ -35,20 +38,20 @@ public class GyroTest extends AbstractComsSetup { @Before public void setUp() throws Exception { logger.fine("Setup: TiltPan camera"); - tpcam = TestBench.getInstance().getTiltPanCam(); - tpcam.setup(); + m_tpcam = TestBench.getInstance().getTiltPanCam(); + m_tpcam.setup(); } @After public void tearDown() throws Exception { - tpcam.teardown(); + m_tpcam.teardown(); } @Test public void testAllGyroTests() { - testInitial(tpcam.getGyro()); - testDeviationOverTime(tpcam.getGyro()); - testGyroAngle(tpcam.getGyro()); + testInitial(m_tpcam.getGyro()); + testDeviationOverTime(m_tpcam.getGyro()); + testGyroAngle(m_tpcam.getGyro()); testGyroAngleCalibratedParameters(); } @@ -58,15 +61,14 @@ public class GyroTest extends AbstractComsSetup { } /** - * Test to see if the Servo and the gyroscope is turning 90 degrees Note servo - * on TestBench is not the same type of servo that servo class was designed - * for so setAngle is significantly off. This has been calibrated for the - * servo on the rig. + * Test to see if the Servo and the gyroscope is turning 90 degrees Note servo on TestBench is not + * the same type of servo that servo class was designed for so setAngle is significantly off. This + * has been calibrated for the servo on the rig. */ public void testGyroAngle(AnalogGyro gyro) { // Set angle for (int i = 0; i < 5; i++) { - tpcam.getPan().set(0); + m_tpcam.getPan().set(0); Timer.delay(.1); } @@ -77,7 +79,7 @@ public class GyroTest extends AbstractComsSetup { // Perform test for (int i = 0; i < 53; i++) { - tpcam.getPan().set(i / 100.0); + m_tpcam.getPan().set(i / 100.0); Timer.delay(0.05); } Timer.delay(1.2); @@ -91,7 +93,8 @@ public class GyroTest extends AbstractComsSetup { assertEquals(errorMessage(diff, TEST_ANGLE), TEST_ANGLE, angle, 10); } - public void testDeviationOverTime(AnalogGyro gyro) { + + protected void testDeviationOverTime(AnalogGyro gyro) { // Make sure that the test isn't influenced by any previous motions. Timer.delay(0.5); gyro.reset(); @@ -104,20 +107,20 @@ public class GyroTest extends AbstractComsSetup { } /** - * Gets calibrated parameters from already calibrated gyro, allocates a - * new gyro with the center and offset parameters, and re-runs the test. + * Gets calibrated parameters from already calibrated gyro, allocates a new gyro with the center + * and offset parameters, and re-runs the test. */ public void testGyroAngleCalibratedParameters() { // Get calibrated parameters to make new Gyro with parameters - double cOffset = tpcam.getGyro().getOffset(); - int cCenter = tpcam.getGyro().getCenter(); - tpcam.freeGyro(); - tpcam.setupGyroParam(cCenter, cOffset); + final double calibratedOffset = m_tpcam.getGyro().getOffset(); + final int calibratedCenter = m_tpcam.getGyro().getCenter(); + m_tpcam.freeGyro(); + m_tpcam.setupGyroParam(calibratedCenter, calibratedOffset); Timer.delay(TiltPanCameraFixture.RESET_TIME); // Repeat tests - testInitial(tpcam.getGyroParam()); - testDeviationOverTime(tpcam.getGyroParam()); - testGyroAngle(tpcam.getGyroParam()); + testInitial(m_tpcam.getGyroParam()); + testDeviationOverTime(m_tpcam.getGyroParam()); + testGyroAngle(m_tpcam.getGyroParam()); } private String errorMessage(double difference, double target) { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java index b5c68253a7..c9edaf6f72 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java @@ -7,14 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -23,10 +15,18 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Arrays; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + @RunWith(Parameterized.class) public class MotorEncoderTest extends AbstractComsSetup { @@ -43,17 +43,23 @@ public class MotorEncoderTest extends AbstractComsSetup { return logger; } + /** + * Constructs the test + * + * @param mef The fixture under test. + */ public MotorEncoderTest(MotorEncoderFixture mef) { logger.fine("Constructor with: " + mef.getType()); - if (me != null && !me.equals(mef)) + if (me != null && !me.equals(mef)) { me.teardown(); + } me = mef; } @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList(new MotorEncoderFixture[][] { {TestBench.getInstance().getTalonPair()}, + return Arrays.asList(new MotorEncoderFixture[][]{{TestBench.getInstance().getTalonPair()}, {TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}}); } @@ -80,9 +86,8 @@ public class MotorEncoderTest extends AbstractComsSetup { } /** - * Test to ensure that the isMotorWithinRange method is functioning properly. - * Really only needs to run on one MotorEncoderFixture to ensure that it is - * working correctly. + * Test to ensure that the isMotorWithinRange method is functioning properly. Really only needs to + * run on one MotorEncoderFixture to ensure that it is working correctly. */ @Test public void testIsMotorWithinRange() { @@ -94,8 +99,8 @@ public class MotorEncoderTest extends AbstractComsSetup { } /** - * This test is designed to see if the values of different motors will - * increment when spun forward + * This test is designed to see if the values of different motors will increment when spun + * forward. */ @Test public void testIncrement() { @@ -110,8 +115,8 @@ public class MotorEncoderTest extends AbstractComsSetup { } /** - * This test is designed to see if the values of different motors will - * decrement when spun in reverse + * This test is designed to see if the values of different motors will decrement when spun in + * reverse. */ @Test public void testDecrement() { @@ -125,12 +130,12 @@ public class MotorEncoderTest extends AbstractComsSetup { } /** - * This method test if the counters count when the motors rotate + * This method test if the counters count when the motors rotate. */ @Test public void testCounter() { - int counter1Start = me.getCounters()[0].get(); - int counter2Start = me.getCounters()[1].get(); + final int counter1Start = me.getCounters()[0].get(); + final int counter2Start = me.getCounters()[1].get(); me.getMotor().set(.75); Timer.delay(MOTOR_RUNTIME); @@ -145,8 +150,8 @@ public class MotorEncoderTest extends AbstractComsSetup { } /** - * Tests to see if you set the speed to something not {@literal <=} 1.0 if the code - * appropriately throttles the value + * Tests to see if you set the speed to something not {@literal <=} 1.0 if the code appropriately + * throttles the value. */ @Test public void testSetHighForwardSpeed() { @@ -156,8 +161,8 @@ public class MotorEncoderTest extends AbstractComsSetup { } /** - * Tests to see if you set the speed to something not {@literal >=} -1.0 if the code - * appropriately throttles the value + * Tests to see if you set the speed to something not {@literal >=} -1.0 if the code appropriately + * throttles the value. */ @Test public void testSetHighReverseSpeed() { @@ -180,8 +185,8 @@ public class MotorEncoderTest extends AbstractComsSetup { pid.disable(); assertTrue( - "PID loop did not reach setpoint within 10 seconds. The average error was: " + pid.getAvgError() + - "The current error was" + pid.getError(), pid.onTarget()); + "PID loop did not reach setpoint within 10 seconds. The average error was: " + pid + .getAvgError() + "The current error was" + pid.getError(), pid.onTarget()); pid.free(); } @@ -208,9 +213,8 @@ public class MotorEncoderTest extends AbstractComsSetup { } /** - * Checks to see if the encoders and counters are appropriately reset to zero - * when reset - *$ + * Checks to see if the encoders and counters are appropriately reset to zero when reset. + * * @param me The MotorEncoderFixture under test */ private void encodersResetCheck(MotorEncoderFixture me) { @@ -223,7 +227,7 @@ public class MotorEncoderTest extends AbstractComsSetup { assertEquals(me.getType() + " Counter2 value was incorrect after reset.", me.getCounters()[1].get(), 0); Timer.delay(0.5); // so this doesn't fail with the 0.5 second default - // timeout on the encoders + // timeout on the encoders assertTrue(me.getType() + " Encoder.getStopped() returned false after the motor was reset.", me .getEncoder().getStopped()); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java index 0245ca101f..5de201e850 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java @@ -7,25 +7,26 @@ package edu.wpi.first.wpilibj; -import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; -import edu.wpi.first.wpilibj.test.AbstractComsSetup; - -import edu.wpi.first.wpilibj.test.TestBench; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.logging.Logger; +import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; +import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import edu.wpi.first.wpilibj.test.TestBench; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** - * Tests Inversion of motors using the SpeedController setInverted + * Tests Inversion of motors using the SpeedController setInverted. */ @RunWith(Parameterized.class) public class MotorInvertingTest extends AbstractComsSetup { @@ -34,18 +35,24 @@ public class MotorInvertingTest extends AbstractComsSetup { private static final double delaytime = 0.3; + /** + * Constructs the test. + * + * @param afixture The fixture under test. + */ public MotorInvertingTest(MotorEncoderFixture afixture) { logger.fine("Constructor with: " + afixture.getType()); - if (fixture != null && !fixture.equals(afixture)) + if (fixture != null && !fixture.equals(afixture)) { fixture.teardown(); + } fixture = afixture; fixture.setup(); } - @Parameterized.Parameters(name = "{index}: {0}") + @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList(new MotorEncoderFixture[][] { {TestBench.getInstance().getTalonPair()}, + return Arrays.asList(new MotorEncoderFixture[][]{{TestBench.getInstance().getTalonPair()}, {TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}}); } @@ -74,7 +81,7 @@ public class MotorInvertingTest extends AbstractComsSetup { fixture.getMotor().setInverted(false); fixture.getMotor().set(motorspeed); Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); + final boolean initDirection = fixture.getEncoder().getDirection(); fixture.getMotor().setInverted(true); fixture.getMotor().set(motorspeed); Timer.delay(delaytime); @@ -88,7 +95,7 @@ public class MotorInvertingTest extends AbstractComsSetup { fixture.getMotor().setInverted(false); fixture.getMotor().set(-motorspeed); Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); + final boolean initDirection = fixture.getEncoder().getDirection(); fixture.getMotor().setInverted(true); fixture.getMotor().set(-motorspeed); Timer.delay(delaytime); @@ -102,7 +109,7 @@ public class MotorInvertingTest extends AbstractComsSetup { fixture.getMotor().setInverted(false); fixture.getMotor().set(motorspeed); Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); + final boolean initDirection = fixture.getEncoder().getDirection(); fixture.getMotor().setInverted(true); fixture.getMotor().set(-motorspeed); Timer.delay(delaytime); @@ -116,7 +123,7 @@ public class MotorInvertingTest extends AbstractComsSetup { fixture.getMotor().setInverted(false); fixture.getMotor().set(-motorspeed); Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); + final boolean initDirection = fixture.getEncoder().getDirection(); fixture.getMotor().setInverted(true); fixture.getMotor().set(motorspeed); Timer.delay(delaytime); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java index 373afdea91..9a273a0625 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java @@ -7,22 +7,23 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.*; - -import java.util.concurrent.Delayed; -import java.util.logging.Logger; - -import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** - * @author Kacper Puczydlowski + * Test that covers the {@link Compressor}. * + * @author Kacper Puczydlowski */ public class PCMTest extends AbstractComsSetup { @@ -48,7 +49,8 @@ public class PCMTest extends AbstractComsSetup { private static DigitalOutput fakePressureSwitch; private static AnalogInput fakeCompressor; - private static DigitalInput fakeSolenoid1, fakeSolenoid2; + private static DigitalInput fakeSolenoid1; + private static DigitalInput fakeSolenoid2; @BeforeClass public static void setUpBeforeClass() throws Exception { @@ -72,24 +74,18 @@ public class PCMTest extends AbstractComsSetup { fakeSolenoid2.free(); } - @Before - public void setUp() throws Exception {} - @Before public void reset() throws Exception { compressor.stop(); fakePressureSwitch.set(false); } - @After - public void tearDown() throws Exception {} - /** - * Test if the compressor turns on and off when the pressure switch is toggled + * Test if the compressor turns on and off when the pressure switch is toggled. */ @Test public void testPressureSwitch() throws Exception { - double range = 0.5; + final double range = 0.1; reset(); compressor.setClosedLoopControl(true); @@ -107,7 +103,7 @@ public class PCMTest extends AbstractComsSetup { } /** - * Test if the correct solenoids turn on and off when they should + * Test if the correct solenoids turn on and off when they should. */ @Test public void testSolenoid() throws Exception { @@ -156,8 +152,8 @@ public class PCMTest extends AbstractComsSetup { } /** - * Test if the correct solenoids turn on and off when they should when used - * with the DoubleSolenoid class. + * Test if the correct solenoids turn on and off when they should when used with the + * DoubleSolenoid class. */ @Test public void doubleSolenoid() { @@ -173,13 +169,15 @@ public class PCMTest extends AbstractComsSetup { Timer.delay(kSolenoidDelayTime); assertFalse("Solenoid #1 did not turn on", fakeSolenoid1.get()); assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get()); - assertTrue("DoubleSolenoid did not report Forward", (solenoid.get() == DoubleSolenoid.Value.kForward)); + assertTrue("DoubleSolenoid did not report Forward", (solenoid.get() == DoubleSolenoid.Value + .kForward)); solenoid.set(DoubleSolenoid.Value.kReverse); Timer.delay(kSolenoidDelayTime); assertTrue("Solenoid #1 did not turn off", fakeSolenoid1.get()); assertFalse("Solenoid #2 did not turn on", fakeSolenoid2.get()); - assertTrue("DoubleSolenoid did not report Reverse", (solenoid.get() == DoubleSolenoid.Value.kReverse)); + assertTrue("DoubleSolenoid did not report Reverse", (solenoid.get() == DoubleSolenoid.Value + .kReverse)); solenoid.free(); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java index cd65d1a8d3..e02b4df88c 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java @@ -7,15 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.Arrays; -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -24,18 +15,30 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Arrays; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.can.CANMessageNotFoundException; import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +/** + * Test that covers the {@link PowerDistributionPanel}. + */ @RunWith(Parameterized.class) public class PDPTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(PCMTest.class.getName()); private static PowerDistributionPanel pdp; private static MotorEncoderFixture me; - private final double expectedStoppedCurrentDraw; + private final double m_expectedStoppedCurrentDraw; @BeforeClass public static void setUpBeforeClass() throws Exception { @@ -51,20 +54,22 @@ public class PDPTest extends AbstractComsSetup { } + @SuppressWarnings("JavadocMethod") public PDPTest(MotorEncoderFixture mef, Double expectedCurrentDraw) { logger.fine("Constructor with: " + mef.getType()); - if (me != null && !me.equals(mef)) + if (me != null && !me.equals(mef)) { me.teardown(); + } me = mef; me.setup(); - this.expectedStoppedCurrentDraw = expectedCurrentDraw; + m_expectedStoppedCurrentDraw = expectedCurrentDraw; } @Parameters(name = "{index}: {0}, Expected Stopped Current Draw: {1}") public static Collection generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList(new Object[][] { + return Arrays.asList(new Object[][]{ {TestBench.getInstance().getTalonPair(), new Double(0.0)}}); } @@ -74,24 +79,23 @@ public class PDPTest extends AbstractComsSetup { } - /** - * Test if the current changes when the motor is driven using a talon + * Test if the current changes when the motor is driven using a talon. */ @Test - public void CheckStoppedCurrentForSpeedController() throws CANMessageNotFoundException { + public void checkStoppedCurrentForSpeedController() throws CANMessageNotFoundException { Timer.delay(0.25); /* The Current should be 0 */ - assertEquals("The low current was not within the expected range.", expectedStoppedCurrentDraw, + assertEquals("The low current was not within the expected range.", m_expectedStoppedCurrentDraw, pdp.getCurrent(me.getPDPChannel()), 0.001); } /** - * Test if the current changes when the motor is driven using a talon + * Test if the current changes when the motor is driven using a talon. */ @Test - public void CheckRunningCurrentForSpeedController() throws CANMessageNotFoundException { + public void checkRunningCurrentForSpeedController() throws CANMessageNotFoundException { /* Set the motor to full forward */ me.getMotor().set(1.0); @@ -99,7 +103,7 @@ public class PDPTest extends AbstractComsSetup { /* The current should now be greater than the low current */ assertThat("The driven current is not greater than the resting current.", - pdp.getCurrent(me.getPDPChannel()), is(greaterThan(expectedStoppedCurrentDraw))); + pdp.getCurrent(me.getPDPChannel()), is(greaterThan(m_expectedStoppedCurrentDraw))); } @Override diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java index 948019e64c..80d9411d2a 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java @@ -7,18 +7,6 @@ package edu.wpi.first.wpilibj; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.logging.Logger; - import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -28,29 +16,43 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + /** + * Test that covers the {@link PIDController}. + * * @author Kacper Puczydlowski * @author Jonathan Leitschuh - * */ @RunWith(Parameterized.class) public class PIDTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(PIDTest.class.getName()); - private NetworkTable table; + private NetworkTable m_table; private static final double absoluteTolerance = 50; private static final double outputRange = 0.25; - private PIDController controller = null; + private PIDController m_controller = null; private static MotorEncoderFixture me = null; + @SuppressWarnings({"MemberName", "EmptyLineSeparator", "MultipleVariableDeclarations"}) private final Double k_p, k_i, k_d; @Override @@ -59,10 +61,12 @@ public class PIDTest extends AbstractComsSetup { } + @SuppressWarnings({"ParameterName", "JavadocMethod"}) public PIDTest(Double p, Double i, Double d, MotorEncoderFixture mef) { logger.fine("Constructor with: " + mef.getType()); - if (PIDTest.me != null && !PIDTest.me.equals(mef)) + if (PIDTest.me != null && !PIDTest.me.equals(mef)) { PIDTest.me.teardown(); + } PIDTest.me = mef; this.k_p = p; this.k_i = i; @@ -78,7 +82,7 @@ public class PIDTest extends AbstractComsSetup { double ki = 0.0005; double kd = 0.0; for (int i = 0; i < 1; i++) { - data.addAll(Arrays.asList(new Object[][] { + data.addAll(Arrays.asList(new Object[][]{ {kp, ki, kd, TestBench.getInstance().getTalonPair()}, {kp, ki, kd, TestBench.getInstance().getVictorPair()}, {kp, ki, kd, TestBench.getInstance().getJaguarPair()}})); @@ -86,15 +90,10 @@ public class PIDTest extends AbstractComsSetup { return data; } - /** - * @throws java.lang.Exception - */ @BeforeClass - public static void setUpBeforeClass() throws Exception {} + public static void setUpBeforeClass() throws Exception { + } - /** - * @throws java.lang.Exception - */ @AfterClass public static void tearDownAfterClass() throws Exception { logger.fine("TearDownAfterClass: " + me.getType()); @@ -102,36 +101,30 @@ public class PIDTest extends AbstractComsSetup { me = null; } - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { logger.fine("Setup: " + me.getType()); me.setup(); - table = NetworkTable.getTable("TEST_PID"); - controller = new PIDController(k_p, k_i, k_d, me.getEncoder(), me.getMotor()); - controller.initTable(table); + m_table = NetworkTable.getTable("TEST_PID"); + m_controller = new PIDController(k_p, k_i, k_d, me.getEncoder(), me.getMotor()); + m_controller.initTable(m_table); } - /** - * @throws java.lang.Exception - */ @After public void tearDown() throws Exception { logger.fine("Teardown: " + me.getType()); - controller.disable(); - controller.free(); - controller = null; + m_controller.disable(); + m_controller.free(); + m_controller = null; me.reset(); } private void setupAbsoluteTolerance() { - controller.setAbsoluteTolerance(absoluteTolerance); + m_controller.setAbsoluteTolerance(absoluteTolerance); } private void setupOutputRange() { - controller.setOutputRange(-outputRange, outputRange); + m_controller.setOutputRange(-outputRange, outputRange); } @Test @@ -139,14 +132,15 @@ public class PIDTest extends AbstractComsSetup { setupAbsoluteTolerance(); setupOutputRange(); double setpoint = 2500.0; - controller.setSetpoint(setpoint); - assertFalse("PID did not begin disabled", controller.isEnable()); - assertEquals("PID.getError() did not start at " + setpoint, setpoint, controller.getError(), 0); - assertEquals(k_p, table.getNumber("p"), 0); - assertEquals(k_i, table.getNumber("i"), 0); - assertEquals(k_d, table.getNumber("d"), 0); - assertEquals(setpoint, table.getNumber("setpoint"), 0); - assertFalse(table.getBoolean("enabled")); + m_controller.setSetpoint(setpoint); + assertFalse("PID did not begin disabled", m_controller.isEnable()); + assertEquals("PID.getError() did not start at " + setpoint, setpoint, + m_controller.getError(), 0); + assertEquals(k_p, m_table.getNumber("p"), 0); + assertEquals(k_i, m_table.getNumber("i"), 0); + assertEquals(k_d, m_table.getNumber("d"), 0); + assertEquals(setpoint, m_table.getNumber("setpoint"), 0); + assertFalse(m_table.getBoolean("enabled")); } @Test @@ -154,15 +148,15 @@ public class PIDTest extends AbstractComsSetup { setupAbsoluteTolerance(); setupOutputRange(); double setpoint = 2500.0; - controller.setSetpoint(setpoint); - controller.enable(); + m_controller.setSetpoint(setpoint); + m_controller.enable(); Timer.delay(.5); - assertTrue(table.getBoolean("enabled")); - assertTrue(controller.isEnable()); + assertTrue(m_table.getBoolean("enabled")); + assertTrue(m_controller.isEnable()); assertThat(0.0, is(not(me.getMotor().get()))); - controller.reset(); - assertFalse(table.getBoolean("enabled")); - assertFalse(controller.isEnable()); + m_controller.reset(); + assertFalse(m_table.getBoolean("enabled")); + assertFalse(m_controller.isEnable()); assertEquals(0, me.getMotor().get(), 0); } @@ -171,10 +165,11 @@ public class PIDTest extends AbstractComsSetup { setupAbsoluteTolerance(); setupOutputRange(); Double setpoint = 2500.0; - controller.disable(); - controller.setSetpoint(setpoint); - controller.enable(); - assertEquals("Did not correctly set set-point", setpoint, new Double(controller.getSetpoint())); + m_controller.disable(); + m_controller.setSetpoint(setpoint); + m_controller.enable(); + assertEquals("Did not correctly set set-point", setpoint, new Double(m_controller + .getSetpoint())); } @Test(timeout = 10000) @@ -182,26 +177,26 @@ public class PIDTest extends AbstractComsSetup { setupAbsoluteTolerance(); setupOutputRange(); double setpoint = 1000.0; - assertEquals(pidData() + "did not start at 0", 0, controller.get(), 0); - controller.setSetpoint(setpoint); + assertEquals(pidData() + "did not start at 0", 0, m_controller.get(), 0); + m_controller.setSetpoint(setpoint); assertEquals(pidData() + "did not have an error of " + setpoint, setpoint, - controller.getError(), 0); - controller.enable(); + m_controller.getError(), 0); + m_controller.enable(); Timer.delay(5); - controller.disable(); - assertTrue(pidData() + "Was not on Target. Controller Error: " + controller.getError(), - controller.onTarget()); + m_controller.disable(); + assertTrue(pidData() + "Was not on Target. Controller Error: " + m_controller.getError(), + m_controller.onTarget()); } private String pidData() { - return me.getType() + " PID {P:" + controller.getP() + " I:" + controller.getI() + " D:" - + controller.getD() + "} "; + return me.getType() + " PID {P:" + m_controller.getP() + " I:" + m_controller.getI() + " D:" + + m_controller.getD() + "} "; } @Test(expected = RuntimeException.class) public void testOnTargetNoToleranceSet() { setupOutputRange(); - controller.onTarget(); + m_controller.onTarget(); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDToleranceTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDToleranceTest.java index 12059afa53..b373b38b7c 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDToleranceTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDToleranceTest.java @@ -1,88 +1,105 @@ package edu.wpi.first.wpilibj; -import java.util.logging.Logger; - import org.junit.After; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; + +import java.util.logging.Logger; import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class PIDToleranceTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(PIDToleranceTest.class.getName()); - private PIDController pid; - private final double setPoint = 50.0; - private final double tolerance = 10.0; - private final double range = 200; - private class fakeInput implements PIDSource{ - public double val; - public fakeInput(){ - val = 0; - } - @Override - public PIDSourceType getPIDSourceType() { - return PIDSourceType.kDisplacement; - } + private static final Logger logger = Logger.getLogger(PIDToleranceTest.class.getName()); + private PIDController m_pid; + private final double m_setPoint = 50.0; + private final double m_tolerance = 10.0; + private final double m_range = 200; - @Override - public double pidGet() { - return val; - } + private class FakeInput implements PIDSource { + public double m_val; - @Override - public void setPIDSourceType(PIDSourceType arg0) {} - }; - private fakeInput inp; - private PIDOutput out = new PIDOutput(){ - @Override - public void pidWrite(double out) { - } - - }; - @Override - protected Logger getClassLogger() { - return logger; - } - @Before - public void setUp() throws Exception{ - inp = new fakeInput(); - pid = new PIDController(0.05,0.0,0.0,inp,out); - pid.setInputRange(-range/2, range/2); - } - - @After - public void tearDown() throws Exception{ - pid.free(); - pid = null; - } - - @Test - public void testAbsoluteTolerance(){ - pid.setAbsoluteTolerance(tolerance); - pid.setSetpoint(setPoint); - pid.enable(); - Timer.delay(1); - assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget()); - inp.val = setPoint+tolerance/2; - Timer.delay(1.0); - assertTrue("Error was not in tolerance when it should have been. Error was "+pid.getAvgError(),pid.onTarget()); - inp.val = setPoint + 10*tolerance; - Timer.delay(1.0); - assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget()); - } - @Test - public void testPercentTolerance(){ - pid.setPercentTolerance(tolerance); - pid.setSetpoint(setPoint); - pid.enable(); - assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget()); - inp.val = setPoint+(tolerance)/200*range;//half of percent tolerance away from setPoint - Timer.delay(1.0); - assertTrue("Error was not in tolerance when it should have been. Error was "+pid.getAvgError(),pid.onTarget()); - inp.val = setPoint + (tolerance)/50*range;//double percent tolerance away from setPoint - Timer.delay(1.0); - assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget()); - } + public FakeInput() { + m_val = 0; + } + + @Override + public PIDSourceType getPIDSourceType() { + return PIDSourceType.kDisplacement; + } + + @Override + public double pidGet() { + return m_val; + } + + @Override + public void setPIDSourceType(PIDSourceType arg0) { + } + } + + private FakeInput m_inp; + private PIDOutput m_out = new PIDOutput() { + @Override + public void pidWrite(double out) { + } + + }; + + @Override + protected Logger getClassLogger() { + return logger; + } + + @Before + public void setUp() throws Exception { + m_inp = new FakeInput(); + m_pid = new PIDController(0.05, 0.0, 0.0, m_inp, m_out); + m_pid.setInputRange(-m_range / 2, m_range / 2); + } + + @After + public void tearDown() throws Exception { + m_pid.free(); + m_pid = null; + } + + @Test + public void testAbsoluteTolerance() { + m_pid.setAbsoluteTolerance(m_tolerance); + m_pid.setSetpoint(m_setPoint); + m_pid.enable(); + Timer.delay(1); + assertFalse("Error was in tolerance when it should not have been. Error was " + + m_pid.getAvgError(), m_pid.onTarget()); + m_inp.m_val = m_setPoint + m_tolerance / 2; + Timer.delay(1.0); + assertTrue("Error was not in tolerance when it should have been. Error was " + + m_pid.getAvgError(), m_pid.onTarget()); + m_inp.m_val = m_setPoint + 10 * m_tolerance; + Timer.delay(1.0); + assertFalse("Error was in tolerance when it should not have been. Error was " + + m_pid.getAvgError(), m_pid.onTarget()); + } + + @Test + public void testPercentTolerance() { + m_pid.setPercentTolerance(m_tolerance); + m_pid.setSetpoint(m_setPoint); + m_pid.enable(); + assertFalse("Error was in tolerance when it should not have been. Error was " + + m_pid.getAvgError(), m_pid.onTarget()); + //half of percent tolerance away from setPoint + m_inp.m_val = m_setPoint + (m_tolerance) / 200 * m_range; + Timer.delay(1.0); + assertTrue("Error was not in tolerance when it should have been. Error was " + + m_pid.getAvgError(), m_pid.onTarget()); + //double percent tolerance away from setPoint + m_inp.m_val = m_setPoint + (m_tolerance) / 50 * m_range; + Timer.delay(1.0); + assertFalse("Error was in tolerance when it should not have been. Error was " + + m_pid.getAvgError(), m_pid.onTarget()); + } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PreferencesTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PreferencesTest.java index e8fb17c74c..176bfc202e 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PreferencesTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PreferencesTest.java @@ -7,9 +7,8 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; import java.io.File; import java.io.FileOutputStream; @@ -17,22 +16,24 @@ import java.io.IOException; import java.io.OutputStream; import java.util.logging.Logger; -import org.junit.Before; -import org.junit.Test; - import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** - * @author jonathanleitschuh + * Tests the {@link Preferences}. * + * @author jonathanleitschuh */ public class PreferencesTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(PreferencesTest.class.getName()); - private NetworkTable prefTable; - private Preferences pref; - private long check; + private NetworkTable m_prefTable; + private Preferences m_pref; + private long m_check; @Override protected Logger getClassLogger() { @@ -40,9 +41,6 @@ public class PreferencesTest extends AbstractComsSetup { } - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { NetworkTable.shutdown(); @@ -55,70 +53,75 @@ public class PreferencesTest extends AbstractComsSetup { file.createNewFile(); OutputStream output = new FileOutputStream(file); output - .write("[NetworkTables Storage 3.0]\ndouble \"/Preferences/checkedValueInt\"=2\ndouble \"/Preferences/checkedValueDouble\"=.2\ndouble \"/Preferences/checkedValueFloat\"=3.14\ndouble \"/Preferences/checkedValueLong\"=172\nstring \"/Preferences/checkedValueString\"=\"hello \\nHow are you ?\"\nboolean \"/Preferences/checkedValueBoolean\"=false\n" + .write(("[NetworkTables Storage 3.0]\ndouble \"/Preferences/checkedValueInt\"=2\ndouble " + + "\"/Preferences/checkedValueDouble\"=.2\ndouble " + + "\"/Preferences/checkedValueFloat\"=3.14\ndouble " + + "\"/Preferences/checkedValueLong\"=172\nstring " + + "\"/Preferences/checkedValueString\"=\"hello \\nHow are you ?\"\nboolean " + + "\"/Preferences/checkedValueBoolean\"=false\n") .getBytes()); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); } NetworkTable.initialize(); - pref = Preferences.getInstance(); - prefTable = NetworkTable.getTable("Preferences"); - check = System.currentTimeMillis(); + m_pref = Preferences.getInstance(); + m_prefTable = NetworkTable.getTable("Preferences"); + m_check = System.currentTimeMillis(); } - public void remove() { - pref.remove("checkedValueLong"); - pref.remove("checkedValueDouble"); - pref.remove("checkedValueString"); - pref.remove("checkedValueInt"); - pref.remove("checkedValueFloat"); - pref.remove("checkedValueBoolean"); + protected void remove() { + m_pref.remove("checkedValueLong"); + m_pref.remove("checkedValueDouble"); + m_pref.remove("checkedValueString"); + m_pref.remove("checkedValueInt"); + m_pref.remove("checkedValueFloat"); + m_pref.remove("checkedValueBoolean"); } - public void addCheckedValue() { - pref.putLong("checkedValueLong", check); - pref.putDouble("checkedValueDouble", 1); - pref.putString("checkedValueString", "checked"); - pref.putInt("checkedValueInt", 1); - pref.putFloat("checkedValueFloat", 1); - pref.putBoolean("checkedValueBoolean", true); + protected void addCheckedValue() { + m_pref.putLong("checkedValueLong", m_check); + m_pref.putDouble("checkedValueDouble", 1); + m_pref.putString("checkedValueString", "checked"); + m_pref.putInt("checkedValueInt", 1); + m_pref.putFloat("checkedValueFloat", 1); + m_pref.putBoolean("checkedValueBoolean", true); } @Test public void testAddRemoveSave() { - assertEquals(pref.getLong("checkedValueLong", 0), 172L); - assertEquals(pref.getDouble("checkedValueDouble", 0), .2, 0); - assertEquals(pref.getString("checkedValueString", ""), "hello \nHow are you ?"); - assertEquals(pref.getInt("checkedValueInt", 0), 2); - assertEquals(pref.getFloat("checkedValueFloat", 0), 3.14, .001); - assertFalse(pref.getBoolean("checkedValueBoolean", true)); + assertEquals(m_pref.getLong("checkedValueLong", 0), 172L); + assertEquals(m_pref.getDouble("checkedValueDouble", 0), .2, 0); + assertEquals(m_pref.getString("checkedValueString", ""), "hello \nHow are you ?"); + assertEquals(m_pref.getInt("checkedValueInt", 0), 2); + assertEquals(m_pref.getFloat("checkedValueFloat", 0), 3.14, .001); + assertFalse(m_pref.getBoolean("checkedValueBoolean", true)); remove(); - assertEquals(pref.getLong("checkedValueLong", 0), 0); - assertEquals(pref.getDouble("checkedValueDouble", 0), 0, 0); - assertEquals(pref.getString("checkedValueString", ""), ""); - assertEquals(pref.getInt("checkedValueInt", 0), 0); - assertEquals(pref.getFloat("checkedValueFloat", 0), 0, 0); - assertFalse(pref.getBoolean("checkedValueBoolean", false)); + assertEquals(m_pref.getLong("checkedValueLong", 0), 0); + assertEquals(m_pref.getDouble("checkedValueDouble", 0), 0, 0); + assertEquals(m_pref.getString("checkedValueString", ""), ""); + assertEquals(m_pref.getInt("checkedValueInt", 0), 0); + assertEquals(m_pref.getFloat("checkedValueFloat", 0), 0, 0); + assertFalse(m_pref.getBoolean("checkedValueBoolean", false)); addCheckedValue(); - pref.save(); - assertEquals(check, pref.getLong("checkedValueLong", 0)); - assertEquals(pref.getDouble("checkedValueDouble", 0), 1, 0); - assertEquals(pref.getString("checkedValueString", ""), "checked"); - assertEquals(pref.getInt("checkedValueInt", 0), 1); - assertEquals(pref.getFloat("checkedValueFloat", 0), 1, 0); - assertTrue(pref.getBoolean("checkedValueBoolean", false)); + m_pref.save(); + assertEquals(m_check, m_pref.getLong("checkedValueLong", 0)); + assertEquals(m_pref.getDouble("checkedValueDouble", 0), 1, 0); + assertEquals(m_pref.getString("checkedValueString", ""), "checked"); + assertEquals(m_pref.getInt("checkedValueInt", 0), 1); + assertEquals(m_pref.getFloat("checkedValueFloat", 0), 1, 0); + assertTrue(m_pref.getBoolean("checkedValueBoolean", false)); } @Test public void testPreferencesToNetworkTables() { String networkedNumber = "networkCheckedValue"; int networkNumberValue = 100; - pref.putInt(networkedNumber, networkNumberValue); - assertEquals(networkNumberValue, (int)(prefTable.getNumber(networkedNumber))); - pref.remove(networkedNumber); + m_pref.putInt(networkedNumber, networkNumberValue); + assertEquals(networkNumberValue, (int) (m_prefTable.getNumber(networkedNumber))); + m_pref.remove(networkedNumber); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java index 524357f7e8..949f401823 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java @@ -7,18 +7,12 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.wpi.first.wpilibj.Relay.Direction; import edu.wpi.first.wpilibj.Relay.InvalidValueException; import edu.wpi.first.wpilibj.Relay.Value; @@ -27,87 +21,90 @@ import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** - * @author jonathanleitschuh + * Tests the {@link RelayCrossConnectFixture}. * + * @author jonathanleitschuh */ public class RelayCrossConnectTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(RelayCrossConnectTest.class.getName()); private static final NetworkTable table = NetworkTable.getTable("_RELAY_CROSS_CONNECT_TEST_"); - private RelayCrossConnectFixture relayFixture; + private RelayCrossConnectFixture m_relayFixture; - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { - relayFixture = TestBench.getRelayCrossConnectFixture(); - relayFixture.setup(); - relayFixture.getRelay().initTable(table); + m_relayFixture = TestBench.getRelayCrossConnectFixture(); + m_relayFixture.setup(); + m_relayFixture.getRelay().initTable(table); } - /** - * @throws java.lang.Exception - */ @After public void tearDown() throws Exception { - relayFixture.reset(); - relayFixture.teardown(); + m_relayFixture.reset(); + m_relayFixture.teardown(); } @Test public void testBothHigh() { - relayFixture.getRelay().setDirection(Direction.kBoth); - relayFixture.getRelay().set(Value.kOn); - relayFixture.getRelay().updateTable(); - assertTrue("Input one was not high when relay set both high", relayFixture.getInputOne().get()); - assertTrue("Input two was not high when relay set both high", relayFixture.getInputTwo().get()); + m_relayFixture.getRelay().setDirection(Direction.kBoth); + m_relayFixture.getRelay().set(Value.kOn); + m_relayFixture.getRelay().updateTable(); + assertTrue("Input one was not high when relay set both high", m_relayFixture.getInputOne() + .get()); + assertTrue("Input two was not high when relay set both high", m_relayFixture.getInputTwo() + .get()); assertEquals("On", table.getString("Value")); } @Test public void testFirstHigh() { - relayFixture.getRelay().setDirection(Direction.kBoth); - relayFixture.getRelay().set(Value.kForward); - relayFixture.getRelay().updateTable(); - assertFalse("Input one was not low when relay set Value.kForward", relayFixture.getInputOne() + m_relayFixture.getRelay().setDirection(Direction.kBoth); + m_relayFixture.getRelay().set(Value.kForward); + m_relayFixture.getRelay().updateTable(); + assertFalse("Input one was not low when relay set Value.kForward", m_relayFixture.getInputOne() .get()); - assertTrue("Input two was not high when relay set Value.kForward", relayFixture.getInputTwo() + assertTrue("Input two was not high when relay set Value.kForward", m_relayFixture + .getInputTwo() .get()); assertEquals("Forward", table.getString("Value")); } @Test public void testSecondHigh() { - relayFixture.getRelay().setDirection(Direction.kBoth); - relayFixture.getRelay().set(Value.kReverse); - relayFixture.getRelay().updateTable(); - assertTrue("Input one was not high when relay set Value.kReverse", relayFixture.getInputOne() + m_relayFixture.getRelay().setDirection(Direction.kBoth); + m_relayFixture.getRelay().set(Value.kReverse); + m_relayFixture.getRelay().updateTable(); + assertTrue("Input one was not high when relay set Value.kReverse", m_relayFixture.getInputOne() .get()); - assertFalse("Input two was not low when relay set Value.kReverse", relayFixture.getInputTwo() + assertFalse("Input two was not low when relay set Value.kReverse", m_relayFixture + .getInputTwo() .get()); assertEquals("Reverse", table.getString("Value")); } @Test(expected = InvalidValueException.class) public void testSetValueForwardWithDirectionReverseThrowingException() { - relayFixture.getRelay().setDirection(Direction.kForward); - relayFixture.getRelay().set(Value.kReverse); + m_relayFixture.getRelay().setDirection(Direction.kForward); + m_relayFixture.getRelay().set(Value.kReverse); } @Test(expected = InvalidValueException.class) public void testSetValueReverseWithDirectionForwardThrowingException() { - relayFixture.getRelay().setDirection(Direction.kReverse); - relayFixture.getRelay().set(Value.kForward); + m_relayFixture.getRelay().setDirection(Direction.kReverse); + m_relayFixture.getRelay().set(Value.kForward); } @Test public void testInitialSettings() { - assertEquals(Value.kOff, relayFixture.getRelay().get()); + assertEquals(Value.kOff, m_relayFixture.getRelay().get()); // Initially both outputs should be off - assertFalse(relayFixture.getInputOne().get()); - assertFalse(relayFixture.getInputTwo().get()); + assertFalse(m_relayFixture.getInputOne().get()); + assertFalse(m_relayFixture.getInputTwo().get()); assertEquals("Off", table.getString("Value")); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java index aa382e0db6..9259deb6c5 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java @@ -7,27 +7,24 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertTrue; - -import java.util.logging.Logger; - import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.fixtures.SampleFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; -import edu.wpi.first.wpilibj.CANTalon; +import static org.junit.Assert.assertTrue; /** - * Sample test for a sample PID controller. This demonstrates the general - * pattern of how to create a test and use testing fixtures and categories. - *$ - * All tests must extend from {@link AbstractComsSetup} in order to ensure that - * Network Communications are set up before the tests are run. - *$ + * Sample test for a sample PID controller. This demonstrates the general pattern of how to create a + * test and use testing fixtures and categories. All tests must extend from {@link + * AbstractComsSetup} in order to ensure that Network Communications are set up before the tests are + * run. + * * @author Fredric Silberberg */ public class SampleTest extends AbstractComsSetup { @@ -58,8 +55,8 @@ public class SampleTest extends AbstractComsSetup { } /** - * This is just a sample test that asserts true. Any traditional junit code - * can be used, these are ordinary junit tests! + * This is just a sample test that asserts true. Any traditional junit code can be used, these are + * ordinary junit tests! */ @Test public void test() { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java index fbd22645aa..1bd69c0cce 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java @@ -7,14 +7,14 @@ package edu.wpi.first.wpilibj; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.Test; - import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertEquals; + public class TimerTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(TimerTest.class.getName()); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java index 6ef4e6f0f5..ee558e22bb 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java @@ -14,9 +14,10 @@ import org.junit.runners.Suite.SuiteClasses; import edu.wpi.first.wpilibj.test.AbstractTestSuite; /** - * @author Jonathan Leitschuh Holds all of the tests in the root wpilibj - * directory Please list alphabetically so that it is easy to determine - * if a test is missing from the list + * Holds all of the tests in the root wpilibj directory. Please list alphabetically so that it is + * easy to determine if a test is missing from the list. + * + * @author Jonathan Leitschuh */ @RunWith(Suite.class) @SuiteClasses({AnalogCrossConnectTest.class, AnalogPotentiometerTest.class, @@ -25,7 +26,7 @@ import edu.wpi.first.wpilibj.test.AbstractTestSuite; DIOCrossConnectTest.class, EncoderTest.class, FilterNoiseTest.class, FilterOutputTest.class, GyroTest.class, MotorEncoderTest.class, MotorInvertingTest.class, PCMTest.class, PDPTest.class, PIDTest.class, - PIDToleranceTest.class, PreferencesTest.class, RelayCrossConnectTest.class, + PIDToleranceTest.class, PreferencesTest.class, RelayCrossConnectTest.class, SampleTest.class, TimerTest.class}) public class WpiLibJTestSuite extends AbstractTestSuite { } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java index 148660facb..0bb9e6b77a 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java @@ -18,12 +18,10 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; /** - * Provides a base implementation for CAN Tests that forces a test of a - * particular mode to provide tests of a certain type. This also allows for a - * standardized base setup for each test. - *$ - * @author jonathanleitschuh + * Provides a base implementation for CAN Tests that forces a test of a particular mode to provide + * tests of a certain type. This also allows for a standardized base setup for each test. * + * @author jonathanleitschuh */ public abstract class AbstractCANTest extends AbstractComsSetup { public static final double kMotorStopTime = 2; @@ -36,27 +34,26 @@ public abstract class AbstractCANTest extends AbstractComsSetup { public static final double kStartupTime = 0.50; public static final double kEncoderPositionTolerance = .75; public static final double kPotentiometerPositionTolerance = 10.0 / 360.0; // +/-10 - // degrees + // degrees public static final double kCurrentTolerance = 0.1; /** - * Stores the status value for the previous test. This is set immediately - * after a failure or success and before the me is torn down. + * Stores the status value for the previous test. This is set immediately after a failure or + * success and before the me is torn down. */ - private String status = ""; + private String m_status = ""; /** - * Extends the default test watcher in order to provide more information about - * a tests failure at runtime. - *$ - * @author jonathanleitschuh + * Extends the default test watcher in order to provide more information about a tests failure at + * runtime. * + * @author jonathanleitschuh */ public class CANTestWatcher extends DefaultTestWatcher { @Override - protected void failed(Throwable e, Description description) { - super.failed(e, description, status); + protected void failed(Throwable exception, Description description) { + super.failed(exception, description, m_status); } } @@ -65,27 +62,29 @@ public abstract class AbstractCANTest extends AbstractComsSetup { return new CANTestWatcher(); } - /** The Fixture under test */ - private CANMotorEncoderFixture me; + /** + * The Fixture under test. + */ + private CANMotorEncoderFixture m_me; /** - * Retrieves the CANMotorEncoderFixture - *$ + * Retrieves the CANMotorEncoderFixture. + * * @return the CANMotorEncoderFixture for this test. */ public CANMotorEncoderFixture getME() { - return me; + return m_me; } /** - * This runs BEFORE the setup of the inherited class + * This runs BEFORE the setup of the inherited class. */ @Before public final void preSetup() { - status = ""; - me = TestBench.getInstance().getCanJaguarPair(); - me.setup(); - me.getMotor().setSafetyEnabled(false); + m_status = ""; + m_me = TestBench.getInstance().getCanJaguarPair(); + m_me.setup(); + m_me.getMotor().setSafetyEnabled(false); } @After @@ -93,11 +92,11 @@ public abstract class AbstractCANTest extends AbstractComsSetup { try { // Stores the status data before tearing it down. // If the test fails unexpectedly then this could cause an exception. - status = me.printStatus(); + m_status = m_me.printStatus(); } finally { - me.teardown(); + m_me.teardown(); } - me = null; + m_me = null; } protected void setCANJaguar(double seconds, double value) { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java index 0d011a6ba6..a4aedd3e81 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java @@ -7,20 +7,21 @@ package edu.wpi.first.wpilibj.can; -import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.Before; -import org.junit.Test; -import org.junit.Ignore; - import edu.wpi.first.wpilibj.CANJaguar; import edu.wpi.first.wpilibj.Timer; +import static org.junit.Assert.assertEquals; + /** - * @author jonathanleitschuh + * Tests the CAN Motor Controller in Current Quad Encoder mode. * + * @author jonathanleitschuh */ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest { private static Logger logger = Logger.getLogger(CANCurrentQuadEncoderModeTest.class.getName()); @@ -29,7 +30,7 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() */ protected void stopMotor() { @@ -38,7 +39,7 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() */ protected void runMotorForward() { @@ -47,7 +48,7 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() */ protected void runMotorReverse() { @@ -96,7 +97,8 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest { for (int i = 0; i < 10; i++) { setCANJaguar(1.0, setpoint); - if (Math.abs(getME().getMotor().getOutputCurrent() - Math.abs(setpoint)) <= kCurrentTolerance) { + if (Math.abs(getME().getMotor().getOutputCurrent() - Math.abs(setpoint)) + <= kCurrentTolerance) { break; } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java index c5f289cb9c..4e4d573c93 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java @@ -7,6 +7,18 @@ package edu.wpi.first.wpilibj.can; +import com.googlecode.junittoolbox.PollingWait; +import com.googlecode.junittoolbox.RunnableAssert; + +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +import edu.wpi.first.wpilibj.CANJaguar; +import edu.wpi.first.wpilibj.Timer; + import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; @@ -14,25 +26,14 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.Test; - -import com.googlecode.junittoolbox.PollingWait; -import com.googlecode.junittoolbox.RunnableAssert; - -import edu.wpi.first.wpilibj.CANJaguar; -import edu.wpi.first.wpilibj.Timer; - /** - * @author jonathanleitschuh + * The default test set to run against the CAN Motor Controllers. * + * @author jonathanleitschuh */ public class CANDefaultTest extends AbstractCANTest { private static final Logger logger = Logger.getLogger(CANDefaultTest.class.getName()); - private final PollingWait wait = new PollingWait().timeoutAfter(65, TimeUnit.MILLISECONDS) + private final PollingWait m_wait = new PollingWait().timeoutAfter(65, TimeUnit.MILLISECONDS) .pollEvery(10, TimeUnit.MILLISECONDS); private static final double kSpikeTime = .5; @@ -42,9 +43,6 @@ public class CANDefaultTest extends AbstractCANTest { return logger; } - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { getME().getMotor().enableControl(); @@ -55,17 +53,18 @@ public class CANDefaultTest extends AbstractCANTest { @Test public void testDefaultGet() { - wait.until(new RunnableAssert("Waiting for CAN Jaguar get to return 0") { + m_wait.until(new RunnableAssert("Waiting for CAN Jaguar get to return 0") { @Override public void run() { - assertEquals("CAN Jaguar did not initialize stopped", 0.0, getME().getMotor().get(), .01f); + assertEquals("CAN Jaguar did not initialize stopped", 0.0, getME().getMotor().get(), + .01f); } }); } @Test public void testDefaultBusVoltage() { - wait.until(new RunnableAssert("Waiting for default bus voltage to be correct") { + m_wait.until(new RunnableAssert("Waiting for default bus voltage to be correct") { @Override public void run() { assertEquals("CAN Jaguar did not start at 14 volts", 14.0f, getME().getMotor() @@ -76,7 +75,7 @@ public class CANDefaultTest extends AbstractCANTest { @Test public void testDefaultOutputVoltage() { - wait.until(new RunnableAssert("Waiting for output voltage to be correct") { + m_wait.until(new RunnableAssert("Waiting for output voltage to be correct") { @Override public void run() { assertEquals("CAN Jaguar did not start with an output voltage of 0", 0.0f, getME() @@ -87,7 +86,7 @@ public class CANDefaultTest extends AbstractCANTest { @Test public void testDefaultOutputCurrent() { - wait.until(new RunnableAssert("Waiting for output current to be correct") { + m_wait.until(new RunnableAssert("Waiting for output current to be correct") { @Override public void run() { assertEquals("CAN Jaguar did not start with an output current of 0", 0.0f, getME() @@ -99,7 +98,7 @@ public class CANDefaultTest extends AbstractCANTest { @Test public void testDefaultTemperature() { final double room_temp = 18.0f; - wait.until(new RunnableAssert("Waiting for temperature to be correct") { + m_wait.until(new RunnableAssert("Waiting for temperature to be correct") { @Override public void run() { assertThat( @@ -112,11 +111,12 @@ public class CANDefaultTest extends AbstractCANTest { @Test public void testDefaultForwardLimit() { getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - wait.until(new RunnableAssert("Waiting for forward limit to not be set") { + m_wait.until(new RunnableAssert("Waiting for forward limit to not be set") { @Override public void run() { getME().getMotor().set(0); - assertTrue("CAN Jaguar did not start with the Forward Limit Switch Off", getME().getMotor() + assertTrue("CAN Jaguar did not start with the Forward Limit Switch Off", getME() + .getMotor() .getForwardLimitOK()); } }); @@ -125,11 +125,12 @@ public class CANDefaultTest extends AbstractCANTest { @Test public void testDefaultReverseLimit() { getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - wait.until(new RunnableAssert("Waiting for reverse limit to not be set") { + m_wait.until(new RunnableAssert("Waiting for reverse limit to not be set") { @Override public void run() { getME().getMotor().set(0); - assertTrue("CAN Jaguar did not start with the Reverse Limit Switch Off", getME().getMotor() + assertTrue("CAN Jaguar did not start with the Reverse Limit Switch Off", getME() + .getMotor() .getReverseLimitOK()); } }); @@ -137,7 +138,7 @@ public class CANDefaultTest extends AbstractCANTest { @Test public void testDefaultNoFaults() { - wait.until(new RunnableAssert("Waiting for no faults") { + m_wait.until(new RunnableAssert("Waiting for no faults") { @Override public void run() { assertEquals("CAN Jaguar initialized with Faults", 0, getME().getMotor().getFaults()); @@ -146,7 +147,6 @@ public class CANDefaultTest extends AbstractCANTest { } - @Test public void testFakeLimitSwitchForwards() { // Given @@ -165,7 +165,8 @@ public class CANDefaultTest extends AbstractCANTest { public void run() throws Exception { getME().getMotor().set(0); assertFalse( - "Setting the forward limit switch high did not cause the forward limit switch to trigger", + "Setting the forward limit switch high did not cause the forward limit switch to " + + "trigger", getME().getMotor().getForwardLimitOK()); } }); @@ -190,7 +191,8 @@ public class CANDefaultTest extends AbstractCANTest { public void run() throws Exception { getME().getMotor().set(0); assertFalse( - "Setting the reverse limit switch high did not cause the forward limit switch to trigger", + "Setting the reverse limit switch high did not cause the forward limit switch to " + + "trigger", getME().getMotor().getReverseLimitOK()); } }); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java index becd5f9153..a6fc64d4bc 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java @@ -7,22 +7,27 @@ package edu.wpi.first.wpilibj.can; -import edu.wpi.first.wpilibj.CANJaguar; -import edu.wpi.first.wpilibj.Timer; import org.junit.Test; -import static org.junit.Assert.assertTrue; + import java.util.logging.Logger; +import edu.wpi.first.wpilibj.CANJaguar; +import edu.wpi.first.wpilibj.Timer; + +import static org.junit.Assert.assertTrue; + /** - * Created by Patrick Murphy on 3/30/15. + * Tests the CAN Jaguar inverted. + * + *

Created by Patrick Murphy on 3/30/15. */ public class CANJaguarInversionTest extends AbstractCANTest { private static final Logger logger = Logger.getLogger(CANJaguarInversionTest.class.getName()); - private static final double motorVoltage = 2.0; - private static final double motorPercent = 0.1; - private static final double motorSpeed = 10; - private static final double delayTime = 0.75; - private static final double speedModeDelayTime = 2.0; + private static final double m_motorVoltage = 2.0; + private static final double m_motorPercent = 0.1; + private static final double m_motorSpeed = 10; + private static final double m_delayTime = 0.75; + private static final double m_speedModeDelayTime = 2.0; @Override protected Logger getClassLogger() { @@ -32,54 +37,52 @@ public class CANJaguarInversionTest extends AbstractCANTest { @Test public void testInvertingVoltageMode() { getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360); - InversionTest(motorVoltage, delayTime); + inversionTest(m_motorVoltage, m_delayTime); } @Test public void testInvertingPercentMode() { getME().getMotor().setPercentMode(CANJaguar.kQuadEncoder, 360); - InversionTest(motorPercent, delayTime); + inversionTest(m_motorPercent, m_delayTime); } @Test public void testInvertingSpeedMode() { getME().getMotor().setSpeedMode(CANJaguar.kQuadEncoder, 360, 0.1, 0.003, 0.01); - InversionTest(motorSpeed, speedModeDelayTime); + inversionTest(m_motorSpeed, m_speedModeDelayTime); } /** - * Runs an inversion test To use set the jaguar to the proper - * mode(PercentVbus, voltage, speed) - *$ - * @param setpoint the speed/voltage/percent to set the motor to - * @param delayTime the amount of time to delay between starting a motor and - * checking the encoder + * Runs an inversion test To use set the jaguar to the proper mode(PercentVbus, voltage, speed). + * + * @param setPoint the speed/voltage/percent to set the motor to + * @param delayTime the amount of time to delay between starting a motor and checking the encoder */ - private void InversionTest(double setpoint, double delayTime) { - CANJaguar jag = this.getME().getMotor(); + private void inversionTest(double setPoint, double delayTime) { + final CANJaguar jag = getME().getMotor(); jag.enableControl(); jag.setInverted(false); - jag.set(setpoint); + jag.set(setPoint); Timer.delay(delayTime); - double initialSpeed = jag.getSpeed(); + final double initialSpeed = jag.getSpeed(); jag.set(0.0); jag.setInverted(true); - jag.set(setpoint); + jag.set(setPoint); Timer.delay(delayTime); jag.set(0.0); - double finalSpeed = jag.getSpeed(); + final double finalSpeed = jag.getSpeed(); assertTrue("Inverting with Positive value does not invert direction", Math.signum(initialSpeed) != Math.signum(finalSpeed)); - jag.set(-setpoint); + jag.set(-setPoint); Timer.delay(delayTime); - initialSpeed = jag.getSpeed(); + final double newInitialSpeed = jag.getSpeed(); jag.set(0.0); jag.setInverted(false); - jag.set(-setpoint); + jag.set(-setPoint); Timer.delay(delayTime); - finalSpeed = jag.getSpeed(); + final double newFinalSpeed = jag.getSpeed(); jag.set(0.0); assertTrue("Inverting with Negative value does not invert direction", - Math.signum(initialSpeed) != Math.signum(finalSpeed)); + Math.signum(newInitialSpeed) != Math.signum(newFinalSpeed)); } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java index 03e72540d1..f92069ac66 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java @@ -7,6 +7,20 @@ package edu.wpi.first.wpilibj.can; +import com.googlecode.junittoolbox.PollingWait; +import com.googlecode.junittoolbox.RunnableAssert; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; + +import edu.wpi.first.wpilibj.CANJaguar; +import edu.wpi.first.wpilibj.Timer; + import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; @@ -15,24 +29,12 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import com.googlecode.junittoolbox.PollingWait; -import com.googlecode.junittoolbox.RunnableAssert; - -import edu.wpi.first.wpilibj.CANJaguar; -import edu.wpi.first.wpilibj.Timer; - /** - * @author jonathanleitschuh + * Tests the CAN motor in PercentQuadEncoderMode. * + * @author jonathanleitschuh */ +@SuppressWarnings("AbbreviationAsWordInName") public class CANPercentQuadEncoderModeTest extends AbstractCANTest { private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class .getName()); @@ -41,7 +43,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() */ protected void stopMotor() { @@ -50,7 +52,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() */ protected void runMotorForward() { @@ -59,7 +61,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() */ protected void runMotorReverse() { @@ -148,8 +150,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { } /** - * Test if we can limit the Jaguar to not rotate forwards when the fake limit - * switch is tripped + * Test if we can limit the Jaguar to not rotate forwards when the fake limit switch is tripped. */ @Test public void shouldNotRotateForwards_WhenFakeLimitSwitchForwardsIsTripped() { @@ -196,7 +197,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { /** - * Test if we can rotate in reverse when the limit switch + * Test if we can rotate in reverse when the limit switch. */ @Test public void shouldRotateReverse_WhenFakeLimitSwitchForwardsIsTripped() { @@ -251,8 +252,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { } /** - * Test if we can limit the Jaguar to only moving forwards with a fake limit - * switch. + * Test if we can limit the Jaguar to only moving forwards with a fake limit switch. */ @Test public void shouldNotRotateReverse_WhenFakeLimitSwitchReversesIsTripped() { @@ -301,9 +301,6 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { * Test if we can limit the Jaguar to only moving forwards with a fake limit * switch. */ - /** - *$ - */ @Test public void shouldRotateForward_WhenFakeLimitSwitchReversesIsTripped() { // Given @@ -368,7 +365,8 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { @Override public boolean getAsBoolean() { return Math.abs((getME().getMotor().getPosition() - jagInitialPosition) - - (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance; + - (getME().getEncoder().get() - encoderInitialPosition)) + < kEncoderPositionTolerance; } }); @@ -391,7 +389,8 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest { @Override public boolean getAsBoolean() { return Math.abs((getME().getMotor().getPosition() - jagInitialPosition) - - (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance; + - (getME().getEncoder().get() - encoderInitialPosition)) + < kEncoderPositionTolerance; } }); assertEquals(getME().getMotor().getPosition() - jagInitialPosition, getME().getEncoder().get() diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java index 0186fe9b9e..6472220d4a 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java @@ -7,28 +7,29 @@ package edu.wpi.first.wpilibj.can; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; +import com.googlecode.junittoolbox.PollingWait; +import com.googlecode.junittoolbox.RunnableAssert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -import com.googlecode.junittoolbox.PollingWait; -import com.googlecode.junittoolbox.RunnableAssert; +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; import edu.wpi.first.wpilibj.CANJaguar; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + /** - * @author jonathanleitschuh + * Tests the CAN Motor controller in Potentiometer Mode. * + * @author jonathanleitschuh */ public class CANPositionPotentiometerModeTest extends AbstractCANTest { private static final Logger logger = Logger.getLogger(CANPositionPotentiometerModeTest.class @@ -41,7 +42,7 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() */ protected void stopMotor() { @@ -50,7 +51,7 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() */ protected void runMotorForward() { @@ -59,7 +60,7 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() */ protected void runMotorReverse() { @@ -85,13 +86,13 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest { /** - * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead - * of the one built into the CAN Jaguar + * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead of the one built + * into the CAN Jaguar. */ @Ignore("Encoder is not yet wired to the FPGA") @Test public void testRotateForward() { - int initialPosition = getME().getEncoder().get(); + final int initialPosition = getME().getEncoder().get(); /* Drive the speed controller briefly to move the encoder */ getME().getMotor().set(kStoppedValue); Timer.delay(kMotorTimeSettling); @@ -104,13 +105,13 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest { } /** - * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead - * of the one built into the CAN Jaguar + * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead of the one built + * into the CAN Jaguar. */ @Ignore("Encoder is not yet wired to the FPGA") @Test public void testRotateReverse() { - int initialPosition = getME().getEncoder().get(); + final int initialPosition = getME().getEncoder().get(); /* Drive the speed controller briefly to move the encoder */ getME().getMotor().set(kStoppedValue); Timer.delay(kMotorTimeSettling); @@ -123,8 +124,8 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest { } /** - * Test if we can get a position in potentiometer mode, using an analog output - * as a fake potentiometer. + * Test if we can get a position in potentiometer mode, using an analog output as a fake + * potentiometer. */ @Test public void testFakePotentiometerPosition() { @@ -141,7 +142,8 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest { public void run() throws Exception { getME().getMotor().set(0); assertEquals( - "CAN Jaguar should have returned the potentiometer position set by the analog output", + "CAN Jaguar should have returned the potentiometer position set by the analog " + + "output", getME().getFakePot().getVoltage(), getME().getMotor().getPosition() * 3, kPotentiometerPositionTolerance * 3); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java index c1cfa10b1c..c663f56cf1 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java @@ -7,21 +7,22 @@ package edu.wpi.first.wpilibj.can; -import static org.junit.Assert.assertEquals; - -import java.util.logging.Level; -import java.util.logging.Logger; - import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import java.util.logging.Level; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.CANJaguar; import edu.wpi.first.wpilibj.Timer; +import static org.junit.Assert.assertEquals; + /** - * @author jonathanleitschuh + * Tests the CAN Motor Encoders in QuadEncoder mode. * + * @author jonathanleitschuh */ public class CANPositionQuadEncoderModeTest extends AbstractCANTest { private static final Logger logger = Logger.getLogger(CANPositionQuadEncoderModeTest.class @@ -35,7 +36,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() */ protected void runMotorForward() { @@ -46,7 +47,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() */ protected void runMotorReverse() { @@ -84,8 +85,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest { } /** - * Test if we can set a position and reach that position with PID control on - * the Jaguar. + * Test if we can set a position and reach that position with PID control on the Jaguar. */ @Test public void testEncoderPositionPIDForward() { @@ -101,8 +101,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest { } /** - * Test if we can set a position and reach that position with PID control on - * the Jaguar. + * Test if we can set a position and reach that position with PID control on the Jaguar. */ @Test public void testEncoderPositionPIDReverse() { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java index 0a98b3112f..216f47c200 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java @@ -7,30 +7,35 @@ package edu.wpi.first.wpilibj.can; +import org.junit.Before; +import org.junit.Test; + +import java.util.logging.Logger; + +import edu.wpi.first.wpilibj.CANJaguar; +import edu.wpi.first.wpilibj.Timer; + import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.Test; - -import edu.wpi.first.wpilibj.CANJaguar; -import edu.wpi.first.wpilibj.Timer; - /** - * @author jonathanleitschuh + * Tests the CAN Speed controllers in quad mode. * + * @author jonathanleitschuh */ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest { private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class .getName()); - /** The stopped value in rev/min */ + /** + * The stopped value in rev/min. + */ private static final double kStoppedValue = 0; - /** The running value in rev/min */ + /** + * The running value in rev/min. + */ private static final double kRunningValue = 50; @Override @@ -49,14 +54,14 @@ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest { @Test public void testDefaultSpeed() { - assertEquals("CAN Jaguar did not start with an initial speed of zero", 0.0f, getME().getMotor() + assertEquals("CAN Jaguar did not start with an initial speed of zero", 0.0f, getME() + .getMotor() .getSpeed(), 0.3f); } /** - * Test if we can drive the motor forward in Speed mode and get a position - * back + * Test if we can drive the motor forward in Speed mode and get a position back. */ @Test public void testRotateForwardSpeed() { @@ -70,8 +75,7 @@ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest { } /** - * Test if we can drive the motor backwards in Speed mode and get a position - * back + * Test if we can drive the motor backwards in Speed mode and get a position back. */ @Test public void testRotateReverseSpeed() { @@ -80,7 +84,8 @@ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest { setCANJaguar(2 * kMotorTime, speed); assertEquals("The motor did not reach the required speed in speed mode", speed, getME() .getMotor().getSpeed(), kEncoderSpeedTolerance); - assertThat("The motor did not move in reverse in speed mode", getME().getMotor().getPosition(), + assertThat("The motor did not move in reverse in speed mode", getME().getMotor() + .getPosition(), is(lessThan(initialPosition))); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java index 5ebd59474e..048bd5d23f 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java @@ -14,8 +14,9 @@ import org.junit.runners.Suite.SuiteClasses; import edu.wpi.first.wpilibj.test.AbstractTestSuite; /** - * @author jonathanleitschuh + * All of the tests to cover the CAN Motor Controllers. * + * @author jonathanleitschuh */ @RunWith(Suite.class) @SuiteClasses({CANCurrentQuadEncoderModeTest.class, CANDefaultTest.class, diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java index cd2e8563fa..b7197bc476 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java @@ -7,34 +7,39 @@ package edu.wpi.first.wpilibj.can; +import com.googlecode.junittoolbox.PollingWait; +import com.googlecode.junittoolbox.RunnableAssert; + +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +import edu.wpi.first.wpilibj.CANJaguar; +import edu.wpi.first.wpilibj.Timer; + import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; - -import org.junit.Before; -import org.junit.Test; - -import com.googlecode.junittoolbox.PollingWait; -import com.googlecode.junittoolbox.RunnableAssert; - -import edu.wpi.first.wpilibj.CANJaguar; -import edu.wpi.first.wpilibj.Timer; - /** - * @author jonathanleitschuh + * Tests the CAN motor controllers in voltage mode work correctly. * + * @author Jonathan Leitschuh */ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest { private static final Logger logger = Logger.getLogger(CANVoltageQuadEncoderModeTest.class .getName()); - /** The stopped value in volts */ + /** + * The stopped value in volts. + */ private static final double kStoppedValue = 0; - /** The running value in volts */ + /** + * The running value in volts. + */ private static final double kRunningValue = 4; private static final double kVoltageTolerance = .25; @@ -44,7 +49,7 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() */ protected void stopMotor() { @@ -53,7 +58,7 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() */ protected void runMotorForward() { @@ -62,7 +67,7 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() */ protected void runMotorReverse() { @@ -74,8 +79,11 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest { return logger; } + /** + * Sets up the test. + */ @Before - public void setUp() throws Exception { + public void setUp() { getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360); getME().getMotor().set(kStoppedValue); getME().getMotor().enableControl(); @@ -100,11 +108,10 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest { /** - * Sets up the test to have the CANJaguar running at the target voltage - *$ + * Sets up the test to have the CANJaguar running at the target voltage. + * * @param targetValue the target voltage - * @param wait the PollingWait to to use to wait for the setup to complete - * with + * @param wait the PollingWait to to use to wait for the setup to complete with */ private void setupMotorVoltageForTest(final double targetValue, PollingWait wait) { getME().getMotor().enableControl(); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java index c671bc6ed5..e53a216a13 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java @@ -1,9 +1,7 @@ /** - * Provides a suite of tests to cover CANJaguar fully in all different control - * modes and with each supported positional input. Different setup parameters - * are provided in each Test class. All test classes that want to take advantage - * of the default test setup frameworks in place should extend - * {@link edu.wpi.first.wpilibj.can.AbstractCANTest AbstractCANTest} - *$ + * Provides a suite of tests to cover CANJaguar fully in all different control modes and with each + * supported positional input. Different setup parameters are provided in each Test class. All test + * classes that want to take advantage of the default test setup frameworks in place should extend + * {@link edu.wpi.first.wpilibj.can.AbstractCANTest AbstractCANTest}. */ -package edu.wpi.first.wpilibj.can; \ No newline at end of file +package edu.wpi.first.wpilibj.can; diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java index 7f1c23c547..6d584bd470 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java @@ -7,17 +7,18 @@ package edu.wpi.first.wpilibj.command; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import org.junit.Before; import edu.wpi.first.wpilibj.mocks.MockCommand; import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + /** - * @author jonathanleitschuh + * The basic test for all {@link Command} tests. * + * @author jonathanleitschuh */ public abstract class AbstractCommandTest extends AbstractComsSetup { @@ -28,21 +29,22 @@ public abstract class AbstractCommandTest extends AbstractComsSetup { } public class ASubsystem extends Subsystem { - Command command; + Command m_command; protected void initDefaultCommand() { - if (command != null) { - setDefaultCommand(command); + if (m_command != null) { + setDefaultCommand(m_command); } } public void init(Command command) { - this.command = command; + m_command = command; } } - public void assertCommandState(MockCommand command, int initialize, int execute, int isFinished, - int end, int interrupted) { + + protected void assertCommandState(MockCommand command, int initialize, int execute, + int isFinished, int end, int interrupted) { assertEquals(initialize, command.getInitializeCount()); assertEquals(execute, command.getExecuteCount()); assertEquals(isFinished, command.getIsFinishedCount()); @@ -50,7 +52,7 @@ public abstract class AbstractCommandTest extends AbstractComsSetup { assertEquals(interrupted, command.getInterruptedCount()); } - public void sleep(int time) { + protected void sleep(int time) { try { Thread.sleep(time); } catch (InterruptedException ex) { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java index 9271ace8ab..6f7cbb8fbd 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java @@ -7,80 +7,58 @@ package edu.wpi.first.wpilibj.command; -import java.util.logging.Logger; - -import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.buttons.InternalButton; import edu.wpi.first.wpilibj.mocks.MockCommand; /** + * Test that covers the {@link edu.wpi.first.wpilibj.buttons.Button} with the {@link Command} + * library. + * * @author Mitchell * @author jonathanleitschuh - * */ public class ButtonTest extends AbstractCommandTest { private static final Logger logger = Logger.getLogger(ButtonTest.class.getName()); - private InternalButton button1; - private InternalButton button2; + private InternalButton m_button1; + private InternalButton m_button2; protected Logger getClassLogger() { return logger; } - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { - button1 = new InternalButton(); - button2 = new InternalButton(); + m_button1 = new InternalButton(); + m_button2 = new InternalButton(); } /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** - * Simple Button Test + * Simple Button Test. */ @Test public void test() { - MockCommand command1 = new MockCommand(); - MockCommand command2 = new MockCommand(); - MockCommand command3 = new MockCommand(); - MockCommand command4 = new MockCommand(); + final MockCommand command1 = new MockCommand(); + final MockCommand command2 = new MockCommand(); + final MockCommand command3 = new MockCommand(); + final MockCommand command4 = new MockCommand(); - button1.whenPressed(command1); - button1.whenReleased(command2); - button1.whileHeld(command3); - button2.whileHeld(command4); + m_button1.whenPressed(command1); + m_button1.whenReleased(command2); + m_button1.whileHeld(command3); + m_button2.whileHeld(command4); assertCommandState(command1, 0, 0, 0, 0, 0); assertCommandState(command2, 0, 0, 0, 0, 0); assertCommandState(command3, 0, 0, 0, 0, 0); assertCommandState(command4, 0, 0, 0, 0, 0); - button1.setPressed(true); + m_button1.setPressed(true); assertCommandState(command1, 0, 0, 0, 0, 0); assertCommandState(command2, 0, 0, 0, 0, 0); assertCommandState(command3, 0, 0, 0, 0, 0); @@ -100,7 +78,7 @@ public class ButtonTest extends AbstractCommandTest { assertCommandState(command2, 0, 0, 0, 0, 0); assertCommandState(command3, 1, 2, 2, 0, 0); assertCommandState(command4, 0, 0, 0, 0, 0); - button2.setPressed(true); + m_button2.setPressed(true); Scheduler.getInstance().run(); assertCommandState(command1, 1, 3, 3, 0, 0); assertCommandState(command2, 0, 0, 0, 0, 0); @@ -111,7 +89,7 @@ public class ButtonTest extends AbstractCommandTest { assertCommandState(command2, 0, 0, 0, 0, 0); assertCommandState(command3, 1, 4, 4, 0, 0); assertCommandState(command4, 1, 1, 1, 0, 0); - button1.setPressed(false); + m_button1.setPressed(false); Scheduler.getInstance().run(); assertCommandState(command1, 1, 5, 5, 0, 0); assertCommandState(command2, 0, 0, 0, 0, 0); @@ -122,7 +100,7 @@ public class ButtonTest extends AbstractCommandTest { assertCommandState(command2, 1, 1, 1, 0, 0); assertCommandState(command3, 1, 4, 4, 0, 1); assertCommandState(command4, 1, 3, 3, 0, 0); - button2.setPressed(false); + m_button2.setPressed(false); Scheduler.getInstance().run(); assertCommandState(command1, 1, 7, 7, 0, 0); assertCommandState(command2, 1, 2, 2, 0, 0); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java index 34008dce72..14c549eb35 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java @@ -7,22 +7,15 @@ package edu.wpi.first.wpilibj.command; -import static org.junit.Assert.*; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.wpi.first.wpilibj.mocks.MockCommand; -import edu.wpi.first.wpilibj.test.AbstractComsSetup; /** - * Ported from the old CrioTest Classes - *$ + * Ported from the old CrioTest Classes. + * * @author Mitchell * @author Jonathan Leitschuh */ @@ -34,38 +27,14 @@ public class CommandParallelGroupTest extends AbstractCommandTest { } /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** - * Simple Parallel Command Group With 2 commands one command terminates first + * Simple Parallel Command Group With 2 commands one command terminates first. */ @Test public void testParallelCommandGroupWithTwoCommands() { - MockCommand command1 = new MockCommand(); - MockCommand command2 = new MockCommand(); + final MockCommand command1 = new MockCommand(); + final MockCommand command2 = new MockCommand(); - CommandGroup commandGroup = new CommandGroup(); + final CommandGroup commandGroup = new CommandGroup(); commandGroup.addParallel(command1); commandGroup.addParallel(command2); @@ -97,11 +66,4 @@ public class CommandParallelGroupTest extends AbstractCommandTest { } - public void sleep(long time) { - try { - Thread.sleep(time); - } catch (InterruptedException ex) { - fail("Sleep Interrupted!?!?!?!?"); - } - } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java index 435bee0500..bacd551e20 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java @@ -7,21 +7,15 @@ package edu.wpi.first.wpilibj.command; -import static org.junit.Assert.*; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.wpi.first.wpilibj.mocks.MockCommand; /** - * Ported from the old CrioTest Classes - *$ + * Ported from the old CrioTest Classes. + * * @author Mitchell * @author Jonathan Leitschuh */ @@ -33,36 +27,11 @@ public class CommandScheduleTest extends AbstractCommandTest { } /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** - * Simple scheduling of a command and making sure the command is run and - * successfully terminates + * Simple scheduling of a command and making sure the command is run and successfully terminates. */ @Test public void testRunAndTerminate() { - MockCommand command = new MockCommand(); + final MockCommand command = new MockCommand(); command.start(); assertCommandState(command, 0, 0, 0, 0, 0); Scheduler.getInstance().run(); @@ -80,12 +49,11 @@ public class CommandScheduleTest extends AbstractCommandTest { } /** - * Simple scheduling of a command and making sure the command is run and - * cancels correctly + * Simple scheduling of a command and making sure the command is run and cancels correctly. */ @Test public void testRunAndCancel() { - MockCommand command = new MockCommand(); + final MockCommand command = new MockCommand(); command.start(); assertCommandState(command, 0, 0, 0, 0, 0); Scheduler.getInstance().run(); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java index 13b90be4f8..141dae38a4 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java @@ -7,20 +7,15 @@ package edu.wpi.first.wpilibj.command; -import java.util.logging.Logger; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.mocks.MockCommand; /** - * Ported from the old CrioTest Classes - *$ + * Ported from the old CrioTest Classes. + * * @author Mitchell * @author Jonathan Leitschuh */ @@ -32,32 +27,8 @@ public class CommandSequentialGroupTest extends AbstractCommandTest { } /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** - * Simple Command Group With 3 commands that all depend on a subsystem. Some - * commands have a timeout + * Simple Command Group With 3 commands that all depend on a subsystem. Some commands have a + * timeout. */ @Test(timeout = 20000) public void testThreeCommandOnSubSystem() { @@ -65,26 +36,26 @@ public class CommandSequentialGroupTest extends AbstractCommandTest { final ASubsystem subsystem = new ASubsystem(); logger.finest("Creating Mock Command1"); - MockCommand command1 = new MockCommand() { + final MockCommand command1 = new MockCommand() { { requires(subsystem); } }; logger.finest("Creating Mock Command2"); - MockCommand command2 = new MockCommand() { + final MockCommand command2 = new MockCommand() { { requires(subsystem); } }; logger.finest("Creating Mock Command3"); - MockCommand command3 = new MockCommand() { + final MockCommand command3 = new MockCommand() { { requires(subsystem); } }; logger.finest("Creating Command Group"); - CommandGroup commandGroup = new CommandGroup(); + final CommandGroup commandGroup = new CommandGroup(); commandGroup.addSequential(command1, 1.0); commandGroup.addSequential(command2, 2.0); commandGroup.addSequential(command3); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java index 066bacdc8b..3eba9cf1f3 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java @@ -7,19 +7,15 @@ package edu.wpi.first.wpilibj.command; -import java.util.logging.Logger; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.mocks.MockCommand; /** - * Ported from the old CrioTest Classes - *$ + * Ported from the old CrioTest Classes. + * * @author Mitchell * @author Jonathan Leitschuh */ @@ -31,43 +27,19 @@ public class CommandSupersedeTest extends AbstractCommandTest { } /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** - * Testing one command superseding another because of dependencies + * Testing one command superseding another because of dependencies. */ @Test public void testOneCommandSupersedingAnotherBecauseOfDependencies() { final ASubsystem subsystem = new ASubsystem(); - MockCommand command1 = new MockCommand() { + final MockCommand command1 = new MockCommand() { { requires(subsystem); } }; - MockCommand command2 = new MockCommand() { + final MockCommand command2 = new MockCommand() { { requires(subsystem); } @@ -108,21 +80,21 @@ public class CommandSupersedeTest extends AbstractCommandTest { } /** - * Testing one command failing superseding another because of dependencies - * because the first command cannot be interrupted" + * Testing one command failing superseding another because of dependencies because the first + * command cannot be interrupted. */ @Test public void testCommandFailingSupersedingBecauseFirstCanNotBeInterrupted() { final ASubsystem subsystem = new ASubsystem(); - MockCommand command1 = new MockCommand() { + final MockCommand command1 = new MockCommand() { { requires(subsystem); setInterruptible(false); } }; - MockCommand command2 = new MockCommand() { + final MockCommand command2 = new MockCommand() { { requires(subsystem); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java index 08eb794b5b..8c1081c4c6 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java @@ -14,8 +14,8 @@ import org.junit.runners.Suite.SuiteClasses; import edu.wpi.first.wpilibj.test.AbstractTestSuite; /** + * Contains a listing of all of the {@link Command} tests. * @author jonathanleitschuh - * */ @RunWith(Suite.class) @SuiteClasses({ButtonTest.class, CommandParallelGroupTest.class, CommandScheduleTest.class, diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java index 4b836bc89c..2e0a56a14b 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java @@ -7,21 +7,16 @@ package edu.wpi.first.wpilibj.command; -import static org.junit.Assert.*; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.wpi.first.wpilibj.mocks.MockCommand; /** - * @author jonathanleitschuh + * Test a {@link Command} that times out. * + * @author jonathanleitschuh */ public class CommandTimeoutTest extends AbstractCommandTest { private static final Logger logger = Logger.getLogger(CommandTimeoutTest.class.getName()); @@ -31,38 +26,14 @@ public class CommandTimeoutTest extends AbstractCommandTest { } /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** - * Command 2 second Timeout Test + * Command 2 second Timeout Test. */ @Test public void testTwoSecondTimeout() { final ASubsystem subsystem = new ASubsystem(); - MockCommand command = new MockCommand() { + final MockCommand command = new MockCommand() { { requires(subsystem); setTimeout(2); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java index eb7805059c..7c7f15ab8c 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java @@ -7,21 +7,16 @@ package edu.wpi.first.wpilibj.command; -import static org.junit.Assert.*; +import org.junit.Test; import java.util.logging.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.wpi.first.wpilibj.mocks.MockCommand; /** - * @author jonathanleitschuh + * Tests the {@link Command} library. * + * @author jonathanleitschuh */ public class DefaultCommandTest extends AbstractCommandTest { private static final Logger logger = Logger.getLogger(DefaultCommandTest.class.getName()); @@ -30,45 +25,22 @@ public class DefaultCommandTest extends AbstractCommandTest { return logger; } - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** - * Testing of default commands where the interrupting command ends itself + * Testing of default commands where the interrupting command ends itself. */ @Test public void testDefaultCommandWhereTheInteruptingCommandEndsItself() { final ASubsystem subsystem = new ASubsystem(); - MockCommand defaultCommand = new MockCommand() { + final MockCommand defaultCommand = new MockCommand() { { requires(subsystem); } }; - MockCommand anotherCommand = new MockCommand() { + final MockCommand anotherCommand = new MockCommand() { { requires(subsystem); } @@ -112,20 +84,20 @@ public class DefaultCommandTest extends AbstractCommandTest { /** - * Testing of default commands where the interrupting command is canceled + * Testing of default commands where the interrupting command is canceled. */ @Test public void testDefaultCommandsInterruptingCommandCanceled() { final ASubsystem subsystem = new ASubsystem(); - MockCommand defaultCommand = new MockCommand() { + final MockCommand defaultCommand = new MockCommand() { { requires(subsystem); } }; - MockCommand anotherCommand = new MockCommand() { + final MockCommand anotherCommand = new MockCommand() { { requires(subsystem); } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java index 96d7962570..3e82b4e5ad 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java @@ -11,45 +11,46 @@ import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.AnalogOutput; /** - * @author jonathanleitschuh + * A fixture that connects an {@link AnalogInput} and an {@link AnalogOutput}. * + * @author jonathanleitschuh */ public abstract class AnalogCrossConnectFixture implements ITestFixture { - private boolean initialized = false; + private boolean m_initialized = false; - private AnalogInput input; - private AnalogOutput output; + private AnalogInput m_input; + private AnalogOutput m_output; - abstract protected AnalogInput giveAnalogInput(); + protected abstract AnalogInput giveAnalogInput(); - abstract protected AnalogOutput giveAnalogOutput(); + protected abstract AnalogOutput giveAnalogOutput(); private void initialize() { synchronized (this) { - if (!initialized) { - input = giveAnalogInput(); - output = giveAnalogOutput(); - initialized = true; + if (!m_initialized) { + m_input = giveAnalogInput(); + m_output = giveAnalogOutput(); + m_initialized = true; } } } /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() */ @Override public boolean setup() { initialize(); - output.setVoltage(0); + m_output.setVoltage(0); return true; } /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() */ @Override @@ -60,27 +61,27 @@ public abstract class AnalogCrossConnectFixture implements ITestFixture { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() */ @Override public boolean teardown() { - input.free(); - output.free(); + m_input.free(); + m_output.free(); return true; } /** - * @return Analog Output + * Analog Output. */ - final public AnalogOutput getOutput() { + public final AnalogOutput getOutput() { initialize(); - return output; + return m_output; } - final public AnalogInput getInput() { + public final AnalogInput getInput() { initialize(); - return input; + return m_input; } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java index a230c4c365..220699ce6a 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java @@ -18,18 +18,19 @@ import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource; /** - * @author jonathanleitschuh + * A fixture that wraps a {@link CANJaguar}. * + * @author jonathanleitschuh */ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture implements ITestFixture { private static final Logger logger = Logger.getLogger(CANMotorEncoderFixture.class.getName()); public static final double RELAY_POWER_UP_TIME = .75; - private FakePotentiometerSource potSource; - private DigitalOutput forwardLimit; - private DigitalOutput reverseLimit; - private Relay powerCycler; - private boolean initialized = false; + private FakePotentiometerSource m_potSource; + private DigitalOutput m_forwardLimit; + private DigitalOutput m_reverseLimit; + private Relay m_powerCycler; + private boolean m_initialized = false; protected abstract FakePotentiometerSource giveFakePotentiometerSource(); @@ -39,24 +40,25 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture - * Designed to allow the user to easily setup and tear down the fixture to allow - * for reuse. This class should be explicitly instantiated in the TestBed class - * to allow any test to access this fixture. This allows tests to be mailable so - * that you can easily reconfigure the physical testbed without breaking the - * tests. + * Represents a physically connected Motor and Encoder to allow for unit tests on these different + * pairs
Designed to allow the user to easily setup and tear down the fixture to allow for + * reuse. This class should be explicitly instantiated in the TestBed class to allow any test to + * access this fixture. This allows tests to be mailable so that you can easily reconfigure the + * physical testbed without breaking the tests. */ public abstract class FilterNoiseFixture implements ITestFixture { private static final Logger logger = Logger.getLogger(FilterNoiseFixture.class.getName()); - private boolean initialized = false; - private boolean tornDown = false; - protected T filter; - private NoiseGenerator data; + private boolean m_initialized = false; + private boolean m_tornDown = false; + protected T m_filter; + private NoiseGenerator m_data; /** - * Where the implementer of this class should pass the filter constructor - *$ - * @return + * Where the implementer of this class should pass the filter constructor. */ - abstract protected T giveFilter(PIDSource source); + protected abstract T giveFilter(PIDSource source); - final private void initialize() { + private void initialize() { synchronized (this) { - if (!initialized) { - initialized = true; // This ensures it is only initialized once + if (!m_initialized) { + m_initialized = true; // This ensures it is only initialized once - data = new NoiseGenerator(TestBench.kStdDev) { + m_data = new NoiseGenerator(TestBench.kStdDev) { @Override + @SuppressWarnings("ParameterName") public double getData(double t) { return 100.0 * Math.sin(2.0 * Math.PI * t); } }; - filter = giveFilter(data); + m_filter = giveFilter(m_data); } } } @@ -61,33 +58,33 @@ public abstract class FilterNoiseFixture implements ITestFi } /** - * Gets the filter for this Object - *$ + * Gets the filter for this Object. + * * @return the filter this object refers too */ public T getFilter() { initialize(); - return filter; + return m_filter; } /** - * Gets the noise generator for this object - *$ + * Gets the noise generator for this object. + * * @return the noise generator that this object refers too */ public NoiseGenerator getNoiseGenerator() { initialize(); - return data; + return m_data; } /** - * Retrieves the name of the filter that this object refers to - *$ + * Retrieves the name of the filter that this object refers to. + * * @return The simple name of the filter {@link Class#getSimpleName()} */ public String getType() { initialize(); - return filter.getClass().getSimpleName(); + return m_filter.getClass().getSimpleName(); } // test here? @@ -108,61 +105,55 @@ public abstract class FilterNoiseFixture implements ITestFi // Get the generic type as a class @SuppressWarnings("unchecked") Class class1 = - (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; + (Class) ((ParameterizedType) getClass().getGenericSuperclass()) + .getActualTypeArguments()[0]; string.append(class1.getSimpleName()); string.append(">"); return string.toString(); } /** - * Adds Gaussian white noise to a function returning data. The noise will have - * the standard deviation provided in the constructor. + * Adds Gaussian white noise to a function returning data. The noise will have the standard + * deviation provided in the constructor. */ public abstract class NoiseGenerator implements PIDSource { - private double noise = 0.0; + private double m_noise = 0.0; // Make sure first call to pidGet() uses count == 0 - private double count = -TestBench.kFilterStep; + private double m_count = -TestBench.kFilterStep; - private double stdDev; - private Random gen = new Random(); + private double m_stdDev; + private Random m_gen = new Random(); NoiseGenerator(double stdDev) { - this.stdDev = stdDev; + m_stdDev = stdDev; } - abstract public double getData(double t); + @SuppressWarnings("ParameterName") + public abstract double getData(double t); - /** - * {@inheritDoc} - */ @Override - public void setPIDSourceType(PIDSourceType pidSource) {} + public void setPIDSourceType(PIDSourceType pidSource) { + } - /** - * {@inheritDoc} - */ @Override public PIDSourceType getPIDSourceType() { return PIDSourceType.kDisplacement; } public double get() { - return getData(count) + noise; + return getData(m_count) + m_noise; } - /** - * {@inheritDoc} - */ @Override public double pidGet() { - noise = gen.nextGaussian() * stdDev; - count += TestBench.kFilterStep; - return getData(count) + noise; + m_noise = m_gen.nextGaussian() * m_stdDev; + m_count += TestBench.kFilterStep; + return getData(m_count) + m_noise; } public void reset() { - count = -TestBench.kFilterStep; + m_count = -TestBench.kFilterStep; } } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FilterOutputFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FilterOutputFixture.java index b353e4dea5..dbdcdcd847 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FilterOutputFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FilterOutputFixture.java @@ -15,52 +15,49 @@ import edu.wpi.first.wpilibj.PIDSourceType; import edu.wpi.first.wpilibj.test.TestBench; /** - * Represents a filterphysically connected Motor and Encoder to allow for unit tests - * on these different pairs
- * Designed to allow the user to easily setup and tear down the fixture to allow - * for reuse. This class should be explicitly instantiated in the TestBed class - * to allow any test to access this fixture. This allows tests to be mailable so - * that you can easily reconfigure the physical testbed without breaking the - * tests. + * Represents a filterphysically connected Motor and Encoder to allow for unit tests on these + * different pairs
Designed to allow the user to easily setup and tear down the fixture to allow + * for reuse. This class should be explicitly instantiated in the TestBed class to allow any test to + * access this fixture. This allows tests to be mailable so that you can easily reconfigure the + * physical testbed without breaking the tests. */ public abstract class FilterOutputFixture implements ITestFixture { private static final Logger logger = Logger.getLogger(FilterOutputFixture.class.getName()); - private boolean initialized = false; - private boolean tornDown = false; - protected T filter; - private DataWrapper data; - private double expectedOutput; + private boolean m_initialized = false; + private boolean m_tornDown = false; + protected T m_filter; + private DataWrapper m_data; + private double m_expectedOutput; public FilterOutputFixture(double expectedOutput) { - this.expectedOutput = expectedOutput; + m_expectedOutput = expectedOutput; } /** - * Get expected output of fixture + * Get expected output of fixture. */ public double getExpectedOutput() { - return expectedOutput; + return m_expectedOutput; } /** - * Where the implementer of this class should pass the filter constructor - *$ - * @return + * Where the implementer of this class should pass the filter constructor. */ - abstract protected T giveFilter(PIDSource source); + protected abstract T giveFilter(PIDSource source); - final private void initialize() { + private void initialize() { synchronized (this) { - if (!initialized) { - initialized = true; // This ensures it is only initialized once + if (!m_initialized) { + m_initialized = true; // This ensures it is only initialized once - data = new DataWrapper() { + m_data = new DataWrapper() { @Override + @SuppressWarnings("ParameterName") public double getData(double t) { return 100.0 * Math.sin(2.0 * Math.PI * t) + 20.0 * Math.cos(50.0 * Math.PI * t); } }; - filter = giveFilter(data); + m_filter = giveFilter(m_data); } } } @@ -72,38 +69,38 @@ public abstract class FilterOutputFixture implements ITestF } /** - * Gets the filter for this Object - *$ + * Gets the filter for this Object. + * * @return the filter this object refers too */ public T getFilter() { initialize(); - return filter; + return m_filter; } /** - * Gets the data wrapper for this object - *$ + * Gets the data wrapper for this object. + * * @return the data wrapper that this object refers too */ public DataWrapper getDataWrapper() { initialize(); - return data; + return m_data; } /** - * Retrieves the name of the filter that this object refers to - *$ + * Retrieves the name of the filter that this object refers to. + * * @return The simple name of the filter {@link Class#getSimpleName()} */ public String getType() { initialize(); - return filter.getClass().getSimpleName(); + return m_filter.getClass().getSimpleName(); } @Override public boolean reset() { - data.reset(); + m_data.reset(); return true; } @@ -118,7 +115,8 @@ public abstract class FilterOutputFixture implements ITestF // Get the generic type as a class @SuppressWarnings("unchecked") Class class1 = - (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; + (Class) ((ParameterizedType) getClass().getGenericSuperclass()) + .getActualTypeArguments()[0]; string.append(class1.getSimpleName()); string.append(">"); return string.toString(); @@ -126,35 +124,31 @@ public abstract class FilterOutputFixture implements ITestF public abstract class DataWrapper implements PIDSource { // Make sure first call to pidGet() uses count == 0 - private double count = -TestBench.kFilterStep; + private double m_count = -TestBench.kFilterStep; - abstract public double getData(double t); + @SuppressWarnings("ParameterName") + public abstract double getData(double t); - /** - * {@inheritDoc} - */ + @Override - public void setPIDSourceType(PIDSourceType pidSource) {} + public void setPIDSourceType(PIDSourceType pidSource) { + } - /** - * {@inheritDoc} - */ + @Override public PIDSourceType getPIDSourceType() { return PIDSourceType.kDisplacement; } - /** - * {@inheritDoc} - */ + @Override public double pidGet() { - count += TestBench.kFilterStep; - return getData(count); + m_count += TestBench.kFilterStep; + return getData(m_count); } public void reset() { - count = -TestBench.kFilterStep; + m_count = -TestBench.kFilterStep; } } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java index 9ba87794bd..69b2079aff 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java @@ -10,44 +10,40 @@ package edu.wpi.first.wpilibj.fixtures; import edu.wpi.first.wpilibj.test.TestBench; /** - * Master interface for all test fixtures. This ensures that all test fixtures - * have setup and teardown methods, to ensure that the tests run properly. - *$ - * Test fixtures should be modeled around the content of a test, rather than the - * actual physical layout of the testing board. They should obtain references to - * hardware from the {@link TestBench} class, which is a singleton. Testing - * Fixtures are responsible for ensuring that the hardware is in an appropriate - * state for the start of a test, and ensuring that future tests will not be - * affected by the results of a test. - *$ + * Master interface for all test fixtures. This ensures that all test fixtures have setup and + * teardown methods, to ensure that the tests run properly. Test fixtures should be modeled around + * the content of a test, rather than the actual physical layout of the testing board. They should + * obtain references to hardware from the {@link TestBench} class, which is a singleton. Testing + * Fixtures are responsible for ensuring that the hardware is in an appropriate state for the start + * of a test, and ensuring that future tests will not be affected by the results of a test. + * * @author Fredric Silberberg */ public interface ITestFixture { /** - * Performs any required setup for this fixture, ensuring that all fixture - * elements are ready for testing. - *$ + * Performs any required setup for this fixture, ensuring that all fixture elements are ready for + * testing. + * * @return True if the fixture is ready for testing */ boolean setup(); /** - * Resets the fixture back to test start state. This should be called by the - * test class in the test setup method to ensure that the hardware is in the - * default state. This differs from {@link ITestFixture#setup()} as that is - * called once, before the class is constructed, so it may need to start - * sensors. This method should not have to start anything, just reset sensors - * and ensure that motors are stopped. - *$ + * Resets the fixture back to test start state. This should be called by the test class in the + * test setup method to ensure that the hardware is in the default state. This differs from {@link + * ITestFixture#setup()} as that is called once, before the class is constructed, so it may need + * to start sensors. This method should not have to start anything, just reset sensors and ensure + * that motors are stopped. + * * @return True if the fixture is ready for testing */ boolean reset(); /** - * Performs any required teardown after use of the fixture, ensuring that - * future tests will not run into conflicts. - *$ + * Performs any required teardown after use of the fixture, ensuring that future tests will not + * run into conflicts. + * * @return True if the teardown succeeded */ boolean teardown(); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java index 309e872fba..114ae32c50 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java @@ -19,74 +19,74 @@ import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.test.TestBench; /** - * Represents a physically connected Motor and Encoder to allow for unit tests - * on these different pairs
- * Designed to allow the user to easily setup and tear down the fixture to allow - * for reuse. This class should be explicitly instantiated in the TestBed class - * to allow any test to access this fixture. This allows tests to be mailable so - * that you can easily reconfigure the physical testbed without breaking the - * tests. + * Represents a physically connected Motor and Encoder to allow for unit tests on these different + * pairs
Designed to allow the user to easily setup and tear down the fixture to allow for + * reuse. This class should be explicitly instantiated in the TestBed class to allow any test to + * access this fixture. This allows tests to be mailable so that you can easily reconfigure the + * physical testbed without breaking the tests. * * @author Jonathan Leitschuh - * */ public abstract class MotorEncoderFixture implements ITestFixture { private static final Logger logger = Logger.getLogger(MotorEncoderFixture.class.getName()); - private boolean initialized = false; - private boolean tornDown = false; - protected T motor; - private Encoder encoder; - private final Counter counters[] = new Counter[2]; - protected DigitalInput aSource; // Stored so it can be freed at tear down - protected DigitalInput bSource; + private boolean m_initialized = false; + private boolean m_tornDown = false; + protected T m_motor; + private Encoder m_encoder; + private final Counter[] m_counters = new Counter[2]; + protected DigitalInput m_alphaSource; // Stored so it can be freed at tear down + protected DigitalInput m_betaSource; /** - * Default constructor for a MotorEncoderFixture + * Default constructor for a MotorEncoderFixture. */ - public MotorEncoderFixture() {} + public MotorEncoderFixture() { + } - abstract public int getPDPChannel(); + public abstract int getPDPChannel(); /** - * Where the implementer of this class should pass the speed controller - * Constructor should only be called from outside this class if the Speed - * controller is not also an implementation of PWM interface - *$ + * Where the implementer of this class should pass the speed controller Constructor should only be + * called from outside this class if the Speed controller is not also an implementation of PWM + * interface. + * * @return SpeedController */ - abstract protected T giveSpeedController(); + protected abstract T giveSpeedController(); /** - * Where the implementer of this class should pass one of the digital inputs
- * CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! - *$ + * Where the implementer of this class should pass one of the digital inputs. + * + *

CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! + * * @return DigitalInput */ - abstract protected DigitalInput giveDigitalInputA(); + protected abstract DigitalInput giveDigitalInputA(); /** - * Where the implementer fo this class should pass the other digital input
- * CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! - *$ + * Where the implementer fo this class should pass the other digital input. + * + *

CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! + * * @return Input B to be used when this class is instantiated */ - abstract protected DigitalInput giveDigitalInputB(); + protected abstract DigitalInput giveDigitalInputB(); - final private void initialize() { + private final void initialize() { synchronized (this) { - if (!initialized) { - initialized = true; // This ensures it is only initialized once + if (!m_initialized) { + m_initialized = true; // This ensures it is only initialized once - aSource = giveDigitalInputA(); - bSource = giveDigitalInputB(); + m_alphaSource = giveDigitalInputA(); + m_betaSource = giveDigitalInputB(); - encoder = new Encoder(aSource, bSource); - counters[0] = new Counter(aSource); - counters[1] = new Counter(bSource); + m_encoder = new Encoder(m_alphaSource, m_betaSource); + m_counters[0] = new Counter(m_alphaSource); + m_counters[1] = new Counter(m_betaSource); logger.fine("Creating the speed controller!"); - motor = giveSpeedController(); // CANJaguar throws an exception if it - // doesn't get the message + m_motor = giveSpeedController(); // CANJaguar throws an exception if it + // doesn't get the message } } } @@ -98,70 +98,68 @@ public abstract class MotorEncoderFixture implements } /** - * Gets the motor for this Object - *$ + * Gets the motor for this Object. + * * @return the motor this object refers too */ public T getMotor() { initialize(); - return motor; + return m_motor; } /** - * Gets the encoder for this object - *$ + * Gets the encoder for this object. + * * @return the encoder that this object refers too */ public Encoder getEncoder() { initialize(); - return encoder; + return m_encoder; } public Counter[] getCounters() { initialize(); - return counters; + return m_counters; } /** - * Retrieves the name of the motor that this object refers to - *$ + * Retrieves the name of the motor that this object refers to. + * * @return The simple name of the motor {@link Class#getSimpleName()} */ public String getType() { initialize(); - return motor.getClass().getSimpleName(); + return m_motor.getClass().getSimpleName(); } /** - * Checks to see if the speed of the motor is within some range of a given - * value. This is used instead of equals() because doubles can have - * inaccuracies. - *$ - * @param value The value to compare against + * Checks to see if the speed of the motor is within some range of a given value. This is used + * instead of equals() because doubles can have inaccuracies. + * + * @param value The value to compare against * @param accuracy The accuracy range to check against to see if the - * @return true if the range of values between motors speed accuracy contains - * the 'value'. + * @return true if the range of values between motors speed accuracy contains the 'value'. */ public boolean isMotorSpeedWithinRange(double value, double accuracy) { initialize(); - return Math.abs((Math.abs(motor.get()) - Math.abs(value))) < Math.abs(accuracy); + return Math.abs((Math.abs(m_motor.get()) - Math.abs(value))) < Math.abs(accuracy); } @Override public boolean reset() { initialize(); - boolean wasReset = true; - motor.setInverted(false); - motor.set(0); + m_motor.setInverted(false); + m_motor.set(0); Timer.delay(TestBench.MOTOR_STOP_TIME); // DEFINED IN THE TestBench - encoder.reset(); - for (Counter c : counters) { + m_encoder.reset(); + for (Counter c : m_counters) { c.reset(); } - wasReset = wasReset && motor.get() == 0; - wasReset = wasReset && encoder.get() == 0; - for (Counter c : counters) { + boolean wasReset = true; + wasReset = wasReset && m_motor.get() == 0; + wasReset = wasReset && m_encoder.get() == 0; + for (Counter c : m_counters) { wasReset = wasReset && c.get() == 0; } @@ -169,54 +167,59 @@ public abstract class MotorEncoderFixture implements } - /** - * Safely tears down the MotorEncoder Fixture in a way that makes sure that - * even if an object fails to initialize the rest of the fixture can still be - * torn down and the resources deallocated + * Safely tears down the MotorEncoder Fixture in a way that makes sure that even if an object + * fails to initialize the rest of the fixture can still be torn down and the resources + * deallocated. */ @Override public boolean teardown() { String type; - if (motor != null) { + if (m_motor != null) { type = getType(); } else { type = "null"; } - if (!tornDown) { + if (!m_tornDown) { boolean wasNull = false; - if (motor instanceof PWM && motor != null) { - ((PWM) motor).free(); - motor = null; - } else if (motor == null) + if (m_motor instanceof PWM && m_motor != null) { + ((PWM) m_motor).free(); + m_motor = null; + } else if (m_motor == null) { wasNull = true; - if (encoder != null) { - encoder.free(); - encoder = null; - } else + } + if (m_encoder != null) { + m_encoder.free(); + m_encoder = null; + } else { wasNull = true; - if (counters[0] != null) { - counters[0].free(); - counters[0] = null; - } else + } + if (m_counters[0] != null) { + m_counters[0].free(); + m_counters[0] = null; + } else { wasNull = true; - if (counters[1] != null) { - counters[1].free(); - counters[1] = null; - } else + } + if (m_counters[1] != null) { + m_counters[1].free(); + m_counters[1] = null; + } else { wasNull = true; - if (aSource != null) { - aSource.free(); - aSource = null; - } else + } + if (m_alphaSource != null) { + m_alphaSource.free(); + m_alphaSource = null; + } else { wasNull = true; - if (bSource != null) { - bSource.free(); - bSource = null; - } else + } + if (m_betaSource != null) { + m_betaSource.free(); + m_betaSource = null; + } else { wasNull = true; + } - tornDown = true; + m_tornDown = true; if (wasNull) { throw new NullPointerException("MotorEncoderFixture had null params at teardown"); @@ -234,7 +237,8 @@ public abstract class MotorEncoderFixture implements // Get the generic type as a class @SuppressWarnings("unchecked") Class class1 = - (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; + (Class) ((ParameterizedType) getClass().getGenericSuperclass()) + .getActualTypeArguments()[0]; string.append(class1.getSimpleName()); string.append(">"); return string.toString(); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFixture.java index 073efa50b6..c69402b2e5 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFixture.java @@ -9,22 +9,19 @@ package edu.wpi.first.wpilibj.fixtures; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Relay; -import edu.wpi.first.wpilibj.Relay.Direction; -import edu.wpi.first.wpilibj.Relay.Value; /** + * A connection between a {@link Relay} and two {@link DigitalInput DigitalInputs}. * @author jonathanleitschuh - * */ public abstract class RelayCrossConnectFixture implements ITestFixture { - private DigitalInput inputOne; - private DigitalInput inputTwo; - private Relay relay; - - private boolean initialized = false; - private boolean freed = false; + private DigitalInput m_inputOne; + private DigitalInput m_inputTwo; + private Relay m_relay; + private boolean m_initialized = false; + private boolean m_freed = false; protected abstract Relay giveRelay(); @@ -35,33 +32,33 @@ public abstract class RelayCrossConnectFixture implements ITestFixture { private void initialize() { synchronized (this) { - if (!initialized) { - relay = giveRelay(); - inputOne = giveInputOne(); - inputTwo = giveInputTwo(); - initialized = true; + if (!m_initialized) { + m_relay = giveRelay(); + m_inputOne = giveInputOne(); + m_inputTwo = giveInputTwo(); + m_initialized = true; } } } public Relay getRelay() { initialize(); - return relay; + return m_relay; } public DigitalInput getInputOne() { initialize(); - return inputOne; + return m_inputOne; } public DigitalInput getInputTwo() { initialize(); - return inputTwo; + return m_inputTwo; } /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() */ @Override @@ -72,7 +69,7 @@ public abstract class RelayCrossConnectFixture implements ITestFixture { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() */ @Override @@ -83,16 +80,16 @@ public abstract class RelayCrossConnectFixture implements ITestFixture { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() */ @Override public boolean teardown() { - if (!freed) { - relay.free(); - inputOne.free(); - inputTwo.free(); - freed = true; + if (!m_freed) { + m_relay.free(); + m_inputOne.free(); + m_inputTwo.free(); + m_freed = true; } else { throw new RuntimeException("You attempted to free the " + RelayCrossConnectFixture.class.getSimpleName() + " multiple times"); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java index f92d9debed..837d1e70d7 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java @@ -9,17 +9,13 @@ package edu.wpi.first.wpilibj.fixtures; /** - * This is an example of how to use the {@link ITestFixture} interface to create - * test fixtures for a test. - *$ + * This is an example of how to use the {@link ITestFixture} interface to create test fixtures for a + * test. + * * @author Fredric Silberberg - *$ */ public class SampleFixture implements ITestFixture { - /** - * {@inheritDoc} - */ @Override public boolean setup() { /* @@ -42,9 +38,6 @@ public class SampleFixture implements ITestFixture { return false; } - /** - * {@inheritDoc} - */ @Override public boolean teardown() { /* diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java index 002443ad17..f67db6ca77 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java @@ -14,21 +14,20 @@ import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.Timer; /** - * A class to represent the a physical Camera with two servos (tilt and pan) - * designed to test to see if the gyroscope is operating normally. + * A class to represent the a physical Camera with two servos (tilt and pan) designed to test to see + * if the gyroscope is operating normally. * * @author Jonathan Leitschuh - * */ public abstract class TiltPanCameraFixture implements ITestFixture { public static final Logger logger = Logger.getLogger(TiltPanCameraFixture.class.getName()); public static final double RESET_TIME = 2.0; - private AnalogGyro gyro; - private AnalogGyro gyroParam; - private Servo tilt; - private Servo pan; - private boolean initialized = false; + private AnalogGyro m_gyro; + private AnalogGyro m_gyroParam; + private Servo m_tilt; + private Servo m_pan; + private boolean m_initialized = false; protected abstract AnalogGyro giveGyro(); @@ -40,24 +39,25 @@ public abstract class TiltPanCameraFixture implements ITestFixture { protected abstract Servo givePan(); /** - * Constructs the TiltPanCamera + * Constructs the TiltPanCamera. */ - public TiltPanCameraFixture() {} + public TiltPanCameraFixture() { + } @Override public boolean setup() { boolean wasSetup = false; - if (!initialized) { - initialized = true; - tilt = giveTilt(); - tilt.set(0); - pan = givePan(); - pan.set(0); + if (!m_initialized) { + m_initialized = true; + m_tilt = giveTilt(); + m_tilt.set(0); + m_pan = givePan(); + m_pan.set(0); Timer.delay(RESET_TIME); logger.fine("Initializing the gyro"); - gyro = giveGyro(); - gyro.reset(); + m_gyro = giveGyro(); + m_gyro.reset(); wasSetup = true; } return wasSetup; @@ -65,50 +65,52 @@ public abstract class TiltPanCameraFixture implements ITestFixture { @Override public boolean reset() { - if(gyro != null) - gyro.reset(); + if (m_gyro != null) { + m_gyro.reset(); + } return true; } public Servo getTilt() { - return tilt; + return m_tilt; } public Servo getPan() { - return pan; + return m_pan; } public AnalogGyro getGyro() { - return gyro; + return m_gyro; } public AnalogGyro getGyroParam() { - return gyroParam; + return m_gyroParam; } // Do not call unless all other instances of Gyro have been deallocated public void setupGyroParam(int center, double offset) { - gyroParam = giveGyroParam(center, offset); - gyroParam.reset(); + m_gyroParam = giveGyroParam(center, offset); + m_gyroParam.reset(); } + public void freeGyro() { - gyro.free(); - gyro = null; + m_gyro.free(); + m_gyro = null; } @Override public boolean teardown() { - tilt.free(); - tilt = null; - pan.free(); - pan = null; - if(gyro !=null){//in case not freed during gyro tests - gyro.free(); - gyro = null; + m_tilt.free(); + m_tilt = null; + m_pan.free(); + m_pan = null; + if (m_gyro != null) { //in case not freed during gyro tests + m_gyro.free(); + m_gyro = null; } - if(gyroParam != null){//in case gyro tests failed before getting to this point - gyroParam.free(); - gyroParam = null; + if (m_gyroParam != null) { //in case gyro tests failed before getting to this point + m_gyroParam.free(); + m_gyroParam = null; } return true; } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java index ba644b83d9..fafc3d5eaf 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java @@ -11,19 +11,20 @@ import edu.wpi.first.wpilibj.DigitalOutput; import edu.wpi.first.wpilibj.Timer; /** - * Simulates an encoder for testing purposes + * Simulates an encoder for testing purposes. + * * @author Ryan O'Meara */ public class FakeCounterSource { private Thread m_task; private int m_count; - private int m_mSec; + private int m_milliSec; private DigitalOutput m_output; private boolean m_allocated; /** - * Thread object that allows emulation of an encoder + * Thread object that allows emulation of an encoder. */ private class EncoderThread extends Thread { @@ -37,19 +38,20 @@ public class FakeCounterSource { m_encoder.m_output.set(false); try { for (int i = 0; i < m_encoder.m_count; i++) { - Thread.sleep(m_encoder.m_mSec); + Thread.sleep(m_encoder.m_milliSec); m_encoder.m_output.set(true); - Thread.sleep(m_encoder.m_mSec); + Thread.sleep(m_encoder.m_milliSec); m_encoder.m_output.set(false); } - } catch (InterruptedException e) { + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } } } /** - * Create a fake encoder on a given port - *$ + * Create a fake encoder on a given port. + * * @param output the port to output the given signal to */ public FakeCounterSource(DigitalOutput output) { @@ -59,8 +61,8 @@ public class FakeCounterSource { } /** - * Create a fake encoder on a given port - *$ + * Create a fake encoder on a given port. + * * @param port The port the encoder is supposed to be on */ public FakeCounterSource(int port) { @@ -70,7 +72,7 @@ public class FakeCounterSource { } /** - * Destroy Object with minimum memory leak + * Destroy Object with minimum memory leak. */ public void free() { m_task = null; @@ -82,36 +84,36 @@ public class FakeCounterSource { } /** - * Common initailization code + * Common initailization code. */ private void initEncoder() { - m_mSec = 1; + m_milliSec = 1; m_task = new EncoderThread(this); m_output.set(false); } /** - * Starts the thread execution task + * Starts the thread execution task. */ public void start() { m_task.start(); } /** - * Waits for the thread to complete + * Waits for the thread to complete. */ public void complete() { try { m_task.join(); - } catch (InterruptedException e) { + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } m_task = new EncoderThread(this); Timer.delay(.01); } /** - * Starts and completes a task set - does not return until thred has finished - * its operations + * Starts and completes a task set - does not return until thred has finished its operations. */ public void execute() { start(); @@ -119,8 +121,8 @@ public class FakeCounterSource { } /** - * Sets the count to run encoder - *$ + * Sets the count to run encoder. + * * @param count The count to emulate to the controller */ public void setCount(int count) { @@ -128,11 +130,11 @@ public class FakeCounterSource { } /** - * Specify the rate to send pulses - *$ - * @param mSec The rate to send out pulses at + * Specify the rate to send pulses. + * + * @param milliSec The rate to send out pulses at */ - public void setRate(int mSec) { - m_mSec = mSec; + public void setRate(int milliSec) { + m_milliSec = milliSec; } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java index b298d7779b..bf8ff09062 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java @@ -11,20 +11,22 @@ import edu.wpi.first.wpilibj.DigitalOutput; import edu.wpi.first.wpilibj.Timer; /** - * Emulates a quadrature encoder + * Emulates a quadrature encoder. + * * @author Ryan O'Meara */ public class FakeEncoderSource { private Thread m_task; private int m_count; - private int m_mSec; + private int m_milliSec; private boolean m_forward; - private DigitalOutput m_outputA, m_outputB; - private final boolean allocatedOutputs; + private final DigitalOutput m_outputA; + private final DigitalOutput m_outputB; + private final boolean m_allocatedOutputs; /** - * Thread object that allows emulation of a quadrature encoder + * Thread object that allows emulation of a quadrature encoder. */ private class QuadEncoderThread extends Thread { @@ -36,7 +38,8 @@ public class FakeEncoderSource { public void run() { - DigitalOutput lead, lag; + final DigitalOutput lead; + final DigitalOutput lag; m_encoder.m_outputA.set(false); m_encoder.m_outputB.set(false); @@ -52,46 +55,62 @@ public class FakeEncoderSource { try { for (int i = 0; i < m_encoder.m_count; i++) { lead.set(true); - Thread.sleep(m_encoder.m_mSec); + Thread.sleep(m_encoder.m_milliSec); lag.set(true); - Thread.sleep(m_encoder.m_mSec); + Thread.sleep(m_encoder.m_milliSec); lead.set(false); - Thread.sleep(m_encoder.m_mSec); + Thread.sleep(m_encoder.m_milliSec); lag.set(false); - Thread.sleep(m_encoder.m_mSec); + Thread.sleep(m_encoder.m_milliSec); } - } catch (InterruptedException e) { + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } } } + /** + * Creates an encoder source using two ports. + * + * @param portA The A port + * @param portB The B port + */ public FakeEncoderSource(int portA, int portB) { m_outputA = new DigitalOutput(portA); m_outputB = new DigitalOutput(portB); - allocatedOutputs = true; + m_allocatedOutputs = true; initQuadEncoder(); } - public FakeEncoderSource(DigitalOutput iA, DigitalOutput iB) { - m_outputA = iA; - m_outputB = iB; - allocatedOutputs = false; + /** + * Creates the fake encoder using two digital outputs. + * + * @param outputA The A digital output + * @param outputB The B digital output + */ + public FakeEncoderSource(DigitalOutput outputA, DigitalOutput outputB) { + m_outputA = outputA; + m_outputB = outputB; + m_allocatedOutputs = false; initQuadEncoder(); } + /** + * Frees the resource. + */ public void free() { m_task = null; - if (allocatedOutputs) { + if (m_allocatedOutputs) { m_outputA.free(); m_outputB.free(); } } /** - * Common initialization code + * Common initialization code. */ private final void initQuadEncoder() { - m_mSec = 1; + m_milliSec = 1; m_forward = true; m_task = new QuadEncoderThread(this); m_outputA.set(false); @@ -99,26 +118,27 @@ public class FakeEncoderSource { } /** - * Starts the thread + * Starts the thread. */ public void start() { m_task.start(); } /** - * Waits for thread to end + * Waits for thread to end. */ public void complete() { try { m_task.join(); - } catch (InterruptedException e) { + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } m_task = new QuadEncoderThread(this); Timer.delay(.01); } /** - * Runs and waits for thread to end before returning + * Runs and waits for thread to end before returning. */ public void execute() { start(); @@ -126,17 +146,17 @@ public class FakeEncoderSource { } /** - * Rate of pulses to send - *$ - * @param mSec Pulse Rate + * Rate of pulses to send. + * + * @param milliSec Pulse Rate */ - public void setRate(int mSec) { - m_mSec = mSec; + public void setRate(int milliSec) { + m_milliSec = milliSec; } /** - * Set the number of pulses to simulate - *$ + * Set the number of pulses to simulate. + * * @param count Pulse count */ public void setCount(int count) { @@ -144,8 +164,8 @@ public class FakeEncoderSource { } /** - * Set which direction the encoder simulates motion in - *$ + * Set which direction the encoder simulates motion in. + * * @param isForward Whether to simulate forward motion */ public void setForward(boolean isForward) { @@ -153,8 +173,8 @@ public class FakeEncoderSource { } /** - * Accesses whether the encoder is simulating forward motion - *$ + * Accesses whether the encoder is simulating forward motion. + * * @return Whether the simulated motion is in the forward direction */ public boolean isForward() { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java index 06406841cd..20466dfea5 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java @@ -10,76 +10,86 @@ package edu.wpi.first.wpilibj.mockhardware; import edu.wpi.first.wpilibj.AnalogOutput; /** - * @author jonathanleitschuh + * A fake source to provide output to a {@link edu.wpi.first.wpilibj.interfaces.Potentiometer}. * + * @author jonathanleitschuh */ public class FakePotentiometerSource { - private AnalogOutput output; - private boolean m_init_output; - private double potMaxAngle; - private double potMaxVoltage = 5.0; - private final double defaultPotMaxAngle; + private AnalogOutput m_output; + private boolean m_initOutput; + private double m_potMaxAngle; + private double m_potMaxVoltage = 5.0; + private final double m_defaultPotMaxAngle; + /** + * Constructs the fake source. + * + * @param output The analog port to output the signal on + * @param defaultPotMaxAngle The default maximum angle the pot supports. + */ public FakePotentiometerSource(AnalogOutput output, double defaultPotMaxAngle) { - this.defaultPotMaxAngle = defaultPotMaxAngle; - potMaxAngle = defaultPotMaxAngle; - this.output = output; - m_init_output = false; + m_defaultPotMaxAngle = defaultPotMaxAngle; + m_potMaxAngle = defaultPotMaxAngle; + m_output = output; + m_initOutput = false; } public FakePotentiometerSource(int port, double defaultPotMaxAngle) { this(new AnalogOutput(port), defaultPotMaxAngle); - m_init_output = true; + m_initOutput = true; } /** - * Sets the maximum voltage output. If not the default is 5.0V - *$ + * Sets the maximum voltage output. If not the default is 5.0V. + * * @param voltage The voltage that indicates that the pot is at the max value. */ public void setMaxVoltage(double voltage) { - potMaxVoltage = voltage; + m_potMaxVoltage = voltage; } public void setRange(double range) { - potMaxAngle = range; + m_potMaxAngle = range; } public void reset() { - potMaxAngle = defaultPotMaxAngle; - output.setVoltage(0.0); + m_potMaxAngle = m_defaultPotMaxAngle; + m_output.setVoltage(0.0); } public void setAngle(double angle) { - output.setVoltage((potMaxVoltage / potMaxAngle) * angle); + m_output.setVoltage((m_potMaxVoltage / m_potMaxAngle) * angle); } public void setVoltage(double voltage) { - output.setVoltage(voltage); + m_output.setVoltage(voltage); } public double getVoltage() { - return output.getVoltage(); + return m_output.getVoltage(); } /** - * Returns the currently set angle - *$ + * Returns the currently set angle. + * * @return the current angle */ public double getAngle() { - double voltage = output.getVoltage(); + double voltage = m_output.getVoltage(); if (voltage == 0) { // Removes divide by zero error return 0; } - return voltage * (potMaxAngle / potMaxVoltage); + return voltage * (m_potMaxAngle / m_potMaxVoltage); } + /** + * Frees the resouce. + */ public void free() { - if (m_init_output) { - output.free(); - output = null; - m_init_output = false; + if (m_initOutput) { + m_output.free(); + m_output = null; + m_initOutput = false; } } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java index 54f79d5e23..bddd2e6878 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java @@ -10,107 +10,106 @@ package edu.wpi.first.wpilibj.mocks; import edu.wpi.first.wpilibj.command.Command; /** - * A class to simulate a simple command The command keeps track of how many - * times each method was called + * A class to simulate a simple command The command keeps track of how many times each method was + * called. * * @author mwills */ public class MockCommand extends Command { - private int initializeCount = 0; - private int executeCount = 0; - private int isFinishedCount = 0; - private boolean hasFinished = false; - private int endCount = 0; - private int interruptedCount = 0; + private int m_initializeCount = 0; + private int m_executeCount = 0; + private int m_isFinishedCount = 0; + private boolean m_hasFinished = false; + private int m_endCount = 0; + private int m_interruptedCount = 0; protected void initialize() { - ++initializeCount; + ++m_initializeCount; } protected void execute() { - ++executeCount; + ++m_executeCount; } protected boolean isFinished() { - ++isFinishedCount; + ++m_isFinishedCount; return isHasFinished(); } protected void end() { - ++endCount; + ++m_endCount; } protected void interrupted() { - ++interruptedCount; + ++m_interruptedCount; } - /** - * @return how many times the initialize method has been called + * How many times the initialize method has been called. */ public int getInitializeCount() { - return initializeCount; + return m_initializeCount; } /** - * @return if the initialize method has been called at least once + * If the initialize method has been called at least once. */ public boolean hasInitialized() { return getInitializeCount() > 0; } /** - * @return how many time the execute method has been called + * How many time the execute method has been called. */ public int getExecuteCount() { - return executeCount; + return m_executeCount; } /** - * @return how many times the isFinished method has been called + * How many times the isFinished method has been called. */ public int getIsFinishedCount() { - return isFinishedCount; + return m_isFinishedCount; } /** - * @return what value the isFinished method will return + * @return what value the isFinished method will return. */ public boolean isHasFinished() { - return hasFinished; + return m_hasFinished; } /** - * @param hasFinished set what value the isFinished method will return + * @param hasFinished set what value the isFinished method will return. */ public void setHasFinished(boolean hasFinished) { - this.hasFinished = hasFinished; + m_hasFinished = hasFinished; } /** - * @return how many times the end method has been called + * How many times the end method has been called. */ public int getEndCount() { - return endCount; + return m_endCount; } /** - * @return if the end method has been called at least once + * If the end method has been called at least once. */ public boolean hasEnd() { return getEndCount() > 0; } /** - * @return how many times the interrupted method has been called + * How many times the interrupted method has been called. */ public int getInterruptedCount() { - return interruptedCount; + return m_interruptedCount; } /** - * @return if the interrupted method has been called at least once + * If the interrupted method has been called at least once. */ public boolean hasInterrupted() { return getInterruptedCount() > 0; diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java index 193df5ae60..9bdfc64c79 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java @@ -7,24 +7,21 @@ package edu.wpi.first.wpilibj.smartdashboard; -import static org.junit.Assert.assertEquals; - -import java.util.logging.Logger; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.networktables.NetworkTableKeyNotDefined; import edu.wpi.first.wpilibj.test.AbstractComsSetup; +import static org.junit.Assert.assertEquals; + /** - * @author jonathanleitschuh + * Test that covers {@link SmartDashboard}. * + * @author jonathanleitschuh */ public class SmartDashboardTest extends AbstractComsSetup { private static final Logger logger = Logger.getLogger(SmartDashboardTest.class.getName()); @@ -34,30 +31,6 @@ public class SmartDashboardTest extends AbstractComsSetup { return logger; } - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception {} - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - @Test(expected = NetworkTableKeyNotDefined.class) public void testGetBadValue() { SmartDashboard.getString("_404_STRING_KEY_SHOULD_NOT_BE_FOUND_"); @@ -94,11 +67,11 @@ public class SmartDashboardTest extends AbstractComsSetup { public void testReplaceString() { String key = "testReplaceString"; String valueOld = "oldValue"; - String valueNew = "newValue"; SmartDashboard.putString(key, valueOld); assertEquals(valueOld, SmartDashboard.getString(key)); assertEquals(valueOld, table.getString(key)); + String valueNew = "newValue"; SmartDashboard.putString(key, valueNew); assertEquals(valueNew, SmartDashboard.getString(key)); assertEquals(valueNew, table.getString(key)); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java index 66e99ec504..8e34cc45d9 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java @@ -14,8 +14,9 @@ import org.junit.runners.Suite.SuiteClasses; import edu.wpi.first.wpilibj.test.AbstractTestSuite; /** - * @author jonathanleitschuh + * All tests pertaining to {@link SmartDashboard}. * + * @author jonathanleitschuh */ @RunWith(Suite.class) @SuiteClasses({SmartDashboardTest.class}) diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java index 1305a7a22b..94703cd839 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java @@ -7,15 +7,15 @@ package edu.wpi.first.wpilibj.test; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runners.model.MultipleFailureException; +import java.util.logging.Level; +import java.util.logging.Logger; + import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.RobotBase; import edu.wpi.first.wpilibj.Timer; @@ -23,16 +23,18 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * This class serves as a superclass for all tests that involve the hardware on - * the roboRIO. It uses an {@link BeforeClass} statement to initialize network - * communications. Any test that needs to use the hardware MUST extend - * from this class, to ensure that all of the hardware will be able to run. - *$ + * This class serves as a superclass for all tests that involve the hardware on the roboRIO. It uses + * an {@link BeforeClass} statement to initialize network communications. Any test that needs to use + * the hardware MUST extend from this class, to ensure that all of the hardware will be able + * to run. + * * @author Fredric Silberberg * @author Jonathan Leitschuh */ public abstract class AbstractComsSetup { - /** Stores whether network coms have been initialized */ + /** + * Stores whether network coms have been initialized. + */ private static boolean initialized = false; /** @@ -40,7 +42,6 @@ public abstract class AbstractComsSetup { * station. After starting network coms, it will loop until the driver station * returns that the robot is enabled, to ensure that tests will be able to run * on the hardware. - *$ */ static { if (!initialized) { @@ -52,15 +53,15 @@ public abstract class AbstractComsSetup { TestBench.out().println("Started coms"); // Wait until the robot is enabled before starting the tests - int i = 0; + int enableCounter = 0; while (!DriverStation.getInstance().isEnabled()) { try { Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + ex.printStackTrace(); } // Prints the message on one line overwriting itself each time - TestBench.out().print("\rWaiting for enable: " + i++); + TestBench.out().print("\rWaiting for enable: " + enableCounter++); } TestBench.out().println(); @@ -74,8 +75,7 @@ public abstract class AbstractComsSetup { protected abstract Logger getClassLogger(); /** - * This causes a stack trace to be printed as the test is running as well as - * at the end + * This causes a stack trace to be printed as the test is running as well as at the end. */ @Rule public final TestWatcher getTestWatcher() { @@ -83,8 +83,8 @@ public abstract class AbstractComsSetup { } /** - * Given as a way to provide a custom test watcher for a test or set of tests - *$ + * Given as a way to provide a custom test watcher for a test or set of tests. + * * @return the test watcher to use */ protected TestWatcher getOverridenTestWatcher() { @@ -93,68 +93,69 @@ public abstract class AbstractComsSetup { protected class DefaultTestWatcher extends TestWatcher { /** - * Allows a failure to supply a custom status message to be displayed along - * with the stack trace. + * Allows a failure to supply a custom status message to be displayed along with the stack + * trace. */ - protected void failed(Throwable e, Description description, String status) { + protected void failed(Throwable throwable, Description description, String status) { TestBench.out().println(); // Instance of is the best way I know to retrieve this data. - if (e instanceof MultipleFailureException) { + if (throwable instanceof MultipleFailureException) { /* * MultipleFailureExceptions hold multiple exceptions in one exception. * In order to properly display these stack traces we have to cast the * throwable and work with the list of thrown exceptions stored within * it. */ - int i = 1; // Running exception count - int failureCount = ((MultipleFailureException) e).getFailures().size(); - for (Throwable singleThrown : ((MultipleFailureException) e).getFailures()) { + int exceptionCount = 1; // Running exception count + int failureCount = ((MultipleFailureException) throwable).getFailures().size(); + for (Throwable singleThrown : ((MultipleFailureException) throwable).getFailures()) { getClassLogger().logp( Level.SEVERE, description.getClassName(), description.getMethodName(), - (i++) + "/" + failureCount + " " + description.getDisplayName() + " failed " - + singleThrown.getMessage() + "\n" + status, singleThrown); + (exceptionCount++) + "/" + failureCount + " " + description.getDisplayName() + " " + + "failed " + singleThrown.getMessage() + "\n" + status, singleThrown); } } else { getClassLogger().logp(Level.SEVERE, description.getClassName(), description.getMethodName(), - description.getDisplayName() + " failed " + e.getMessage() + "\n" + status, e); + description.getDisplayName() + " failed " + throwable.getMessage() + "\n" + status, + throwable); } - super.failed(e, description); + super.failed(throwable, description); } /* * (non-Javadoc) - *$ + * * @see org.junit.rules.TestWatcher#failed(java.lang.Throwable, * org.junit.runner.Description) */ @Override - protected void failed(Throwable e, Description description) { - failed(e, description, ""); + protected void failed(Throwable exception, Description description) { + failed(exception, description, ""); } /* * (non-Javadoc) - *$ + * * @see org.junit.rules.TestWatcher#starting(org.junit.runner.Description) */ @Override protected void starting(Description description) { TestBench.out().println(); // Wait until the robot is enabled before starting the next tests - int i = 0; + int enableCounter = 0; while (!DriverStation.getInstance().isEnabled()) { try { Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (InterruptedException ex) { + ex.printStackTrace(); } // Prints the message on one line overwriting itself each time - TestBench.out().print("\rWaiting for enable: " + i++); + TestBench.out().print("\rWaiting for enable: " + enableCounter++); } getClassLogger().logp(Level.INFO, description.getClassName(), description.getMethodName(), "Starting"); @@ -167,12 +168,12 @@ public abstract class AbstractComsSetup { super.succeeded(description); } - }; + } /** * Logs a simple message without the logger formatting associated with it. - *$ - * @param level The level to log the message at + * + * @param level The level to log the message at * @param message The message to log */ protected void simpleLog(Level level, String message) { @@ -182,50 +183,50 @@ public abstract class AbstractComsSetup { } /** - * Provided as a replacement to lambda functions to allow for repeatable - * checks to see if a correct state is reached - *$ - * @author Jonathan Leitschuh + * Provided as a replacement to lambda functions to allow for repeatable checks to see if a + * correct state is reached. * + * @author Jonathan Leitschuh */ public abstract class BooleanCheck { - public BooleanCheck() {} + public BooleanCheck() { + } /** - * Runs the enclosed code and evaluates it to determine what state it should - * return. - *$ + * Runs the enclosed code and evaluates it to determine what state it should return. + * * @return true if the code provided within the method returns true */ - abstract public boolean getAsBoolean(); - }; + public abstract boolean getAsBoolean(); + } /** * Delays until either the correct state is reached or we reach the timeout. - *$ - * @param level The level to log the message at. - * @param timeout How long the delay should run before it should timeout and - * allow the test to continue - * @param message The message to accompany the delay. The message will display - * 'message' took 'timeout' seconds if it passed. - * @param correctState A method to determine if the test has reached a state - * where it is valid to continue + * + * @param level The level to log the message at. + * @param timeout How long the delay should run before it should timeout and allow the test + * to continue + * @param message The message to accompany the delay. The message will display 'message' took + * 'timeout' seconds if it passed. + * @param correctState A method to determine if the test has reached a state where it is valid to + * continue * @return a double representing how long the delay took to run in seconds. */ public double delayTillInCorrectStateWithMessage(Level level, double timeout, String message, - BooleanCheck correctState) { - int i = 0; + BooleanCheck correctState) { + int timeoutIndex; // As long as we are not in the correct state and the timeout has not been // reached then continue to run this loop - for (i = 0; i < (timeout * 100) && !correctState.getAsBoolean(); i++) { + for (timeoutIndex = 0; timeoutIndex < (timeout * 100) && !correctState.getAsBoolean(); + timeoutIndex++) { Timer.delay(.01); } if (correctState.getAsBoolean()) { - simpleLog(level, message + " took " + (i * .01) + " seconds"); + simpleLog(level, message + " took " + (timeoutIndex * .01) + " seconds"); } else { - simpleLog(level, message + " timed out after " + (i * .01) + " seconds"); + simpleLog(level, message + " timed out after " + (timeoutIndex * .01) + " seconds"); } - return i * .01; + return timeoutIndex * .01; } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java index 93a23c0de1..d8d81958d6 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java @@ -7,6 +7,11 @@ package edu.wpi.first.wpilibj.test; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.Request; +import org.junit.runners.Suite.SuiteClasses; + import java.lang.reflect.Method; import java.util.List; import java.util.Vector; @@ -14,33 +19,23 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.Request; -import org.junit.runners.Suite.SuiteClasses; -import org.junit.runners.model.InitializationError; - /** - * Allows tests suites and tests to be run selectively from the command line - * using a regex text pattern. - *$ - * @author jonathanleitschuh + * Allows tests suites and tests to be run selectively from the command line using a regex text + * pattern. * + * @author jonathanleitschuh */ public abstract class AbstractTestSuite { private static final Logger logger = Logger.getLogger(AbstractTestSuite.class.getName()); /** - * Gets all of the classes listed within the SuiteClasses annotation. To use - * it, annotate a class with @RunWith(Suite.class) and - * @SuiteClasses({TestClass1.class, ...}). When you run this - * class, it will run all the tests in all the suite classes. When loading the - * tests using regex the test list will be generated from this annotation. - *$ - * @return the list of classes listed in the - * @SuiteClasses({TestClass1.class, ...}) annotation. - * @throws RuntimeException If the @SuiteClasses annotation is - * missing. + * Gets all of the classes listed within the SuiteClasses annotation. To use it, annotate a class + * with @RunWith(Suite.class) and @SuiteClasses({TestClass1.class, + * ...}). When you run this class, it will run all the tests in all the suite classes. When + * loading the tests using regex the test list will be generated from this annotation. + * + * @return the list of classes listed in the @SuiteClasses({TestClass1.class, ...}). + * @throws RuntimeException If the @SuiteClasses annotation is missing. */ protected List> getAnnotatedTestClasses() { SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class); @@ -66,23 +61,22 @@ public abstract class AbstractTestSuite { } /** - * Stores a method name and method class pair. Used when searching for methods - * matching a given regex text. - *$ - * @author jonathanleitschuh + * Stores a method name and method class pair. Used when searching for methods matching a given + * regex text. * + * @author jonathanleitschuh */ protected class ClassMethodPair { - public final Class methodClass; - public final String methodName; + public final Class m_methodClass; + public final String m_methodName; - public ClassMethodPair(Class klass, Method m) { - this.methodClass = klass; - this.methodName = m.getName(); + public ClassMethodPair(Class klass, Method method) { + m_methodClass = klass; + m_methodName = method.getName(); } public Request getMethodRunRequest() { - return Request.method(methodClass, methodName); + return Request.method(m_methodClass, m_methodName); } } @@ -105,9 +99,9 @@ public abstract class AbstractTestSuite { /** - * Gets all of the test classes listed in this suite. Does not include any of - * the test suites. All of these classes contain tests. - *$ + * Gets all of the test classes listed in this suite. Does not include any of the test suites. All + * of these classes contain tests. + * * @param runningList the running list of classes to prevent recursion. * @return The list of base test classes. */ @@ -117,21 +111,20 @@ public abstract class AbstractTestSuite { if (areAnySuperClassesOfTypeAbstractTestSuite(c)) { // Create a new instance of this class so that we can retrieve its data try { - AbstractTestSuite suite = null; - Object o = c.newInstance(); - suite = (AbstractTestSuite) c.newInstance(); + AbstractTestSuite suite = (AbstractTestSuite) c.newInstance(); // Add the tests from this suite that match the regex to the list of // tests to run runningList = suite.getAllContainedBaseTests(runningList); - } catch (InstantiationException | IllegalAccessException e) { + } catch (InstantiationException | IllegalAccessException ex) { // This shouldn't happen unless the constructor is changed in some // way. - logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e); + logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", + ex); } } else if (c.getAnnotation(SuiteClasses.class) != null) { logger.log(Level.SEVERE, - String.format("class '%s' must extend %s to be searchable using regex.", c.getName()), - AbstractTestSuite.class.getName()); + String.format("class '%s' must extend %s to be searchable using regex.", + c.getName(), AbstractTestSuite.class.getName())); } else { // This is a class containing tests // so add it to the list runningList.add(c); @@ -141,9 +134,9 @@ public abstract class AbstractTestSuite { } /** - * Gets all of the test classes listed in this suite. Does not include any of - * the test suites. All of these classes contain tests. - *$ + * Gets all of the test classes listed in this suite. Does not include any of the test suites. All + * of these classes contain tests. + * * @return The list of base test classes. */ public List> getAllContainedBaseTests() { @@ -153,10 +146,10 @@ public abstract class AbstractTestSuite { /** - * Retrieves all of the classes listed in the - * @SuiteClasses annotation that match the given regex text. - *$ - * @param regex the text pattern to retrieve. + * Retrieves all of the classes listed in the @SuiteClasses annotation that match the + * given regex text. + * + * @param regex the text pattern to retrieve. * @param runningList the running list of classes to prevent recursion * @return The list of classes matching the regex pattern */ @@ -171,9 +164,9 @@ public abstract class AbstractTestSuite { } /** - * Retrieves all of the classes listed in the - * @SuiteClasses annotation that match the given regex text. - *$ + * Retrieves all of the classes listed in the @SuiteClasses annotation that match the + * given regex text. + * * @param regex the text pattern to retrieve. * @return The list of classes matching the regex pattern */ @@ -183,15 +176,15 @@ public abstract class AbstractTestSuite { } /** - * Searches through all of the suites and tests and loads only the test or - * test suites matching the regex text. This method also prevents a single - * test from being loaded multiple times by loading the suite first then - * loading tests from all non loaded suites. - *$ + * Searches through all of the suites and tests and loads only the test or test suites matching + * the regex text. This method also prevents a single test from being loaded multiple times by + * loading the suite first then loading tests from all non loaded suites. + * * @param regex the regex text to search for * @return the list of suite and/or test classes matching the regex. */ - private List> getSuiteOrTestMatchingRegex(final String regex, List> runningList) { + private List> getSuiteOrTestMatchingRegex(final String regex, List> + runningList) { // Get any test suites matching the regex using the superclass methods runningList = getAllClassMatching(regex, runningList); @@ -206,22 +199,22 @@ public abstract class AbstractTestSuite { // Prevents recursively adding tests/suites that have already been added if (!runningList.contains(c)) { try { - AbstractTestSuite suite = null; + final AbstractTestSuite suite; // Check the class to make sure that it is not a test class if (areAnySuperClassesOfTypeAbstractTestSuite(c)) { // Create a new instance of this class so that we can retrieve its // data. - Object o = c.newInstance(); suite = (AbstractTestSuite) c.newInstance(); // Add the tests from this suite that match the regex to the list of // tests to run runningList = suite.getSuiteOrTestMatchingRegex(regex, runningList); } - } catch (InstantiationException | IllegalAccessException e) { + } catch (InstantiationException | IllegalAccessException ex) { // This shouldn't happen unless the constructor is changed in some // way. - logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e); + logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", + ex); } } } @@ -229,11 +222,10 @@ public abstract class AbstractTestSuite { } /** - * Searches through all of the suites and tests and loads only the test or - * test suites matching the regex text. This method also prevents a single - * test from being loaded multiple times by loading the suite first then - * loading tests from all non loaded suites. - *$ + * Searches through all of the suites and tests and loads only the test or test suites matching + * the regex text. This method also prevents a single test from being loaded multiple times by + * loading the suite first then loading tests from all non loaded suites. + * * @param regex the regex text to search for * @return the list of suite and/or test classes matching the regex. */ @@ -243,26 +235,21 @@ public abstract class AbstractTestSuite { } - /** - * Retrieves all of the classes listed in the - * @SuiteClasses annotation. - *$ + * Retrieves all of the classes listed in the @SuiteClasses annotation. + * * @return List of SuiteClasses - * @throws RuntimeException If the @SuiteClasses annotation is - * missing. + * @throws RuntimeException If the @SuiteClasses annotation is missing. */ public List> getAllClasses() { return getAnnotatedTestClasses(); } /** - * Gets the name of all of the classes listed within the - * @SuiteClasses annotation. - *$ + * Gets the name of all of the classes listed within the @SuiteClasses annotation. + * * @return the list of classes. - * @throws RuntimeException If the @SuiteClasses annotation is - * missing. + * @throws RuntimeException If the @SuiteClasses annotation is missing. */ public List getAllClassName() { List classNames = new Vector(); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractTestSuiteTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuiteTest.java similarity index 68% rename from wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractTestSuiteTest.java rename to wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuiteTest.java index e3be60ccb1..210db6657c 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractTestSuiteTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuiteTest.java @@ -7,13 +7,6 @@ package edu.wpi.first.wpilibj.test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; - -import java.util.List; - import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -22,11 +15,20 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.model.InitializationError; +import java.util.List; + import edu.wpi.first.wpilibj.test.AbstractTestSuite.ClassMethodPair; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; + /** - * @author jonathanleitschuh + * Yes, this is the test system testing itself. Functionally, this is making sure that all tests get + * run correctly when you use parametrized arguments. * + * @author jonathanleitschuh */ public class AbstractTestSuiteTest { @@ -37,20 +39,17 @@ public class AbstractTestSuiteTest { class TestForAbstractTestSuite extends AbstractTestSuite { } - TestForAbstractTestSuite testSuite; + TestForAbstractTestSuite m_testSuite; - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { - testSuite = new TestForAbstractTestSuite(); + m_testSuite = new TestForAbstractTestSuite(); } @Test public void testGetTestsMatchingAll() throws InitializationError { // when - List> collectedTests = testSuite.getAllClassMatching(".*"); + List> collectedTests = m_testSuite.getAllClassMatching(".*"); // then assertEquals(7, collectedTests.size()); } @@ -58,7 +57,7 @@ public class AbstractTestSuiteTest { @Test public void testGetTestsMatchingSample() throws InitializationError { // when - List> collectedTests = testSuite.getAllClassMatching(".*Sample.*"); + List> collectedTests = m_testSuite.getAllClassMatching(".*Sample.*"); // then assertEquals(4, collectedTests.size()); } @@ -66,7 +65,7 @@ public class AbstractTestSuiteTest { @Test public void testGetTestsMatchingUnusual() throws InitializationError { // when - List> collectedTests = testSuite.getAllClassMatching(".*Unusual.*"); + List> collectedTests = m_testSuite.getAllClassMatching(".*Unusual.*"); // then assertEquals(1, collectedTests.size()); assertEquals(UnusualTest.class, collectedTests.get(0)); @@ -75,7 +74,7 @@ public class AbstractTestSuiteTest { @Test public void testGetTestsFromSuiteMatchingAll() throws InitializationError { // when - List> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*"); + List> collectedTests = m_testSuite.getSuiteOrTestMatchingRegex(".*"); // then assertEquals(7, collectedTests.size()); } @@ -83,58 +82,61 @@ public class AbstractTestSuiteTest { @Test public void testGetTestsFromSuiteMatchingTest() throws InitializationError { // when - List> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*Test.*"); + List> collectedTests = m_testSuite.getSuiteOrTestMatchingRegex(".*Test.*"); // then assertEquals(7, collectedTests.size()); - assertThat(collectedTests, hasItems(new Class[] {FirstSubSuiteTest.class, - SecondSubSuiteTest.class, UnusualTest.class})); + assertThat(collectedTests, hasItems(FirstSubSuiteTest.class, + SecondSubSuiteTest.class, UnusualTest.class)); assertThat(collectedTests, - not(hasItems(new Class[] {ExampleSubSuite.class, EmptySuite.class}))); + not(hasItems(new Class[]{ExampleSubSuite.class, EmptySuite.class}))); } @Test public void testGetMethodFromTest() { // when - List pairs = testSuite.getMethodMatching(".*Method.*"); + List pairs = m_testSuite.getMethodMatching(".*Method.*"); // then assertEquals(1, pairs.size()); - assertEquals(FirstSubSuiteTest.class, pairs.get(0).methodClass); - assertEquals(FirstSubSuiteTest.METHODNAME, pairs.get(0).methodName); + assertEquals(FirstSubSuiteTest.class, pairs.get(0).m_methodClass); + assertEquals(FirstSubSuiteTest.METHODNAME, pairs.get(0).m_methodName); } } - +@SuppressWarnings("OneTopLevelClass") class FirstSampleTest { } - +@SuppressWarnings("OneTopLevelClass") class SecondSampleTest { } - +@SuppressWarnings("OneTopLevelClass") class ThirdSampleTest { } - +@SuppressWarnings("OneTopLevelClass") class FourthSampleTest { } - +@SuppressWarnings("OneTopLevelClass") class UnusualTest { } // This is a member of both suites @Ignore("Prevents ANT from trying to run these as tests") +@SuppressWarnings("OneTopLevelClass") class FirstSubSuiteTest { public static final String METHODNAME = "aTestMethod"; @Test - public void aTestMethod() {} + @SuppressWarnings("MethodName") + public void aTestMethod() { + } } - +@SuppressWarnings("OneTopLevelClass") class SecondSubSuiteTest { } @@ -142,6 +144,7 @@ class SecondSubSuiteTest { @RunWith(Suite.class) @SuiteClasses({FirstSubSuiteTest.class, SecondSubSuiteTest.class, UnusualTest.class}) @Ignore("Prevents ANT from trying to run these as tests") +@SuppressWarnings("OneTopLevelClass") class ExampleSubSuite extends AbstractTestSuite { } @@ -149,5 +152,6 @@ class ExampleSubSuite extends AbstractTestSuite { @Ignore("Prevents ANT from trying to run these as tests") @RunWith(Suite.class) @SuiteClasses({}) +@SuppressWarnings("OneTopLevelClass") class EmptySuite extends AbstractTestSuite { } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java index 9654a993d3..ac1b41ee05 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java @@ -7,8 +7,6 @@ package edu.wpi.first.wpilibj.test; -import java.io.File; - import org.apache.tools.ant.BuildLogger; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; @@ -16,15 +14,21 @@ import org.apache.tools.ant.taskdefs.optional.junit.FormatterElement; import org.apache.tools.ant.taskdefs.optional.junit.JUnitTask; import org.apache.tools.ant.taskdefs.optional.junit.JUnitTest; +import java.io.File; + /** - * Provides an entry point for tests to run with ANT. This allows ant to output - * JUnit XML test results for Jenkins. - *$ - * @author jonathanleitschuh + * Provides an entry point for tests to run with ANT. This allows ant to output JUnit XML test + * results for Jenkins. * + * @author jonathanleitschuh */ public class AntJunitLanucher { + /** + * Main entry point for jenkins + * + * @param args Arguments passed to java. + */ public static void main(String... args) { if (args.length == 0) { String path = @@ -35,7 +39,6 @@ public class AntJunitLanucher { try { // Create the file to store the test output new File(pathToReports).mkdirs(); - JUnitTask task = new JUnitTask(); project.setProperty("java.io.tmpdir", pathToReports); @@ -46,6 +49,8 @@ public class AntJunitLanucher { formatToScreen.setType(typeScreen); formatToScreen.setUseFile(false); formatToScreen.setOutput(System.out); + + JUnitTask task = new JUnitTask(); task.addFormatter(formatToScreen); // add a build listener to the project @@ -73,8 +78,8 @@ public class AntJunitLanucher { TestBench.out().println("Beginning Test Execution With ANT"); task.execute(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } else { TestBench.out().println( diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java index 823824bfee..a371898b24 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java @@ -7,19 +7,16 @@ package edu.wpi.first.wpilibj.test; -import java.util.logging.Logger; - import org.junit.Test; +import java.util.logging.Logger; + /** - * This class is designated to allow for simple testing of the library without - * the overlying testing framework. This test is NOT run as a normal part of the - * testing process and must be explicitly selected at runtime by using the - * 'quick' argument. - *$ - * This test should never be committed with changes to it but can be used during - * development to aid in feature testing. - *$ + * This class is designated to allow for simple testing of the library without the overlying testing + * framework. This test is NOT run as a normal part of the testing process and must be explicitly + * selected at runtime by using the 'quick' argument. This test should never be committed with + * changes to it but can be used during development to aid in feature testing. + * * @author Jonathan Leitschuh */ public class QuickTest extends AbstractComsSetup { @@ -27,7 +24,7 @@ public class QuickTest extends AbstractComsSetup { /* * (non-Javadoc) - *$ + * * @see edu.wpi.first.wpilibj.test.AbstractComsSetup#getClassLogger() */ @Override diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java index 276d16060a..6b19befc6c 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java @@ -7,20 +7,22 @@ package edu.wpi.first.wpilibj.test; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + /** - * This JUnit Rule allows you to apply this rule to any test to allow it to run - * multiple times. This is important if you have a test that fails only - * "sometimes" and needs to be rerun to find the issue. + * This JUnit Rule allows you to apply this rule to any test to allow it to run multiple times. This + * is important if you have a test that fails only "sometimes" and needs to be rerun to find the + * issue. * - * This code was originally found here: Running JUnit Tests Repeatedly Without Loops + *

This code was originally found here: + * + * Running JUnit Tests Repeatedly Without Loops * * @author Frank Appel */ @@ -28,24 +30,27 @@ public class RepeatRule implements TestRule { @Retention(RetentionPolicy.RUNTIME) @Target({java.lang.annotation.ElementType.METHOD}) public @interface Repeat { - public abstract int times(); + /** + * The number of times to repeat the test. + */ + int times(); } private static class RepeatStatement extends Statement { - private final int times; - private final Statement statement; + private final int m_times; + private final Statement m_statement; private RepeatStatement(int times, Statement statement) { - this.times = times; - this.statement = statement; + m_times = times; + m_statement = statement; } @Override public void evaluate() throws Throwable { - for (int i = 0; i < times; i++) { - statement.evaluate(); + for (int i = 0; i < m_times; i++) { + m_statement.evaluate(); } } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java index 621172dae6..ca16d6d3a9 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java @@ -34,23 +34,21 @@ import edu.wpi.first.wpilibj.fixtures.FilterOutputFixture; import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.fixtures.RelayCrossConnectFixture; import edu.wpi.first.wpilibj.fixtures.TiltPanCameraFixture; -import edu.wpi.first.wpilibj.interfaces.Gyro; import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource; /** - * This class provides access to all of the elements on the test bench, for use - * in fixtures. This class is a singleton, you should use {@link #getInstance()} - * to obtain a reference to the {@code TestBench}. + * This class provides access to all of the elements on the test bench, for use in fixtures. This + * class is a singleton, you should use {@link #getInstance()} to obtain a reference to the {@code + * TestBench}. * - * TODO: This needs to be updated to the most recent test bench setup. + *

TODO: This needs to be updated to the most recent test bench setup. * * @author Fredric Silberberg */ public final class TestBench { /** - * The time that it takes to have a motor go from rotating at full speed to - * completely stopped + * The time that it takes to have a motor go from rotating at full speed to completely stopped. */ public static final double MOTOR_STOP_TIME = 0.25; @@ -95,18 +93,21 @@ public final class TestBench { public static final int kMovAvgTaps = 6; public static final double kMovAvgExpectedOutput = -10.191644; - /** The Singleton instance of the Test Bench */ + /** + * The Singleton instance of the Test Bench. + */ private static TestBench instance = null; /** - * The single constructor for the TestBench. This method is private in order - * to prevent multiple TestBench objects from being allocated + * The single constructor for the TestBench. This method is private in order to prevent multiple + * TestBench objects from being allocated. */ - protected TestBench() {} + protected TestBench() { + } /** - * Constructs a new set of objects representing a connected set of Talon - * controlled Motors and an encoder + * Constructs a new set of objects representing a connected set of Talon controlled Motors and an + * encoder. * * @return a freshly allocated Talon, Encoder pair */ @@ -137,8 +138,8 @@ public final class TestBench { } /** - * Constructs a new set of objects representing a connected set of Victor - * controlled Motors and an encoder + * Constructs a new set of objects representing a connected set of Victor controlled Motors and an + * encoder. * * @return a freshly allocated Victor, Encoder pair */ @@ -169,8 +170,8 @@ public final class TestBench { } /** - * Constructs a new set of objects representing a connected set of Jaguar - * controlled Motors and an encoder + * Constructs a new set of objects representing a connected set of Jaguar controlled Motors and an + * encoder. * * @return a freshly allocated Jaguar, Encoder pair */ @@ -232,7 +233,7 @@ public final class TestBench { /* * (non-Javadoc) - *$ + * * @see * edu.wpi.first.wpilibj.fixtures.CANMotorEncoderFixture#givePowerCycleRelay * () @@ -249,10 +250,9 @@ public final class TestBench { } /** - * Constructs a new set of objects representing a connected set of CANJaguar - * controlled Motors and an encoder
- * Note: The CANJaguar is not freshly allocated because the CANJaguar lacks a - * free() method + * Constructs a new set of objects representing a connected set of CANJaguar controlled Motors and + * an encoder
Note: The CANJaguar is not freshly allocated because the CANJaguar lacks a + * free() method. * * @return an existing CANJaguar and a freshly allocated Encoder */ @@ -302,20 +302,18 @@ public final class TestBench { } /** - * Gets two lists of possible DIO pairs for the two pairs - *$ - * @return + * Gets two lists of possible DIO pairs for the two pairs. */ private List> getDIOCrossConnect() { List> pairs = new ArrayList>(); List setA = - Arrays.asList(new Integer[][] { + Arrays.asList(new Integer[][]{ {new Integer(DIOCrossConnectA1), new Integer(DIOCrossConnectA2)}, {new Integer(DIOCrossConnectA2), new Integer(DIOCrossConnectA1)}}); pairs.add(setA); List setB = - Arrays.asList(new Integer[][] { + Arrays.asList(new Integer[][]{ {new Integer(DIOCrossConnectB1), new Integer(DIOCrossConnectB2)}, {new Integer(DIOCrossConnectB2), new Integer(DIOCrossConnectB1)}}); pairs.add(setB); @@ -323,6 +321,7 @@ public final class TestBench { return pairs; } + @SuppressWarnings("JavadocMethod") public static AnalogCrossConnectFixture getAnalogCrossConnectFixture() { AnalogCrossConnectFixture analogIO = new AnalogCrossConnectFixture() { @Override @@ -338,6 +337,7 @@ public final class TestBench { return analogIO; } + @SuppressWarnings("JavadocMethod") public static RelayCrossConnectFixture getRelayCrossConnectFixture() { RelayCrossConnectFixture relay = new RelayCrossConnectFixture() { @@ -360,9 +360,9 @@ public final class TestBench { } /** - * Return a single Collection containing all of the DIOCrossConnectFixtures in - * all two pair combinations - *$ + * Return a single Collection containing all of the DIOCrossConnectFixtures in all two pair + * combinations. + * * @return pairs of DIOCrossConnectFixtures */ public Collection getDIOCrossConnectCollection() { @@ -374,19 +374,16 @@ public final class TestBench { } /** - * Gets an array of pairs for the encoder to use using two different lists - *$ - * @param listA - * @param listB + * Gets an array of pairs for the encoder to use using two different lists. + * * @param flip whether this encoder needs to be flipped * @return A list of different inputs to use for the tests */ private Collection getPairArray(List listA, List listB, - boolean flip) { + boolean flip) { Collection encoderPortPairs = new ArrayList(); for (Integer[] portPairsA : listA) { - ArrayList construtorInput = new ArrayList(); - Integer inputs[] = new Integer[5]; + Integer[] inputs = new Integer[5]; inputs[0] = portPairsA[0]; // InputA inputs[1] = portPairsA[1]; // InputB @@ -396,6 +393,7 @@ public final class TestBench { inputs[4] = flip ? 0 : 1; // The flip bit } + ArrayList construtorInput = new ArrayList(); construtorInput.add(inputs); inputs = inputs.clone(); @@ -411,8 +409,8 @@ public final class TestBench { } /** - * Constructs the list of inputs to be used for the encoder test - *$ + * Constructs the list of inputs to be used for the encoder test. + * * @return A collection of different input pairs to use for the encoder */ public Collection getEncoderDIOCrossConnectCollection() { @@ -427,8 +425,7 @@ public final class TestBench { } /** - * Constructs a new set of objects representing a single-pole IIR filter with - * a noisy data source + * Constructs a new set of objects representing a single-pole IIR filter with a noisy data source. * * @return a single-pole IIR filter with a noisy data source */ @@ -437,15 +434,15 @@ public final class TestBench { @Override protected LinearDigitalFilter giveFilter(PIDSource source) { return LinearDigitalFilter.singlePoleIIR(source, - kSinglePoleIIRTimeConstant, - kFilterStep); + kSinglePoleIIRTimeConstant, + kFilterStep); } }; } /** - * Constructs a new set of objects representing a moving average filter with a - * noisy data source using a linear digital filter + * Constructs a new set of objects representing a moving average filter with a noisy data source + * using a linear digital filter. * * @return a moving average filter with a noisy data source */ @@ -459,8 +456,8 @@ public final class TestBench { } /** - * Constructs a new set of objects representing a single-pole IIR filter with - * a repeatable data source + * Constructs a new set of objects representing a single-pole IIR filter with a repeatable data + * source. * * @return a single-pole IIR filter with a repeatable data source */ @@ -469,15 +466,14 @@ public final class TestBench { @Override protected LinearDigitalFilter giveFilter(PIDSource source) { return LinearDigitalFilter.singlePoleIIR(source, - kSinglePoleIIRTimeConstant, - kFilterStep); + kSinglePoleIIRTimeConstant, + kFilterStep); } }; } /** - * Constructs a new set of objects representing a high-pass filter with a - * repeatable data source + * Constructs a new set of objects representing a high-pass filter with a repeatable data source. * * @return a high-pass filter with a repeatable data source */ @@ -486,14 +482,14 @@ public final class TestBench { @Override protected LinearDigitalFilter giveFilter(PIDSource source) { return LinearDigitalFilter.highPass(source, kHighPassTimeConstant, - kFilterStep); + kFilterStep); } }; } /** - * Constructs a new set of objects representing a moving average filter with a - * repeatable data source using a linear digital filter + * Constructs a new set of objects representing a moving average filter with a repeatable data + * source using a linear digital filter. * * @return a moving average filter with a repeatable data source */ @@ -507,9 +503,8 @@ public final class TestBench { } /** - * Gets the singleton of the TestBench. If the TestBench is not already - * allocated in constructs an new instance of it. Otherwise it returns the - * existing instance. + * Gets the singleton of the TestBench. If the TestBench is not already allocated in constructs an + * new instance of it. Otherwise it returns the existing instance. * * @return The Singleton instance of the TestBench */ @@ -521,10 +516,10 @@ public final class TestBench { } /** - * Provides access to the output stream for the test system. This should be - * used instead of System.out This is gives us a way to implement changes to - * where the output text of this test system is sent. - *$ + * Provides access to the output stream for the test system. This should be used instead of + * System.out This is gives us a way to implement changes to where the output text of this test + * system is sent. + * * @return The test bench global print stream. */ public static PrintStream out() { @@ -532,10 +527,10 @@ public final class TestBench { } /** - * Provides access to the error stream for the test system. This should be - * used instead of System.err This is gives us a way to implement changes to - * where the output text of this test system is sent. - *$ + * Provides access to the error stream for the test system. This should be used instead of + * System.err This is gives us a way to implement changes to where the output text of this test + * system is sent. + * * @return The test bench global print stream. */ public static PrintStream err() { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java index 5b8d200073..dd896e8797 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java @@ -7,16 +7,6 @@ package edu.wpi.first.wpilibj.test; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Vector; -import java.util.logging.LogManager; -import java.util.logging.Logger; -import java.util.regex.Pattern; - import junit.framework.JUnit4TestAdapter; import junit.runner.Version; @@ -27,16 +17,24 @@ import org.junit.runner.notification.Failure; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import java.util.regex.Pattern; + import edu.wpi.first.wpilibj.WpiLibJTestSuite; import edu.wpi.first.wpilibj.can.CANTestSuite; import edu.wpi.first.wpilibj.command.CommandTestSuite; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboardTestSuite; /** - * The WPILibJ Integeration Test Suite collects all of the tests to be run by - * junit. In order for a test to be run, it must be added the list of suite - * classes below. The tests will be run in the order they are listed in the - * suite classes annotation. + * The WPILibJ Integeration Test Suite collects all of the tests to be run by junit. In order for a + * test to be run, it must be added the list of suite classes below. The tests will be run in the + * order they are listed in the suite classes annotation. */ @RunWith(Suite.class) // These are listed on separate lines to prevent merge conflicts @@ -47,17 +45,19 @@ public class TestSuite extends AbstractTestSuite { // Sets up the logging output final InputStream inputStream = TestSuite.class.getResourceAsStream("/logging.properties"); try { - if (inputStream == null) + if (inputStream == null) { throw new NullPointerException("./logging.properties was not loaded"); + } LogManager.getLogManager().readConfiguration(inputStream); Logger.getAnonymousLogger().info("Loaded"); - } catch (final IOException | NullPointerException e) { + } catch (final IOException | NullPointerException ex) { Logger.getAnonymousLogger().severe("Could not load default logging.properties file"); - Logger.getAnonymousLogger().severe(e.getMessage()); + Logger.getAnonymousLogger().severe(ex.getMessage()); } TestBench.out().println("Starting Tests"); } + private static final Logger WPILIBJ_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj"); private static final Logger WPILIBJ_COMMAND_ROOT_LOGGER = Logger .getLogger("edu.wpi.first.wpilibj.command"); @@ -72,6 +72,9 @@ public class TestSuite extends AbstractTestSuite { private static TestSuite instance = null; + /** + * Get the singleton instance of the test suite. + */ public static TestSuite getInstance() { if (instance == null) { instance = new TestSuite(); @@ -80,13 +83,13 @@ public class TestSuite extends AbstractTestSuite { } /** - * This has to be public so that the JUnit4 + * This has to be public so that the JUnit4. */ - public TestSuite() {} + public TestSuite() { + } /** - * Displays a help message for the user when they use the --help flag at - * runtime. + * Displays a help message for the user when they use the --help flag at runtime. */ protected static void displayHelp() { StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n"); @@ -104,7 +107,8 @@ public class TestSuite extends AbstractTestSuite { + QUICK_TEST_FLAG + " or " + CLASS_NAME_FILTER + " and run them the given number of times.\n"); helpMessage - .append("[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This documentation can be found at " + .append("[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This " + + "documentation can be found at " + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n"); helpMessage.append("\n"); helpMessage.append("\n"); @@ -113,8 +117,8 @@ public class TestSuite extends AbstractTestSuite { } /** - * Lets the user know that they used the TestSuite improperly and gives - * details about how to use it correctly in the future. + * Lets the user know that they used the TestSuite improperly and gives details about how to use + * it correctly in the future. */ protected static void displayInvalidUsage(String message, String... args) { StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n"); @@ -133,16 +137,16 @@ public class TestSuite extends AbstractTestSuite { /** * Prints the loaded tests before they are run. - *$ + * * @param classes the classes that were loaded. */ protected static void printLoadedTests(final Class... classes) { StringBuilder loadedTestsMessage = new StringBuilder("The following tests were loaded:\n"); - Package p = null; + Package packagE = null; for (Class c : classes) { - if (c.getPackage().equals(p)) { - p = c.getPackage(); - loadedTestsMessage.append(p.getName() + "\n"); + if (c.getPackage().equals(packagE)) { + packagE = c.getPackage(); + loadedTestsMessage.append(packagE.getName() + "\n"); } loadedTestsMessage.append("\t" + c.getSimpleName() + "\n"); } @@ -151,16 +155,15 @@ public class TestSuite extends AbstractTestSuite { /** - * Parses the arguments passed at runtime and runs the appropriate tests based - * upon these arguments - *$ + * Parses the arguments passed at runtime and runs the appropriate tests based upon these + * arguments + * * @param args the args passed into the program at runtime - * @return the restults of the tests that have run. If no tests were run then - * null is returned. + * @return the restults of the tests that have run. If no tests were run then null is returned. */ protected static Result parseArgsRunAndGetResult(final String[] args) { if (args.length == 0) { // If there are no args passed at runtime then just - // run all of the tests. + // run all of the tests. printLoadedTests(TestSuite.class); return JUnitCore.runClasses(TestSuite.class); } @@ -171,7 +174,6 @@ public class TestSuite extends AbstractTestSuite { // The class filter was passed boolean classFilter = false; String classRegex = ""; - boolean repeatFilter = false; int repeatCount = 1; for (String s : args) { @@ -180,22 +182,20 @@ public class TestSuite extends AbstractTestSuite { methodRegex = new String(s).replace(METHOD_NAME_FILTER, ""); } if (Pattern.matches(METHOD_REPEAT_FILTER + ".*", s)) { - repeatFilter = true; try { repeatCount = Integer.parseInt(new String(s).replace(METHOD_REPEAT_FILTER, "")); - } catch (NumberFormatException e) { + } catch (NumberFormatException ex) { displayInvalidUsage("The argument passed to the repeat rule was not a valid integer.", args); } } if (Pattern.matches(CLASS_NAME_FILTER + ".*", s)) { classFilter = true; - classRegex = new String(s).replace(CLASS_NAME_FILTER, ""); + classRegex = s.replace(CLASS_NAME_FILTER, ""); } } - ArrayList argsParsed = new ArrayList(Arrays.asList(args)); if (argsParsed.contains(HELP_FLAG)) { // If the user inputs the help flag then return the help message and exit @@ -214,46 +214,46 @@ public class TestSuite extends AbstractTestSuite { */ class MultipleResult extends Result { private static final long serialVersionUID = 1L; - private final List failures = new Vector(); - private int runCount = 0; - private int ignoreCount = 0; - private long runTime = 0; + private final List m_failures = new ArrayList<>(); + private int m_runCount = 0; + private int m_ignoreCount = 0; + private long m_runTime = 0; @Override public int getRunCount() { - return runCount; + return m_runCount; } @Override public int getFailureCount() { - return failures.size(); + return m_failures.size(); } @Override public long getRunTime() { - return runTime; + return m_runTime; } @Override public List getFailures() { - return failures; + return m_failures; } @Override public int getIgnoreCount() { - return ignoreCount; + return m_ignoreCount; } /** - * Adds the given result's data to this result - *$ - * @param r the result to add to this result + * Adds the given result's data to this result. + * + * @param result the result to add to this result */ - void addResult(Result r) { - failures.addAll(r.getFailures()); - runCount += r.getRunCount(); - ignoreCount += r.getIgnoreCount(); - runTime += r.getRunTime(); + void addResult(Result result) { + m_failures.addAll(result.getFailures()); + m_runCount += result.getRunCount(); + m_ignoreCount += result.getIgnoreCount(); + m_runTime += result.getRunTime(); } } @@ -261,19 +261,20 @@ public class TestSuite extends AbstractTestSuite { if (methodFilter) { List pairs = (new TestSuite()).getMethodMatching(methodRegex); if (pairs.size() == 0) { - displayInvalidUsage("None of the arguments passed to the method name filter matched.", args); + displayInvalidUsage("None of the arguments passed to the method name filter matched.", + args); return null; } // Print out the list of tests before we run them TestBench.out().println("Running the following tests:"); Class classListing = null; for (ClassMethodPair p : pairs) { - if (!p.methodClass.equals(classListing)) { + if (!p.m_methodClass.equals(classListing)) { // Only display the class name every time it changes - classListing = p.methodClass; + classListing = p.m_methodClass; TestBench.out().println(classListing); } - TestBench.out().println("\t" + p.methodName); + TestBench.out().println("\t" + p.m_methodName); } @@ -353,9 +354,9 @@ public class TestSuite extends AbstractTestSuite { } /** - * This is used by ant to get the Junit tests. This is required because the - * tests try to load using a JUnit 3 framework. JUnit4 uses annotations to - * load tests. This method allows JUnit3 to load JUnit4 tests. + * This is used by ant to get the Junit tests. This is required because the tests try to load + * using a JUnit 3 framework. JUnit4 uses annotations to load tests. This method allows JUnit3 to + * load JUnit4 tests. */ public static junit.framework.Test suite() { return new JUnit4TestAdapter(TestSuite.class); @@ -363,8 +364,8 @@ public class TestSuite extends AbstractTestSuite { /** - * The method called at runtime - *$ + * The method called at runtime. + * * @param args The test suites to run */ public static void main(String[] args) { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java index eadb82b3c0..4b0ea006b7 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java @@ -1,13 +1,11 @@ /** - * This is the starting point for the integration testing framework. This - * package should contain classes that are not explicitly for testing the - * library but instead provide the framework that the tests can extend from. - * Every test should extend from - * {@link edu.wpi.first.wpilibj.test.AbstractComsSetup} to ensure that Network - * Communications is properly instantiated before the test is run. - *$ - * The {@link edu.wpi.first.wpilibj.test.TestBench} should contain the port - * numbers for all of the hardware and these values should not be explicitly - * defined anywhere else in the testing framework. + * This is the starting point for the integration testing framework. This package should contain + * classes that are not explicitly for testing the library but instead provide the framework that + * the tests can extend from. Every test should extend from + * {@link edu.wpi.first.wpilibj.test.AbstractComsSetup} + * to ensure that Network Communications is properly instantiated before the test is run. The + * {@link edu.wpi.first.wpilibj.test.TestBench} should contain the port numbers for all of the + * hardware and these values should not be explicitly defined anywhere else in the testing + * framework. */ -package edu.wpi.first.wpilibj.test; \ No newline at end of file +package edu.wpi.first.wpilibj.test; diff --git a/wpilibjIntegrationTests/src/main/resources/logging.properties b/wpilibjIntegrationTests/src/main/resources/logging.properties index 3081004405..304d41a407 100644 --- a/wpilibjIntegrationTests/src/main/resources/logging.properties +++ b/wpilibjIntegrationTests/src/main/resources/logging.properties @@ -2,9 +2,7 @@ # classes. These handlers will be installed during VM startup. # By default we only configure a ConsoleHandler, which will only # show messages at the INFO and above levels. -handlers = java.util.logging.ConsoleHandler - - +handlers=java.util.logging.ConsoleHandler # Default global logging level. # This specifies which kinds of events are logged across # all loggers. For any given facility this global level @@ -12,15 +10,13 @@ handlers = java.util.logging.ConsoleHandler # Note that the ConsoleHandler also has a separate level # setting to limit messages printed to the console. #.level= INFO -.level= INFO - +.level=INFO ############################################################ # Handler specific properties. # Describes specific configuration info for Handlers. ############################################################ java.util.logging.ConsoleHandler.level=FINER java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter - ############################################################ # Facility specific properties. # Provides extra control for each logger.