35 Commits

Author SHA1 Message Date
Daniel Carta b41ed2667c Testing 9/18 2025-09-18 17:51:05 -06:00
Daniel Carta 5279c085e1 Match Scouting Indicator Overhaul
Redo of the UI for the scouting indicator and overall enhancement of the UI
2025-06-17 11:15:36 -06:00
Michael Mikovsky 41460fcd7e Use android log. Fixes #5 2025-05-27 09:29:57 -06:00
Michael Mikovsky 782fb73050 Delete TODO.md 2025-05-26 11:18:01 -06:00
Michael Mikovsky 7e9954d78a Merge pull request #6 from Team4388/python-file-transfer
Add HTTP file transfer
2025-05-26 17:07:25 +00:00
Michael Mikovsky 65baecac35 Fix crash 2025-05-26 10:13:28 -06:00
Michael Mikovsky e278bc10a1 Add java side of http syncing 2025-05-25 18:48:02 -06:00
Michael Mikovsky 5d727cf359 Add upload and download to python server 2025-05-25 13:51:45 -06:00
Michael Mikovsky ae147771cb Start working on the server 2025-05-25 13:44:37 -06:00
Michael Mikovsky 36801e2f9b Add comments to classes and update TODO 2025-04-21 12:06:37 -06:00
Michael Mikovsky 50419e284c Fix sorting crash 2025-04-13 10:45:33 -06:00
Michael Mikovsky c8c278b316 Finish up report tool 2025-04-12 14:22:27 -06:00
Michael Mikovsky e280fc8523 Add scout notice, start work on scouting report system 2025-04-11 22:07:41 -06:00
Michael Mikovsky e559b4dac9 Add mutli-user scouting data attribution 2025-04-10 14:17:46 -06:00
Michael Mikovsky b83d67359e Add scouting dashboard details 2025-04-10 14:00:31 -06:00
Michael Mikovsky 15c503bbb7 Standardize colors 2025-04-10 11:55:06 -06:00
Michael Mikovsky e2b0eee354 Fix candlestick problems 2025-04-10 10:52:58 -06:00
Michael Mikovsky ea41c5db24 Backwards compatibility 2025-04-09 22:07:52 -06:00
Michael Mikovsky 2210d8d654 Add candlestick charts 2025-04-09 18:35:28 -06:00
Michael Mikovsky 9f2ef1b5ed Add field image option 2025-04-08 12:45:33 -06:00
Michael Mikovsky 2dfad418e3 Add revert button 2025-04-08 12:27:09 -06:00
Michael Mikovsky 465b94ac7e Add fields displayed within field editor 2025-04-08 11:48:23 -06:00
Michael Mikovsky 72921a7c11 Fix field updating issue 2025-04-07 21:41:34 -06:00
Michael Mikovsky eaa14adbd9 Work on Field Editor, Improve capitalization of classes 2025-04-04 14:15:30 -06:00
Michael Mikovsky a371f2f449 Add UUIDs, Work on redesigning fields editor 2025-04-03 08:38:24 -06:00
Michael Mikovsky 6c38147c6d Improve TBA event downloading 2025-04-01 12:41:37 -06:00
Michael Mikovsky 3f4a2309b3 Add loading indicator for field data 2025-03-31 16:37:29 -06:00
Michael Mikovsky 5447b64857 Change header byte length, add data view by field type 2025-03-31 11:58:45 -06:00
Michael Mikovsky 967dc3c967 Add rescout option 2025-03-26 10:56:05 -06:00
Michael Mikovsky d2c075da9c Add options for team number and quick alliance swap 2025-03-25 12:06:03 -06:00
Michael Mikovsky fbdd2206c0 Move fields to settings, add setting for match number 2025-03-25 11:50:16 -06:00
Michael Mikovsky 71ef386075 Add team icons and colored cards 2025-03-24 22:29:29 -06:00
Michael Mikovsky ee3c3b6b9c Improve error popup system 2025-03-24 12:41:43 -06:00
Michael Mikovsky 534207ebb1 Fix more scouting data crashing 2025-03-15 06:09:47 -06:00
Michael Mikovsky d458ad7669 Update Version Number 2025-03-07 12:31:10 -07:00
126 changed files with 7154 additions and 3204 deletions
+6
View File
@@ -1,3 +1,9 @@
# Python server
__pycache__/
metadata.json
api_key.txt
server_data/
# Gradle files # Gradle files
.gradle/ .gradle/
build/ build/
-24
View File
@@ -1,24 +0,0 @@
### TODO:
##### Scouting:
##### Data Analysis:
- Statbotics intigration???
##### Functionality:
- Test new FTP thing
- UUIDs instead of names for the fields
- Fix data storage crashes
- Match selector instead of list for individual team views
### In Progress:
##### Scouting:
- Make scouting UI look much better
##### Data Analysis:
##### Functionality:
### Done:
##### Scouting:
- Make practice mode
- Description for fields
##### Data Analysis:
##### Functionality:
- "Send Meta Files" button
- Year selector
+3 -3
View File
@@ -25,8 +25,8 @@ android {
applicationId = "com.ridgebotics.ridgescout" applicationId = "com.ridgebotics.ridgescout"
minSdk = 24 minSdk = 24
targetSdk = 34 targetSdk = 34
versionCode = 9 // **IMPORTANT** Increment this before releasing on github versionCode = 11 // **IMPORTANT** Increment this before releasing on github
versionName = "1.2"// **IMPORTANT** Change this before releasing on github (<Year num since 2024>.<Update Version>) versionName = "1.4"// **IMPORTANT** Change this before releasing on github (<Year num since 2024>.<Update Version>)
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
@@ -57,7 +57,7 @@ dependencies {
implementation(libs.constraintlayout) implementation(libs.constraintlayout)
implementation(libs.lifecycle.livedata.ktx) implementation(libs.lifecycle.livedata.ktx)
implementation(libs.lifecycle.viewmodel.ktx) implementation(libs.lifecycle.viewmodel.ktx)
implementation(libs.navigation.fragment) implementation("androidx.navigation:navigation-fragment:2.8.9")
implementation(libs.navigation.ui) implementation(libs.navigation.ui)
implementation(libs.preference) implementation(libs.preference)
// implementation(libs.support.annotations) // implementation(libs.support.annotations)
@@ -3,16 +3,14 @@ package com.ridgebotics.ridgescout;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.view.MenuItem;
import com.ridgebotics.ridgescout.databinding.ActivityMainBinding; import com.ridgebotics.ridgescout.databinding.ActivityMainBinding;
import com.ridgebotics.ridgescout.scoutingData.fields; import com.ridgebotics.ridgescout.scoutingData.Fields;
import com.ridgebotics.ridgescout.utility.SentimentAnalysis; import com.ridgebotics.ridgescout.utility.SentimentAnalysis;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController; import androidx.navigation.NavController;
import androidx.navigation.NavOptions; import androidx.navigation.NavOptions;
@@ -21,12 +19,14 @@ import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI; import androidx.navigation.ui.NavigationUI;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.SettingsManager;
import com.google.android.material.navigation.NavigationBarView;
import java.util.Objects; import java.util.Objects;
import java.util.TimeZone; import java.util.TimeZone;
// Entrypoint for the scouting app.
// Configures stuff like the nav menu
// Also has some extra functions like a better back stack or a way to suppress the back button.
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
@@ -40,19 +40,21 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
// Load shared prefrences
settingsManager.prefs = this.getSharedPreferences( SettingsManager.prefs = this.getSharedPreferences(
"com.ridgebotics.ridgescout", Context.MODE_PRIVATE); "com.ridgebotics.ridgescout", Context.MODE_PRIVATE);
if(!fileEditor.fileExist(fields.matchFieldsFilename)){ // Load default match fields
fields.save(fields.matchFieldsFilename, fields.default_match_fields); if(!FileEditor.fileExist(Fields.matchFieldsFilename)){
Fields.save(Fields.matchFieldsFilename, Fields.default_match_fields);
} }
if(!fileEditor.fileExist(fields.pitsFieldsFilename)){ // Load default pit fields
fields.save(fields.pitsFieldsFilename, fields.default_pit_fields); if(!FileEditor.fileExist(Fields.pitsFieldsFilename)){
Fields.save(Fields.pitsFieldsFilename, Fields.default_pit_fields);
} }
// get time zone for FTP file transfer
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
AlertManager.init(this); AlertManager.init(this);
@@ -76,7 +78,7 @@ public class MainActivity extends AppCompatActivity {
appBarConfiguration = new AppBarConfiguration.Builder( appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_scouting, R.id.navigation_scouting,
R.id.navigation_data, R.id.navigation_data_parent,
R.id.navigation_transfer, R.id.navigation_transfer,
R.id.navigation_settings) R.id.navigation_settings)
.build(); .build();
@@ -0,0 +1,178 @@
package com.ridgebotics.ridgescout.scoutingData;
import com.ridgebotics.ridgescout.types.input.CheckboxType;
import com.ridgebotics.ridgescout.types.input.DropdownType;
import com.ridgebotics.ridgescout.types.input.FieldposType;
import com.ridgebotics.ridgescout.types.input.FieldType;
import com.ridgebotics.ridgescout.types.input.NumberType;
import com.ridgebotics.ridgescout.types.input.TallyType;
import com.ridgebotics.ridgescout.types.input.TextType;
import com.ridgebotics.ridgescout.types.input.SliderType;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList;
import java.util.UUID;
// The mechanism to load, save, and create the fields based off of the raw types from ScoutingDataWriter.java
public class Fields {
// public static ScoutingVersion sv = new ScoutingVersion();
public static final String matchFieldsFilename = "matches.fields";
public static final String pitsFieldsFilename = "pits.fields";
private static String uuid(){
return UUID.randomUUID().toString();
}
public static final FieldType[][] default_match_fields = new FieldType[][] {
{
new FieldposType(uuid(),"Auto start pos", "Where does the robot start its auto?", new int[]{0,0}),
new TallyType(uuid(),"Auto L4 Coral", "How many coral did this robot score in L4 during auto?", 0),
new TallyType(uuid(),"Auto L3 Coral", "How many coral did this robot score in L3 during auto?", 0),
new TallyType(uuid(),"Auto L2 Coral", "How many coral did this robot score in L2 during auto?", 0),
new TallyType(uuid(),"Auto L1/Trough Coral", "How many coral did this robot score in L1 during auto?", 0),
new TallyType(uuid(),"Auto Processor Algae", "How many algae did this robot score in the Barge during auto?", 0),
new TallyType(uuid(),"Auto Barge Algae", "How many algae did this robot score in the Barge during auto?", 0),
new DropdownType(uuid(),"Auto Quality", "How did the robot drive during auto?", new String[]{"Smooth", "Jittery"}, 0),
new TextType(uuid(),"Auto Comments", "Anything interesting about auto", ""),
new TallyType(uuid(),"Teleop L4 Coral", "How many coral did this robot score in L4 during auto?", 0),
new TallyType(uuid(),"Teleop L3 Coral", "How many coral did this robot score in L3 during auto?", 0),
new TallyType(uuid(),"Teleop L2 Coral", "How many coral did this robot score in L2 during auto?", 0),
new TallyType(uuid(),"Teleop L1 Coral", "How many coral did this robot score in L1 during auto?", 0),
new TallyType(uuid(),"Teleop Processor Algae", "How many algae did this robot score in the Barge during auto?", 0),
new TallyType(uuid(),"Teleop Barge Algae", "How many algae did this robot score in the Barge during auto?", 0),
new CheckboxType(uuid(),"Upper Algae Removal", "Did the robot remove upper Algae?", 0),
new CheckboxType(uuid(),"Lower Algae Removal", "Did the robot remove lower Algae?", 0),
new DropdownType(uuid(),"Teleop Quality", "How did the robot drive during Teleop?", new String[]{"Smooth", "Jittery"}, 0),
new TextType(uuid(),"Teleop Comments", "Anything interesting about Teleop", ""),
new DropdownType(uuid(),"Climb State", "What was the final condition of the robot?", new String[]{"Nothing", "Continued Cycling", "Park", "Attempted Shallow", "Shallow", "Attempted Deep", "Deep"}, 0),
new DropdownType(uuid(),"Robot Condition", "Was anything broken?", new String[]{"Everything was working", "Something was maybe broken", "Something was broken", "Robot was disabled for part of the match", "Missing robot"}, 0),
new TextType(uuid(),"Other Comments", "Any other comments you have", "")
}
};
public static final FieldType[][] default_pit_fields = new FieldType[][] {
{
new DropdownType(uuid(),"Drivetrain type", "What type of drivetrain does this team have?", new String[]{"Swerve Drive", "Tank Drive (Differential)", "Other, Info in comments"}, 0),
new DropdownType(uuid(),"Intake type", "What type of intake does this team have?", new String[]{"Ground only", "Player Station only", "Both", "Other, Info in comments"}, 0),
new DropdownType(uuid(),"Intake Consistency", "How consistent is the robot at intakeing?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new DropdownType(uuid(),"Score Area", "What does this robot score?", new String[]{"Only Algae", "Mostly Algae", "Both", "Mostly Coral", "Only Coral"}, 0),
new CheckboxType(uuid(),"L4 Scoring", "Will the robot score in Layer 4?", 0),
new CheckboxType(uuid(),"L3 Scoring", "Will the robot score in Layer 3?", 0),
new CheckboxType(uuid(),"L2 Scoring", "Will the robot score in Layer 3?", 0),
new CheckboxType(uuid(),"L1/Trough Scoring", "Will the robot score in Layer 1?", 0),
new CheckboxType(uuid(),"Processor Scoring", "Will the robot score in the Processor?", 0),
new CheckboxType(uuid(),"Barge Scoring", "Will the robot score algae in the Barge?", 0),
new DropdownType(uuid(),"Scoring Consistency", "How consistent is the robot at Scoring?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new TextType(uuid(),"Auto Capability", "What autos does this team have?", ""),
new DropdownType(uuid(),"Auto Consistency", "How consistent is the robot at Auto?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new DropdownType(uuid(),"Climb type", "What does the robot do to climb?", new String[]{"No Climb", "Only Shallow", "Only Deep", "Both Shallow and Deep"}, 0),
new DropdownType(uuid(),"Climb Consistency", "How consistent is the robot at climbing?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new TextType(uuid(),"Cool Comments", "Is there anything cool about the robot?", ""),
new TextType(uuid(),"Comments", "Things go here", "Day 1:\n\nDay 2:\n\nDay 3:\n")
}
};
public static boolean save(String filename, FieldType[][] values){
try {
ByteBuilder bb = new ByteBuilder();
for (int i = 0; i < values.length; i++) {
bb.addRaw(127, save_version(values[i]));
}
FileEditor.writeFile(filename, bb.build());
return true;
}catch (ByteBuilder.buildingException e) {
AlertManager.error(e);
return false;
// throw new RuntimeException(e);
}
}
private static byte[] save_version(FieldType[] values) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
for(int i =0; i < values.length; i++){
bb.addRaw(values[i].get_byte_id(), values[i].encode());
}
return bb.build();
}
public static FieldType[][] load(String filename){
byte[] bytes = FileEditor.readFile(filename);
// System.out.println(bytes);
try {
BuiltByteParser bbp = new BuiltByteParser(bytes);
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
FieldType[][] values = new FieldType[objects.size()][];
for(int i = 0 ; i < objects.size(); i++){
values[i] = load_version((byte[]) objects.get(i).get());
}
return values;
} catch (Exception e) {
AlertManager.error(e);
return null;
}
}
private static FieldType[] load_version(byte[] bytes) throws BuiltByteParser.byteParsingExeption{
BuiltByteParser bbp = new BuiltByteParser(bytes);
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
FieldType[] output = new FieldType[objects.size()];
for(int i = 0 ; i < objects.size(); i++){
BuiltByteParser.parsedObject obj = objects.get(i);
FieldType t = null;
switch (obj.getType()){
case FieldType.slider_type_id:
t = new SliderType();
break;
case FieldType.dropdownType:
t = new DropdownType();
break;
case FieldType.notesType:
t = new TextType();
break;
case FieldType.tallyType:
t = new TallyType();
break;
case FieldType.numberType:
t = new NumberType();
break;
case FieldType.checkboxType:
t = new CheckboxType();
break;
case FieldType.fieldposType:
t = new FieldposType();
break;
}
t.decode((byte[]) obj.get());
output[i] = t;
}
return output;
}
}
@@ -1,25 +1,30 @@
package com.ridgebotics.ridgescout.scoutingData; package com.ridgebotics.ridgescout.scoutingData;
import com.ridgebotics.ridgescout.scoutingData.transfer.transferType; import android.util.Log;
import com.ridgebotics.ridgescout.scoutingData.transfer.TransferType;
import com.ridgebotics.ridgescout.types.ScoutingArray; import com.ridgebotics.ridgescout.types.ScoutingArray;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.intArrType; import com.ridgebotics.ridgescout.types.data.IntArrType;
import com.ridgebotics.ridgescout.types.data.stringType; import com.ridgebotics.ridgescout.types.data.StringType;
import com.ridgebotics.ridgescout.types.input.inputType; import com.ridgebotics.ridgescout.types.input.FieldType;
import com.ridgebotics.ridgescout.types.data.intType; import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
// Mostly an extension of Fields.java. Saves the raw data from each Field Type.
public class ScoutingDataWriter { public class ScoutingDataWriter {
// private static final int int_type_id = 255; // private static final int int_type_id = 255;
// private static final int string_type_id = 254; // private static final int string_type_id = 254;
public static boolean save(int version, String username, String filename, dataType[] data){ public static boolean save(int version, String username, String filename, RawDataType[] data){
ByteBuilder bb = new ByteBuilder(); ByteBuilder bb = new ByteBuilder();
try { try {
bb.addInt(version); bb.addInt(version);
@@ -28,19 +33,19 @@ public class ScoutingDataWriter {
switch (data[i].getValueType()){ switch (data[i].getValueType()){
case NUM: case NUM:
bb.addInt((int) data[i].forceGetValue()); bb.addInt((int) data[i].forceGetValue());
System.out.println("Saved INT: " + data[i].getName() + ", ("+ data[i].get() +")"); Log.i(ScoutingDataWriter.class.toString(),"Saved INT: " + data[i].getUUID() + ", ("+ data[i].get() +")");
break; break;
case STRING: case STRING:
bb.addString((String) data[i].forceGetValue()); bb.addString((String) data[i].forceGetValue());
System.out.println("Saved STR: " + data[i].getName() + ", ("+ data[i].get() +")"); Log.i(ScoutingDataWriter.class.toString(), "Saved STR: " + data[i].getUUID() + ", ("+ data[i].get() +")");
break; break;
case NUMARR: case NUMARR:
bb.addIntArray((int[]) data[i].forceGetValue()); bb.addIntArray((int[]) data[i].forceGetValue());
System.out.println("Saved INT Array: " + data[i].getName() + ", ("+ Arrays.toString((int[]) data[i].get()) +")"); Log.i(ScoutingDataWriter.class.toString(), "Saved INT Array: " + data[i].getUUID() + ", ("+ Arrays.toString((int[]) data[i].get()) +")");
} }
} }
byte[] bytes = bb.build(); byte[] bytes = bb.build();
fileEditor.writeFile(filename, bytes); FileEditor.writeFile(filename, bytes);
return true; return true;
} catch (ByteBuilder.buildingException e) { } catch (ByteBuilder.buildingException e) {
AlertManager.error(e); AlertManager.error(e);
@@ -55,38 +60,46 @@ public class ScoutingDataWriter {
public ScoutingArray data; public ScoutingArray data;
} }
public static ParsedScoutingDataResult load(String filename, inputType[][] values , transferType[][] transferValues){ public static ParsedScoutingDataResult load(String filename, FieldType[][] values , TransferType[][] transferValues){
byte[] bytes = fileEditor.readFile(filename); byte[] bytes = FileEditor.readFile(filename);
BuiltByteParser bbp = new BuiltByteParser(bytes); BuiltByteParser bbp = new BuiltByteParser(bytes);
try { try {
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse(); ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
dataType[] dataTypes = new dataType[objects.size()-2]; RawDataType[] rawDataTypes = new RawDataType[objects.size()-2];
int version = ((int)objects.get(0).get()); int version = ((int)objects.get(0).get());
if(values.length <= version) {
// AlertManager.addSimpleError("Error loading " + filename);
AlertManager.error(new BuiltByteParser.byteParsingExeption("Field version (" +version + ") is too recent as compared to latest version (" + (values.length-1) + ")!"));
return null;
}
// System.out.println(version); // System.out.println(version);
String username = (String) objects.get(1).get(); String username = (String) objects.get(1).get();
for(int i = 0; i < values[version].length; i++){ for(int i = 0; i < values[version].length; i++){
switch (objects.get(i+2).getType()){ switch (objects.get(i+2).getType()){
case 1: // Int case 1: // Int
dataTypes[i] = intType.newNull(values[version][i].name); rawDataTypes[i] = IntType.newNull(values[version][i].UUID);
dataTypes[i].forceSetValue(objects.get(i+2).get()); rawDataTypes[i].forceSetValue(objects.get(i+2).get());
System.out.println("Loaded INT: " + values[version][i].name + ", ("+ dataTypes[i].get() +")"); Log.i(ParsedScoutingDataResult.class.toString(),"Loaded INT: " + values[version][i].name + " (" + values[version][i].UUID + ") " + ", ("+ rawDataTypes[i].get() +")");
break; break;
case 2: // String case 2: // String
dataTypes[i] = stringType.newNull(values[version][i].name); rawDataTypes[i] = StringType.newNull(values[version][i].UUID);
dataTypes[i].forceSetValue(objects.get(i+2).get()); rawDataTypes[i].forceSetValue(objects.get(i+2).get());
System.out.println("Loaded STR: " + values[version][i].name + ", ("+ dataTypes[i].get() +")"); Log.i(ParsedScoutingDataResult.class.toString(),"Loaded STR: " + values[version][i].name + " (" + values[version][i].UUID + ") " + ", ("+ rawDataTypes[i].get() +")");
break; break;
case 3: // Int array case 3: // Int array
dataTypes[i] = intArrType.newNull(values[version][i].name); rawDataTypes[i] = IntArrType.newNull(values[version][i].UUID);
dataTypes[i].forceSetValue(objects.get(i+2).get()); rawDataTypes[i].forceSetValue(objects.get(i+2).get());
System.out.println("Loaded intARR: " + values[version][i].name + ", ("+ Arrays.toString((int[])dataTypes[i].get()) +")"); Log.i(ParsedScoutingDataResult.class.toString(),"Loaded intARR: " + values[version][i].name + " (" + values[version][i].UUID + ") " + ", ("+ Arrays.toString((int[]) rawDataTypes[i].get()) +")");
break; break;
} }
} }
ScoutingArray msa = new ScoutingArray(version, dataTypes, values, transferValues); ScoutingArray msa = new ScoutingArray(version, rawDataTypes, values, transferValues);
msa.update(); msa.update();
ParsedScoutingDataResult psda = new ParsedScoutingDataResult(); ParsedScoutingDataResult psda = new ParsedScoutingDataResult();
@@ -104,4 +117,15 @@ public class ScoutingDataWriter {
} }
} }
// A function that takes in a list of names seperated by commas, and adds a name if it is not included
// This is used for multi-scouter attribution to data.
public static String checkAddName(String prevnames, String name){
List<String> names = new ArrayList<>(List.of(prevnames.split(", ")));
if(!names.contains(name))
names.add(name);
return String.join(", ", names);
}
} }
@@ -1,195 +0,0 @@
package com.ridgebotics.ridgescout.scoutingData;
import com.ridgebotics.ridgescout.types.input.checkboxType;
import com.ridgebotics.ridgescout.types.input.dropdownType;
import com.ridgebotics.ridgescout.types.input.fieldposType;
import com.ridgebotics.ridgescout.types.input.inputType;
import com.ridgebotics.ridgescout.types.input.numberType;
import com.ridgebotics.ridgescout.types.input.tallyType;
import com.ridgebotics.ridgescout.types.input.textType;
import com.ridgebotics.ridgescout.types.input.sliderType;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.fileEditor;
import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList;
public class fields {
// public static ScoutingVersion sv = new ScoutingVersion();
public static final String matchFieldsFilename = "matches.fields";
public static final String pitsFieldsFilename = "pits.fields";
public static final inputType[][] default_match_fields = new inputType[][] {
{
new fieldposType("Auto start pos", "Where does the robot start its auto?", new int[]{0,0}),
new tallyType("Auto L4 Coral", "How many coral did this robot score in L4 during auto?", 0),
new tallyType("Auto L3 Coral", "How many coral did this robot score in L3 during auto?", 0),
new tallyType("Auto L2 Coral", "How many coral did this robot score in L2 during auto?", 0),
new tallyType("Auto L1/Trough Coral", "How many coral did this robot score in L1 during auto?", 0),
new tallyType("Auto Processor Algae", "How many algae did this robot score in the Barge during auto?", 0),
new tallyType("Auto Barge Algae", "How many algae did this robot score in the Barge during auto?", 0),
new dropdownType("Auto Quality", "How did the robot drive during auto?", new String[]{"Smooth", "Jittery"}, 0),
new textType("Auto Comments", "Anything interesting about auto", ""),
new tallyType("Teleop L4 Coral", "How many coral did this robot score in L4 during auto?", 0),
new tallyType("Teleop L3 Coral", "How many coral did this robot score in L3 during auto?", 0),
new tallyType("Teleop L2 Coral", "How many coral did this robot score in L2 during auto?", 0),
new tallyType("Teleop L1 Coral", "How many coral did this robot score in L1 during auto?", 0),
new tallyType("Teleop Processor Algae", "How many algae did this robot score in the Barge during auto?", 0),
new tallyType("Teleop Barge Algae", "How many algae did this robot score in the Barge during auto?", 0),
new checkboxType("Upper Algae Removal", "Did the robot remove upper Algae?", 0),
new checkboxType("Lower Algae Removal", "Did the robot remove lower Algae?", 0),
new dropdownType("Teleop Quality", "How did the robot drive during Teleop?", new String[]{"Smooth", "Jittery"}, 0),
new textType("Teleop Comments", "Anything interesting about Teleop", ""),
new dropdownType("Climb State", "What was the final condition of the robot?", new String[]{"Nothing", "Continued Cycling", "Park", "Attempted Shallow", "Shallow", "Attempted Deep", "Deep"}, 0),
new dropdownType("Robot Condition", "Was anything broken?", new String[]{"Everything was working", "Something was maybe broken", "Something was broken", "Robot was disabled for part of the match", "Missing robot"}, 0),
new textType("Other Comments", "Any other comments you have", "")
}
};
public static final inputType[][] default_pit_fields = new inputType[][] {
{
new dropdownType("Drivetrain type", "What type of drivetrain does this team have?", new String[]{"Swerve Drive", "Tank Drive (Differential)", "Other, Info in comments"}, 0),
new dropdownType("Intake type", "What type of intake does this team have?", new String[]{"Ground only", "Player Station only", "Both", "Other, Info in comments"}, 0),
new dropdownType("Intake Consistency", "How consistent is the robot at intakeing?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new dropdownType("Score Area", "What does this robot score?", new String[]{"Only Algae", "Mostly Algae", "Both", "Mostly Coral", "Only Coral"}, 0),
new checkboxType("L4 Scoring", "Will the robot score in Layer 4?", 0),
new checkboxType("L3 Scoring", "Will the robot score in Layer 3?", 0),
new checkboxType("L2 Scoring", "Will the robot score in Layer 3?", 0),
new checkboxType("L1/Trough Scoring", "Will the robot score in Layer 1?", 0),
new checkboxType("Processor Scoring", "Will the robot score in the Processor?", 0),
new checkboxType("Barge Scoring", "Will the robot score algae in the Barge?", 0),
new dropdownType("Scoring Consistency", "How consistent is the robot at Scoring?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new textType("Auto Capability", "What autos does this team have?", ""),
new dropdownType("Auto Consistency", "How consistent is the robot at Auto?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new dropdownType("Climb type", "What does the robot do to climb?", new String[]{"No Climb", "Only Shallow", "Only Deep", "Both Shallow and Deep"}, 0),
new dropdownType("Climb Consistency", "How consistent is the robot at climbing?", new String[]{"Does not work", "Worked a few times during testing", "Works most of the time", "Fails sometimes", "Never fails"}, 0),
new textType("Cool Comments", "Is there anything cool about the robot?", ""),
new textType("Comments", "Things go here", "Day 1:\n\nDay 2:\n\nDay 3:\n")
}
};
public static boolean save(String filename, inputType[][] values){
try {
ByteBuilder bb = new ByteBuilder();
for (int i = 0; i < values.length; i++) {
bb.addRaw(127, save_version(values[i]));
}
fileEditor.writeFile(filename, bb.build());
return true;
}catch (ByteBuilder.buildingException e) {
AlertManager.error(e);
return false;
// throw new RuntimeException(e);
}
}
private static byte[] save_version(inputType[] values) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
for(int i =0; i < values.length; i++){
bb.addRaw(values[i].get_byte_id(), values[i].encode());
}
return bb.build();
}
public static inputType[][] load(String filename){
byte[] bytes = fileEditor.readFile(filename);
// System.out.println(bytes);
try {
BuiltByteParser bbp = new BuiltByteParser(bytes);
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
inputType[][] values = new inputType[objects.size()][];
for(int i = 0 ; i < objects.size(); i++){
values[i] = load_version((byte[]) objects.get(i).get());
}
return values;
} catch (Exception e) {
AlertManager.error(e);
return null;
}
}
private static inputType[] load_version(byte[] bytes) throws BuiltByteParser.byteParsingExeption{
BuiltByteParser bbp = new BuiltByteParser(bytes);
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
inputType[] output = new inputType[objects.size()];
for(int i = 0 ; i < objects.size(); i++){
BuiltByteParser.parsedObject obj = objects.get(i);
inputType t = null;
switch (obj.getType()){
case inputType.slider_type_id:
t = new sliderType();
break;
case inputType.dropdownType:
t = new dropdownType();
break;
case inputType.notesType:
t = new textType();
break;
case inputType.tallyType:
t = new tallyType();
break;
case inputType.numberType:
t = new numberType();
break;
case inputType.checkboxType:
t = new checkboxType();
break;
case inputType.fieldposType:
t = new fieldposType();
break;
}
t.decode((byte[]) obj.get());
output[i] = t;
}
return output;
}
// public static void test(){
// ScoutingVersion.transferType[][] transferValues = sv.get_transfer_values(values);
//
// ScoutingVersion.ScoutingArray msa = sv.new ScoutingArray(0, new ScoutingVersion.dataType[]{
// sv.new stringType("name", "test-username"),
// sv.new intType("How good is robot", 12)
// }, values, transferValues);
//
// msa.update();
//
// for(ScoutingVersion.dataType dt : msa.array){
// if(dt == null) continue;
// switch (dt.getValueType()){
// case NUM:
// System.out.println(dt.name + " " + (int) dt.get());
// break;
// case STRING:
// System.out.println(dt.name + " " + (String) dt.get());
// break;
// }
//
// }
// }
}
@@ -0,0 +1,9 @@
package com.ridgebotics.ridgescout.scoutingData.transfer;
// Transfer type if a field was created
public class CreateTransferType extends TransferType {
public transferValue getType() {return transferValue.CREATE;}
public CreateTransferType(String UUID){
super(UUID);
}
}
@@ -0,0 +1,9 @@
package com.ridgebotics.ridgescout.scoutingData.transfer;
// Transfer type if a field directly transfers
public class DirectTransferType extends TransferType {
public transferValue getType() {return transferValue.DIRECT;}
public DirectTransferType(String UUID){
super(UUID);
}
}
@@ -0,0 +1,48 @@
package com.ridgebotics.ridgescout.scoutingData.transfer;
import com.ridgebotics.ridgescout.types.input.FieldType;
// The "Transfer Types" system, a component in the loading of scouting data.
// Dictates how the
// For example, a field can be created in one version, and how the app updates it is by obtaining it's transfer value, in this case being "create".
public abstract class TransferType {
public enum transferValue {
DIRECT,
CREATE
}
public String UUID;
public abstract transferValue getType();
public TransferType(String UUID){
this.UUID = UUID;
}
private static FieldType get_input_type_by_UUID(FieldType[] values, String UUID){
for(FieldType it : values){
if(it.UUID.equals(UUID)){
return it;
}
}
return null;
}
//Inputs:
public static TransferType[][] get_transfer_values(FieldType[][] values) {
TransferType[][] output = new TransferType[values.length][];
for(int a = 1; a < values.length; a++){
TransferType[] v = new TransferType[values[a].length];
for(int b = 0; b < values[a].length; b++){
String UUID = values[a][b].UUID;
if(get_input_type_by_UUID(values[a-1], UUID) != null){
v[b] = new DirectTransferType(UUID);
}else{
v[b] = new CreateTransferType(UUID);
}
}
output[a-1] = v;
}
return output;
}
}
@@ -1,8 +0,0 @@
package com.ridgebotics.ridgescout.scoutingData.transfer;
public class createTransferType extends transferType {
public transferValue getType() {return transferValue.CREATE;}
public createTransferType(String name){
super(name);
}
}
@@ -1,8 +0,0 @@
package com.ridgebotics.ridgescout.scoutingData.transfer;
public class directTransferType extends transferType {
public transferValue getType() {return transferValue.DIRECT;}
public directTransferType(String name){
super(name);
}
}
@@ -1,41 +0,0 @@
package com.ridgebotics.ridgescout.scoutingData.transfer;
import com.ridgebotics.ridgescout.types.input.inputType;
public abstract class transferType {
public enum transferValue {
DIRECT,
CREATE
}
public String name;
public abstract transferValue getType();
public transferType(String name){
this.name = name;
}
private static inputType get_input_type_by_name(inputType[] values, String name){
for(inputType it : values){
if(it.name.equals(name)){
return it;
}
}
return null;
}
public static transferType[][] get_transfer_values(inputType[][] values) {
transferType[][] output = new transferType[values.length][];
for(int a = 1; a < values.length; a++){
transferType[] v = new transferType[values[a].length];
for(int b = 0; b < values[a].length; b++){
String name = values[a][b].name;
if(get_input_type_by_name(values[a-1], name) != null){
v[b] = new directTransferType(name);
}else{
v[b] = new createTransferType(name);
}
}
output[a-1] = v;
}
return output;
}
}
@@ -1,21 +1,24 @@
package com.ridgebotics.ridgescout.types; package com.ridgebotics.ridgescout.types;
import com.ridgebotics.ridgescout.scoutingData.transfer.createTransferType; import android.util.Log;
import com.ridgebotics.ridgescout.scoutingData.transfer.directTransferType;
import com.ridgebotics.ridgescout.scoutingData.transfer.transferType;
import com.ridgebotics.ridgescout.types.data.dataType;
import com.ridgebotics.ridgescout.types.data.intType;
import com.ridgebotics.ridgescout.types.data.stringType;
import com.ridgebotics.ridgescout.types.input.inputType;
import com.ridgebotics.ridgescout.scoutingData.transfer.CreateTransferType;
import com.ridgebotics.ridgescout.scoutingData.transfer.DirectTransferType;
import com.ridgebotics.ridgescout.scoutingData.transfer.TransferType;
import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.types.data.StringType;
import com.ridgebotics.ridgescout.types.input.FieldType;
// A wrapper class for the stuff going on in Fields.java and ScoutingDataWriter.java.
public class ScoutingArray { public class ScoutingArray {
public int version; public int version;
public dataType[] array; public RawDataType[] array;
public inputType[][] values; public FieldType[][] values;
public int latest_version_num; public int latest_version_num;
public transferType[][] transfer_values; public TransferType[][] transfer_values;
public ScoutingArray(int version, dataType[] array, inputType[][] values, transferType[][] transfer_values){ public ScoutingArray(int version, RawDataType[] array, FieldType[][] values, TransferType[][] transfer_values){
this.version = version; this.version = version;
this.array = array; this.array = array;
this.values = values; this.values = values;
@@ -23,53 +26,50 @@ public class ScoutingArray {
this.transfer_values = transfer_values; this.transfer_values = transfer_values;
} }
public ScoutingArray(int version, dataType[] array, inputType[][] values){ public ScoutingArray(int version, RawDataType[] array, FieldType[][] values){
this(version, array, values, transferType.get_transfer_values(values)); this(version, array, values, TransferType.get_transfer_values(values));
} }
public void update(){ public void update(){
while(version<latest_version_num){ while(version<latest_version_num){
dataType[] new_values = new dataType[transfer_values[version].length]; RawDataType[] new_values = new RawDataType[transfer_values[version].length];
for(int i = 0; i < transfer_values[version].length; i++){ for(int i = 0; i < transfer_values[version].length; i++){
transferType tv = transfer_values[version][i]; TransferType tv = transfer_values[version][i];
switch (tv.getType()){ switch (tv.getType()){
case DIRECT: case DIRECT:
new_values[i] = direct_transfer((directTransferType) tv); new_values[i] = direct_transfer((DirectTransferType) tv);
continue; continue;
// case RENAME:
// new_values[i] = rename_transfer((renameTransferType) tv);
// continue;
case CREATE: case CREATE:
new_values[i] = create_transfer((createTransferType) tv); new_values[i] = create_transfer((CreateTransferType) tv);
continue; continue;
} }
} }
this.array = new_values; this.array = new_values;
version++; version++;
System.out.println("Updated to " + version); Log.i(getClass().toString(),"Updated to " + version);
} }
} }
private inputType get_input_type_by_name(int version, String name){ private FieldType get_input_type_by_UUID(int version, String UUID){
for(inputType it : values[version]){ for(FieldType it : values[version]){
if(it.name.equals(name)){ if(it.UUID.equals(UUID)){
return it; return it;
} }
} }
return null; return null;
} }
private dataType get_data_type_by_name(String name){ private RawDataType get_data_type_by_UUID(String UUID){
for(dataType dt : array){ for(RawDataType dt : array){
if(dt.getName().equals(name)){ if(dt.getUUID().equals(UUID)){
return dt; return dt;
} }
} }
return null; return null;
} }
private dataType direct_transfer(directTransferType tv){ private RawDataType direct_transfer(DirectTransferType tv){
return get_data_type_by_name(tv.name); return get_data_type_by_UUID(tv.UUID);
} }
// private dataType rename_transfer(renameTransferType tv){ // private dataType rename_transfer(renameTransferType tv){
@@ -78,13 +78,13 @@ public class ScoutingArray {
// return dt; // return dt;
// } // }
private dataType create_transfer(createTransferType tv){ private RawDataType create_transfer(CreateTransferType tv){
inputType it = get_input_type_by_name(version+1, tv.name); FieldType it = get_input_type_by_UUID(version+1, tv.UUID);
switch (it.getValueType()){ switch (it.getValueType()){
case NUM: case NUM:
return intType.newNull(it.name); return IntType.newNull(it.UUID);
case STRING: case STRING:
return stringType.newNull(it.name); return StringType.newNull(it.UUID);
} }
return null; return null;
} }
@@ -3,24 +3,26 @@ package com.ridgebotics.ridgescout.types;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
public class file { // Basically just holds a byte array and a filename, and then us just encoded.
public class ScoutingFile {
public static final int typecode = 255; public static final int typecode = 255;
public String filename; public String filename;
public byte[] data; public byte[] data;
public file(){} public ScoutingFile(){}
public file(String filename){ public ScoutingFile(String filename){
this(filename, fileEditor.readFile(filename)); this(filename, FileEditor.readFile(filename));
} }
public file(String filename, byte[] data){ public ScoutingFile(String filename, byte[] data){
this.filename = filename; this.filename = filename;
this.data = data; this.data = data;
} }
@@ -28,8 +30,15 @@ public class file {
public byte[] encode(){ public byte[] encode(){
try { try {
ByteBuilder bb = new ByteBuilder() ByteBuilder bb = new ByteBuilder()
.addString(filename) .addString(filename);
.addRaw(255, Objects.requireNonNull(fileEditor.readFile(filename)));
// byte[] data = Objects.requireNonNull(fileEditor.readFile(filename));
// for(int i = 0; i < data.length / 65535; i++){
// bb.addRaw(255, fileEditor.getByteBlock(data, i*65535, (i+1)*65535));
// }
bb.addRaw(255, Objects.requireNonNull(FileEditor.readFile(filename)));
return bb.build(); return bb.build();
@@ -39,18 +48,18 @@ public class file {
} }
} }
public static file decode(byte[] bytes){ public static ScoutingFile decode(byte[] bytes){
try{ try{
ArrayList<BuiltByteParser.parsedObject> objects = new BuiltByteParser(bytes).parse(); ArrayList<BuiltByteParser.parsedObject> objects = new BuiltByteParser(bytes).parse();
file f = new file(); ScoutingFile f = new ScoutingFile();
f.filename = (String) objects.get(0).get(); f.filename = (String) objects.get(0).get();
f.data = (byte[]) objects.get(1).get(); f.data = (byte[]) objects.get(1).get();
return f; return f;
}catch (BuiltByteParser.byteParsingExeption e){ }catch (Exception e){
AlertManager.error(e); AlertManager.error(e);
return null; return null;
} }
@@ -58,6 +67,6 @@ public class file {
public boolean write(){ public boolean write(){
if(data == null || filename == null) return false; if(data == null || filename == null) return false;
return fileEditor.writeFile(filename, data); return FileEditor.writeFile(filename, data);
} }
} }
@@ -1,6 +1,8 @@
package com.ridgebotics.ridgescout.types.data; package com.ridgebotics.ridgescout.types.data;
public class intArrType extends dataType {
// Int array raw data type
public class IntArrType extends RawDataType {
public static final int[] nullval = new int[]{255, 255}; public static final int[] nullval = new int[]{255, 255};
// public static final int unselectedval = 1; // public static final int unselectedval = 1;
@@ -23,13 +25,13 @@ public class intArrType extends dataType {
forceSetValue((int[]) value); forceSetValue((int[]) value);
} }
public intArrType(String name, int[] value) { public IntArrType(String name, int[] value) {
super(name); super(name);
set(value); set(value);
} }
public static intArrType newNull(String name){ public static IntArrType newNull(String name){
return new intArrType(name, nullval); return new IntArrType(name, nullval);
} }
// public static intType newUnselected(String name){ // public static intType newUnselected(String name){
@@ -1,6 +1,7 @@
package com.ridgebotics.ridgescout.types.data; package com.ridgebotics.ridgescout.types.data;
public class intType extends dataType { // Number raw data type
public class IntType extends RawDataType {
public static final int nullval = 255; public static final int nullval = 255;
// public static final int unselectedval = 1; // public static final int unselectedval = 1;
@@ -23,13 +24,13 @@ public class intType extends dataType {
forceSetValue((int) value); forceSetValue((int) value);
} }
public intType(String name, int value) { public IntType(String name, int value) {
super(name); super(name);
set(value); set(value);
} }
public static intType newNull(String name){ public static IntType newNull(String name){
final intType a = new intType(name, 0); final IntType a = new IntType(name, 0);
a.forceSetValue(nullval); a.forceSetValue(nullval);
return a; return a;
} }
@@ -1,10 +1,7 @@
package com.ridgebotics.ridgescout.types.data; package com.ridgebotics.ridgescout.types.data;
import androidx.annotation.NonNull; // Abstract class for raw data types for use in fields.
public abstract class RawDataType {
import org.jetbrains.annotations.NotNull;
public abstract class dataType {
public enum valueTypes { public enum valueTypes {
NUM, NUM,
NUMARR, NUMARR,
@@ -12,7 +9,7 @@ public abstract class dataType {
} }
private Object value; private Object value;
private final String name; private final String UUID;
public abstract valueTypes getValueType(); public abstract valueTypes getValueType();
@@ -28,9 +25,9 @@ public abstract class dataType {
public abstract boolean isNull(); public abstract boolean isNull();
// public abstract boolean isUnselected(); // public abstract boolean isUnselected();
public String getName() {return name;} public String getUUID() {return UUID;}
public dataType(String name){ public RawDataType(String UUID){
this.name = name; this.UUID = UUID;
} }
} }
@@ -1,6 +1,7 @@
package com.ridgebotics.ridgescout.types.data; package com.ridgebotics.ridgescout.types.data;
public class stringType extends dataType{ // String raw data type
public class StringType extends RawDataType {
public static final String nullval = "null"; public static final String nullval = "null";
// public static final String unselectedval = ""; // public static final String unselectedval = "";
@@ -23,13 +24,13 @@ public class stringType extends dataType{
forceSetValue(value); forceSetValue(value);
} }
public stringType(String name, String value) { public StringType(String name, String value) {
super(name); super(name);
forceSetValue(value); forceSetValue(value);
} }
public static stringType newNull(String name){ public static StringType newNull(String name){
final stringType a = new stringType(name, ""); final StringType a = new StringType(name, "");
a.forceSetValue(nullval); a.forceSetValue(nullval);
return a; return a;
} }
@@ -2,17 +2,18 @@ package com.ridgebotics.ridgescout.types;
import static com.ridgebotics.ridgescout.utility.DataManager.event; import static com.ridgebotics.ridgescout.utility.DataManager.event;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.IntStream; import java.util.stream.IntStream;
// Class to contain data for an entire event.
// Easily encoded and decoded to binary format.
public class frcEvent { public class frcEvent {
public static final int typecode = 254; public static final int typecode = 254;
@@ -35,6 +36,10 @@ public class frcEvent {
bb.addRaw(frcMatch.typecode, match.encode()); bb.addRaw(frcMatch.typecode, match.encode());
} }
if(SettingsManager.getEVCode().equals("unset")){
SettingsManager.setEVCode(eventCode);
}
return bb.build(); return bb.build();
} catch (ByteBuilder.buildingException e) { } catch (ByteBuilder.buildingException e) {
AlertManager.error(e); AlertManager.error(e);
@@ -117,6 +122,18 @@ public class frcEvent {
return maxMatch; return maxMatch;
} }
public frcMatch getNextTeamMatch(int teamNum, int curMatch){
frcMatch[] teamMatches = getTeamMatches(teamNum);
for(int i = 0; i < teamMatches.length; i++) {
if (teamMatches[i].matchIndex > curMatch)
return teamMatches[i];
}
return null;
}
// public // public
// Returns the soonest match that there will be all the possible upcoming data on other teams // Returns the soonest match that there will be all the possible upcoming data on other teams
@@ -141,4 +158,29 @@ public class frcEvent {
} }
} }
} }
public frcTeam getTeamByNum(int teamNum){
for(int i = 0; i < teams.size(); i++){
frcTeam team = teams.get(i);
if(team.teamNumber == teamNum)
return team;
}
return null;
}
public boolean getIsBlueAlliance(int teamNum, int matchNum){
return getIsBlueAlliance(teamNum, matches.get(matchNum));
}
public boolean getIsBlueAlliance(int teamNum, frcMatch match){
for(int i = 0; i < match.redAlliance.length; i++)
if(match.redAlliance[i] == teamNum) return false;
for(int i = 0; i < match.blueAlliance.length; i++)
if(match.blueAlliance[i] == teamNum) return true;
return false;
}
} }
@@ -9,6 +9,8 @@ import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
// Class to contain data for the six teams numbers in a single match
// Easily encoded and decoded to binary format.
public class frcMatch { public class frcMatch {
public static final int typecode = 253; public static final int typecode = 253;
public frcMatch(){} public frcMatch(){}
@@ -27,7 +29,7 @@ public class frcMatch {
.addInt(redAlliance[1]) .addInt(redAlliance[1])
.addInt(redAlliance[2]) .addInt(redAlliance[2])
.build(); .build();
} catch (ByteBuilder.buildingException e) { } catch (Exception e) {
AlertManager.error(e); AlertManager.error(e);
return new byte[1]; return new byte[1];
} }
@@ -49,7 +51,7 @@ public class frcMatch {
return frc; return frc;
} catch (BuiltByteParser.byteParsingExeption e) { } catch (Exception e) {
AlertManager.error(e); AlertManager.error(e);
return null; return null;
} }
@@ -1,21 +1,36 @@
package com.ridgebotics.ridgescout.types; package com.ridgebotics.ridgescout.types;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
// Class to contain data for a team, in an event.
// Easily encoded and decoded to binary format.
public class frcTeam { public class frcTeam {
public static final int typecode = 252; public static final int typecode = 252;
private static final int[] DEFAULT_COLOR_ARR = new int[]{64,64,64};
private static final int DEFAULT_COLOR = Color.argb(255, DEFAULT_COLOR_ARR[0],DEFAULT_COLOR_ARR[1],DEFAULT_COLOR_ARR[2]);
public int teamNumber = 0; public int teamNumber = 0;
public String teamName = "null"; public String teamName = "null";
public String city = "null"; public String city = "null";
public String stateOrProv = "null"; public String stateOrProv = "null";
public String school = "null"; public String school = "null";
public String country = "null"; public String country = "null";
public Bitmap bitmap = null;
public int[] teamColor = DEFAULT_COLOR_ARR;
public int startingYear = 0; public int startingYear = 0;
public String getDescription(){ public String getDescription(){
@@ -32,6 +47,8 @@ public class frcTeam {
.addString(school) .addString(school)
.addString(country) .addString(country)
.addInt(startingYear) .addInt(startingYear)
.addRaw(127, encodeBitmap(bitmap))
.addIntArray(teamColor)
.build(); .build();
} catch (ByteBuilder.buildingException e) { } catch (ByteBuilder.buildingException e) {
AlertManager.error(e); AlertManager.error(e);
@@ -52,6 +69,13 @@ public class frcTeam {
frc.country = (String) objects.get(5).get(); frc.country = (String) objects.get(5).get();
frc.startingYear = (int) objects.get(6).get(); frc.startingYear = (int) objects.get(6).get();
if(objects.size() == 9){
frc.bitmap = decodeBitmap((BuiltByteParser.rawObject) objects.get(7));
frc.teamColor = (int[]) objects.get(8).get();
// System.out.println(Arrays.toString(frc.teamColor));
}
return frc; return frc;
} catch (BuiltByteParser.byteParsingExeption e) { } catch (BuiltByteParser.byteParsingExeption e) {
@@ -60,6 +84,111 @@ public class frcTeam {
} }
} }
public static byte[] encodeBitmap(Bitmap bitmap){
if(bitmap == null) return new byte[]{0};
ByteArrayOutputStream blob = new ByteArrayOutputStream();
if(bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* Ignored for PNGs */, blob)){
return blob.toByteArray();
}else{
return new byte[]{0};
}
}
public static Bitmap decodeBitmap(BuiltByteParser.rawObject rawObject){
if(rawObject.getType() != 127) return null;
byte[] bytes = (byte[]) rawObject.get();
if(bytes.length <= 1) return null;
return BitmapFactory.decodeByteArray(bytes,0,bytes.length);
}
public static int[] findPrimaryColor(Bitmap bitmap) {
if (bitmap == null) {
return DEFAULT_COLOR_ARR;
}
// Step 1: Posterize the image (reduce color levels)
Bitmap posterizedBitmap = posterize(bitmap, 8); // 8 levels of posterization
// Step 2: Find the most saturated and frequent color
return findMostSaturatedAndFrequentColor(posterizedBitmap);
}
// Posterize the image by reducing color levels
private static Bitmap posterize(Bitmap original, int levels) {
int width = original.getWidth();
int height = original.getHeight();
Bitmap posterized = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int step = 255 / (levels - 1);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel = original.getPixel(x, y);
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
// Quantize the RGB values
r = (r / step) * step;
g = (g / step) * step;
b = (b / step) * step;
int newPixel = Color.rgb(r, g, b);
posterized.setPixel(x, y, newPixel);
}
}
return posterized;
}
// Find the most saturated and frequent color
private static int[] findMostSaturatedAndFrequentColor(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Map<Integer, Integer> colorFrequency = new HashMap<>();
// Count the frequency of each color
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel = bitmap.getPixel(x, y);
colorFrequency.put(pixel, colorFrequency.getOrDefault(pixel, 0) + 1);
}
}
// Find the most saturated and frequent color
int primaryColor = DEFAULT_COLOR; // Default fallback
double maxColorness = -1;
int maxFrequency = 0;
for (Map.Entry<Integer, Integer> entry : colorFrequency.entrySet()) {
int color = entry.getKey();
int frequency = entry.getValue();
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
double colorness = Math.pow(hsv[1],2)+Math.pow(hsv[2],2);
// Prioritize saturation, then frequency
if ((colorness > maxColorness && frequency > maxFrequency * 0.5) && Color.alpha(color) > 127) { //|| (colorness == maxColorness)
maxColorness = colorness;
// maxFrequency = frequency;
primaryColor = color;
}
}
float[] hsv = new float[3];
Color.colorToHSV(primaryColor, hsv);
primaryColor = Color.HSVToColor(new float[]{hsv[0], Math.max(hsv[1], (float) 0.2), Math.max(hsv[2], (float) 0.3)});
return new int[]{Color.red(primaryColor),Color.blue(primaryColor),Color.green(primaryColor)};
}
public int getTeamColor(){
return Color.argb(255,teamColor[0],teamColor[2],teamColor[1]);
}
@NonNull @NonNull
public String toString(){ public String toString(){
return "frcTeam Num: " + teamNumber + ", " + getDescription(); return "frcTeam Num: " + teamNumber + ", " + getDescription();
@@ -1,20 +1,18 @@
package com.ridgebotics.ridgescout.types.input; package com.ridgebotics.ridgescout.types.input;
import android.app.Activity; import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.checkbox_colors;
import static com.ridgebotics.ridgescout.utility.Colors.checkbox_data_color;
import static com.ridgebotics.ridgescout.utility.Colors.checkbox_value_text_color;
import android.content.Context; import android.content.Context;
import android.graphics.Color; import android.graphics.Color;
import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.RelativeLayout; import android.widget.TableLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.charts.PieChart;
@@ -25,49 +23,42 @@ import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.data.PieEntry;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.intType; import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
public class checkboxType extends inputType { public class CheckboxType extends FieldType {
public int get_byte_id() {return checkboxType;} public int get_byte_id() {return checkboxType;}
public inputTypes getInputType(){return inputTypes.CHECKBOX;} public inputTypes getInputType(){return inputTypes.CHECKBOX;}
public dataType.valueTypes getValueType(){return dataType.valueTypes.NUM;} public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.NUM;}
public Object get_fallback_value(){return 0;} public Object get_fallback_value(){return 0;}
public checkboxType(){}; public CheckboxType(){};
public String get_type_name(){return "Checkbox";} public String get_type_name(){return "Checkbox";}
public checkboxType(String name, String description, int isChecked){ public CheckboxType(String UUID, String name, String description, int isChecked){
super(name, description); super(UUID, name, description);
this.default_value = isChecked; this.default_value = isChecked;
} }
public byte[] encode() throws ByteBuilder.buildingException { public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
bb.addString(name);
bb.addString(description);
bb.addInt((int)default_value); bb.addInt((int)default_value);
return bb.build();
} }
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption {
BuiltByteParser bbp = new BuiltByteParser(bytes);
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
name = (String) objects.get(0).get(); public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
description = (String) objects.get(1).get(); default_value = objects.get(0).get();
default_value = objects.get(2).get();
} }
// public PowerSpinnerView dropdown = null; // public PowerSpinnerView dropdown = null;
public CheckBox checkBox = null; public CheckBox checkBox = null;
public View createView(Context context, Function<dataType, Integer> onUpdate){ public View createView(Context context, Function<RawDataType, Integer> onUpdate){
checkBox = new CheckBox(context); checkBox = new CheckBox(context);
checkBox.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline6); checkBox.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline6);
checkBox.setText(name); checkBox.setText(name);
@@ -80,7 +71,7 @@ public class checkboxType extends inputType {
} }
public void setViewValue(Object value) { public void setViewValue(Object value) {
if(checkBox == null) return; if(checkBox == null) return;
if(intType.isNull((int) value)){ if(IntType.isNull((int) value)){
nullify(); nullify();
return; return;
} }
@@ -94,10 +85,10 @@ public class checkboxType extends inputType {
isBlank = true; isBlank = true;
checkBox.setVisibility(View.GONE); checkBox.setVisibility(View.GONE);
} }
public dataType getViewValue(){ public RawDataType getViewValue(){
if(checkBox == null) return null; if(checkBox == null) return null;
if(checkBox.getVisibility() == View.GONE) return new intType(name, intType.nullval); if(checkBox.getVisibility() == View.GONE) return new IntType(name, IntType.nullval);
return new intType(name, checkBox.isChecked() ? 1 : 0); return new IntType(name, checkBox.isChecked() ? 1 : 0);
} }
@@ -105,7 +96,7 @@ public class checkboxType extends inputType {
public void add_individual_view(LinearLayout parent, dataType data){ public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return; if(data.isNull()) return;
CheckBox cb = new CheckBox(parent.getContext()); CheckBox cb = new CheckBox(parent.getContext());
cb.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline6); cb.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline6);
@@ -116,11 +107,7 @@ public class checkboxType extends inputType {
} }
public void add_compiled_view(LinearLayout parent, RawDataType[] data){
public static int[] colors = {0x7f00ff00, 0x7f7f0000};
public void add_compiled_view(LinearLayout parent, dataType[] data){
PieChart chart = new PieChart(parent.getContext()); PieChart chart = new PieChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -149,7 +136,7 @@ public class checkboxType extends inputType {
entries.add(new PieEntry((float) numFalse, "False")); entries.add(new PieEntry((float) numFalse, "False"));
PieDataSet pieDataSet = new PieDataSet(entries, name); PieDataSet pieDataSet = new PieDataSet(entries, name);
pieDataSet.setColors(colors); pieDataSet.setColors(checkbox_colors);
PieData pieData = new PieData(pieDataSet); PieData pieData = new PieData(pieDataSet);
chart.setDrawHoleEnabled(false); chart.setDrawHoleEnabled(false);
chart.setData(pieData); chart.setData(pieData);
@@ -160,7 +147,7 @@ public class checkboxType extends inputType {
public void add_history_view(LinearLayout parent, dataType[] data){ public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -168,7 +155,7 @@ public class checkboxType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
LineData lineData = new LineData(); LineData lineData = new LineData();
@@ -184,11 +171,11 @@ public class checkboxType extends inputType {
} }
LineDataSet dataSet = new LineDataSet(entries, "is checked"); LineDataSet dataSet = new LineDataSet(entries, "is checked");
dataSet.setColor(Color.RED); dataSet.setColor(checkbox_data_color);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(Color.BLACK);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(checkbox_value_text_color);
lineData.addDataSet(dataSet); lineData.addDataSet(dataSet);
@@ -220,7 +207,11 @@ public class checkboxType extends inputType {
parent.addView(chart); parent.addView(chart);
} }
public String toString(dataType data){ public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
}
public String toString(RawDataType data){
return (int) data.get() == 1 ? "true" : "false"; return (int) data.get() == 1 ? "true" : "false";
} }
} }
@@ -1,8 +1,10 @@
package com.ridgebotics.ridgescout.types.input; package com.ridgebotics.ridgescout.types.input;
import static com.google.android.material.internal.ContextUtils.getActivity; import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.chart_text;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_1;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_2;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.graphics.Color; import android.graphics.Color;
import android.view.Gravity; import android.view.Gravity;
@@ -10,13 +12,12 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.Nullable; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.ui.views.CustomSpinnerView;
import com.ridgebotics.ridgescout.types.data.intType;
import com.ridgebotics.ridgescout.ui.CustomSpinnerView;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.charts.LineChart;
@@ -32,44 +33,36 @@ import com.github.mikephil.charting.data.PieEntry;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
public class dropdownType extends inputType { public class DropdownType extends FieldType {
public String[] text_options; public String[] text_options;
public int get_byte_id() {return dropdownType;} public int get_byte_id() {return dropdownType;}
public inputTypes getInputType(){return inputTypes.DROPDOWN;} public inputTypes getInputType(){return inputTypes.DROPDOWN;}
public dataType.valueTypes getValueType(){return dataType.valueTypes.NUM;} public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.NUM;}
public Object get_fallback_value(){return 0;} public Object get_fallback_value(){return 0;}
public dropdownType(){}; public DropdownType(){};
public String get_type_name(){return "Dropdown";} public String get_type_name(){return "Dropdown";}
public dropdownType(String name, String description, String[] text_options, int defaultSelIndex){ public DropdownType(String UUID, String name, String description, String[] text_options, int defaultSelIndex){
super(name, description); super(UUID, name, description);
this.text_options = text_options; this.text_options = text_options;
this.default_value = defaultSelIndex; this.default_value = defaultSelIndex;
} }
public byte[] encode() throws ByteBuilder.buildingException { public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
bb.addString(name);
bb.addString(description);
bb.addInt((int)default_value); bb.addInt((int)default_value);
bb.addStringArray(text_options); bb.addStringArray(text_options);
return bb.build();
} }
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption { public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
BuiltByteParser bbp = new BuiltByteParser(bytes); default_value = objects.get(0).get();
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse(); text_options = (String[]) objects.get(1).get();
name = (String) objects.get(0).get();
description = (String) objects.get(1).get();
default_value = objects.get(2).get();
text_options = (String[]) objects.get(3).get();
} }
public CustomSpinnerView dropdown = null; public CustomSpinnerView dropdown = null;
public View createView(Context context, Function<dataType, Integer> onUpdate){ public View createView(Context context, Function<RawDataType, Integer> onUpdate){
dropdown = new CustomSpinnerView(context); dropdown = new CustomSpinnerView(context);
ArrayList<String> iconSpinnerItems = new ArrayList<>(Arrays.asList(text_options)); ArrayList<String> iconSpinnerItems = new ArrayList<>(Arrays.asList(text_options));
@@ -85,7 +78,7 @@ public class dropdownType extends inputType {
} }
public void setViewValue(Object value) { public void setViewValue(Object value) {
if(dropdown == null) return; if(dropdown == null) return;
if(intType.isNull((int) value)){ if(IntType.isNull((int) value)){
nullify(); nullify();
return; return;
} }
@@ -99,10 +92,10 @@ public class dropdownType extends inputType {
isBlank = true; isBlank = true;
dropdown.setVisibility(View.GONE); dropdown.setVisibility(View.GONE);
} }
public dataType getViewValue(){ public RawDataType getViewValue(){
if(dropdown == null) return null; if(dropdown == null) return null;
if(dropdown.getVisibility() == View.GONE) return new intType(name, intType.nullval); if(dropdown.getVisibility() == View.GONE) return new IntType(name, IntType.nullval);
return new intType(name, dropdown.getIndex()); return new IntType(name, dropdown.getIndex());
} }
@@ -110,7 +103,7 @@ public class dropdownType extends inputType {
public void add_individual_view(LinearLayout parent, dataType data){ public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return; if(data.isNull()) return;
TextView tv = new TextView(parent.getContext()); TextView tv = new TextView(parent.getContext());
tv.setLayoutParams(new FrameLayout.LayoutParams( tv.setLayoutParams(new FrameLayout.LayoutParams(
@@ -146,7 +139,7 @@ public class dropdownType extends inputType {
return colors; return colors;
} }
public void add_compiled_view(LinearLayout parent, dataType[] data){ public void add_compiled_view(LinearLayout parent, RawDataType[] data){
PieChart chart = new PieChart(parent.getContext()); PieChart chart = new PieChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -154,7 +147,7 @@ public class dropdownType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
parent.addView(chart); parent.addView(chart);
int[] data_2 = new int[text_options.length]; int[] data_2 = new int[text_options.length];
@@ -180,7 +173,7 @@ public class dropdownType extends inputType {
public void add_history_view(LinearLayout parent, dataType[] data){ public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -188,7 +181,7 @@ public class dropdownType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
@@ -210,10 +203,10 @@ public class dropdownType extends inputType {
LineDataSet dataSet = new LineDataSet(entries, text_options[i]); LineDataSet dataSet = new LineDataSet(entries, text_options[i]);
dataSet.setColor(colors[i]); dataSet.setColor(colors[i]);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
lineData.addDataSet(dataSet); lineData.addDataSet(dataSet);
} }
@@ -229,9 +222,9 @@ public class dropdownType extends inputType {
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
chart.getAxisLeft().setAxisMinimum(0.f); chart.getAxisLeft().setAxisMinimum(0.f);
chart.getAxisLeft().setAxisMaximum(1.f); chart.getAxisLeft().setAxisMaximum(1.f);
@@ -240,13 +233,17 @@ public class dropdownType extends inputType {
chart.getAxisRight().setAxisMaximum(1.f); chart.getAxisRight().setAxisMaximum(1.f);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
chart.invalidate(); chart.invalidate();
parent.addView(chart); parent.addView(chart);
} }
public String toString(dataType data){ public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
}
public String toString(RawDataType data){
return text_options[(int) data.get()]; return text_options[(int) data.get()];
} }
} }
@@ -0,0 +1,105 @@
package com.ridgebotics.ridgescout.types.input;
import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
// Abstract class for fields.
public abstract class FieldType {
// Define what the IDS are for each type
public static final int slider_type_id = 255;
public static final int dropdownType = 254;
public static final int notesType = 253;
public static final int tallyType = 252;
public static final int numberType = 251;
public static final int checkboxType = 250;
public static final int fieldposType = 249;
public static final int toggleType = 248;
public enum inputTypes {
SLIDER,
DROPDOWN,
NOTES_INPUT,
TALLY,
NUMBER,
CHECKBOX,
FIELDPOS,
TOGGLE;
}
public String UUID;
public String name;
public String description;
public Object default_value;
public abstract inputTypes getInputType();
public abstract RawDataType.valueTypes getValueType();
public abstract Object get_fallback_value();
public abstract int get_byte_id();
public FieldType(){}
public FieldType(String UUID, String name, String description){
this.UUID = UUID;
this.name = name;
this.description = description;
}
public abstract String get_type_name();
public byte[] encode() throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
bb.addString(UUID);
bb.addString(name);
bb.addString(description);
encodeData(bb);
return bb.build();
}
public abstract void encodeData(ByteBuilder byteBuilder) throws ByteBuilder.buildingException;
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption {
BuiltByteParser bbp = new BuiltByteParser(bytes);
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
UUID = (String) objects.remove(0).get();
name = (String) objects.remove(0).get();
description = (String) objects.remove(0).get();
decodeData(objects);
}
public abstract void decodeData(ArrayList<BuiltByteParser.parsedObject> objects);
// public abstract dataType[] getConfig();
// public abstract void setConfig(dataType[] config);
public abstract View createView(Context context, Function<RawDataType, Integer> onUpdate);
public boolean isBlank = false;
public abstract void nullify();
public void setViewValue(RawDataType type){setViewValue(type.get());}
public abstract void setViewValue(Object value);
public abstract RawDataType getViewValue();
public abstract void add_individual_view(LinearLayout parent, RawDataType data);
public abstract void add_compiled_view(LinearLayout parent, RawDataType[] data);
public abstract void add_history_view(LinearLayout parent, RawDataType[] data);
public abstract void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data);
public abstract String toString(RawDataType data);
}
@@ -1,47 +1,44 @@
package com.ridgebotics.ridgescout.types.input; package com.ridgebotics.ridgescout.types.input;
import static android.text.InputType.TYPE_CLASS_NUMBER; import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.chart_text;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_1;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_2;
import static com.ridgebotics.ridgescout.utility.Colors.fieldpos_data;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TableLayout;
import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.data.LineDataSet;
import com.ridgebotics.ridgescout.R; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.IntArrType;
import com.ridgebotics.ridgescout.types.data.intArrType; import com.ridgebotics.ridgescout.ui.views.FieldPosView;
import com.ridgebotics.ridgescout.types.data.intType; import com.ridgebotics.ridgescout.ui.views.MultiFieldPosView;
import com.ridgebotics.ridgescout.ui.scouting.FieldPosView;
import com.ridgebotics.ridgescout.ui.scouting.MultiFieldPosView;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
public class fieldposType extends inputType { public class FieldposType extends FieldType {
public int get_byte_id() {return fieldposType;} public int get_byte_id() {return fieldposType;}
public inputTypes getInputType(){return inputTypes.FIELDPOS;} public inputTypes getInputType(){return inputTypes.FIELDPOS;}
public dataType.valueTypes getValueType(){return dataType.valueTypes.NUM;} public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.NUM;}
public Object get_fallback_value(){return 0;} public Object get_fallback_value(){return 0;}
public fieldposType(){} public FieldposType(){}
public String get_type_name(){return "Field Pos";} public String get_type_name(){return "Field Pos";}
public fieldposType(String name, String description, int[] default_value){ public FieldposType(String UUID, String name, String description, int[] default_value){
super(name, description); super(UUID, name, description);
this.default_value = default_value; this.default_value = default_value;
} }
@@ -49,21 +46,12 @@ public class fieldposType extends inputType {
public byte[] encode() throws ByteBuilder.buildingException { public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
bb.addString(name);
bb.addString(description);
bb.addIntArray((int[]) default_value); bb.addIntArray((int[]) default_value);
return bb.build();
} }
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption { public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
BuiltByteParser bbp = new BuiltByteParser(bytes); default_value = objects.get(0).get();
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
name = (String) objects.get(0).get();
description = (String) objects.get(1).get();
default_value = objects.get(2).get();
} }
@@ -72,9 +60,9 @@ public class fieldposType extends inputType {
public FieldPosView field = null; public FieldPosView field = null;
public View createView(Context context, Function<dataType, Integer> onUpdate){ public View createView(Context context, Function<RawDataType, Integer> onUpdate){
field = new FieldPosView(context, pos -> { field = new FieldPosView(context, pos -> {
onUpdate.apply(new intArrType(name, pos)); onUpdate.apply(new IntArrType(name, pos));
}); });
setViewValue(default_value); setViewValue(default_value);
return field; return field;
@@ -83,7 +71,7 @@ public class fieldposType extends inputType {
public void setViewValue(Object value) { public void setViewValue(Object value) {
if(field == null) return; if(field == null) return;
if(intArrType.isNull((int[]) value)){ if(IntArrType.isNull((int[]) value)){
nullify(); nullify();
return; return;
} }
@@ -100,15 +88,15 @@ public class fieldposType extends inputType {
isBlank = true; isBlank = true;
field.setVisibility(View.GONE); field.setVisibility(View.GONE);
} }
public dataType getViewValue(){ public RawDataType getViewValue(){
if(field == null) return null; if(field == null) return null;
if(field.getVisibility() == View.GONE) return intArrType.newNull(name); if(field.getVisibility() == View.GONE) return IntArrType.newNull(name);
return new intArrType(name, field.getPos()); return new IntArrType(name, field.getPos());
} }
public void add_individual_view(LinearLayout parent, dataType data){ public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return; if(data.isNull()) return;
FieldPosView fp = new FieldPosView(parent.getContext()); FieldPosView fp = new FieldPosView(parent.getContext());
@@ -151,7 +139,7 @@ public class fieldposType extends inputType {
return entries; return entries;
} }
private static int findMin(dataType[] data){ private static int findMin(RawDataType[] data){
int min = (int)data[0].get(); int min = (int)data[0].get();
for(int i = 1; i < data.length; i++) for(int i = 1; i < data.length; i++)
if((int)data[i].get() < min) if((int)data[i].get() < min)
@@ -159,7 +147,7 @@ public class fieldposType extends inputType {
return min; return min;
} }
private static int findMax(dataType[] data){ private static int findMax(RawDataType[] data){
int max = (int)data[0].get(); int max = (int)data[0].get();
for(int i = 1; i < data.length; i++) for(int i = 1; i < data.length; i++)
if((int)data[i].get() > max) if((int)data[i].get() > max)
@@ -167,7 +155,7 @@ public class fieldposType extends inputType {
return max; return max;
} }
public void add_compiled_view(LinearLayout parent, dataType[] data){ public void add_compiled_view(LinearLayout parent, RawDataType[] data){
MultiFieldPosView mfp = new MultiFieldPosView(parent.getContext()); MultiFieldPosView mfp = new MultiFieldPosView(parent.getContext());
for(int i = 0; i < data.length; i++){ for(int i = 0; i < data.length; i++){
if(data[i].isNull()) continue; if(data[i].isNull()) continue;
@@ -176,7 +164,7 @@ public class fieldposType extends inputType {
parent.addView(mfp); parent.addView(mfp);
} }
public void add_history_view(LinearLayout parent, dataType[] data){ public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -184,7 +172,7 @@ public class fieldposType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
int min = 0; int min = 0;
int max = 255; int max = 255;
@@ -198,8 +186,8 @@ public class fieldposType extends inputType {
} }
LineDataSet dataSet = new LineDataSet(entries, "Field position Y value"); LineDataSet dataSet = new LineDataSet(entries, "Field position Y value");
dataSet.setColor(Color.BLUE); dataSet.setColor(fieldpos_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
@@ -213,14 +201,14 @@ public class fieldposType extends inputType {
chart.setDragEnabled(false); chart.setDragEnabled(false);
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
chart.getAxisLeft().setAxisMinimum(min); chart.getAxisLeft().setAxisMinimum(min);
@@ -233,7 +221,11 @@ public class fieldposType extends inputType {
parent.addView(chart); parent.addView(chart);
} }
public String toString(dataType data){ public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
}
public String toString(RawDataType data){
int[] intarr = (int[]) data.get(); int[] intarr = (int[]) data.get();
return "[" + intarr[0] + "," + intarr[1] + "]"; return "[" + intarr[0] + "," + intarr[1] + "]";
} }
@@ -2,9 +2,13 @@ package com.ridgebotics.ridgescout.types.input;
import static android.text.InputType.TYPE_CLASS_NUMBER; import static android.text.InputType.TYPE_CLASS_NUMBER;
import android.app.Activity; import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.chart_text;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_1;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_2;
import static com.ridgebotics.ridgescout.utility.Colors.number_data;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.view.Gravity; import android.view.Gravity;
@@ -13,6 +17,7 @@ import android.view.ViewGroup;
import android.widget.EditText; import android.widget.EditText;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView; import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.charts.LineChart;
@@ -20,24 +25,25 @@ import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.data.LineDataSet;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.intType; import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
public class numberType extends inputType { public class NumberType extends FieldType {
public int get_byte_id() {return numberType;} public int get_byte_id() {return numberType;}
public inputTypes getInputType(){return inputTypes.NUMBER;} public inputTypes getInputType(){return inputTypes.NUMBER;}
public dataType.valueTypes getValueType(){return dataType.valueTypes.NUM;} public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.NUM;}
public Object get_fallback_value(){return 0;} public Object get_fallback_value(){return 0;}
public numberType(){} public NumberType(){}
public String get_type_name(){return "Number";} public String get_type_name(){return "Number";}
public numberType(String name, String description, int default_value){ public NumberType(String UUID, String name, String description, int default_value){
super(name, description); super(UUID, name, description);
this.default_value = default_value; this.default_value = default_value;
} }
@@ -45,20 +51,11 @@ public class numberType extends inputType {
public byte[] encode() throws ByteBuilder.buildingException { public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
bb.addString(name);
bb.addString(description);
bb.addInt((int)default_value); bb.addInt((int)default_value);
return bb.build();
} }
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption { public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
BuiltByteParser bbp = new BuiltByteParser(bytes); default_value = objects.get(0).get();
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
name = (String) objects.get(0).get();
description = (String) objects.get(1).get();
default_value = objects.get(2).get();
} }
@@ -67,7 +64,7 @@ public class numberType extends inputType {
public EditText num = null; public EditText num = null;
public View createView(Context context, Function<dataType, Integer> onUpdate){ public View createView(Context context, Function<RawDataType, Integer> onUpdate){
num = new EditText(context); num = new EditText(context);
num.setInputType(TYPE_CLASS_NUMBER); num.setInputType(TYPE_CLASS_NUMBER);
num.addTextChangedListener(new TextWatcher() { num.addTextChangedListener(new TextWatcher() {
@@ -85,7 +82,7 @@ public class numberType extends inputType {
public void setViewValue(Object value) { public void setViewValue(Object value) {
if(num == null) return; if(num == null) return;
if(intType.isNull((int)value)){ if(IntType.isNull((int)value)){
nullify(); nullify();
return; return;
} }
@@ -98,28 +95,28 @@ public class numberType extends inputType {
isBlank = true; isBlank = true;
num.setVisibility(View.GONE); num.setVisibility(View.GONE);
} }
public dataType getViewValue(){ public RawDataType getViewValue(){
if(num == null) return null; if(num == null) return null;
if(num.getVisibility() == View.GONE) return intType.newNull(name); if(num.getVisibility() == View.GONE) return IntType.newNull(name);
return new intType(name, safeToInt(num.getText().toString())); return new IntType(name, safeToInt(num.getText().toString()));
} }
private int safeToInt(String num){ private int safeToInt(String num){
if(num.isEmpty()) if(num.isEmpty())
return intType.nullval; return IntType.nullval;
try { try {
return Integer.parseInt(num); return Integer.parseInt(num);
}catch (NumberFormatException e){ }catch (NumberFormatException e){
return intType.nullval; return IntType.nullval;
} }
} }
public void add_individual_view(LinearLayout parent, dataType data){ public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return; if(data.isNull()) return;
TextView tv = new TextView(parent.getContext()); TextView tv = new TextView(parent.getContext());
@@ -166,7 +163,7 @@ public class numberType extends inputType {
return entries; return entries;
} }
private static int findMin(dataType[] data){ private static int findMin(RawDataType[] data){
int min = (int)data[0].get(); int min = (int)data[0].get();
for(int i = 1; i < data.length; i++) for(int i = 1; i < data.length; i++)
if((int)data[i].get() < min) if((int)data[i].get() < min)
@@ -174,7 +171,7 @@ public class numberType extends inputType {
return min; return min;
} }
private static int findMax(dataType[] data){ private static int findMax(RawDataType[] data){
int max = (int)data[0].get(); int max = (int)data[0].get();
for(int i = 1; i < data.length; i++) for(int i = 1; i < data.length; i++)
if((int)data[i].get() > max) if((int)data[i].get() > max)
@@ -182,7 +179,7 @@ public class numberType extends inputType {
return max; return max;
} }
public void add_compiled_view(LinearLayout parent, dataType[] data){ public void add_compiled_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -190,7 +187,7 @@ public class numberType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
int min = findMin(data); int min = findMin(data);
int max = findMax(data); int max = findMax(data);
@@ -215,8 +212,8 @@ public class numberType extends inputType {
LineDataSet dataSet = new LineDataSet(entries, name); LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(Color.BLUE); dataSet.setColor(number_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
@@ -231,7 +228,7 @@ public class numberType extends inputType {
LineDataSet normalDistSet = new LineDataSet(normalDistEntries, "Normal Distribution"); LineDataSet normalDistSet = new LineDataSet(normalDistEntries, "Normal Distribution");
normalDistSet.setColor(Color.RED); normalDistSet.setColor(dropdown_value_text_2);
normalDistSet.setDrawCircles(false); normalDistSet.setDrawCircles(false);
normalDistSet.setDrawValues(false); normalDistSet.setDrawValues(false);
normalDistSet.setLineWidth(2f); normalDistSet.setLineWidth(2f);
@@ -246,14 +243,14 @@ public class numberType extends inputType {
chart.setDragEnabled(false); chart.setDragEnabled(false);
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
parent.addView(chart); parent.addView(chart);
} }
@@ -261,7 +258,7 @@ public class numberType extends inputType {
public void add_history_view(LinearLayout parent, dataType[] data){ public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -269,7 +266,7 @@ public class numberType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
int min = findMin(data); int min = findMin(data);
int max = findMax(data); int max = findMax(data);
@@ -284,8 +281,8 @@ public class numberType extends inputType {
LineDataSet dataSet = new LineDataSet(entries, name); LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(Color.BLUE); dataSet.setColor(number_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
@@ -299,14 +296,14 @@ public class numberType extends inputType {
chart.setDragEnabled(false); chart.setDragEnabled(false);
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
chart.getAxisLeft().setAxisMinimum(min); chart.getAxisLeft().setAxisMinimum(min);
@@ -319,7 +316,11 @@ public class numberType extends inputType {
parent.addView(chart); parent.addView(chart);
} }
public String toString(dataType data){ public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
}
public String toString(RawDataType data){
return String.valueOf((int) data.get()); return String.valueOf((int) data.get());
} }
} }
@@ -1,17 +1,22 @@
package com.ridgebotics.ridgescout.types.input; package com.ridgebotics.ridgescout.types.input;
import android.app.Activity; import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.chart_text;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_1;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_2;
import static com.ridgebotics.ridgescout.utility.Colors.slider_data;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TableLayout;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.intType; import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
@@ -24,20 +29,21 @@ import com.google.android.material.slider.Slider;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
public class sliderType extends inputType { public class SliderType extends FieldType {
// public int defaultValue; // public int defaultValue;
public int min; public int min;
public int max; public int max;
public int get_byte_id() {return slider_type_id;} public int get_byte_id() {return slider_type_id;}
public inputTypes getInputType(){return inputTypes.SLIDER;} public inputTypes getInputType(){return inputTypes.SLIDER;}
public dataType.valueTypes getValueType(){return dataType.valueTypes.NUM;} public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.NUM;}
public Object get_fallback_value(){return 0;} public Object get_fallback_value(){return 0;}
public sliderType(){}; public SliderType(){};
public String get_type_name(){return "Slider";} public String get_type_name(){return "Slider";}
public sliderType(String name, String description, int defaultValue, int min, int max){ public SliderType(String UUID, String name, String description, int defaultValue, int min, int max){
super(name, description); super(UUID, name, description);
this.default_value = defaultValue; this.default_value = defaultValue;
this.min = min; this.min = min;
this.max = max; this.max = max;
@@ -46,24 +52,15 @@ public class sliderType extends inputType {
public byte[] encode() throws ByteBuilder.buildingException { public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder(); bb.addInt((int) default_value);
bb.addString(name);
bb.addString(description);
bb.addInt((int)default_value);
bb.addInt(min); bb.addInt(min);
bb.addInt(max); bb.addInt(max);
return bb.build();
} }
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption { public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
BuiltByteParser bbp = new BuiltByteParser(bytes); default_value = objects.get(0).get();
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse(); min = (int) objects.get(1).get();
max = (int) objects.get(2).get();
name = (String) objects.get(0).get();
description = (String) objects.get(1).get();
default_value = objects.get(2).get();
min = (int) objects.get(3).get();
max = (int) objects.get(4).get();
} }
@@ -71,7 +68,7 @@ public class sliderType extends inputType {
public Slider slider = null; public Slider slider = null;
public View createView(Context context, Function<dataType, Integer> onUpdate){ public View createView(Context context, Function<RawDataType, Integer> onUpdate){
slider = new Slider(context); slider = new Slider(context);
setViewValue(default_value); setViewValue(default_value);
slider.setStepSize((float) 1 / (max-min)); slider.setStepSize((float) 1 / (max-min));
@@ -86,7 +83,7 @@ public class sliderType extends inputType {
public void setViewValue(Object value) { public void setViewValue(Object value) {
if(slider == null) return; if(slider == null) return;
if(intType.isNull((int) value)){ if(IntType.isNull((int) value)){
nullify(); nullify();
return; return;
} }
@@ -97,7 +94,7 @@ public class sliderType extends inputType {
float slidervalue = round_position*step_size; float slidervalue = round_position*step_size;
if(slidervalue > 1 || slidervalue < 0) { if(slidervalue > 1 || slidervalue < 0) {
AlertManager.error("Error loading slider " + name); AlertManager.addSimpleError("Error loading slider " + name);
slider.setValue(0); slider.setValue(0);
}else{ }else{
slider.setValue(slidervalue); slider.setValue(slidervalue);
@@ -106,10 +103,10 @@ public class sliderType extends inputType {
slider.setVisibility(View.VISIBLE); slider.setVisibility(View.VISIBLE);
} }
public dataType getViewValue(){ public RawDataType getViewValue(){
if(slider == null) return null; if(slider == null) return null;
if(slider.getVisibility() == View.GONE) return intType.newNull(name); if(slider.getVisibility() == View.GONE) return IntType.newNull(name);
return new intType(name, min + (int) (slider.getValue() * (max-min))); return new IntType(name, min + (int) (slider.getValue() * (max-min)));
} }
public void nullify(){ public void nullify(){
isBlank = true; isBlank = true;
@@ -121,7 +118,7 @@ public class sliderType extends inputType {
public void add_individual_view(LinearLayout parent, dataType data){ public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return; if(data.isNull()) return;
Slider slider = new Slider(parent.getContext()); Slider slider = new Slider(parent.getContext());
@@ -130,7 +127,7 @@ public class sliderType extends inputType {
int round_position = Math.round(slider_position / step_size); int round_position = Math.round(slider_position / step_size);
float value = round_position*step_size; float value = round_position*step_size;
if(value > 1 || value < 0) { if(value > 1 || value < 0) {
AlertManager.error("Error loading slider " + name); AlertManager.addSimpleError("Error loading slider " + name);
slider.setValue(0); slider.setValue(0);
}else{ }else{
slider.setValue(value); slider.setValue(value);
@@ -175,7 +172,7 @@ public class sliderType extends inputType {
return entries; return entries;
} }
public void add_compiled_view(LinearLayout parent, dataType[] data){ public void add_compiled_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -183,7 +180,7 @@ public class sliderType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
int[] values = new int[max-min+1]; int[] values = new int[max-min+1];
@@ -205,8 +202,8 @@ public class sliderType extends inputType {
LineDataSet dataSet = new LineDataSet(entries, name); LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(Color.BLUE); dataSet.setColor(slider_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
@@ -221,7 +218,7 @@ public class sliderType extends inputType {
LineDataSet normalDistSet = new LineDataSet(normalDistEntries, "Normal Distribution"); LineDataSet normalDistSet = new LineDataSet(normalDistEntries, "Normal Distribution");
normalDistSet.setColor(Color.RED); normalDistSet.setColor(dropdown_value_text_2);
normalDistSet.setDrawCircles(false); normalDistSet.setDrawCircles(false);
normalDistSet.setDrawValues(false); normalDistSet.setDrawValues(false);
normalDistSet.setLineWidth(2f); normalDistSet.setLineWidth(2f);
@@ -236,14 +233,14 @@ public class sliderType extends inputType {
chart.setDragEnabled(false); chart.setDragEnabled(false);
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
parent.addView(chart); parent.addView(chart);
} }
@@ -251,7 +248,7 @@ public class sliderType extends inputType {
public void add_history_view(LinearLayout parent, dataType[] data){ public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -259,7 +256,7 @@ public class sliderType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
List<Entry> entries = new ArrayList<>(); List<Entry> entries = new ArrayList<>();
for (int i = 0; i < data.length; i++){ for (int i = 0; i < data.length; i++){
@@ -271,8 +268,8 @@ public class sliderType extends inputType {
LineDataSet dataSet = new LineDataSet(entries, name); LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(Color.BLUE); dataSet.setColor(slider_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
@@ -286,14 +283,14 @@ public class sliderType extends inputType {
chart.setDragEnabled(false); chart.setDragEnabled(false);
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
chart.getAxisLeft().setAxisMinimum(min); chart.getAxisLeft().setAxisMinimum(min);
@@ -306,7 +303,11 @@ public class sliderType extends inputType {
parent.addView(chart); parent.addView(chart);
} }
public String toString(dataType data){ public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
}
public String toString(RawDataType data){
return String.valueOf((int) data.get()); return String.valueOf((int) data.get());
} }
} }
@@ -1,18 +1,27 @@
package com.ridgebotics.ridgescout.types.input; package com.ridgebotics.ridgescout.types.input;
import android.app.Activity; import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.chart_text;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_1;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_2;
import static com.ridgebotics.ridgescout.utility.Colors.tally_data;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView; import android.widget.TextView;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.intType; import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.ui.scouting.TallyCounterView; import com.ridgebotics.ridgescout.ui.views.CandlestickHeader;
import com.ridgebotics.ridgescout.ui.views.CandlestickView;
import com.ridgebotics.ridgescout.ui.data.DataProcessing;
import com.ridgebotics.ridgescout.ui.views.TallyCounterView;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.charts.LineChart;
@@ -22,18 +31,20 @@ import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.data.LineDataSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
public class tallyType extends inputType { public class TallyType extends FieldType {
public int get_byte_id() {return tallyType;} public int get_byte_id() {return tallyType;}
public inputTypes getInputType(){return inputTypes.TALLY;} public inputTypes getInputType(){return inputTypes.TALLY;}
public dataType.valueTypes getValueType(){return dataType.valueTypes.NUM;} public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.NUM;}
public Object get_fallback_value(){return 0;} public Object get_fallback_value(){return 0;}
public tallyType(){} public TallyType(){}
public String get_type_name(){return "Tally";} public String get_type_name(){return "Tally";}
public tallyType(String name, String description, int default_value){ public TallyType(String UUID, String name, String description, int default_value){
super(name, description); super(UUID, name, description);
this.default_value = default_value; this.default_value = default_value;
} }
@@ -41,20 +52,11 @@ public class tallyType extends inputType {
public byte[] encode() throws ByteBuilder.buildingException { public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder(); bb.addInt((int) default_value);
bb.addString(name);
bb.addString(description);
bb.addInt((int)default_value);
return bb.build();
} }
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption { public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
BuiltByteParser bbp = new BuiltByteParser(bytes); default_value = objects.get(0).get();
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
name = (String) objects.get(0).get();
description = (String) objects.get(1).get();
default_value = objects.get(2).get();
} }
@@ -63,7 +65,8 @@ public class tallyType extends inputType {
public TallyCounterView tally = null; public TallyCounterView tally = null;
public View createView(Context context, Function<dataType, Integer> onUpdate){
public View createView(Context context, Function<RawDataType, Integer> onUpdate){
tally = new TallyCounterView(context); tally = new TallyCounterView(context);
tally.setOnCountChangedListener(n -> onUpdate.apply(getViewValue())); tally.setOnCountChangedListener(n -> onUpdate.apply(getViewValue()));
@@ -75,7 +78,7 @@ public class tallyType extends inputType {
public void setViewValue(Object value) { public void setViewValue(Object value) {
if(tally == null) return; if(tally == null) return;
if(intType.isNull((int)value)){ if(IntType.isNull((int)value)){
nullify(); nullify();
return; return;
} }
@@ -88,10 +91,10 @@ public class tallyType extends inputType {
isBlank = true; isBlank = true;
tally.setVisibility(View.GONE); tally.setVisibility(View.GONE);
} }
public dataType getViewValue(){ public RawDataType getViewValue(){
if(tally == null) return null; if(tally == null) return null;
if(tally.getVisibility() == View.GONE) return intType.newNull(name); if(tally.getVisibility() == View.GONE) return IntType.newNull(name);
return new intType(name, tally.getValue()); return new IntType(name, tally.getValue());
} }
@@ -99,7 +102,7 @@ public class tallyType extends inputType {
public void add_individual_view(LinearLayout parent, dataType data){ public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return; if(data.isNull()) return;
TextView tv = new TextView(parent.getContext()); TextView tv = new TextView(parent.getContext());
@@ -146,7 +149,7 @@ public class tallyType extends inputType {
return entries; return entries;
} }
private static int findMin(dataType[] data){ private static int findMin(RawDataType[] data){
int min = (int)data[0].get(); int min = (int)data[0].get();
for(int i = 1; i < data.length; i++) for(int i = 1; i < data.length; i++)
if((int)data[i].get() < min) if((int)data[i].get() < min)
@@ -154,7 +157,7 @@ public class tallyType extends inputType {
return min; return min;
} }
private static int findMax(dataType[] data){ private static int findMax(RawDataType[] data){
int max = (int)data[0].get(); int max = (int)data[0].get();
for(int i = 1; i < data.length; i++) for(int i = 1; i < data.length; i++)
if((int)data[i].get() > max) if((int)data[i].get() > max)
@@ -162,7 +165,7 @@ public class tallyType extends inputType {
return max; return max;
} }
public void add_compiled_view(LinearLayout parent, dataType[] data){ public void add_compiled_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -195,8 +198,8 @@ public class tallyType extends inputType {
LineDataSet dataSet = new LineDataSet(entries, name); LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(Color.BLUE); dataSet.setColor(tally_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
@@ -211,7 +214,7 @@ public class tallyType extends inputType {
LineDataSet normalDistSet = new LineDataSet(normalDistEntries, "Normal Distribution"); LineDataSet normalDistSet = new LineDataSet(normalDistEntries, "Normal Distribution");
normalDistSet.setColor(Color.RED); normalDistSet.setColor(dropdown_value_text_2);
normalDistSet.setDrawCircles(false); normalDistSet.setDrawCircles(false);
normalDistSet.setDrawValues(false); normalDistSet.setDrawValues(false);
normalDistSet.setLineWidth(2f); normalDistSet.setLineWidth(2f);
@@ -226,14 +229,14 @@ public class tallyType extends inputType {
chart.setDragEnabled(false); chart.setDragEnabled(false);
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
parent.addView(chart); parent.addView(chart);
} }
@@ -241,7 +244,7 @@ public class tallyType extends inputType {
public void add_history_view(LinearLayout parent, dataType[] data){ public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -249,7 +252,7 @@ public class tallyType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
int min = findMin(data); int min = findMin(data);
int max = findMax(data); int max = findMax(data);
@@ -264,8 +267,8 @@ public class tallyType extends inputType {
LineDataSet dataSet = new LineDataSet(entries, name); LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(Color.BLUE); dataSet.setColor(tally_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
@@ -279,14 +282,14 @@ public class tallyType extends inputType {
chart.setDragEnabled(false); chart.setDragEnabled(false);
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
chart.getAxisLeft().setAxisMinimum(min); chart.getAxisLeft().setAxisMinimum(min);
@@ -299,7 +302,66 @@ public class tallyType extends inputType {
parent.addView(chart); parent.addView(chart);
} }
public String toString(dataType data){ public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
int[] tmp_abs_bounds = DataProcessing.getNumberBounds(data);
int absmin = tmp_abs_bounds[0];
int absmax = tmp_abs_bounds[1];
//(int[]) teamData.get(i).get())[0];
// AlertManager.alert("Results","Min: " + min + " Max: " + max);
parent.removeAllViews();
List<CandlestickView> views = new ArrayList<>();
for(Integer teamNum : data.keySet()){
CandlestickView candlestickView = new CandlestickView(parent.getContext());
candlestickView.fromTeamData(data.get(teamNum), teamNum, absmin, absmax);
views.add(candlestickView);
}
TableRow row = new TableRow(parent.getContext());
// Make candlestick chart fill full width
parent.setColumnStretchable(1, true);
// Fill in top left cell
row.addView(new View(parent.getContext()));
CandlestickHeader header = new CandlestickHeader(parent.getContext());
header.setScale(absmin, absmax);
row.addView(header);
parent.addView(row);
// parent.addView(new );
try {
Collections.sort(views, (a, b) -> (int) ((b.average - a.average) * 50.f));
}catch (Exception e){}
for(int i = 0; i < views.size(); i++){
row = new TableRow(parent.getContext());
CandlestickView view = views.get(i);
TextView teamNum = new TextView(parent.getContext());
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.gravity = Gravity.CENTER;
teamNum.setLayoutParams(params);
teamNum.setPadding(10,10,10,10);
teamNum.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline6);
teamNum.setText(String.valueOf(view.teamNum));
row.addView(teamNum);
row.addView(view);
parent.addView(row);
}
}
public String toString(RawDataType data){
return String.valueOf((int) data.get()); return String.valueOf((int) data.get());
} }
} }
@@ -1,8 +1,12 @@
package com.ridgebotics.ridgescout.types.input; package com.ridgebotics.ridgescout.types.input;
import android.app.Activity; import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.chart_text;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_1;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_2;
import static com.ridgebotics.ridgescout.utility.Colors.text_data;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.view.Gravity; import android.view.Gravity;
@@ -11,10 +15,11 @@ import android.view.ViewGroup;
import android.widget.EditText; import android.widget.EditText;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView; import android.widget.TextView;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.data.stringType; import com.ridgebotics.ridgescout.types.data.StringType;
import com.ridgebotics.ridgescout.utility.SentimentAnalysis; import com.ridgebotics.ridgescout.utility.SentimentAnalysis;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
@@ -26,17 +31,18 @@ import com.github.mikephil.charting.data.LineDataSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
public class textType extends inputType { public class TextType extends FieldType {
public int get_byte_id() {return notesType;} public int get_byte_id() {return notesType;}
public inputTypes getInputType(){return inputTypes.NOTES_INPUT;} public inputTypes getInputType(){return inputTypes.NOTES_INPUT;}
public dataType.valueTypes getValueType(){return dataType.valueTypes.STRING;} public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.STRING;}
public Object get_fallback_value(){return "<no-notes>";} public Object get_fallback_value(){return "<no-notes>";}
public textType(){} public TextType(){}
public textType(String name, String description, String default_text){ public TextType(String UUID, String name, String description, String default_text){
super(name, description); super(UUID, name, description);
this.default_value = default_text; this.default_value = default_text;
} }
public String get_type_name(){return "Text";} public String get_type_name(){return "Text";}
@@ -47,20 +53,11 @@ public class textType extends inputType {
public byte[] encode() throws ByteBuilder.buildingException { public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
ByteBuilder bb = new ByteBuilder();
bb.addString(name);
bb.addString(description);
bb.addString((String) default_value); bb.addString((String) default_value);
return bb.build();
} }
public void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption { public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
BuiltByteParser bbp = new BuiltByteParser(bytes); default_value = objects.get(0).get();
ArrayList<BuiltByteParser.parsedObject> objects = bbp.parse();
name = (String) objects.get(0).get();
description = (String) objects.get(1).get();
default_value = objects.get(2).get();
} }
@@ -78,7 +75,7 @@ public class textType extends inputType {
public EditText text = null; public EditText text = null;
public View createView(Context context, Function<dataType, Integer> onUpdate){ public View createView(Context context, Function<RawDataType, Integer> onUpdate){
text = new EditText(context); text = new EditText(context);
text.setText((String)default_value); text.setText((String)default_value);
text.addTextChangedListener(new TextWatcher() { text.addTextChangedListener(new TextWatcher() {
@@ -92,7 +89,7 @@ public class textType extends inputType {
} }
public void setViewValue(Object value) { public void setViewValue(Object value) {
if(text == null) return; if(text == null) return;
if(stringType.isNull((String) value)){ if(StringType.isNull((String) value)){
nullify(); nullify();
return; return;
} }
@@ -104,16 +101,16 @@ public class textType extends inputType {
isBlank = true; isBlank = true;
text.setVisibility(View.GONE); text.setVisibility(View.GONE);
} }
public dataType getViewValue(){ public RawDataType getViewValue(){
if(text == null) return null; if(text == null) return null;
if(text.getVisibility() == View.GONE) return new stringType(name, stringType.nullval); if(text.getVisibility() == View.GONE) return new StringType(name, StringType.nullval);
return new stringType(name, text.getText().toString()); return new StringType(name, text.getText().toString());
} }
public void add_individual_view(LinearLayout parent, dataType data){ public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return; if(data.isNull()) return;
TextView tv = new TextView(parent.getContext()); TextView tv = new TextView(parent.getContext());
tv.setLayoutParams(new FrameLayout.LayoutParams( tv.setLayoutParams(new FrameLayout.LayoutParams(
@@ -143,7 +140,7 @@ public class textType extends inputType {
TextView positive_text; TextView positive_text;
public void add_compiled_view(LinearLayout parent, dataType[] data) { public void add_compiled_view(LinearLayout parent, RawDataType[] data) {
positive_mean = 0; positive_mean = 0;
count = 0; count = 0;
@@ -172,7 +169,7 @@ public class textType extends inputType {
} }
public void add_history_view(LinearLayout parent, dataType[] data){ public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext()); LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -180,7 +177,7 @@ public class textType extends inputType {
); );
layout.height = 350; layout.height = 350;
chart.setLayoutParams(layout); chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025); chart.setBackgroundColor(chart_background);
List<Entry> entries = new ArrayList<>(); List<Entry> entries = new ArrayList<>();
@@ -195,11 +192,11 @@ public class textType extends inputType {
); );
} }
LineDataSet dataSet = new LineDataSet(entries, "Sentiment"); LineDataSet dataSet = new LineDataSet(entries, "Sentiment");
dataSet.setColor(Color.BLUE); dataSet.setColor(text_data);
dataSet.setValueTextColor(Color.BLACK); dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false); dataSet.setDrawCircles(false);
dataSet.setDrawValues(false); dataSet.setDrawValues(false);
dataSet.setValueTextColor(Color.RED); dataSet.setValueTextColor(dropdown_value_text_2);
LineData lineData = new LineData(dataSet); LineData lineData = new LineData(dataSet);
@@ -213,9 +210,9 @@ public class textType extends inputType {
chart.setScaleEnabled(false); chart.setScaleEnabled(false);
chart.getXAxis().setTextColor(Color.WHITE); chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(Color.WHITE); chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(Color.WHITE); chart.getAxisRight().setTextColor(chart_text);
chart.getAxisLeft().setAxisMinimum(0.f); chart.getAxisLeft().setAxisMinimum(0.f);
chart.getAxisLeft().setAxisMaximum(1.f); chart.getAxisLeft().setAxisMaximum(1.f);
@@ -224,14 +221,18 @@ public class textType extends inputType {
chart.getAxisRight().setAxisMaximum(1.f); chart.getAxisRight().setAxisMaximum(1.f);
Legend legend = chart.getLegend(); Legend legend = chart.getLegend();
legend.setTextColor(Color.WHITE); legend.setTextColor(chart_text);
chart.invalidate(); chart.invalidate();
parent.addView(chart); parent.addView(chart);
} }
public String toString(dataType data){ public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
}
public String toString(RawDataType data){
return String.valueOf(data.get()); return String.valueOf(data.get());
} }
} }
@@ -0,0 +1,368 @@
package com.ridgebotics.ridgescout.types.input;
import static com.ridgebotics.ridgescout.utility.Colors.chart_background;
import static com.ridgebotics.ridgescout.utility.Colors.chart_text;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_1;
import static com.ridgebotics.ridgescout.utility.Colors.dropdown_value_text_2;
import static com.ridgebotics.ridgescout.utility.Colors.tally_data;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.ridgebotics.ridgescout.types.data.IntType;
import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.ui.data.DataProcessing;
import com.ridgebotics.ridgescout.ui.views.CandlestickHeader;
import com.ridgebotics.ridgescout.ui.views.CandlestickView;
import com.ridgebotics.ridgescout.ui.views.TallyCounterView;
import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class ToggleType extends FieldType {
public int get_byte_id() {return toggleType;}
public inputTypes getInputType(){return inputTypes.TOGGLE;}
public RawDataType.valueTypes getValueType(){return RawDataType.valueTypes.NUM;}
public Object get_fallback_value(){return 0;}
public ToggleType(){}
public String get_type_name(){return "Toggle";}
public ToggleType(String UUID, String name, String description, int default_value){
super(UUID, name, description);
this.default_value = default_value;
}
public void encodeData(ByteBuilder bb) throws ByteBuilder.buildingException {
bb.addInt((int) default_value);
}
public void decodeData(ArrayList<BuiltByteParser.parsedObject> objects) {
default_value = objects.get(0).get();
}
public TallyCounterView tally = null;
public View createView(Context context, Function<RawDataType, Integer> onUpdate){
tally = new TallyCounterView(context);
tally.setOnCountChangedListener(n -> onUpdate.apply(getViewValue()));
setViewValue(default_value);
return tally;
}
public void setViewValue(Object value) {
if(tally == null) return;
if(IntType.isNull((int)value)){
nullify();
return;
}
isBlank = false;
tally.setVisibility(View.VISIBLE);
tally.setValue((int) value);
}
public void nullify(){
isBlank = true;
tally.setVisibility(View.GONE);
}
public RawDataType getViewValue(){
if(tally == null) return null;
if(tally.getVisibility() == View.GONE) return IntType.newNull(name);
return new IntType(name, tally.getValue());
}
public void add_individual_view(LinearLayout parent, RawDataType data){
if(data.isNull()) return;
TextView tv = new TextView(parent.getContext());
tv.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(String.valueOf((int) data.get()));
tv.setTextSize(24);
parent.addView(tv);
}
private static float calculateMean(int[] data) {
float sum = 0;
for (int value : data) {
sum += (float) value;
}
return sum / data.length;
}
private static float calculateStandardDeviation(int[] data, float mean) {
float sum = 0;
for (int value : data) {
sum += (float) Math.pow((float) value - mean, 2);
}
return (float) Math.sqrt(sum / (data.length - 1));
}
private static List<Entry> generateNormalDistribution(float mean, float stdDev, int count, int scale) {
List<Entry> entries = new ArrayList<>();
for (int i = 0; i < count; i++) {
float y = (float) ((1 / (stdDev * Math.sqrt(2 * Math.PI)))
* Math.exp(-0.5 * Math.pow(((float) i - mean) / stdDev, 2)));
entries.add(new Entry((float) i, y*scale)); // Scale y for visibility
}
return entries;
}
private static int findMin(RawDataType[] data){
int min = (int)data[0].get();
for(int i = 1; i < data.length; i++)
if((int)data[i].get() < min)
min = (int)data[i].get();
return min;
}
private static int findMax(RawDataType[] data){
int max = (int)data[0].get();
for(int i = 1; i < data.length; i++)
if((int)data[i].get() > max)
max = (int)data[i].get();
return max;
}
public void add_compiled_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
layout.height = 350;
chart.setLayoutParams(layout);
chart.setBackgroundColor(0xff252025);
int min = findMin(data);
int max = findMax(data);
int[] values = new int[max-min+1];
for (int i = 0; i < data.length; i++)
if(data[i] != null && data[i].isNull())
values[(int) data[i].get()-min]++;
ArrayList<Integer> mean_temp = new ArrayList<>();
for (int i = 0; i < data.length; i++)
if((int)data[i].get() != 0)
mean_temp.add((int) data[i].get());
int[] mean_vals = mean_temp.stream().mapToInt(Integer::intValue).toArray();
List<Entry> entries = new ArrayList<>();
for (int i = 0; i < values.length; i++)
entries.add(new Entry(i, values[i]));
LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(tally_data);
dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false);
dataSet.setDrawValues(false);
// Calculate mean and standard deviation
float mean = calculateMean(mean_vals);
float stdDev = calculateStandardDeviation(mean_vals, mean);
// Generate normal distribution curve
List<Entry> normalDistEntries = generateNormalDistribution(mean-min, stdDev, max-min+1, (max-min)/data.length);
LineDataSet normalDistSet = new LineDataSet(normalDistEntries, "Normal Distribution");
normalDistSet.setColor(dropdown_value_text_2);
normalDistSet.setDrawCircles(false);
normalDistSet.setDrawValues(false);
normalDistSet.setLineWidth(2f);
LineData lineData = new LineData(dataSet, normalDistSet);
chart.setData(lineData);
chart.invalidate();
chart.getDescription().setEnabled(false);
chart.setTouchEnabled(false);
chart.setDragEnabled(false);
chart.setScaleEnabled(false);
dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend();
legend.setTextColor(chart_text);
parent.addView(chart);
}
public void add_history_view(LinearLayout parent, RawDataType[] data){
LineChart chart = new LineChart(parent.getContext());
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
layout.height = 350;
chart.setLayoutParams(layout);
chart.setBackgroundColor(chart_background);
int min = findMin(data);
int max = findMax(data);
List<Entry> entries = new ArrayList<>();
for (int i = 0; i < data.length; i++){
if(data[i] == null) continue;
if(data[i].isNull()) continue;
entries.add(new Entry(i, (float)(int) data[i].get()));
}
LineDataSet dataSet = new LineDataSet(entries, name);
dataSet.setColor(tally_data);
dataSet.setValueTextColor(dropdown_value_text_1);
dataSet.setDrawCircles(false);
dataSet.setDrawValues(false);
LineData lineData = new LineData(dataSet);
chart.setData(lineData);
chart.invalidate();
chart.getDescription().setEnabled(false);
chart.setTouchEnabled(false);
chart.setDragEnabled(false);
chart.setScaleEnabled(false);
dataSet.setValueTextColor(dropdown_value_text_2);
chart.getXAxis().setTextColor(chart_text);
chart.getAxisLeft().setTextColor(chart_text);
chart.getAxisRight().setTextColor(chart_text);
Legend legend = chart.getLegend();
legend.setTextColor(chart_text);
chart.getAxisLeft().setAxisMinimum(min);
chart.getAxisLeft().setAxisMaximum(max);
chart.getAxisRight().setAxisMinimum(min);
chart.getAxisRight().setAxisMaximum(max);
parent.addView(chart);
}
public void addDataToTable(TableLayout parent, Map<Integer, List<RawDataType>> data){
int[] tmp_abs_bounds = DataProcessing.getNumberBounds(data);
int absmin = tmp_abs_bounds[0];
int absmax = tmp_abs_bounds[1];
//(int[]) teamData.get(i).get())[0];
// AlertManager.alert("Results","Min: " + min + " Max: " + max);
parent.removeAllViews();
List<CandlestickView> views = new ArrayList<>();
for(Integer teamNum : data.keySet()){
CandlestickView candlestickView = new CandlestickView(parent.getContext());
candlestickView.fromTeamData(data.get(teamNum), teamNum, absmin, absmax);
views.add(candlestickView);
}
TableRow row = new TableRow(parent.getContext());
// Make candlestick chart fill full width
parent.setColumnStretchable(1, true);
// Fill in top left cell
row.addView(new View(parent.getContext()));
CandlestickHeader header = new CandlestickHeader(parent.getContext());
header.setScale(absmin, absmax);
row.addView(header);
parent.addView(row);
// parent.addView(new );
try {
Collections.sort(views, (a, b) -> (int) ((b.average - a.average) * 50.f));
}catch (Exception e){}
for(int i = 0; i < views.size(); i++){
row = new TableRow(parent.getContext());
CandlestickView view = views.get(i);
TextView teamNum = new TextView(parent.getContext());
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.gravity = Gravity.CENTER;
teamNum.setLayoutParams(params);
teamNum.setPadding(10,10,10,10);
teamNum.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline6);
teamNum.setText(String.valueOf(view.teamNum));
row.addView(teamNum);
row.addView(view);
parent.addView(row);
}
}
public String toString(RawDataType data){
return String.valueOf((int) data.get());
}
}
@@ -1,113 +0,0 @@
package com.ridgebotics.ridgescout.types.input;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import com.ridgebotics.ridgescout.types.data.dataType;
import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder;
import java.util.function.Function;
public abstract class inputType {
public static final int slider_type_id = 255;
public static final int dropdownType = 254;
public static final int notesType = 253;
public static final int tallyType = 252;
public static final int numberType = 251;
public static final int checkboxType = 250;
public static final int fieldposType = 249;
public enum inputTypes {
SLIDER,
DROPDOWN,
NOTES_INPUT,
TALLY,
NUMBER,
CHECKBOX,
FIELDPOS
}
public String name;
public String description;
public Object default_value;
public abstract inputTypes getInputType();
public abstract dataType.valueTypes getValueType();
public abstract Object get_fallback_value();
public abstract int get_byte_id();
public inputType(){}
public inputType(String name, String description){
this.name = name;
this.description = description;
}
public abstract String get_type_name();
public abstract byte[] encode() throws ByteBuilder.buildingException;
public abstract void decode(byte[] bytes) throws BuiltByteParser.byteParsingExeption;
// public abstract dataType[] getConfig();
// public abstract void setConfig(dataType[] config);
public abstract View createView(Context context, Function<dataType, Integer> onUpdate);
public boolean isBlank = false;
public abstract void nullify();
public void setViewValue(dataType type){setViewValue(type.get());}
public abstract void setViewValue(Object value);
public abstract dataType getViewValue();
// private enum parameterTypeEnum {
// paramNumber,
// paramString,
// paramStringArray
// }
//
// public static class parameterType {
// public String name;
// public parameterTypeEnum id;
// }
//
// public static class paramNumber extends parameterType {
// public int val;
// public paramNumber(String name, int val){
// this.name = name + " (Number)";
// this.val = val;
// this.id = parameterTypeEnum.paramNumber;
// }
// }
//
// public static class paramString extends parameterType {
// public String val;
// public paramString(String name, String val){
// this.name = name + " (String)";
// this.val = val;
// this.id = parameterTypeEnum.paramString;
// }
// }
//
// public static class paramStringArray extends parameterType {
// public String[] val;
// public paramStringArray(String name, String[] val){
// this.name = name + " (String array)";
// this.val = val;
// this.id = parameterTypeEnum.paramStringArray;
// }
// }
// public abstract parameterType[] getDefaultParameters();
public abstract void add_individual_view(LinearLayout parent, dataType data);
public abstract void add_compiled_view(LinearLayout parent, dataType[] data);
public abstract void add_history_view(LinearLayout parent, dataType[] data);
public abstract String toString(dataType data);
}
@@ -1,126 +0,0 @@
package com.ridgebotics.ridgescout.ui;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.event;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentTeamSelectorBinding;
import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.fileEditor;
import java.util.Arrays;
public class TeamSelectorFragment extends Fragment {
private FragmentTeamSelectorBinding binding;
private static boolean pits_mode;
public static void setPits_mode(boolean mode){
pits_mode = mode;
}
private static onTeamSelected onSelect = new onTeamSelected() {@Override public void onSelect(TeamSelectorFragment self, frcTeam team) {}};
public interface onTeamSelected {
void onSelect(TeamSelectorFragment self, frcTeam team);
}
public static void setOnSelect(onTeamSelected tmponSelect){
onSelect = tmponSelect;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentTeamSelectorBinding.inflate(inflater, container, false);
// event = fileEditor.g
DataManager.reload_event();
if(evcode == null || evcode.equals("unset")){
AlertManager.error("You somehow have not loaded an event!");
return binding.getRoot();
}
load_teams();
return binding.getRoot();
}
public void load_teams(){
// binding.pitFileIndicator.setVisibility(View.GONE);
// binding.pitTeamName.setVisibility(View.GONE);
// binding.pitTeamDescription.setVisibility(View.GONE);
//
// clear_fields();
int[] teamNums = new int[event.teams.size()];
for(int i = 0 ; i < event.teams.size(); i++){
teamNums[i] = event.teams.get(i).teamNumber;
}
Arrays.sort(teamNums);
TableLayout table = new TableLayout(getContext());
table.setStretchAllColumns(true);
binding.teams.addView(table);
for(int i = 0; i < event.teams.size(); i++){
frcTeam team = null;
for(int a = 0 ; a < event.teams.size(); a++){
if(event.teams.get(a).teamNumber == teamNums[i]){
team = event.teams.get(a);
break;
}
}
TableRow tr = new TableRow(getContext());
TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT
);
rowParams.setMargins(20,20,20,20);
tr.setLayoutParams(rowParams);
tr.setPadding(20,20,20,20);
table.addView(tr);
if(!pits_mode || fileEditor.fileExist(evcode + "-" + team.teamNumber + ".pitscoutdata")){
tr.setBackgroundColor(0x3000FF00);
}else{
tr.setBackgroundColor(0x30FF0000);
}
TextView tv = new TextView(getContext());
tv.setText(String.valueOf(team.teamNumber));
tv.setTextSize(20);
tr.addView(tv);
tv = new TextView(getContext());
tv.setText(team.teamName);
tv.setTextSize(16);
tr.addView(tv);
frcTeam finalTeam = team;
tr.setOnClickListener(v -> {
onSelect.onSelect(this, finalTeam);
});
}
}
}
@@ -1,8 +1,14 @@
package com.ridgebotics.ridgescout.ui.data; package com.ridgebotics.ridgescout.ui.data;
import static android.view.View.GONE;
import static android.view.View.VISIBLE; import static android.view.View.VISIBLE;
import static androidx.navigation.fragment.FragmentKt.findNavController;
import static com.ridgebotics.ridgescout.utility.Colors.datafragment_option_1;
import static com.ridgebotics.ridgescout.utility.Colors.datafragment_option_2;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.event;
import static com.ridgebotics.ridgescout.utility.DataManager.match_latest_values;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@@ -14,65 +20,119 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.scoutingData.fields;
import com.ridgebotics.ridgescout.utility.settingsManager;
import com.ridgebotics.ridgescout.databinding.FragmentDataBinding;
import com.ridgebotics.ridgescout.types.frcTeam; import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.ui.TeamSelectorFragment; import com.ridgebotics.ridgescout.ui.views.FieldBorderedRow;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.ui.views.TeamListOption;
import com.ridgebotics.ridgescout.types.frcEvent; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import com.ridgebotics.ridgescout.databinding.FragmentDataBinding;
import java.util.Arrays;
import java.util.List;
// Fragment for the menu of the data tab.
// Shows either by field type or by team.
// This is held in a sub-fragment under DataParentFragment
public class DataFragment extends Fragment { public class DataFragment extends Fragment {
private FragmentDataBinding binding; private FragmentDataBinding binding;
private int option = 0;
private boolean submenu = false;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) { @Nullable Bundle savedInstanceState) {
binding = FragmentDataBinding.inflate(inflater, container, false); binding = FragmentDataBinding.inflate(inflater, container, false);
binding.table.setStretchAllColumns(true);
View root = binding.getRoot(); View root = binding.getRoot();
String evcode = settingsManager.getEVCode(); if(evcode == null || evcode.equals("unset") || event == null){
binding.fieldsButton.setOnClickListener(v -> {
binding.fieldsButton.setEnabled(false);
binding.fieldsButtons.setVisibility(VISIBLE);
});
binding.fieldsMatchesButton.setOnClickListener(v -> {
FieldsFragment.set_filename(fields.matchFieldsFilename);
findNavController(this).navigate(R.id.action_navigation_data_to_navigation_data_fields);
});
binding.fieldsPitsButton.setOnClickListener(v -> {
FieldsFragment.set_filename(fields.pitsFieldsFilename);
findNavController(this).navigate(R.id.action_navigation_data_to_navigation_data_fields);
});
if(evcode.equals("unset")){
binding.noEventError.setVisibility(VISIBLE); binding.noEventError.setVisibility(VISIBLE);
binding.dataTypeDropdown.setVisibility(GONE);
return root;
}
binding.buttons.setVisibility(VISIBLE); option = SettingsManager.getDataMode();
binding.teamsButton.setEnabled(false);
binding.fieldsButton.setVisibility(VISIBLE);
binding.dataTypeDropdown.setTitle("Data type");
binding.dataTypeDropdown.setOptions(List.of(new String[]{
"By Team", "By Data Field"
}), option);
binding.dataTypeDropdown.setOnClickListener((item, index) -> {
option = index;
SettingsManager.setDataMode(option);
reload_views();
});
reload_views();
return root; return root;
} }
frcEvent event = frcEvent.decode(fileEditor.readFile(evcode + ".eventdata")); public void reload_views(){
binding.table.removeViews(1, binding.table.getChildCount()-1);
binding.teamsButton.setOnClickListener(v -> { switch (option) {
TeamSelectorFragment.setPits_mode(false); case 0:
TeamSelectorFragment.setOnSelect((self, team) -> { load_teams();
TeamsFragment.setTeam(team); break;
findNavController(self).navigate(R.id.action_navigation_team_selector_to_navigation_data_teams); case 1:
load_fields();
break;
}
}
public void load_teams(){
int[] teamNums = new int[event.teams.size()];
for(int i = 0 ; i < event.teams.size(); i++){
teamNums[i] = event.teams.get(i).teamNumber;
}
Arrays.sort(teamNums);
for(int i = 0; i < event.teams.size(); i++){
frcTeam team = null;
for(int a = 0 ; a < event.teams.size(); a++){
if(event.teams.get(a).teamNumber == teamNums[i]){
team = event.teams.get(a);
break;
}
}
assert team != null;
TeamListOption teamRow = new TeamListOption(getContext());
binding.table.addView(teamRow);
teamRow.fromTeam(team);
frcTeam finalTeam = team;
teamRow.setOnClickListener(v -> {
TeamsFragment.setTeam(finalTeam);
((DataParentFragment) getParentFragment()).moveToFragment(new TeamsFragment());
// findNavController(this).navigate(R.id.action_navigation_data_parent_to_navigation_data_teams);
}); });
findNavController(this).navigate(R.id.action_navigation_data_to_navigation_team_selector); }
}
public void load_fields(){
DataManager.reload_match_fields();
if(match_latest_values == null) return;
for(int i = 0; i < match_latest_values.length; i++){
FieldBorderedRow tr = new FieldBorderedRow(getContext());
tr.fromField(match_latest_values[i]);
tr.setColor(i % 2 == 0 ? datafragment_option_1 : datafragment_option_2);
binding.table.addView(tr);
final int fi = i;
tr.setOnClickListener(v -> {
FieldDataFragment.setFieldIndex(fi);
((DataParentFragment) getParentFragment()).moveToFragment(new FieldDataFragment());
// findNavController(get).navigate(R.id.action_navigation_data_parent_to_navigation_data_field_data);
}); });
return root; }
} }
} }
@@ -0,0 +1,183 @@
package com.ridgebotics.ridgescout.ui.data;
import static android.content.Context.CLIPBOARD_SERVICE;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.event;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.databinding.FragmentDataParentBinding;
import com.ridgebotics.ridgescout.types.frcMatch;
import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.AutoSaveManager;
import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import java.util.ArrayList;
import java.util.List;
// Holds the scouting data editor aswell as the sub-fragment for the scouting data browser
public class DataParentFragment extends Fragment {
private FragmentDataParentBinding binding;
private DataFragment dataFragment;
private boolean editBoxEnabled = true;
private int teamNum = SettingsManager.getTeamNum();
private frcMatch[] ourMatches;
private int matchIndex = 0;
private AutoSaveManager asm;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentDataParentBinding.inflate(inflater, container, false);
DataManager.reload_event();
if (savedInstanceState == null && dataFragment == null){
dataFragment = new DataFragment();
//add child fragment
getChildFragmentManager()
.beginTransaction()
.add(R.id.data_subfragment, dataFragment, "Data Subfragment")
.commit();
}
if(evcode.equals("unset") || event == null){
binding.reportToggleButton.setVisibility(GONE);
return binding.getRoot();
}
ourMatches = event.getTeamMatches(SettingsManager.getTeamNum());
matchIndex = SettingsManager.getReportMatchIndex(evcode);
if(ourMatches.length == 0){
binding.reportToggleButton.setVisibility(GONE);
return binding.getRoot();
}
binding.scoutUpButton.setOnClickListener(v -> {
matchIndex++;
updateButtons();
});
binding.scoutDownButton.setOnClickListener(v -> {
matchIndex--;
updateButtons();
});
updateButtons();
binding.reportToggleButton.setOnClickListener(view -> {
editBoxEnabled =! editBoxEnabled;
binding.ScoutingEditBox.setVisibility(editBoxEnabled ? GONE : VISIBLE);
binding.reportToggleButton.setText(editBoxEnabled ? "▲ report" : "▼ report");
});
binding.reportCopyButton.setOnClickListener(v -> {
// ClipData e = new ClipData();
ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText(
"Scouting report",
binding.scoutingReportEdittext.getText().toString()
);
clipboardManager.setPrimaryClip(clipData);
AlertManager.toast("Copied report to clipboard!");
});
asm = new AutoSaveManager(() -> SettingsManager.setScoutingReport(evcode, matchIndex, binding.scoutingReportEdittext.getText().toString()), 300);
asm.start();
binding.scoutingReportEdittext.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
asm.update();
}
@Override public void afterTextChanged(Editable editable) {}
});
return binding.getRoot();
}
private void updateButtons(){
binding.matchNum.setText(String.valueOf(ourMatches[matchIndex].matchIndex));
binding.scoutUpButton.setEnabled(matchIndex < ourMatches.length-1);
binding.scoutDownButton.setEnabled(matchIndex > 0);
SettingsManager.setReportIndex(matchIndex, evcode);
String report = SettingsManager.getScoutingReport(evcode, matchIndex);
if(report.isEmpty()) report = generateScoutingTemplate(ourMatches[matchIndex]);
binding.scoutingReportEdittext.setText(report);
}
public void moveToFragment(Fragment newFragment){
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.data_subfragment, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
// Generate format for scouting data
private String generateScoutingTemplate(frcMatch nextMatch){
boolean isBlueAlliance = event.getIsBlueAlliance(teamNum, nextMatch);
List<frcTeam> ourAlliance = new ArrayList<>();
List<frcTeam> opposingAlliance = new ArrayList<>();
for(int a = 0; a < nextMatch.blueAlliance.length; a++)
if(nextMatch.blueAlliance[a] != teamNum){
(isBlueAlliance ? ourAlliance : opposingAlliance).add(event.getTeamByNum(nextMatch.blueAlliance[a]));
}
for(int a = 0; a < nextMatch.redAlliance.length; a++)
if(nextMatch.redAlliance[a] != teamNum){
(!isBlueAlliance ? ourAlliance : opposingAlliance).add(event.getTeamByNum(nextMatch.redAlliance[a]));
}
String output = "Match: " + (nextMatch.matchIndex) + "\n";
output += "## Our Alliance ##";
output += getTeamNameAndNum(ourAlliance.get(0));
output += getTeamNameAndNum(ourAlliance.get(1));
output += "\n## Opposing Alliance ##";
output += getTeamNameAndNum(opposingAlliance.get(0));
output += getTeamNameAndNum(opposingAlliance.get(1));
output += getTeamNameAndNum(opposingAlliance.get(2));
return output;
}
private static String getTeamNameAndNum(frcTeam team){
return "\n" + team.teamNumber + " " + team.teamName + ": \n";
}
}
@@ -0,0 +1,108 @@
package com.ridgebotics.ridgescout.ui.data;
import com.ridgebotics.ridgescout.types.data.RawDataType;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
// Helper class for scouting data by fields.
public class DataProcessing {
public static int[] getNumberBounds(Map<Integer, List<RawDataType>> data){
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(Integer teamNum : data.keySet()){
List<RawDataType> teamData = data.get(teamNum);
int[] locBounds = getNumberBounds(teamData);
if(locBounds[1] > max) max = locBounds[1];
if(locBounds[0] < min) min = locBounds[0];
}
return new int[]{min, max};
}
public static int[] getNumberBounds(List<RawDataType> data){
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
if(data == null) return new int[]{min, max};
for(int i = 0; i < data.size(); i++){
RawDataType dataPoint = data.get(i);
// if(dataPoint == null) continue;
int num = (int) dataPoint.get();
if(num > max) max = num;
if(num < min) min = num;
}
return new int[]{min, max};
}
//https://stackoverflow.com/questions/42381759/finding-first-quartile-and-third-quartile-in-integer-array-using-java#63891545
public static float[] getQuartiles(List<RawDataType> data) {
float ans[] = new float[3];
float[] val = new float[data.size()];
for(int i = 0; i < val.length; i++){
val[i] = (int) data.get(i).get();
}
for (int quartileType = 1; quartileType < 4; quartileType++) {
float length = val.length + 1;
float quartile;
float newArraySize = (length * ((float) (quartileType) * 25 / 100)) - 1;
Arrays.sort(val);
if (newArraySize % 1 == 0) {
quartile = val[(int) (newArraySize)];
} else {
int newArraySize1 = (int) (newArraySize);
quartile = (val[newArraySize1] + val[newArraySize1 + 1]) / 2;
}
ans[quartileType - 1] = quartile;
}
return ans;
}
/**
* Calculates the specified percentile of a dataset.
*
* @param data The dataset to analyze
* @param percentile The percentile to find (0-100)
* @return The value at the specified percentile
*/
public static float calculatePercentile(float[] data, float percentile) {
// Make a copy of the data to avoid modifying the original
float[] dataCopy = Arrays.copyOf(data, data.length);
// Sort the data in ascending order
Arrays.sort(dataCopy);
// Calculate the position as a fraction
float position = (percentile / 100.0f) * (dataCopy.length - 1);
// Get the integer part of the position
int lowerIndex = (int) Math.floor(position);
int upperIndex = (int) Math.ceil(position);
// If position is already an integer, return the value at that position
if (lowerIndex == upperIndex) {
return dataCopy[lowerIndex];
}
// Otherwise, interpolate between the two adjacent values
float fraction = position - lowerIndex;
float lowerValue = dataCopy[lowerIndex];
float upperValue = dataCopy[upperIndex];
// Linear interpolation
return lowerValue + fraction * (upperValue - lowerValue);
}
}
@@ -0,0 +1,114 @@
package com.ridgebotics.ridgescout.ui.data;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.event;
import static com.ridgebotics.ridgescout.utility.DataManager.match_latest_values;
import static com.ridgebotics.ridgescout.utility.DataManager.match_transferValues;
import static com.ridgebotics.ridgescout.utility.DataManager.match_values;
import static com.ridgebotics.ridgescout.utility.DataManager.rescout_list;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentDataFieldDataBinding;
import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter;
import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.FileEditor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// Fragment for viewing the data of a specfic field.
public class FieldDataFragment extends Fragment {
private FragmentDataFieldDataBinding binding;
private static int fieldIndex = -1;
public static void setFieldIndex(int index){
fieldIndex = index;
}
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentDataFieldDataBinding.inflate(inflater, container, false);
binding.table.setStretchAllColumns(true);
View root = binding.getRoot();
if (fieldIndex == -1)
return root;
startLoading("Loading data...");
Thread t = new Thread(() -> {
Map<Integer, List<RawDataType>> data = new HashMap<>();
for (int teamIndex = 0; teamIndex < event.teams.size(); teamIndex++) {
int teamNum = event.teams.get(teamIndex).teamNumber;
List<String> filenames = new ArrayList<>(List.of(FileEditor.getMatchesByTeamNum(evcode, event.teams.get(teamIndex).teamNumber)));
filenames.removeAll(rescout_list);
ArrayList<RawDataType> teamData = new ArrayList<>();
for (int i = 0; i < filenames.size(); i++) {
try {
Log.i(getClass().toString(), "Loading: " + filenames.get(i));
ScoutingDataWriter.ParsedScoutingDataResult psda = ScoutingDataWriter.load(filenames.get(i), match_values, match_transferValues);
if (psda.data.array[fieldIndex] != null && psda.data.array[fieldIndex].get() != null && !psda.data.array[fieldIndex].isNull())
teamData.add(psda.data.array[fieldIndex]);
} catch (Exception e) {
AlertManager.error("Failure to load file " + filenames.get(i), e);
}
}
data.put(teamNum, teamData);
}
Log.i(getClass().toString(), "Finished!");
getActivity().runOnUiThread(() -> {
binding.table.setStretchAllColumns(false);
match_latest_values[fieldIndex].addDataToTable(binding.table, data);
stopLoading();
});
});
t.start();
return root;
}
private ProgressDialog loadingDialog;
private void startLoading(String title){
getActivity().runOnUiThread(() -> {
if(loadingDialog != null && loadingDialog.isShowing())
loadingDialog.dismiss();
loadingDialog = ProgressDialog.show(getActivity(), title, "Please wait...");
});
}
private void stopLoading(){
getActivity().runOnUiThread(() -> {
if (loadingDialog != null)
loadingDialog.cancel();
loadingDialog = null;
});
}
}
@@ -1,343 +0,0 @@
package com.ridgebotics.ridgescout.ui.data;
import static android.text.InputType.TYPE_CLASS_NUMBER;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;
import com.ridgebotics.ridgescout.types.input.checkboxType;
import com.ridgebotics.ridgescout.types.input.dropdownType;
import com.ridgebotics.ridgescout.types.input.fieldposType;
import com.ridgebotics.ridgescout.types.input.inputType;
import com.ridgebotics.ridgescout.types.input.numberType;
import com.ridgebotics.ridgescout.types.input.sliderType;
import com.ridgebotics.ridgescout.types.input.tallyType;
import com.ridgebotics.ridgescout.types.input.textType;
import com.ridgebotics.ridgescout.utility.AlertManager;
public class FieldEditorHelper {
private enum parameterTypeEnum {
paramNumber,
paramString,
paramStringArray,
paramNumberArray
}
public static class parameterType {
public String name;
public parameterTypeEnum id;
}
public static class paramNumber extends parameterType{
public int val;
public paramNumber(String name, int val){
this.name = name + " (Number)";
this.val = val;
this.id = parameterTypeEnum.paramNumber;
}
}
public static class paramString extends parameterType {
public String val;
public paramString(String name, String val){
this.name = name + " (String)";
this.val = val;
this.id = parameterTypeEnum.paramString;
}
}
public static class paramStringArray extends parameterType{
public String[] val;
public paramStringArray(String name, String[] val){
this.name = name + " (String array)";
this.val = val;
this.id = parameterTypeEnum.paramStringArray;
}
}
// public static class paramNumberArray extends parameterType{
// public int[] val;
// public paramNumberArray(String name, int[] val){
// this.name = name + " (Number array)";
// this.val = val;
// this.id = parameterTypeEnum.paramNumberArray;
// }
// }
public static final parameterType[] defaultSliderParams = new parameterType[]{
new paramString("Description", ""),
new paramNumber("Min", 0),
new paramNumber("Max", 10),
new paramNumber("Default Value", 5)
};
public static final parameterType[] defaultDropdownParams = new parameterType[]{
new paramString("Description", ""),
new paramStringArray("Default Value", new String[]{"Zero","One","Two","Three"}),
new paramNumber("Default Option", 0),
};
public static final parameterType[] defaultTextParams = new parameterType[]{
new paramString("Description", ""),
new paramString("Default Value", "")
};
public static final parameterType[] defaultTallyParams = new parameterType[]{
new paramString("Description", ""),
new paramNumber("Default Value", 0)
};
public static final parameterType[] defaultNumberParams = new parameterType[]{
new paramString("Description", ""),
new paramNumber("Default Value", 0)
};
public static final parameterType[] defaultCheckboxParam = new parameterType[]{
new paramString("Description", ""),
new paramNumber("Default Value ( 1 or 0 )", 0)
};
public static final parameterType[] defaultFieldPosParam = new parameterType[]{
new paramString("Description", ""),
new paramNumber("Default X", 0),
new paramNumber("Default Y", 0)
};
private static parameterType[] getSliderParams(sliderType s){
return new parameterType[]{
new paramString("Description", s.description),
new paramNumber("Min", s.min),
new paramNumber("Max", s.max),
new paramNumber("Default Value", (int) s.default_value)
};
}
private static parameterType[] getDropdownParams(dropdownType s){
return new parameterType[]{
new paramString("Description", s.description),
new paramStringArray("Default Value",s.text_options),
new paramNumber("Default Option", (int) s.default_value),
};
}
private static parameterType[] getTextParams(textType s){
return new parameterType[]{
new paramString("Description", s.description),
new paramString("Default Value", (String) s.default_value)
};
}
private static parameterType[] getTallyParams(tallyType s){
return new parameterType[]{
new paramString("Description", s.description),
new paramNumber("Default Value", (int) s.default_value)
};
}
private static parameterType[] getNumberParams(numberType s){
return new parameterType[]{
new paramString("Description", s.description),
new paramNumber("Default Value", (int) s.default_value)
};
}
private static parameterType[] getCheckboxParam(checkboxType s){
return new parameterType[]{
new paramString("Description", s.description),
new paramNumber("Default Value ( 1 or 0 )", (int) s.default_value)
};
}
private static parameterType[] getFieldPosParam(fieldposType s){
return new parameterType[]{
new paramString("Description", s.description),
new paramNumber("Default X", ((int[]) s.default_value)[0]),
new paramNumber("Default Y", ((int[]) s.default_value)[1])
};
}
public static void setSliderParams(sliderType s, parameterType[] types){
s.description = ((paramString) types[0]).val;
s.min = ((paramNumber) types[1]).val;
s.max = ((paramNumber) types[2]).val;
s.default_value = ((paramNumber) types[3]).val;
}
public static void setDropdownParams(dropdownType s, parameterType[] types){
s.description = ((paramString) types[0]).val;
s.text_options = ((paramStringArray) types[1]).val;
s.default_value = ((paramNumber) types[2]).val;
}
public static void setTextParams(textType s, parameterType[] types){
s.description = ((paramString) types[0]).val;
s.default_value = ((paramString) types[1]).val;
}
public static void setTallyParams(tallyType s, parameterType[] types){
s.description = ((paramString) types[0]).val;
s.default_value = ((paramNumber) types[1]).val;
}
public static void setNumberParams(numberType s, parameterType[] types){
s.description = ((paramString) types[0]).val;
s.default_value = ((paramNumber) types[1]).val;
}
public static void setCheckboxParam(checkboxType s, parameterType[] types){
s.description = ((paramString) types[0]).val;
s.default_value = ((paramNumber) types[1]).val;
}
public static void setFieldPosParam(fieldposType s, parameterType[] types){
s.description = ((paramString) types[0]).val;
s.default_value = new int[]{
((paramNumber) types[1]).val,
((paramNumber) types[2]).val
};
}
private static void setInputParameter(inputType t, parameterType[] types){
switch (t.getInputType()){
case TALLY:
setTallyParams((tallyType) t, types);
break;
case SLIDER:
setSliderParams((sliderType) t, types);
break;
case DROPDOWN:
setDropdownParams((dropdownType) t, types);
break;
case NOTES_INPUT:
setTextParams((textType) t, types);
break;
case NUMBER:
setNumberParams((numberType) t, types);
break;
case CHECKBOX:
setCheckboxParam((checkboxType) t, types);
break;
case FIELDPOS:
setFieldPosParam((fieldposType) t, types);
break;
}
}
private static parameterType[] getParamsFromInputType(inputType t){
switch (t.getInputType()){
case TALLY:
return getTallyParams((tallyType) t);
case SLIDER:
return getSliderParams((sliderType) t);
case DROPDOWN:
return getDropdownParams((dropdownType) t);
case NOTES_INPUT:
return getTextParams((textType) t);
case NUMBER:
return getNumberParams((numberType) t);
case CHECKBOX:
return getCheckboxParam((checkboxType) t);
case FIELDPOS:
return getFieldPosParam((fieldposType) t);
}
return new parameterType[]{};
}
private static View createNumberEdit(Context c, int value){
EditText text = new EditText(c);
text.setInputType(TYPE_CLASS_NUMBER);
text.setText(String.valueOf(value));
return text;
}
private static View createStringEdit(Context c, String value){
EditText text = new EditText(c);
text.setText(value);
return text;
}
private static View createStringArrayEdit(Context c, String[] value){
EditText text = new EditText(c);
text.setText(String.join("\n", value));
return text;
}
private static View createEdit(Context c, parameterType t){
switch (t.id){
case paramNumber:
return createNumberEdit(c, ((paramNumber) t).val);
case paramString:
return createStringEdit(c, ((paramString) t).val);
case paramStringArray:
return createStringArrayEdit(c, ((paramStringArray) t).val);
}
return null;
}
private static boolean readEdit(View v, parameterType t){
try{
String val;
switch (t.id) {
case paramNumber:
val = ((EditText) v).getText().toString();
if(val.isEmpty() || val.isBlank()) return false;
((paramNumber) t).val = Integer.parseInt(val);
break;
case paramString:
val = ((EditText) v).getText().toString();
//if(val.isEmpty() || val.isBlank()) return false;
((paramString) t).val = val;
break;
case paramStringArray:
val = ((EditText) v).getText().toString();
if(val.isEmpty() || val.isBlank()) return false;
((paramStringArray) t).val = val.split("\n");
break;
}
} catch (Exception e) {
AlertManager.error(e);
return false;
}
return true;
}
private parameterType[] types;
private View[] views;
private inputType t;
public FieldEditorHelper(Context c, inputType t, TableLayout parentView, parameterType[] tmptypes){
this.types = tmptypes;
this.t = t;
views = new View[types.length];
for(int i = 0; i < types.length; i++){
TextView tv = new TextView(c);
tv.setText(types[i].name);
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setTextSize(20);
parentView.addView(tv);
views[i] = createEdit(c, types[i]);
parentView.addView(views[i]);
}
}
public FieldEditorHelper(Context c, inputType t, TableLayout parentView){
this(c,t,parentView,getParamsFromInputType(t));
}
public boolean save(){
for(int i = 0; i < types.length; i++){
if(!readEdit(views[i], types[i]))
return false;
}
setInputParameter(t, types);
return true;
}
}
@@ -1,563 +0,0 @@
package com.ridgebotics.ridgescout.ui.data;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import com.ridgebotics.ridgescout.MainActivity;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.databinding.FragmentDataFieldsBinding;
import com.ridgebotics.ridgescout.scoutingData.fields;
import com.ridgebotics.ridgescout.types.input.checkboxType;
import com.ridgebotics.ridgescout.types.input.dropdownType;
import com.ridgebotics.ridgescout.types.input.fieldposType;
import com.ridgebotics.ridgescout.types.input.inputType;
import com.ridgebotics.ridgescout.types.input.numberType;
import com.ridgebotics.ridgescout.types.input.sliderType;
import com.ridgebotics.ridgescout.types.input.tallyType;
import com.ridgebotics.ridgescout.types.input.textType;
import com.ridgebotics.ridgescout.ui.CustomSpinnerView;
import com.ridgebotics.ridgescout.utility.AlertManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FieldsFragment extends Fragment {
FragmentDataFieldsBinding binding;
private static String filename;
public static void set_filename(String tmpfilename){
filename = tmpfilename;
}
@SuppressLint("ClickableViewAccessibility")
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentDataFieldsBinding.inflate(inflater, container, false);
binding.valueEditScrollview.setOnTouchListener((v, event) -> true);
binding.saveButton.setVisibility(View.GONE);
binding.cancelEditButton.setVisibility(View.GONE);
binding.editButton.setVisibility(View.GONE);
binding.upButton.setVisibility(View.GONE);
binding.addButton.setVisibility(View.GONE);
binding.downButton.setVisibility(View.GONE);
binding.deleteButton.setVisibility(View.GONE);
binding.valueEditContainer.setVisibility(View.GONE);
load_field_menu();
((MainActivity) getActivity()).setOnBackPressed(() -> {
if(binding.saveButton.getVisibility() == View.GONE) return true;
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Warning!");
alert.setMessage("You have not saved your progress!");
alert.setPositiveButton("Return", null);
alert.setNeutralButton("Quit without saving", (dialogInterface, i) -> {
binding.saveButton.setVisibility(View.GONE);
if(getActivity() != null)
getActivity().onBackPressed();
});
alert.setCancelable(true);
alert.create().show();
return false;
});
return binding.getRoot();
}
private static final int background_color = 0x5000ff00;
private static final int unfocused_background_color = 0x2000ff00;
inputType[][] values;
private void load_field_menu() {
values = fields.load(filename);
binding.fieldsArea.bringToFront();
binding.fieldsArea.setStretchAllColumns(true);
binding.fieldsArea.removeAllViews();
binding.fieldsArea.setReorderingEnabled(false);
if(values == null) return;
for(int i = 0; i < values.length; i++){
TableRow tr = new TableRow(getContext());
TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT
);
rowParams.setMargins(20,20,20,20);
tr.setLayoutParams(rowParams);
tr.setPadding(20,20,20,20);
TextView tv = new TextView(getContext());
tv.setText("v" + i);
tv.setTextSize(20);
tr.addView(tv);
tv = new TextView(getContext());
tv.setText(values[i].length + " Fields");
tv.setTextSize(16);
tr.addView(tv);
binding.fieldsArea.addView(tr);
if(i == values.length-1) {
tr.setBackgroundColor(background_color);
int fi = i;
tr.setOnClickListener(v -> {
display_fields(values[fi]);
});
}else{
tr.setBackgroundColor(unfocused_background_color);
}
}
if(values.length > 1) {
binding.revertVersionButton.setVisibility(View.VISIBLE);
binding.revertVersionButton.setOnClickListener(v -> {
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Warning!");
alert.setMessage("If there is any data set this version, it will be deleted!");
alert.setPositiveButton("OK", (dialog, which) -> {
inputType[][] newArr = new inputType[values.length - 1][];
System.arraycopy(values, 0, newArr, 0, values.length - 1);
if(fields.save(filename, newArr))
AlertManager.toast("Saved");
load_field_menu();
});
alert.setNegativeButton("Cancel", null);
alert.setCancelable(true);
alert.create().show();
});
}
}
private void display_fields(inputType[] version_values) {
binding.fieldsArea.removeAllViews();
binding.fieldsArea.setReorderingEnabled(false);
binding.revertVersionButton.setVisibility(View.GONE);
binding.saveButton.setVisibility(View.GONE);
binding.editButton.setVisibility(View.GONE);
binding.upButton.setVisibility(View.VISIBLE);
binding.addButton.setVisibility(View.VISIBLE);
binding.downButton.setVisibility(View.VISIBLE);
updateUpDownAvailability();
binding.valueEditContainer.setVisibility(View.GONE);
for(int i = 0; i < version_values.length; i++){
addRow(version_values[i]);
}
selindex = -1;
binding.addButton.setOnClickListener(this::addField);
binding.saveButton.setOnClickListener(this::buttonfunc);
}
// Make sure the user cannot move fields when they shouldn't
private void updateUpDownAvailability(){
binding.upButton.setEnabled(selindex != -1 && selindex != 0);
binding.downButton.setEnabled(selindex != -1 && selindex != values[values.length-1].length-1);
}
private void addRow(inputType field){
TableRow tr = getTableRow(field);
binding.fieldsArea.addView(tr);
tr.setOnClickListener(v -> {
binding.editButton.setVisibility(View.VISIBLE);
trOnClick(values[values.length-1], tr);
updateUpDownAvailability();
});
binding.upButton.setOnClickListener(v -> {
if(selindex != 0) {
binding.saveButton.setVisibility(View.VISIBLE);
binding.fieldsArea.updateRowOrder(selindex, selindex - 1);
selindex -= 1;
}
updateUpDownAvailability();
});
binding.downButton.setOnClickListener(v -> {
if(selindex != values[values.length-1].length-1) {
binding.saveButton.setVisibility(View.VISIBLE);
binding.fieldsArea.updateRowOrder(selindex, selindex + 1);
selindex += 1;
}
updateUpDownAvailability();
});
}
private void buttonfunc(View v){
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Warning!");
alert.setMessage("Changing or removing some values will result in lost data!\nBut this will create a new field version, and you can revert at any time.");
alert.setPositiveButton("OK", (dialog, which) -> {
inputType[][] currentValues = fields.load(filename);
assert currentValues != null;
inputType[][] newValues = new inputType[currentValues.length+1][];
System.arraycopy(currentValues, 0, newValues, 0, currentValues.length);
newValues[newValues.length-1] = new inputType[values[values.length-1].length];
for(int i = 0; i < values[values.length-1].length; i++){
newValues[newValues.length-1][i] = values[values.length-1][binding.fieldsArea.getReorderedIndexes().get(i)];
}
// newValues[newValues.length-1] = values[values.length-1];
if(fields.save(filename, newValues))
AlertManager.toast("Saved");
Navigation.findNavController((Activity) getContext(), R.id.nav_host_fragment_activity_main).navigate(R.id.action_navigation_data_fields_to_navigation_data);
});
alert.setNegativeButton("Cancel", null);
alert.setCancelable(true);
alert.create().show();
}
private int selindex = -1;
private void trOnClick(inputType[] version_values, TableRow tr){
selindex = -1;
for(int i = 0; i < binding.fieldsArea.getChildCount(); i++){
View v = binding.fieldsArea.getChildAt(i);
if(v.equals(tr)) {
tr.setBackgroundColor(background_color);
selindex = i;
} else
binding.fieldsArea.getChildAt(i).setBackgroundColor(unfocused_background_color);
}
onFieldSelect(version_values[binding.fieldsArea.getReorderedIndexes().get(selindex)]);
}
private void onFieldSelect(inputType field){
//System.out.println(field.name);
binding.editButton.setOnClickListener(v -> {
binding.editButton.setVisibility(View.GONE);
binding.addButton.setVisibility(View.GONE);
binding.upButton.setVisibility(View.GONE);
binding.downButton.setVisibility(View.GONE);
binding.ValueEditTable.removeAllViews();
binding.valueEditContainer.setVisibility(View.VISIBLE);
TextView tv = new TextView(getContext());
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setText(field.name);
tv.setPadding(8,8,8,8);
tv.setTextSize(24);
binding.ValueEditTable.addView(tv);
final FieldEditorHelper fe = new FieldEditorHelper(
getContext(),
field,
binding.ValueEditTable
);
binding.saveButton.setVisibility(View.VISIBLE);
binding.saveButton.setOnClickListener(a -> {
System.out.println(fe.save());
defaultVisibility();
});
binding.cancelEditButton.setVisibility(View.VISIBLE);
binding.cancelEditButton.setOnClickListener(a -> {
defaultVisibility();
});
binding.deleteButton.setVisibility(View.VISIBLE);
binding.deleteButton.setOnClickListener(a -> {
deleteField(field);
});
});
}
private void deleteField(inputType field){
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Warning!");
alert.setMessage("Removing a value will result in data being deleted in subsequent field versions!");
alert.setNegativeButton("Cancel", null);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
defaultVisibility();
int oldindex = -1;
for(int i = 0; i < values[values.length - 1].length; i++){
if(values[values.length - 1][i].equals(field)){
oldindex = i;
break;
}
}
if(oldindex != -1) {
System.out.println(Arrays.toString(values[values.length - 1]));
binding.fieldsArea.removeViewAt(selindex);
binding.fieldsArea.removeElement(oldindex);
values[values.length - 1] = removeElement(values[values.length - 1], oldindex);
selindex = -1;
AlertManager.toast("Removed!");
binding.editButton.setVisibility(View.GONE);
System.out.println(Arrays.toString(values[values.length - 1]));
//System.out.println(values[values.length-1].length);
}
}
});
alert.setCancelable(true);
alert.create().show();
}
public inputType[] removeElement(inputType[] src, int i) {
inputType[] newArray = new inputType[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
}
private void defaultVisibility() {
binding.editButton.setVisibility(View.VISIBLE);
binding.addButton.setVisibility(View.VISIBLE);
binding.upButton.setVisibility(View.VISIBLE);
binding.downButton.setVisibility(View.VISIBLE);
binding.ValueEditTable.removeAllViews();
binding.valueEditContainer.setVisibility(View.GONE);
binding.cancelEditButton.setVisibility(View.GONE);
binding.deleteButton.setVisibility(View.GONE);
binding.saveButton.setOnClickListener(this::buttonfunc);
}
private void addField(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
final EditText input = new EditText(getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String title = input.getText().toString();
if(title.isEmpty() || title.isBlank()) {
AlertManager.error("Title cannot be blank!");
return;
}
addField_Part_2(title);
}
});
builder.show();
}
private void addField_Part_2(String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Type");
final CustomSpinnerView dropdown = new CustomSpinnerView(getContext());
List<String> options = new ArrayList<>();
options.add("Slider");
options.add("Text");
options.add("Dropdown");
options.add("Tally");
options.add("Number");
options.add("Checkbox");
options.add("Field Position");
dropdown.setOptions(options, 0);
dropdown.setTitle("Type");
builder.setView(dropdown);
builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
builder.setPositiveButton("OK", (dialog, which) -> addField_Part_3(title, dropdown.getIndex()));
builder.show();
}
private void addField_Part_3(String title, int typeIndex) {
switch (typeIndex){
case 0:
sliderType slider = new sliderType();
slider.name = title;
FieldEditorHelper.setSliderParams(slider, FieldEditorHelper.defaultSliderParams);
addField_Part_4(slider);
break;
case 1:
textType text = new textType();
text.name = title;
FieldEditorHelper.setTextParams(text, FieldEditorHelper.defaultTextParams);
addField_Part_4(text);
break;
case 2:
dropdownType dropdown = new dropdownType();
dropdown.name = title;
FieldEditorHelper.setDropdownParams(dropdown, FieldEditorHelper.defaultDropdownParams);
addField_Part_4(dropdown);
break;
case 3:
tallyType tally = new tallyType();
tally.name = title;
FieldEditorHelper.setTallyParams(tally, FieldEditorHelper.defaultTallyParams);
addField_Part_4(tally);
break;
case 4:
numberType num = new numberType();
num.name = title;
FieldEditorHelper.setNumberParams(num, FieldEditorHelper.defaultNumberParams);
addField_Part_4(num);
break;
case 5:
checkboxType cb = new checkboxType();
cb.name = title;
FieldEditorHelper.setCheckboxParam(cb, FieldEditorHelper.defaultCheckboxParam);
addField_Part_4(cb);
break;
case 6:
fieldposType fp = new fieldposType();
fp.name = title;
FieldEditorHelper.setFieldPosParam(fp, FieldEditorHelper.defaultFieldPosParam);
addField_Part_4(fp);
break;
}
}
private void addField_Part_4(inputType field) {
binding.editButton.setVisibility(View.GONE);
binding.addButton.setVisibility(View.GONE);
binding.upButton.setVisibility(View.GONE);
binding.downButton.setVisibility(View.GONE);
binding.ValueEditTable.removeAllViews();
binding.valueEditContainer.setVisibility(View.VISIBLE);
TextView tv = new TextView(getContext());
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setText(field.name);
tv.setPadding(8,8,8,8);
tv.setTextSize(24);
binding.ValueEditTable.addView(tv);
final FieldEditorHelper fe = new FieldEditorHelper(
getContext(),
field,
binding.ValueEditTable
);
binding.saveButton.setVisibility(View.VISIBLE);
binding.saveButton.setOnClickListener(a -> {
inputType[] newValues = new inputType[values[values.length-1].length+1];
System.arraycopy(values[values.length-1], 0, newValues, 0, values[values.length-1].length);
newValues[newValues.length-1] = field;
values[values.length-1] = newValues;
// AlertManager.alert("Test", String.valueOf(binding.fieldsArea.getReorderedIndexes()));
//TableRow tr = getTableRow(field);
//binding.fieldsArea.addView(tr);
addRow(field);
System.out.println(fe.save());
defaultVisibility();
});
binding.cancelEditButton.setVisibility(View.VISIBLE);
binding.cancelEditButton.setOnClickListener(a -> {
defaultVisibility();
});
}
private @NonNull TableRow getTableRow(inputType field) {
TableRow tr = new TableRow(getContext());
TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT
);
rowParams.setMargins(20,20,20,20);
tr.setLayoutParams(rowParams);
tr.setPadding(20,20,20,20);
tr.setBackgroundColor(unfocused_background_color);
TextView tv = new TextView(getContext());
tv.setText(field.get_type_name());
tv.setTextSize(12);
tr.addView(tv);
tv = new TextView(getContext());
tv.setText(field.name);
tv.setTextSize(20);
tr.addView(tv);
return tr;
}
}
@@ -1,5 +1,7 @@
package com.ridgebotics.ridgescout.ui.data; package com.ridgebotics.ridgescout.ui.data;
import static com.ridgebotics.ridgescout.utility.Colors.toggletitle_black_background;
import static com.ridgebotics.ridgescout.utility.Colors.toggletitle_unselected;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode; import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.match_latest_values; import static com.ridgebotics.ridgescout.utility.DataManager.match_latest_values;
import static com.ridgebotics.ridgescout.utility.DataManager.match_transferValues; import static com.ridgebotics.ridgescout.utility.DataManager.match_transferValues;
@@ -14,28 +16,25 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.ui.CustomSpinnerView;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.SettingsManager;
import com.ridgebotics.ridgescout.databinding.FragmentDataTeamsBinding; import com.ridgebotics.ridgescout.databinding.FragmentDataTeamsBinding;
import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter; import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.frcTeam; import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.google.android.material.divider.MaterialDivider;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
// Fragment for viewing the data of a team.
public class TeamsFragment extends Fragment { public class TeamsFragment extends Fragment {
FragmentDataTeamsBinding binding; FragmentDataTeamsBinding binding;
@@ -60,16 +59,14 @@ public class TeamsFragment extends Fragment {
options.add("Compiled"); options.add("Compiled");
options.add("History"); options.add("History");
binding.dataTypeSpinner.setOptions(options, 0); binding.dataTypeSpinner.setOptions(options, SettingsManager.getTeamsDataMode());
binding.dataTypeSpinner.setOnClickListener((item, index) -> { binding.dataTypeSpinner.setOnClickListener((item, index) -> {
settingsManager.setDataMode(index); SettingsManager.setTeamsDataMode(index);
loadTeam(index); loadTeam(index);
}); });
// binding.teamsMainElem. loadTeam(SettingsManager.getTeamsDataMode());
loadTeam(settingsManager.getDataMode());
return binding.getRoot(); return binding.getRoot();
} }
@@ -84,12 +81,7 @@ public class TeamsFragment extends Fragment {
// ll.setOrientation(LinearLayout.VERTICAL); // ll.setOrientation(LinearLayout.VERTICAL);
// binding.teamsArea.addView(ll); // binding.teamsArea.addView(ll);
binding.dataTeamCard.fromTeam(team);
binding.teamName2.setText(String.valueOf(team.teamNumber));
binding.teamDescription2.setText(team.getDescription());
// tv = new TextView(getContext()); // tv = new TextView(getContext());
// tv.setLayoutParams(new FrameLayout.LayoutParams( // tv.setLayoutParams(new FrameLayout.LayoutParams(
@@ -101,8 +93,8 @@ public class TeamsFragment extends Fragment {
// tv.setTextSize(16); // tv.setTextSize(16);
// ll.addView(tv); // ll.addView(tv);
add_pit_data(team); try {add_pit_data(team);}catch(Exception e){AlertManager.error(e);}
add_match_data(team, mode); try {add_match_data(team, mode);}catch(Exception e){AlertManager.error(e);}
} }
public void add_pit_data(frcTeam team){ public void add_pit_data(frcTeam team){
@@ -124,7 +116,7 @@ public class TeamsFragment extends Fragment {
// ll.addView(new MaterialDivider(getContext())); // ll.addView(new MaterialDivider(getContext()));
if(!fileEditor.fileExist(filename)){ if(!FileEditor.fileExist(filename)){
TextView tv = new TextView(getContext()); TextView tv = new TextView(getContext());
tv.setLayoutParams(new FrameLayout.LayoutParams( tv.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
@@ -157,12 +149,12 @@ public class TeamsFragment extends Fragment {
ViewGroup.LayoutParams.WRAP_CONTENT ViewGroup.LayoutParams.WRAP_CONTENT
)); ));
tv.setGravity(Gravity.CENTER_HORIZONTAL); tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(psda.data.array[a].getName()); tv.setText(pit_latest_values[a].name);
tv.setTextSize(25); tv.setTextSize(25);
if(psda.data.array[a].isNull()){ if(psda.data.array[a].isNull()){
tv.setBackgroundColor(0xffff0000); tv.setBackgroundColor(toggletitle_unselected);
tv.setTextColor(0xff000000); tv.setTextColor(toggletitle_black_background);
} }
@@ -180,7 +172,7 @@ public class TeamsFragment extends Fragment {
public void add_match_data(frcTeam team, int mode){ public void add_match_data(frcTeam team, int mode){
binding.matchArea.removeAllViews(); binding.matchArea.removeAllViews();
binding.individualViewSelector.setVisibility(View.GONE); binding.individualViewSelector.setVisibility(View.GONE);
String[] files = fileEditor.getMatchesByTeamNum(evcode, team.teamNumber); String[] files = FileEditor.getMatchesByTeamNum(evcode, team.teamNumber);
if(files.length == 0){ if(files.length == 0){
TextView tv = new TextView(getContext()); TextView tv = new TextView(getContext());
@@ -262,22 +254,22 @@ public class TeamsFragment extends Fragment {
ViewGroup.LayoutParams.WRAP_CONTENT ViewGroup.LayoutParams.WRAP_CONTENT
)); ));
tv.setGravity(Gravity.CENTER_HORIZONTAL); tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(psda.data.array[i].getName()); tv.setText(match_latest_values[i].name);
tv.setTextSize(25); tv.setTextSize(25);
if (psda.data.array[i].isNull()) { if (psda.data.array[i].isNull()) {
tv.setBackgroundColor(0xffff0000); tv.setBackgroundColor(toggletitle_unselected);
tv.setTextColor(0xff000000); tv.setTextColor(toggletitle_black_background);
} }
binding.matchArea.addView(tv); binding.matchArea.addView(tv);
if(psda.data.array[i] != null)
match_latest_values[i].add_individual_view(binding.matchArea, psda.data.array[i]); match_latest_values[i].add_individual_view(binding.matchArea, psda.data.array[i]);
} }
}catch (Exception e){ }catch (Exception e){
e.printStackTrace(); AlertManager.error("Failure to load file " + files[matchIndex], e);
AlertManager.alert("Warning!", "Failure to load file " + files[matchIndex]);
} }
} }
@@ -288,16 +280,16 @@ public class TeamsFragment extends Fragment {
public void add_compiled_views(String[] files){ public void add_compiled_views(String[] files){
dataType[][] data = new dataType[match_latest_values.length][files.length]; RawDataType[][] data = new RawDataType[match_latest_values.length][files.length];
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
try { try {
ScoutingDataWriter.ParsedScoutingDataResult psda = ScoutingDataWriter.load(files[i], match_values, match_transferValues); ScoutingDataWriter.ParsedScoutingDataResult psda = ScoutingDataWriter.load(files[i], match_values, match_transferValues);
for (int a = 0; a < data.length; a++) { for (int a = 0; a < data.length; a++) {
if(psda.data.array[a] != null && psda.data.array[a].get() != null)
data[a][i] = psda.data.array[a]; data[a][i] = psda.data.array[a];
} }
} catch (Exception e){ } catch (Exception e){
e.printStackTrace(); AlertManager.error("Failure to load file " + files[i], e);
AlertManager.alert("Warning!", "Failure to load file " + files[i]);
} }
} }
@@ -313,6 +305,7 @@ public class TeamsFragment extends Fragment {
tv.setTextSize(30); tv.setTextSize(30);
binding.matchArea.addView(tv); binding.matchArea.addView(tv);
if(data[i] != null)
match_latest_values[i].add_compiled_view(binding.matchArea, data[i]); match_latest_values[i].add_compiled_view(binding.matchArea, data[i]);
} }
} }
@@ -322,16 +315,16 @@ public class TeamsFragment extends Fragment {
public void add_history_views(String[] files){ public void add_history_views(String[] files){
dataType[][] data = new dataType[match_latest_values.length][files.length]; RawDataType[][] data = new RawDataType[match_latest_values.length][files.length];
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
try { try {
ScoutingDataWriter.ParsedScoutingDataResult psda = ScoutingDataWriter.load(files[i], match_values, match_transferValues); ScoutingDataWriter.ParsedScoutingDataResult psda = ScoutingDataWriter.load(files[i], match_values, match_transferValues);
for (int a = 0; a < data.length; a++) { for (int a = 0; a < data.length; a++) {
if(psda.data.array[a] != null && psda.data.array[a].get() != null)
data[a][i] = psda.data.array[a]; data[a][i] = psda.data.array[a];
} }
}catch (Exception e){ }catch (Exception e){
e.printStackTrace(); AlertManager.error("Failure to load file " + files[i], e);
AlertManager.alert("Warning!", "Failure to load file " + files[i]);
} }
} }
@@ -347,6 +340,7 @@ public class TeamsFragment extends Fragment {
tv.setTextSize(30); tv.setTextSize(30);
binding.matchArea.addView(tv); binding.matchArea.addView(tv);
if(data[i] != null)
match_latest_values[i].add_history_view(binding.matchArea, data[i]); match_latest_values[i].add_history_view(binding.matchArea, data[i]);
} }
} }
@@ -1,18 +1,17 @@
package com.ridgebotics.ridgescout.ui.scouting; package com.ridgebotics.ridgescout.ui.scouting;
import static android.widget.LinearLayout.HORIZONTAL; import static com.ridgebotics.ridgescout.utility.Colors.color_found;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode; import static com.ridgebotics.ridgescout.utility.Colors.color_not_found;
import static com.ridgebotics.ridgescout.utility.Colors.color_rescout;
import static com.ridgebotics.ridgescout.utility.DataManager.event; import static com.ridgebotics.ridgescout.utility.DataManager.event;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.text.InputType; import android.text.InputType;
import android.view.Gravity; import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.ScrollView; import android.widget.ScrollView;
@@ -21,22 +20,22 @@ import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentScoutingEventBinding; import com.ridgebotics.ridgescout.databinding.FragmentScoutingEventBinding;
import com.ridgebotics.ridgescout.types.frcTeam; import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.ui.CustomSpinnerView; import com.ridgebotics.ridgescout.ui.views.CustomSpinnerView;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.types.frcEvent; import com.ridgebotics.ridgescout.types.frcEvent;
import com.ridgebotics.ridgescout.types.frcMatch; import com.ridgebotics.ridgescout.types.frcMatch;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.SettingsManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
// Fragment to show the status of scouting, aswell as adding or removing matches and teams manually.
public class EventFragment extends Fragment { public class EventFragment extends Fragment {
FragmentScoutingEventBinding binding; FragmentScoutingEventBinding binding;
@@ -59,10 +58,6 @@ public class EventFragment extends Fragment {
add_pit_scouting(event); add_pit_scouting(event);
add_match_scouting(event); add_match_scouting(event);
} }
public static int color_found = 0x7f00ff00;
public static int color_not_found = 0x7f7f0000;
private void addTableText(TableRow tr, String textStr){ private void addTableText(TableRow tr, String textStr){
TextView text = new TextView(getContext()); TextView text = new TextView(getContext());
text.setTextSize(18); text.setTextSize(18);
@@ -73,7 +68,7 @@ public class EventFragment extends Fragment {
public void add_pit_scouting(frcEvent event){ public void add_pit_scouting(frcEvent event){
if(settingsManager.getCustomEvents()){ if(SettingsManager.getCustomEvents()){
binding.teamsMinusBtn.setVisibility(View.VISIBLE); binding.teamsMinusBtn.setVisibility(View.VISIBLE);
binding.teamsMinusBtn.setOnClickListener(view -> removeTeam()); binding.teamsMinusBtn.setOnClickListener(view -> removeTeam());
binding.teamsPlusBtn.setVisibility(View.VISIBLE); binding.teamsPlusBtn.setVisibility(View.VISIBLE);
@@ -104,8 +99,24 @@ public class EventFragment extends Fragment {
text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
text.setText(String.valueOf(num)); text.setText(String.valueOf(num));
if(fileEditor.fileExist(event.eventCode + "-" + num + ".pitscoutdata")){ final String filename = event.eventCode + "-" + num + ".pitscoutdata";
if(FileEditor.fileExist(filename)){
final boolean[] rescout = {DataManager.rescout_list.contains(filename)};
text.setBackgroundColor(rescout[0] ? color_rescout : color_found);
text.setOnLongClickListener(view -> {
rescout[0] = !rescout[0];
if(rescout[0]) {
text.setBackgroundColor(color_rescout);
DataManager.rescout_list.add(filename);
}else{
text.setBackgroundColor(color_found); text.setBackgroundColor(color_found);
DataManager.rescout_list.remove(filename);
}
DataManager.save_rescout_list();
return true;
});
}else{ }else{
text.setBackgroundColor(color_not_found); text.setBackgroundColor(color_not_found);
} }
@@ -119,7 +130,7 @@ public class EventFragment extends Fragment {
public void add_match_scouting(frcEvent event){ public void add_match_scouting(frcEvent event){
if(settingsManager.getCustomEvents()){ if(SettingsManager.getCustomEvents()){
binding.matchesMinusBtn.setVisibility(View.VISIBLE); binding.matchesMinusBtn.setVisibility(View.VISIBLE);
binding.matchesMinusBtn.setOnClickListener(view -> removeMatch()); binding.matchesMinusBtn.setOnClickListener(view -> removeMatch());
binding.matchesPlusBtn.setVisibility(View.VISIBLE); binding.matchesPlusBtn.setVisibility(View.VISIBLE);
@@ -158,8 +169,25 @@ public class EventFragment extends Fragment {
} }
text.setText(String.valueOf(team_num)); text.setText(String.valueOf(team_num));
if(fileEditor.fileExist(event.eventCode + "-" + match.matchIndex + "-" + alliance_position + "-" + team_num + ".matchscoutdata")){ final String filename = event.eventCode + "-" + match.matchIndex + "-" + alliance_position + "-" + team_num + ".matchscoutdata";
if(FileEditor.fileExist(filename)){
final boolean[] rescout = {DataManager.rescout_list.contains(filename)};
text.setBackgroundColor(rescout[0] ? color_rescout : color_found);
text.setOnLongClickListener(view -> {
rescout[0] = !rescout[0];
if(rescout[0]) {
text.setBackgroundColor(color_rescout);
DataManager.rescout_list.add(filename);
}else{
text.setBackgroundColor(color_found); text.setBackgroundColor(color_found);
DataManager.rescout_list.remove(filename);
}
DataManager.save_rescout_list();
return true;
});
}else{ }else{
text.setBackgroundColor(color_not_found); text.setBackgroundColor(color_not_found);
} }
@@ -222,7 +250,7 @@ public class EventFragment extends Fragment {
team.startingYear = safeToInt(startingYear.getText().toString()); team.startingYear = safeToInt(startingYear.getText().toString());
event.teams.add(team); event.teams.add(team);
fileEditor.setEvent(event); FileEditor.setEvent(event);
reloadTable(); reloadTable();
}); });
@@ -249,11 +277,11 @@ public class EventFragment extends Fragment {
builder.setPositiveButton("OK", (dialogInterface, i) -> { builder.setPositiveButton("OK", (dialogInterface, i) -> {
int index = dropdown.getIndex(); int index = dropdown.getIndex();
System.out.println(index); Log.i(getClass().toString(), String.valueOf(index));
if(!(index >= 0 && index < teamNums.size())) return; if(!(index >= 0 && index < teamNums.size())) return;
event.teams.remove(index); event.teams.remove(index);
fileEditor.setEvent(event); FileEditor.setEvent(event);
reloadTable(); reloadTable();
}); });
@@ -334,7 +362,7 @@ public class EventFragment extends Fragment {
}; };
event.matches.add(match); event.matches.add(match);
fileEditor.setEvent(event); FileEditor.setEvent(event);
reloadTable(); reloadTable();
}); });
@@ -364,7 +392,7 @@ public class EventFragment extends Fragment {
builder.setPositiveButton("OK", (dialogInterface, i) -> { builder.setPositiveButton("OK", (dialogInterface, i) -> {
if(dropdown.getIndex() == -1) return; if(dropdown.getIndex() == -1) return;
event.matches.remove(dropdown.getIndex()); event.matches.remove(dropdown.getIndex());
fileEditor.setEvent(event); FileEditor.setEvent(event);
reloadTable(); reloadTable();
}); });
@@ -1,10 +1,15 @@
package com.ridgebotics.ridgescout.ui.scouting; package com.ridgebotics.ridgescout.ui.scouting;
import static com.ridgebotics.ridgescout.utility.AutoSaveManager.AUTO_SAVE_DELAY;
import static com.ridgebotics.ridgescout.utility.Colors.rescout_color;
import static com.ridgebotics.ridgescout.utility.Colors.saved_color;
import static com.ridgebotics.ridgescout.utility.Colors.unsaved_color;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode; import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.event; import static com.ridgebotics.ridgescout.utility.DataManager.event;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@@ -15,22 +20,20 @@ import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.google.android.material.divider.MaterialDivider; import com.google.android.material.divider.MaterialDivider;
import com.ridgebotics.ridgescout.ui.ToggleTitleView; import com.ridgebotics.ridgescout.ui.views.ToggleTitleView;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.SettingsManager;
import com.ridgebotics.ridgescout.databinding.FragmentScoutingMatchBinding; import com.ridgebotics.ridgescout.databinding.FragmentScoutingMatchBinding;
import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter; import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.frcMatch; import com.ridgebotics.ridgescout.types.frcMatch;
import com.ridgebotics.ridgescout.types.frcTeam; import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.types.input.inputType; import com.ridgebotics.ridgescout.types.input.FieldType;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.AutoSaveManager; import com.ridgebotics.ridgescout.utility.AutoSaveManager;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import java.util.ArrayList;
import java.util.function.Function;
// Fragment for match scouting data editing.
public class MatchScoutingFragment extends Fragment { public class MatchScoutingFragment extends Fragment {
private FragmentScoutingMatchBinding binding; private FragmentScoutingMatchBinding binding;
@@ -43,17 +46,16 @@ public class MatchScoutingFragment extends Fragment {
DataManager.reload_match_fields(); DataManager.reload_match_fields();
alliance_position = settingsManager.getAllyPos(); alliance_position = SettingsManager.getAllyPos();
username = settingsManager.getUsername(); username = SettingsManager.getUsername();
binding.username.setText(username); binding.bindicator.setUsername(username);
binding.alliancePosText.setText(alliance_position); binding.bindicator.setAlliancePos(alliance_position);
binding.bindicator.bringToFront();
binding.teamDescription.setVisibility(View.GONE); binding.matchTeamCard.setVisibility(View.GONE);
binding.teamName.setVisibility(View.GONE);
clear_fields(); clear_fields();
binding.teamDescription.setVisibility(View.VISIBLE); binding.matchTeamCard.setVisibility(View.VISIBLE);
binding.teamName.setVisibility(View.VISIBLE);
if(DataManager.match_values == null || DataManager.match_values.length == 0){ if(DataManager.match_values == null || DataManager.match_values.length == 0){
TextView tv = new TextView(getContext()); TextView tv = new TextView(getContext());
@@ -65,33 +67,32 @@ public class MatchScoutingFragment extends Fragment {
binding.nextButton.setOnClickListener(v -> { binding.bindicator.match_indicator_next_button.setOnClickListener(v -> {
if(edited) save(); if(edited) save();
settingsManager.setMatchNum(cur_match_num+1); SettingsManager.setMatchNum(cur_match_num+1);
cur_match_num += 1; cur_match_num += 1;
update_match_num(); update_match_num();
update_scouting_data(); update_scouting_data();
}); });
if(SettingsManager.getEnableQuickAlliancePosChange())
boolean fileIndicatorTapped = false; binding.bindicator.setOnClickListener(v -> {
binding.fileIndicator.setOnClickListener(v -> { // if(e.getAction() != MotionEvent.ACTION_MOVE) return true;
// if(e.getAction() != MotionEvent.ACTION_MOVE) return true; // System.out.println(e.getAxisValue(0));
// System.out.println(e.getAxisValue(0));
if(edited) save(); if(edited) save();
alliance_position = incrementMatchPos(alliance_position); alliance_position = incrementMatchPos(alliance_position);
settingsManager.setAllyPos(alliance_position); SettingsManager.setAllyPos(alliance_position);
binding.alliancePosText.setText(alliance_position); binding.bindicator.setAlliancePos(alliance_position);
update_match_num(); update_match_num();
update_scouting_data(); update_scouting_data();
// return true; // return true;
}); });
binding.backButton.setOnClickListener(v -> { binding.bindicator.match_indicator_back_button.setOnClickListener(v -> {
if(edited) save(); if(edited) save();
settingsManager.setMatchNum(cur_match_num-1); SettingsManager.setMatchNum(cur_match_num-1);
cur_match_num -= 1; cur_match_num -= 1;
update_match_num(); update_match_num();
update_scouting_data(); update_scouting_data();
@@ -101,17 +102,22 @@ public class MatchScoutingFragment extends Fragment {
// if(edited) save(); // if(edited) save();
// }); // });
cur_match_num = settingsManager.getMatchNum(); cur_match_num = SettingsManager.getMatchNum();
if(cur_match_num >= event.matches.size()) { if(cur_match_num >= event.matches.size()) {
cur_match_num = 0; cur_match_num = 0;
settingsManager.setMatchNum(0); SettingsManager.setMatchNum(0);
} }
update_match_num(); update_match_num();
create_fields(); create_fields();
update_scouting_data(); update_scouting_data();
if(DataManager.scoutNotice.isEmpty())
binding.scoutingNoticeBox.setVisibility(View.GONE);
else
binding.scoutingNoticeText.setText(DataManager.scoutNotice);
return binding.getRoot(); return binding.getRoot();
} }
@@ -133,35 +139,35 @@ public class MatchScoutingFragment extends Fragment {
return "red-1"; return "red-1";
} }
private static final int unsaved_color = 0x60ff0000;
private static final int saved_color = 0x6000ff00;
String alliance_position; String alliance_position;
int cur_match_num; int cur_match_num;
String username; String username;
String fileUsernames = "";
String filename; String filename;
boolean edited = false; boolean edited = false;
boolean rescout = false;
ToggleTitleView[] titles; ToggleTitleView[] titles;
AutoSaveManager asm = new AutoSaveManager(this::save); AutoSaveManager asm = new AutoSaveManager(this::save, AUTO_SAVE_DELAY);
public void save(){ public void save(){
System.out.println("Saved!"); Log.i(this.getClass().toString(), "Saved!");
edited = false; edited = false;
set_indicator_color(saved_color); enableRescoutButton();
AlertManager.toast("Saved " + filename); AlertManager.toast("Saved " + filename);
save_fields(); save_fields();
} }
public void set_indicator_color(int color){ public void set_indicator_color(int color){
binding.fileIndicator.setBackgroundColor(color); binding.bindicator.setColor(color);
} }
public void update_asm(){ public void update_asm(){
// v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN); // v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
edited = true; edited = true;
set_indicator_color(unsaved_color); set_indicator_color(unsaved_color);
disableRescoutButton();
asm.update(); asm.update();
} }
@@ -234,18 +240,18 @@ public class MatchScoutingFragment extends Fragment {
edited = false; edited = false;
binding.matchnum.setText(String.valueOf(cur_match_num+1)); binding.bindicator.setMatchNum(String.valueOf(cur_match_num+1));
if(cur_match_num <= 0){ if(cur_match_num <= 0){
binding.backButton.setVisibility(View.GONE); binding.bindicator.match_indicator_back_button.setVisibility(View.GONE);
}else{ }else{
binding.backButton.setVisibility(View.VISIBLE); binding.bindicator.match_indicator_back_button.setVisibility(View.VISIBLE);
} }
if(cur_match_num >= event.matches.size()-1){ if(cur_match_num >= event.matches.size()-1){
binding.nextButton.setVisibility(View.GONE); binding.bindicator.match_indicator_next_button.setVisibility(View.GONE);
}else{ }else{
binding.nextButton.setVisibility(View.VISIBLE); binding.bindicator.match_indicator_next_button.setVisibility(View.VISIBLE);
} }
} }
@@ -267,7 +273,7 @@ public class MatchScoutingFragment extends Fragment {
break; break;
} }
binding.barTeamNum.setText(String.valueOf(team_num)); binding.bindicator.setTeamNum(String.valueOf(team_num));
frcTeam team = null; frcTeam team = null;
for(int i=0; i < event.teams.size(); i++){ for(int i=0; i < event.teams.size(); i++){
@@ -280,6 +286,8 @@ public class MatchScoutingFragment extends Fragment {
filename = evcode + "-" + (cur_match_num+1) + "-" + alliance_position + "-" + team_num + ".matchscoutdata"; filename = evcode + "-" + (cur_match_num+1) + "-" + alliance_position + "-" + team_num + ".matchscoutdata";
rescout = DataManager.rescout_list.contains(filename);
return team; return team;
} }
@@ -292,16 +300,15 @@ public class MatchScoutingFragment extends Fragment {
frcTeam team = get_team(match); frcTeam team = get_team(match);
if(team == null) { if(team == null) {
AlertManager.error("This team does not exist!"); AlertManager.addSimpleError("This team does not exist!");
binding.teamName.setText("ERROR!"); binding.matchTeamCard.setTeamName("Error!");
binding.teamDescription.setText("ERROR!"); binding.matchTeamCard.setTeamDescription("Error!");
return; return;
} }
binding.teamName.setText(team.teamName); binding.matchTeamCard.fromTeam(team);
binding.teamDescription.setText(team.getDescription());
boolean new_file = !fileEditor.fileExist(filename); boolean new_file = !FileEditor.fileExist(filename);
if(asm.isRunning){ if(asm.isRunning){
asm.stop(); asm.stop();
@@ -310,14 +317,16 @@ public class MatchScoutingFragment extends Fragment {
if(new_file){ if(new_file){
default_fields(); default_fields();
set_indicator_color(unsaved_color); set_indicator_color(unsaved_color);
disableRescoutButton();
}else{ }else{
try { try {
get_fields(); get_fields();
set_indicator_color(saved_color); enableRescoutButton();
} catch (Exception e){ } catch (Exception e){
AlertManager.error(e); AlertManager.error(e);
default_fields(); default_fields();
set_indicator_color(unsaved_color); set_indicator_color(unsaved_color);
disableRescoutButton();
} }
} }
@@ -329,7 +338,7 @@ public class MatchScoutingFragment extends Fragment {
public void default_fields(){ public void default_fields(){
for(int i = 0; i < DataManager.match_latest_values.length; i++){ for(int i = 0; i < DataManager.match_latest_values.length; i++){
inputType input = DataManager.match_latest_values[i]; FieldType input = DataManager.match_latest_values[i];
input.setViewValue(input.default_value); input.setViewValue(input.default_value);
titles[i].enable(); titles[i].enable();
@@ -341,7 +350,8 @@ public class MatchScoutingFragment extends Fragment {
public void get_fields(){ public void get_fields(){
ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, DataManager.match_values, DataManager.match_transferValues); ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, DataManager.match_values, DataManager.match_transferValues);
dataType[] types = psdr.data.array; RawDataType[] types = psdr.data.array;
fileUsernames = psdr.username;
for(int i = 0; i < DataManager.match_latest_values.length; i++){ for(int i = 0; i < DataManager.match_latest_values.length; i++){
@@ -362,15 +372,37 @@ public class MatchScoutingFragment extends Fragment {
public void save_fields(){ public void save_fields(){
dataType[] types = new dataType[DataManager.match_latest_values.length]; RawDataType[] types = new RawDataType[DataManager.match_latest_values.length];
for(int i = 0; i < DataManager.match_latest_values.length; i++){ for(int i = 0; i < DataManager.match_latest_values.length; i++){
types[i] = DataManager.match_latest_values[i].getViewValue(); types[i] = DataManager.match_latest_values[i].getViewValue();
} }
if(ScoutingDataWriter.save(DataManager.match_values.length-1, username, filename, types)) if(ScoutingDataWriter.save(DataManager.match_values.length-1, ScoutingDataWriter.checkAddName(fileUsernames, username), filename, types))
System.out.println("Saved!"); Log.i(getClass().toString(), "Saved!");
else else
System.out.println("Error saving"); Log.i(getClass().toString(), "Error saving");
}
private void enableRescoutButton(){
set_indicator_color(rescout ? rescout_color : saved_color);
binding.bindicator.setOnLongClickListener(v -> {
rescout = !rescout;
if(rescout){
set_indicator_color(rescout_color);
DataManager.rescout_list.add(filename);
DataManager.save_rescout_list();
}else{
set_indicator_color(saved_color);
DataManager.rescout_list.remove(filename);
DataManager.save_rescout_list();
}
return true;
});
}
private void disableRescoutButton(){
binding.bindicator.setOnLongClickListener(null);
} }
} }
@@ -1,36 +1,41 @@
package com.ridgebotics.ridgescout.ui.scouting; package com.ridgebotics.ridgescout.ui.scouting;
import static com.ridgebotics.ridgescout.utility.AutoSaveManager.AUTO_SAVE_DELAY;
import static com.ridgebotics.ridgescout.utility.Colors.rescout_color;
import static com.ridgebotics.ridgescout.utility.Colors.saved_color;
import static com.ridgebotics.ridgescout.utility.Colors.unsaved_color;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode; import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.pit_latest_values; import static com.ridgebotics.ridgescout.utility.DataManager.pit_latest_values;
import static com.ridgebotics.ridgescout.utility.DataManager.pit_transferValues; import static com.ridgebotics.ridgescout.utility.DataManager.pit_transferValues;
import static com.ridgebotics.ridgescout.utility.DataManager.pit_values; import static com.ridgebotics.ridgescout.utility.DataManager.pit_values;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.google.android.material.divider.MaterialDivider; import com.google.android.material.divider.MaterialDivider;
import com.ridgebotics.ridgescout.ui.ToggleTitleView; import com.ridgebotics.ridgescout.ui.views.ToggleTitleView;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.SettingsManager;
import com.ridgebotics.ridgescout.databinding.FragmentScoutingPitBinding; import com.ridgebotics.ridgescout.databinding.FragmentScoutingPitBinding;
import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter; import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.frcTeam; import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.types.input.inputType; import com.ridgebotics.ridgescout.types.input.FieldType;
import com.ridgebotics.ridgescout.utility.AutoSaveManager; import com.ridgebotics.ridgescout.utility.AutoSaveManager;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.function.Function; import java.util.function.Function;
// Fragment for pit scouting data editing
public class PitScoutingFragment extends Fragment { public class PitScoutingFragment extends Fragment {
FragmentScoutingPitBinding binding; FragmentScoutingPitBinding binding;
@@ -46,42 +51,51 @@ public class PitScoutingFragment extends Fragment {
binding = FragmentScoutingPitBinding.inflate(inflater, container, false); binding = FragmentScoutingPitBinding.inflate(inflater, container, false);
username = settingsManager.getUsername(); username = SettingsManager.getUsername();
DataManager.reload_pit_fields(); DataManager.reload_pit_fields();
if(pit_latest_values == null) {
AlertManager.addSimpleError("Error loading pit fields!");
return binding.getRoot();
}
if(DataManager.scoutNotice.isEmpty())
binding.scoutingNoticeBox.setVisibility(View.GONE);
else
binding.scoutingNoticeText.setText(DataManager.scoutNotice);
loadTeam(); loadTeam();
return binding.getRoot(); return binding.getRoot();
} }
private static final int unsaved_color = 0x60ff0000;
private static final int saved_color = 0x6000ff00;
boolean edited = false; boolean edited = false;
boolean rescout = false;
String filename; String filename;
String username; String username;
String fileUsernames = "";
ToggleTitleView[] titles; ToggleTitleView[] titles;
AutoSaveManager asm = new AutoSaveManager(this::save); AutoSaveManager asm = new AutoSaveManager(this::save, AUTO_SAVE_DELAY);
ArrayList<dataType> dataTypes; ArrayList<RawDataType> rawDataTypes;
public void save(){ public void save(){
edited = false; edited = false;
set_indicator_color(saved_color); enableRescoutButton();
dataType[] types = new dataType[pit_latest_values.length]; RawDataType[] types = new RawDataType[pit_latest_values.length];
for(int i = 0; i < pit_latest_values.length; i++){ for(int i = 0; i < pit_latest_values.length; i++){
types[i] = pit_latest_values[i].getViewValue(); types[i] = pit_latest_values[i].getViewValue();
} }
if(ScoutingDataWriter.save(pit_values.length-1, username, filename, types)) { if(ScoutingDataWriter.save(pit_values.length-1, ScoutingDataWriter.checkAddName(fileUsernames, username), filename, types)) {
System.out.println("Saved!"); Log.i(getClass().toString(), "Saved!");
AlertManager.toast("Saved " + filename); Log.i(getClass().toString(), "Saved " + filename);
}else }else
System.out.println("Error saving"); Log.i(getClass().toString(), "Error saving");
} }
public void set_indicator_color(int color){ public void set_indicator_color(int color){
@@ -92,6 +106,7 @@ public class PitScoutingFragment extends Fragment {
// v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN); // v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
edited = true; edited = true;
set_indicator_color(unsaved_color); set_indicator_color(unsaved_color);
disableRescoutButton();
asm.update(); asm.update();
} }
@@ -100,16 +115,13 @@ public class PitScoutingFragment extends Fragment {
// clear_fields(); // clear_fields();
binding.pitFileIndicator.setVisibility(View.VISIBLE); binding.pitFileIndicator.setVisibility(View.VISIBLE);
binding.pitTeamName.setVisibility(View.VISIBLE); binding.pitsTeamCard.setVisibility(View.VISIBLE);
binding.pitTeamDescription.setVisibility(View.VISIBLE);
binding.pitTeamName.setText(team.teamName);
binding.pitTeamDescription.setText(team.getDescription());
binding.pitBarTeamNum.setText(String.valueOf(team.teamNumber)); binding.pitBarTeamNum.setText(String.valueOf(team.teamNumber));
binding.pitUsername.setText(SettingsManager.getUsername());
binding.pitsTeamCard.fromTeam(team);
filename = evcode + "-" + team.teamNumber + ".pitscoutdata"; filename = evcode + "-" + team.teamNumber + ".pitscoutdata";
rescout = DataManager.rescout_list.contains(filename);
boolean new_file = !fileEditor.fileExist(filename);
if(asm.isRunning){ if(asm.isRunning){
asm.stop(); asm.stop();
@@ -117,13 +129,16 @@ public class PitScoutingFragment extends Fragment {
create_fields(); create_fields();
if(new_file){ if(!FileEditor.fileExist(filename)){
default_fields(); default_fields();
set_indicator_color(unsaved_color); set_indicator_color(unsaved_color);
disableRescoutButton();
}else{ }else{
try { try {
get_fields(); get_fields();
set_indicator_color(saved_color);
enableRescoutButton();
} catch (Exception e){ } catch (Exception e){
AlertManager.error(e); AlertManager.error(e);
default_fields(); default_fields();
@@ -131,10 +146,34 @@ public class PitScoutingFragment extends Fragment {
} }
} }
binding.pitFileIndicator.bringToFront();
asm.start(); asm.start();
} }
private void enableRescoutButton(){
set_indicator_color(rescout ? rescout_color : saved_color);
binding.pitFileIndicator.setOnLongClickListener(v -> {
rescout = !rescout;
if(rescout){
set_indicator_color(rescout_color);
DataManager.rescout_list.add(filename);
DataManager.save_rescout_list();
}else{
set_indicator_color(saved_color);
DataManager.rescout_list.remove(filename);
DataManager.save_rescout_list();
}
return true;
});
}
private void disableRescoutButton(){
binding.pitFileIndicator.setOnLongClickListener(null);
}
private void create_fields() { private void create_fields() {
if(asm.isRunning){ if(asm.isRunning){
@@ -164,9 +203,9 @@ public class PitScoutingFragment extends Fragment {
} }
}); });
View v = pit_latest_values[i].createView(getContext(), new Function<dataType, Integer>() { View v = pit_latest_values[i].createView(getContext(), new Function<RawDataType, Integer>() {
@Override @Override
public Integer apply(dataType dataType) { public Integer apply(RawDataType dataType) {
// edited = true; // edited = true;
if(asm.isRunning) if(asm.isRunning)
update_asm(); update_asm();
@@ -180,7 +219,7 @@ public class PitScoutingFragment extends Fragment {
public void default_fields(){ public void default_fields(){
for(int i = 0; i < pit_latest_values.length; i++){ for(int i = 0; i < pit_latest_values.length; i++){
inputType input = pit_latest_values[i]; FieldType input = pit_latest_values[i];
input.setViewValue(input.default_value); input.setViewValue(input.default_value);
titles[i].enable(); titles[i].enable();
} }
@@ -189,7 +228,9 @@ public class PitScoutingFragment extends Fragment {
public void get_fields(){ public void get_fields(){
ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, pit_values, pit_transferValues); ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, pit_values, pit_transferValues);
dataType[] types = psdr.data.array; RawDataType[] types = psdr.data.array;
fileUsernames = psdr.username;
for(int i = 0; i < pit_latest_values.length; i++){ for(int i = 0; i < pit_latest_values.length; i++){
pit_latest_values[i].setViewValue(types[i]); pit_latest_values[i].setViewValue(types[i]);
@@ -0,0 +1,139 @@
package com.ridgebotics.ridgescout.ui.scouting;
import static com.ridgebotics.ridgescout.utility.Colors.color_found;
import static com.ridgebotics.ridgescout.utility.Colors.color_not_found;
import static com.ridgebotics.ridgescout.utility.Colors.color_rescout;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.event;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentTeamSelectorBinding;
import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.ui.views.TeamListOption;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.FileEditor;
import java.util.Arrays;
// Fragment for choosing which team to pit scout
public class PitSelectorFragment extends Fragment {
private FragmentTeamSelectorBinding binding;
private static onTeamSelected onSelect = new onTeamSelected() {@Override public void onSelect(PitSelectorFragment self, frcTeam team) {}};
public interface onTeamSelected {
void onSelect(PitSelectorFragment self, frcTeam team);
}
public static void setOnSelect(onTeamSelected tmponSelect){
onSelect = tmponSelect;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentTeamSelectorBinding.inflate(inflater, container, false);
// event = fileEditor.g
DataManager.reload_event();
if(evcode == null || evcode.equals("unset")){
AlertManager.addSimpleError("You somehow have not loaded an event!");
return binding.getRoot();
}
load_teams();
return binding.getRoot();
}
public void load_teams(){
// binding.pitFileIndicator.setVisibility(View.GONE);
// binding.pitTeamName.setVisibility(View.GONE);
// binding.pitTeamDescription.setVisibility(View.GONE);
//
// clear_fields();
int[] teamNums = new int[event.teams.size()];
for(int i = 0 ; i < event.teams.size(); i++){
teamNums[i] = event.teams.get(i).teamNumber;
}
Arrays.sort(teamNums);
TableLayout table = new TableLayout(getContext());
table.setStretchAllColumns(true);
binding.teams.addView(table);
for(int i = 0; i < event.teams.size(); i++){
frcTeam team = null;
for(int a = 0 ; a < event.teams.size(); a++){
if(event.teams.get(a).teamNumber == teamNums[i]){
team = event.teams.get(a);
break;
}
}
assert team != null;
// TableRow tr = new TableRow(getContext());
// TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
// FrameLayout.LayoutParams.WRAP_CONTENT,
// FrameLayout.LayoutParams.WRAP_CONTENT
// );
// rowParams.setMargins(20,20,20,20);
// tr.setLayoutParams(rowParams);
// tr.setPadding(20,20,20,20);
// table.addView(tr);
TeamListOption teamRow = new TeamListOption(getContext());
table.addView(teamRow);
teamRow.fromTeam(team);
String filename = evcode + "-" + team.teamNumber + ".pitscoutdata";
if (FileEditor.fileExist(filename)) {
final boolean[] rescout = {DataManager.rescout_list.contains(filename)};
teamRow.setColor(DataManager.rescout_list.contains(filename) ? color_rescout : color_found);
teamRow.setOnLongClickListener(v -> {
rescout[0] = !rescout[0];
if(rescout[0]){
DataManager.rescout_list.add(filename);
teamRow.setColor(color_rescout);
DataManager.save_rescout_list();
}else{
DataManager.rescout_list.remove(filename);
teamRow.setColor(color_found);
DataManager.save_rescout_list();
}
return true;
});
} else {
teamRow.setColor(color_not_found);
teamRow.setOnLongClickListener(v -> true);
}
frcTeam finalTeam = team;
teamRow.setOnClickListener(v -> onSelect.onSelect(this, finalTeam));
}
}
}
@@ -3,6 +3,7 @@ package com.ridgebotics.ridgescout.ui.scouting;
import static android.widget.LinearLayout.VERTICAL; import static android.widget.LinearLayout.VERTICAL;
import static androidx.navigation.fragment.FragmentKt.findNavController; import static androidx.navigation.fragment.FragmentKt.findNavController;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.event; import static com.ridgebotics.ridgescout.utility.DataManager.event;
import android.app.AlertDialog; import android.app.AlertDialog;
@@ -21,15 +22,16 @@ import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.R; import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.types.frcEvent; import com.ridgebotics.ridgescout.types.frcEvent;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import com.ridgebotics.ridgescout.databinding.FragmentScoutingBinding; import com.ridgebotics.ridgescout.databinding.FragmentScoutingBinding;
import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.ui.TeamSelectorFragment;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Set;
// Main dashbord page
public class ScoutingFragment extends Fragment { public class ScoutingFragment extends Fragment {
private FragmentScoutingBinding binding; private FragmentScoutingBinding binding;
@@ -44,7 +46,7 @@ public class ScoutingFragment extends Fragment {
DataManager.reload_event(); DataManager.reload_event();
if(settingsManager.getCustomEvents()){ if(SettingsManager.getCustomEvents()){
binding.eventAddButton.setVisibility(View.VISIBLE); binding.eventAddButton.setVisibility(View.VISIBLE);
binding.eventAddButton.setOnClickListener(view -> { binding.eventAddButton.setOnClickListener(view -> {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
@@ -71,7 +73,7 @@ public class ScoutingFragment extends Fragment {
event.teams = new ArrayList<>(); event.teams = new ArrayList<>();
event.matches = new ArrayList<>(); event.matches = new ArrayList<>();
fileEditor.setEvent(event); FileEditor.setEvent(event);
}); });
@@ -84,6 +86,12 @@ public class ScoutingFragment extends Fragment {
if(event == null){ if(event == null){
binding.noEventError.setVisibility(View.VISIBLE); binding.noEventError.setVisibility(View.VISIBLE);
binding.textMatchAlliance.setVisibility(View.GONE);
binding.textName.setVisibility(View.GONE);
binding.textNextMatch.setVisibility(View.GONE);
binding.textRescoutIndicator.setVisibility(View.GONE);
binding.matchScoutingButton.setEnabled(false); binding.matchScoutingButton.setEnabled(false);
binding.pitScoutingButton.setEnabled(false); binding.pitScoutingButton.setEnabled(false);
binding.eventButton.setEnabled(false); binding.eventButton.setEnabled(false);
@@ -104,18 +112,32 @@ public class ScoutingFragment extends Fragment {
}); });
binding.pitScoutingButton.setOnClickListener(v -> { binding.pitScoutingButton.setOnClickListener(v -> {
TeamSelectorFragment.setPits_mode(true); PitSelectorFragment.setOnSelect((self, team) -> {
TeamSelectorFragment.setOnSelect((self, team) -> {
PitScoutingFragment.setTeam(team); PitScoutingFragment.setTeam(team);
findNavController(self).navigate(R.id.action_navigation_team_selector_to_navigation_pit_scouting); findNavController(self).navigate(R.id.action_navigation_scouting_pit_selector_to_navigation_pit_scouting);
}); });
findNavController(this).navigate(R.id.action_navigation_scouting_to_navigation_team_selector); findNavController(this).navigate(R.id.action_navigation_scouting_to_navigation_scouting_pit_selector);
}); });
binding.eventButton.setOnClickListener(v -> { binding.eventButton.setOnClickListener(v -> {
findNavController(this).navigate(R.id.action_navigation_scouting_to_navigation_scouting_event); findNavController(this).navigate(R.id.action_navigation_scouting_to_navigation_scouting_event);
}); });
binding.textName.setText("Welcome, " + SettingsManager.getUsername() + "!");
int matchNum = SettingsManager.getMatchNum();
int nextMatch = -1;
try {
nextMatch = event.getNextTeamMatch(SettingsManager.getTeamNum(), matchNum).matchIndex;
} catch (Exception e){
AlertManager.error(e);
}
binding.textNextMatch.setText("Our next match: Match " + nextMatch);
binding.textMatchAlliance.setText("Match: " + (matchNum+1) + ", " + SettingsManager.getAllyPos());
binding.textRescoutIndicator.setText("Things to rescout: " + DataManager.rescout_list.size());
return binding.getRoot(); return binding.getRoot();
} }
@@ -0,0 +1,473 @@
package com.ridgebotics.ridgescout.ui.settings;
import static android.text.InputType.TYPE_CLASS_NUMBER;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import com.ridgebotics.ridgescout.types.input.CheckboxType;
import com.ridgebotics.ridgescout.types.input.DropdownType;
import com.ridgebotics.ridgescout.types.input.FieldposType;
import com.ridgebotics.ridgescout.types.input.FieldType;
import com.ridgebotics.ridgescout.types.input.NumberType;
import com.ridgebotics.ridgescout.types.input.SliderType;
import com.ridgebotics.ridgescout.types.input.TallyType;
import com.ridgebotics.ridgescout.types.input.TextType;
import com.ridgebotics.ridgescout.types.input.ToggleType;
import com.ridgebotics.ridgescout.utility.AlertManager;
import java.lang.reflect.Field;
import java.util.UUID;
// Class to help with fields editor fragment, containing the defaults for each field.
public class FieldEditorHelper {
private enum parameterTypeEnum {
paramNumber,
paramString,
paramStringArray,
paramNumberArray,
paramBoolean
}
public static class parameterType {
public String name;
public parameterTypeEnum id;
}
public static class paramNumber extends parameterType{
public int val;
public paramNumber(String name, int val){
this.name = name + " (Number)";
this.val = val;
this.id = parameterTypeEnum.paramNumber;
}
}
public static class paramString extends parameterType {
public String val;
public paramString(String name, String val){
this.name = name + " (String)";
this.val = val;
this.id = parameterTypeEnum.paramString;
}
}
public static class paramStringArray extends parameterType{
public String[] val;
public paramStringArray(String name, String[] val){
this.name = name + " (String array)";
this.val = val;
this.id = parameterTypeEnum.paramStringArray;
}
}
public static class paramBoolean extends parameterType{
public boolean val;
public paramBoolean(String name, boolean val){
this.name = name + " (Boolean)";
this.val = val;
this.id = parameterTypeEnum.paramBoolean;
}
}
// public static class paramNumberArray extends parameterType{
// public int[] val;
// public paramNumberArray(String name, int[] val){
// this.name = name + " (Number array)";
// this.val = val;
// this.id = parameterTypeEnum.paramNumberArray;
// }
// }
public static final parameterType[] defaultSliderParams = new parameterType[]{
new paramString("Name", "New Slider"),
new paramString("Description", ""),
new paramNumber("Min", 0),
new paramNumber("Max", 10),
new paramNumber("Default Value", 5)
};
public static final parameterType[] defaultDropdownParams = new parameterType[]{
new paramString("Name", "New Dropdown"),
new paramString("Description", ""),
new paramStringArray("Default Value", new String[]{"Zero","One","Two","Three"}),
new paramNumber("Default Option", 0),
};
public static final parameterType[] defaultTextParams = new parameterType[]{
new paramString("Name", "New Text"),
new paramString("Description", ""),
new paramString("Default Value", "")
};
public static final parameterType[] defaultTallyParams = new parameterType[]{
new paramString("Name", "New Tally"),
new paramString("Description", ""),
new paramNumber("Default Value", 0)
};
public static final parameterType[] defaultNumberParams = new parameterType[]{
new paramString("Name", "New Number"),
new paramString("Description", ""),
new paramNumber("Default Value", 0)
};
public static final parameterType[] defaultCheckboxParam = new parameterType[]{
new paramString("Name", "New Checkbox"),
new paramString("Description", ""),
new paramNumber("Default Value ( 1 or 0 )", 0)
};
public static final parameterType[] defaultFieldPosParam = new parameterType[]{
new paramString("Name", "New Field Position"),
new paramString("Description", ""),
new paramNumber("Default X", 0),
new paramNumber("Default Y", 0)
};
public static final parameterType[] defaultToggleParam = new parameterType[]{
new paramString("Name", "New Toggle"),
new paramString("Description", ""),
new paramBoolean("Default true or false",true)
};
private static parameterType[] getSliderParams(SliderType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramNumber("Min", s.min),
new paramNumber("Max", s.max),
new paramNumber("Default Value", (int) s.default_value)
};
}
private static parameterType[] getDropdownParams(DropdownType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramStringArray("Default Value",s.text_options),
new paramNumber("Default Option", (int) s.default_value),
};
}
private static parameterType[] getTextParams(TextType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramString("Default Value", (String) s.default_value)
};
}
private static parameterType[] getTallyParams(TallyType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramNumber("Default Value", (int) s.default_value)
};
}
private static parameterType[] getNumberParams(NumberType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramNumber("Default Value", (int) s.default_value)
};
}
private static parameterType[] getCheckboxParam(CheckboxType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramNumber("Default Value ( 1 or 0 )", (int) s.default_value)
};
}
private static parameterType[] getFieldPosParam(FieldposType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramNumber("Default X", ((int[]) s.default_value)[0]),
new paramNumber("Default Y", ((int[]) s.default_value)[1])
};
}
private static parameterType[] getToggleParams(ToggleType s){
return new parameterType[]{
new paramString("Name", s.name),
new paramString("Description", s.description),
new paramBoolean("Default true or false", (boolean) s.default_value)
};
}
public static void setSliderParams(SliderType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.min = ((paramNumber) types[2]).val;
s.max = ((paramNumber) types[3]).val;
s.default_value = ((paramNumber) types[4]).val;
}
public static void setDropdownParams(DropdownType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.text_options = ((paramStringArray) types[2]).val;
s.default_value = ((paramNumber) types[3]).val;
}
public static void setTextParams(TextType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.default_value = ((paramString) types[2]).val;
}
public static void setTallyParams(TallyType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.default_value = ((paramNumber) types[2]).val;
}
public static void setNumberParams(NumberType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.default_value = ((paramNumber) types[2]).val;
}
public static void setCheckboxParam(CheckboxType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.default_value = ((paramNumber) types[2]).val;
}
public static void setFieldPosParam(FieldposType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.default_value = new int[]{
((paramNumber) types[2]).val,
((paramNumber) types[3]).val
};
}
public static void setToggleParam(ToggleType s, parameterType[] types){
s.name = ((paramString) types[0]).val;
s.description = ((paramString) types[1]).val;
s.default_value = ((paramBoolean) types[2]).val;
}
private static void setInputParameter(FieldType t, parameterType[] types){
switch (t.getInputType()){
case TALLY:
setTallyParams((TallyType) t, types);
break;
case SLIDER:
setSliderParams((SliderType) t, types);
break;
case DROPDOWN:
setDropdownParams((DropdownType) t, types);
break;
case NOTES_INPUT:
setTextParams((TextType) t, types);
break;
case NUMBER:
setNumberParams((NumberType) t, types);
break;
case CHECKBOX:
setCheckboxParam((CheckboxType) t, types);
break;
case FIELDPOS:
setFieldPosParam((FieldposType) t, types);
break;
case TOGGLE:
setToggleParam((ToggleType) t, types);
break;
}
}
private static parameterType[] getParamsFromInputType(FieldType t){
switch (t.getInputType()){
case TALLY:
return getTallyParams((TallyType) t);
case SLIDER:
return getSliderParams((SliderType) t);
case DROPDOWN:
return getDropdownParams((DropdownType) t);
case NOTES_INPUT:
return getTextParams((TextType) t);
case NUMBER:
return getNumberParams((NumberType) t);
case CHECKBOX:
return getCheckboxParam((CheckboxType) t);
case FIELDPOS:
return getFieldPosParam((FieldposType) t);
case TOGGLE:
return getToggleParams((ToggleType) t);
}
return new parameterType[]{};
}
private static View createNumberEdit(Context c, int value){
EditText text = new EditText(c);
text.setInputType(TYPE_CLASS_NUMBER);
text.setText(String.valueOf(value));
text.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
return text;
}
private static View createStringEdit(Context c, String value){
EditText text = new EditText(c);
text.setText(value);
text.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
return text;
}
private static View createStringArrayEdit(Context c, String[] value){
EditText text = new EditText(c);
text.setText(String.join("\n", value));
text.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
return text;
}
private static View createBooleanEdit(Context c, boolean value){
EditText text = new EditText(c);
text.setText(value);
text.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
return text;
}
private static View createEdit(Context c, parameterType t){
switch (t.id){
case paramNumber:
return createNumberEdit(c, ((paramNumber) t).val);
case paramString:
return createStringEdit(c, ((paramString) t).val);
case paramStringArray:
return createStringArrayEdit(c, ((paramStringArray) t).val);
}
return null;
}
private static boolean readEdit(View v, parameterType t){
try{
String val;
switch (t.id) {
case paramNumber:
val = ((EditText) v).getText().toString();
if(val.isEmpty() || val.isBlank()) return false;
((paramNumber) t).val = Integer.parseInt(val);
break;
case paramString:
val = ((EditText) v).getText().toString();
//if(val.isEmpty() || val.isBlank()) return false;
((paramString) t).val = val;
break;
case paramStringArray:
val = ((EditText) v).getText().toString();
if(val.isEmpty() || val.isBlank()) return false;
((paramStringArray) t).val = val.split("\n");
break;
}
} catch (Exception e) {
AlertManager.error(e);
return false;
}
return true;
}
public static FieldType createNewFieldType(int n){
switch(n){
case 0:
SliderType slider = new SliderType();
slider.UUID = UUID.randomUUID().toString();
setSliderParams(slider, defaultSliderParams);
return slider;
case 1:
TextType textType = new TextType();
textType.UUID = UUID.randomUUID().toString();
setTextParams(textType, defaultTextParams);
return textType;
case 2:
DropdownType dropdownType = new DropdownType();
dropdownType.UUID = UUID.randomUUID().toString();
setDropdownParams(dropdownType, defaultDropdownParams);
return dropdownType;
case 3:
TallyType tallyType = new TallyType();
tallyType.UUID = UUID.randomUUID().toString();
setTallyParams(tallyType, defaultTallyParams);
return tallyType;
case 4:
NumberType numberType = new NumberType();
numberType.UUID = UUID.randomUUID().toString();
setNumberParams(numberType, defaultNumberParams);
return numberType;
case 5:
CheckboxType checkboxType = new CheckboxType();
checkboxType.UUID = UUID.randomUUID().toString();
setCheckboxParam(checkboxType, defaultCheckboxParam);
return checkboxType;
case 6:
FieldposType fieldposType = new FieldposType();
fieldposType.UUID = UUID.randomUUID().toString();
setFieldPosParam(fieldposType, defaultFieldPosParam);
return fieldposType;
case 7:
ToggleType toggleType = new ToggleType();
toggleType.UUID = UUID.randomUUID().toString();
setToggleParam(toggleType, defaultToggleParam);
return toggleType;
}
return null;
}
private parameterType[] types;
private View[] views;
private FieldType t;
public FieldEditorHelper(Context c, FieldType t, TableLayout parentView, parameterType[] tmptypes){
this.types = tmptypes;
this.t = t;
views = new View[types.length];
for(int i = 0; i < types.length; i++){
TextView tv = new TextView(c);
tv.setText(types[i].name);
tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
tv.setTextSize(20);
parentView.addView(tv);
views[i] = createEdit(c, types[i]);
parentView.addView(views[i]);
}
}
public FieldEditorHelper(Context c, FieldType t, TableLayout parentView){
this(c,t,parentView,getParamsFromInputType(t));
}
public boolean save(){
for(int i = 0; i < types.length; i++){
if(!readEdit(views[i], types[i]))
return false;
}
setInputParameter(t, types);
return true;
}
}
@@ -0,0 +1,312 @@
package com.ridgebotics.ridgescout.ui.settings;
import static com.ridgebotics.ridgescout.utility.Colors.background_color;
import static com.ridgebotics.ridgescout.utility.Colors.unfocused_background_color;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import com.ridgebotics.ridgescout.MainActivity;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.databinding.FragmentSettingsFieldsBinding;
import com.ridgebotics.ridgescout.scoutingData.Fields;
import com.ridgebotics.ridgescout.types.input.FieldType;
import com.ridgebotics.ridgescout.ui.views.CustomSpinnerView;
import com.ridgebotics.ridgescout.ui.views.FieldDisplay;
import com.ridgebotics.ridgescout.utility.AlertManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// Fragment that shows the field editor.
public class FieldsFragment extends Fragment {
FragmentSettingsFieldsBinding binding;
private static String filename;
public static void set_filename(String tmpfilename){
filename = tmpfilename;
}
private int index = -1;
private boolean edited = false;
List<FieldType> values;
List<FieldDisplay> views;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentSettingsFieldsBinding.inflate(inflater, container, false);
binding.upButton.setEnabled(false);
binding.downButton.setEnabled(false);
binding.saveButton.setEnabled(false);
FieldType[][] tmp_values = Fields.load(filename);
if(tmp_values == null || tmp_values.length == 0) return binding.getRoot();
values = new ArrayList(List.of(tmp_values[tmp_values.length-1]));
views = new ArrayList<>();
for(int i = 0; i < values.size(); i++){
createFieldDisplay(values.get(i));
}
// Up and down buttons
binding.upButton.setOnClickListener(v -> {
if(index <= 0) return;
Collections.swap(values, index, index-1);
Collections.swap(views, index, index-1);
index--;
updateRowOrder();
});
binding.downButton.setOnClickListener(v -> {
if(index >= values.size()-1) return;
Collections.swap(values, index, index+1);
Collections.swap(views, index, index+1);
index++;
updateRowOrder();
});
// Add Field button
binding.addButton.setOnClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Type");
final CustomSpinnerView dropdown = new CustomSpinnerView(getContext());
List<String> options = new ArrayList<>();
options.add("Slider");
options.add("Text");
options.add("Dropdown");
options.add("Tally");
options.add("Number");
options.add("Checkbox");
options.add("Field Position");
dropdown.setOptions(options, 0);
dropdown.setTitle("Type");
builder.setView(dropdown);
builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
builder.setPositiveButton("OK", (dialog, which) -> addField(dropdown.getIndex()));
builder.show();
});
// Back button listener
((MainActivity) getActivity()).setOnBackPressed(() -> {
if(!edited) return true;
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Warning!");
alert.setMessage("You have not saved your progress!");
alert.setPositiveButton("Return", null);
alert.setNeutralButton("Quit without saving", (dialogInterface, i) -> {
edited = false;
if(getActivity() != null)
getActivity().onBackPressed();
});
alert.setCancelable(true);
alert.create().show();
return false;
});
binding.saveButton.setOnClickListener(l -> save());
if(tmp_values.length > 1)
binding.revertButton.setOnClickListener(v -> revertPopup());
else
binding.revertButton.setEnabled(false);
return binding.getRoot();
}
@SuppressLint("ClickableViewAccessibility")
private void createFieldDisplay(FieldType field){
final FieldDisplay fd = new FieldDisplay(getContext());
views.add(fd);
fd.setField(field);
fd.setColor(unfocused_background_color);
fd.coloredBackground.setOnTouchListener((view, motionEvent) -> {
FieldsFragment.this.setFocus(fd, false);
return true;
});
fd.editButton.setOnClickListener(v -> openEditor(fd));
binding.fieldsArea.addView(fd);
}
private void updateRowOrder(){
enableSaving();
binding.fieldsArea.removeAllViews();
for(int i = 0; i < views.size(); i++){
binding.fieldsArea.addView(views.get(i));
}
binding.upButton.setEnabled(index != -1 && index > 0);
binding.downButton.setEnabled(index != -1 && index < views.size()-1);
}
private void setFocus(FieldDisplay fd, boolean scroll){
index = views.indexOf(fd);
for(int a = 0; a < values.size(); a++) {
views.get(a).setColor(unfocused_background_color);
views.get(a).hideButtons();
}
fd.setColor(background_color);
fd.showButtons();
binding.upButton.setEnabled(index != -1 && index > 0);
binding.downButton.setEnabled(index != -1 && index < views.size()-1);
if(scroll)
binding.scrollView.post(() -> binding.scrollView.scrollTo(0, fd.getTop()));
}
private void openEditor(FieldDisplay fd){
FieldType field = fd.getField();
ScrollView sv = new ScrollView(getContext());
TableLayout table = new TableLayout(getContext());
table.setStretchAllColumns(true);
table.setPadding(10, 10, 10, 10);
sv.addView(table);
TextView UUID = new TextView(getContext());
UUID.setText("Type: " + field.get_type_name() + "\nUUID: " + field.UUID);
table.addView(UUID);
FieldEditorHelper f = new FieldEditorHelper(getContext(), field, table);
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Edit " + field.name);
alert.setView(sv);
alert.setCancelable(false);
alert.setNeutralButton("Cancel", (dialogInterface, i) -> {});
alert.setPositiveButton("Save", (dialogInterface, i) -> {
f.save();
fd.setField(field);
enableSaving();
});
AlertDialog dialog = alert.create();
dialog.show();
Button deleteButton = new Button(getContext());
deleteButton.setText("DELETE");
deleteButton.setOnClickListener(l -> {
AlertDialog.Builder alert2 = new AlertDialog.Builder(getContext());
alert2.setTitle("Warning!");
alert2.setMessage("This may destroy any data after being saved!");
alert2.setPositiveButton("Return", (dialogInterface, i) -> {});
alert2.setNeutralButton("DELETE", (dialogInterface, i) -> {
removeField(field);
dialog.cancel();
});
alert2.setCancelable(true);
alert2.create().show();
});
table.addView(deleteButton);
}
private void enableSaving(){
edited = true;
binding.saveButton.setEnabled(true);
}
private void addField(int n){
FieldType field = FieldEditorHelper.createNewFieldType(n);
values.add(field);
createFieldDisplay(field);
setFocus(views.get(views.size()-1), true);
enableSaving();
}
private void removeField(FieldType field){
int fieldIndex = values.indexOf(field);
views.remove(fieldIndex);
values.remove(fieldIndex);
index = -1;
updateRowOrder();
}
private void save(){
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Warning!");
alert.setMessage("Changing or removing some values will result in lost data! but you can revert at any time.");
alert.setNeutralButton("Save", (dialog, which) -> {
FieldType[][] currentValues = Fields.load(filename);
assert currentValues != null;
FieldType[][] newValues = new FieldType[currentValues.length+1][];
System.arraycopy(currentValues, 0, newValues, 0, currentValues.length);
Log.i(getClass().toString(), "Length: " + values.size());
newValues[currentValues.length] = new FieldType[values.size()];
for(int i = 0; i < values.size(); i++) {
FieldType value = values.get(i);
newValues[currentValues.length][i] = value;
}
if(Fields.save(filename, newValues))
AlertManager.toast("Saved");
Navigation.findNavController((Activity) getContext(), R.id.nav_host_fragment_activity_main).navigate(R.id.action_navigation_data_fields_to_navigation_settings);
});
alert.setNegativeButton("Cancel", null);
alert.setCancelable(true);
alert.create().show();
}
public void revertPopup(){
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Warning!");
alert.setMessage("If there is any data scouted with this version of the fields, it will cause conflicts!\nYou should know what you are doing");
alert.setNeutralButton("Revert and delete version", (dialog, which) -> {
FieldType[][] currentValues = Fields.load(filename);
assert currentValues != null;
FieldType[][] newValues = new FieldType[currentValues.length-1][];
System.arraycopy(currentValues, 0, newValues, 0, currentValues.length - 1);
if(Fields.save(filename, newValues))
AlertManager.toast("Saved");
Navigation.findNavController((Activity) getContext(), R.id.nav_host_fragment_activity_main).navigate(R.id.action_navigation_data_fields_to_navigation_settings);
});
alert.setNegativeButton("Cancel", null);
alert.setCancelable(true);
alert.create().show();
}
}
@@ -1,47 +1,60 @@
package com.ridgebotics.ridgescout.ui.settings; package com.ridgebotics.ridgescout.ui.settings;
import static com.ridgebotics.ridgescout.utility.settingsManager.AllyPosKey; import static android.view.View.VISIBLE;
import static com.ridgebotics.ridgescout.utility.settingsManager.CustomEventsKey; import static androidx.navigation.fragment.FragmentKt.findNavController;
import static com.ridgebotics.ridgescout.utility.settingsManager.SelEVCodeKey; import static com.ridgebotics.ridgescout.utility.SettingsManager.AllyPosKey;
import static com.ridgebotics.ridgescout.utility.settingsManager.UnameKey; import static com.ridgebotics.ridgescout.utility.SettingsManager.CustomEventsKey;
import static com.ridgebotics.ridgescout.utility.settingsManager.WifiModeKey; import static com.ridgebotics.ridgescout.utility.SettingsManager.EnableQuickAllianceChangeKey;
import static com.ridgebotics.ridgescout.utility.settingsManager.YearNumKey; import static com.ridgebotics.ridgescout.utility.SettingsManager.FieldImageKey;
import static com.ridgebotics.ridgescout.utility.settingsManager.defaults; import static com.ridgebotics.ridgescout.utility.SettingsManager.MatchNumKey;
import static com.ridgebotics.ridgescout.utility.settingsManager.getEditor; import static com.ridgebotics.ridgescout.utility.SettingsManager.SelEVCodeKey;
import static com.ridgebotics.ridgescout.utility.settingsManager.prefs; import static com.ridgebotics.ridgescout.utility.SettingsManager.TeamNumKey;
import static com.ridgebotics.ridgescout.utility.SettingsManager.UnameKey;
import static com.ridgebotics.ridgescout.utility.SettingsManager.WifiModeKey;
import static com.ridgebotics.ridgescout.utility.SettingsManager.YearNumKey;
import static com.ridgebotics.ridgescout.utility.SettingsManager.defaults;
import static com.ridgebotics.ridgescout.utility.SettingsManager.getEditor;
import static com.ridgebotics.ridgescout.utility.SettingsManager.prefs;
import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import android.text.Editable; import android.text.Editable;
import android.text.InputType; import android.text.InputType;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TableLayout; import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.checkbox.MaterialCheckBox; import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout; import com.google.android.material.textfield.TextInputLayout;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.databinding.FragmentSettingsBinding; import com.ridgebotics.ridgescout.databinding.FragmentSettingsBinding;
import com.ridgebotics.ridgescout.ui.CustomSpinnerPopup; import com.ridgebotics.ridgescout.scoutingData.Fields;
import com.ridgebotics.ridgescout.ui.CustomSpinnerView; import com.ridgebotics.ridgescout.ui.views.CustomSpinnerView;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.ui.views.TallyCounterView;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
// Fragment to edit settings, aswell as redirect to the fields editor.
public class settingsFragment extends Fragment { public class SettingsFragment extends Fragment {
private FragmentSettingsBinding binding; private FragmentSettingsBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater, public View onCreateView(@NonNull LayoutInflater inflater,
@@ -50,6 +63,28 @@ public class settingsFragment extends Fragment {
binding = FragmentSettingsBinding.inflate(inflater, container, false); binding = FragmentSettingsBinding.inflate(inflater, container, false);
View root = binding.getRoot(); View root = binding.getRoot();
reloadSettings();
binding.fieldsButton.setOnClickListener(v -> {
binding.fieldsButton.setEnabled(false);
binding.fieldsButtons.setVisibility(VISIBLE);
});
binding.fieldsMatchesButton.setOnClickListener(v -> {
FieldsFragment.set_filename(Fields.matchFieldsFilename);
findNavController(this).navigate(R.id.action_navigation_settings_to_navigation_data_fields);
});
binding.fieldsPitsButton.setOnClickListener(v -> {
FieldsFragment.set_filename(Fields.pitsFieldsFilename);
findNavController(this).navigate(R.id.action_navigation_settings_to_navigation_data_fields);
});
return root;
}
private void reloadSettings(){
String[] alliance_pos_list = new String[]{"red-1", "red-2", "red-3", String[] alliance_pos_list = new String[]{"red-1", "red-2", "red-3",
"blue-1", "blue-2", "blue-3"}; "blue-1", "blue-2", "blue-3"};
@@ -58,27 +93,61 @@ public class settingsFragment extends Fragment {
manager.addItem(new CheckboxSettingsItem(CustomEventsKey, "Custom Events")); manager.addItem(new CheckboxSettingsItem(CustomEventsKey, "Custom Events"));
StringSettingsItem FTPServer = new StringSettingsItem(settingsManager.FTPServer, "FTP Server (Sync)"); StringSettingsItem FTPKey = new StringSettingsItem(com.ridgebotics.ridgescout.utility.SettingsManager.FTPKey, "Sync Key");
manager.addItem(FTPKey);
StringSettingsItem FTPServer = new StringSettingsItem(com.ridgebotics.ridgescout.utility.SettingsManager.FTPServer, "Sync Server (Sync)");
manager.addItem(FTPServer); manager.addItem(FTPServer);
CheckboxSettingsItem FTPSendMetaFiles = new CheckboxSettingsItem(settingsManager.FTPSendMetaFiles, "Sync meta files"); CheckboxSettingsItem FTPSendMetaFiles = new CheckboxSettingsItem(com.ridgebotics.ridgescout.utility.SettingsManager.FTPSendMetaFiles, "⚠ Send meta files");
manager.addItem(FTPSendMetaFiles); manager.addItem(FTPSendMetaFiles);
CheckboxSettingsItem FTPEnabled = new CheckboxSettingsItem(settingsManager.FTPEnabled, "FTP Enabled", FTPServer, FTPSendMetaFiles); CheckboxSettingsItem FTPEnabled = new CheckboxSettingsItem(com.ridgebotics.ridgescout.utility.SettingsManager.FTPEnabled, "FTP Enabled", FTPServer, FTPKey, FTPSendMetaFiles);
manager.addItem(FTPEnabled); manager.addItem(FTPEnabled);
manager.addItem(new CheckboxSettingsItem(WifiModeKey, "Wifi Mode", FTPEnabled)); manager.addItem(new CheckboxSettingsItem(WifiModeKey, "Wifi Mode", FTPEnabled));
manager.addItem(new CheckboxSettingsItem(EnableQuickAllianceChangeKey, "Enable quick alliance swap", null));
manager.addItem(new DropdownSettingsItem(FieldImageKey, "Field Image", new String[]{
"2025",
"2025 (Flipped)"
}));
manager.addItem(new NumberSettingsItem(YearNumKey, "Year", 0, 9999)); manager.addItem(new NumberSettingsItem(YearNumKey, "Year", 0, 9999));
manager.addItem(new DropdownSettingsItem(AllyPosKey, "Alliance Pos", alliance_pos_list));
manager.addItem(new DropdownSettingsItem(SelEVCodeKey, "Event Code", fileEditor.getEventList().toArray(new String[0])));
manager.addItem(new StringSettingsItem(UnameKey, "Username"));
manager.addItem(new DropdownSettingsItem(AllyPosKey, "Alliance Pos", alliance_pos_list));
int max = 0;
boolean hasEvent = false;
if(!DataManager.getevcode().equals("unset")){
DataManager.reload_event();
max = DataManager.event.matches.size();
hasEvent = true;
}
TallySettingsItem matchNum = new TallySettingsItem(MatchNumKey, "Match Number", max);
matchNum.setEnabled(hasEvent);
manager.addItem(matchNum);
DropdownSettingsItem eventCode = new DropdownSettingsItem(SelEVCodeKey, "Event Code", FileEditor.getEventList().toArray(new String[0]));
eventCode.reloadOnChange(true);
manager.addItem(eventCode);
manager.addItem(new StringSettingsItem(UnameKey, "Username"));
manager.addItem(new NumberSettingsItem(TeamNumKey, "Team Number", 0, 99999));
binding.SettingsTable.removeAllViews();
manager.getView(binding.SettingsTable); manager.getView(binding.SettingsTable);
if(!DataManager.getevcode().equals("unset")){
return root; Button editNoticeButton = new Button(getContext());
editNoticeButton.setText("Edit Scout Notice");
binding.SettingsTable.addView(editNoticeButton);
editNoticeButton.setOnClickListener(v->editNotice());
} }
}
@Override @Override
public void onDestroyView() { public void onDestroyView() {
@@ -87,6 +156,27 @@ public class settingsFragment extends Fragment {
} }
private void editNotice(){
ScrollView sv = new ScrollView(getContext());
EditText editText = new EditText(getContext());
editText.setText(DataManager.scoutNotice);
sv.addView(editText);
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Edit Notice");
alert.setView(sv);
alert.setNeutralButton("Cancel", null);
alert.setPositiveButton("Save", (dialogInterface, i) -> {
DataManager.scoutNotice = editText.getText().toString();
DataManager.save_scout_notice();
});
alert.setCancelable(false);
alert.create().show();
}
@@ -103,6 +193,7 @@ public class settingsFragment extends Fragment {
private String key; private String key;
private String title; private String title;
private T defaultValue; private T defaultValue;
public View view;
public SettingsItem(String key, String title, T defaultValue) { public SettingsItem(String key, String title, T defaultValue) {
this.key = key; this.key = key;
@@ -110,6 +201,14 @@ public class settingsFragment extends Fragment {
this.defaultValue = defaultValue; this.defaultValue = defaultValue;
} }
private boolean reloadOnChange = false;
public void reloadOnChange(boolean enabled){
reloadOnChange = enabled;
}
public boolean isReloadOnChange(){
return reloadOnChange;
}
public abstract View createView(Context context); public abstract View createView(Context context);
public abstract T getValue(); public abstract T getValue();
@@ -146,6 +245,7 @@ public class settingsFragment extends Fragment {
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
getEditor().putString(getKey(), s.toString()).apply(); getEditor().putString(getKey(), s.toString()).apply();
if(isReloadOnChange()) reloadSettings();
} }
@Override @Override
@@ -205,6 +305,7 @@ public class settingsFragment extends Fragment {
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
editText.setText(String.valueOf(getDefaultValue())); editText.setText(String.valueOf(getDefaultValue()));
} }
if(isReloadOnChange()) reloadSettings();
} }
@Override @Override
@@ -225,6 +326,66 @@ public class settingsFragment extends Fragment {
} }
} }
public class TallySettingsItem extends SettingsItem<Integer> {
private int max;
public TallySettingsItem(String key, String title, int max) {
super(key, title, prefs.getInt(key, (int) defaults.get(key)));
this.max = max;
}
TallyCounterView tally;
private boolean enabled;
@Override
public void setEnabled(boolean enabled){
this.enabled = enabled;
if(tally != null)
tally.setEnabled(enabled);
}
@Override
public View createView(Context context) {
LinearLayout ll = new LinearLayout(getContext());
ll.setOrientation(LinearLayout.VERTICAL);
tally = new TallyCounterView(getContext());
int value = getValue()+1;
if(value >= max){
value = max;
getEditor().putInt(getKey(), Math.max(0,max-1)).apply();
}
tally.setValue(value);
tally.setBounds(1, max);
tally.setOnCountChangedListener(count -> {
getEditor().putInt(getKey(), Math.max(0,count-1)).apply();
if(isReloadOnChange()) reloadSettings();
});
tally.setEnabled(enabled);
TextView tv = new TextView(getContext());
tv.setText(getTitle());
tv.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline6);
tv.setGravity(Gravity.CENTER);
ll.addView(tv);
ll.addView(tally);
return ll;
}
@Override
public Integer getValue() {
return prefs.getInt(getKey(), (int) defaults.get(getKey()));
}
}
public class DropdownSettingsItem extends SettingsItem<String> { public class DropdownSettingsItem extends SettingsItem<String> {
private String[] options; private String[] options;
@@ -257,6 +418,7 @@ public class settingsFragment extends Fragment {
dropdown.setOnClickListener((item, index) -> { dropdown.setOnClickListener((item, index) -> {
getEditor().putString(getKey(), item).apply(); getEditor().putString(getKey(), item).apply();
if(isReloadOnChange()) reloadSettings();
}); });
return dropdown; return dropdown;
@@ -271,9 +433,9 @@ public class settingsFragment extends Fragment {
public class CheckboxSettingsItem extends SettingsItem<Boolean> { public class CheckboxSettingsItem extends SettingsItem<Boolean> {
private List<SettingsItem<?>> controlledItems; private List<SettingsItem<?>> controlledItems;
public CheckboxSettingsItem(String key, String title, SettingsItem<?>... controlledItems) { public CheckboxSettingsItem(String key, String title, @Nullable SettingsItem<?>... controlledItems) {
super(key, title, prefs.getBoolean(key, (Boolean) defaults.get(key))); super(key, title, prefs.getBoolean(key, (Boolean) defaults.get(key)));
this.controlledItems = Arrays.asList(controlledItems); this.controlledItems = (controlledItems != null) ? Arrays.asList(controlledItems) : new ArrayList<>();
} }
MaterialCheckBox checkBox; MaterialCheckBox checkBox;
@@ -297,6 +459,7 @@ public class settingsFragment extends Fragment {
for (SettingsItem<?> item : controlledItems) { for (SettingsItem<?> item : controlledItems) {
item.setEnabled(isChecked); item.setEnabled(isChecked);
} }
if(isReloadOnChange()) reloadSettings();
}); });
for (SettingsItem<?> item : controlledItems) { for (SettingsItem<?> item : controlledItems) {
@@ -337,7 +500,11 @@ public class settingsFragment extends Fragment {
itemContainer.setOrientation(LinearLayout.VERTICAL); itemContainer.setOrientation(LinearLayout.VERTICAL);
itemContainer.setPadding(32, 0, 32, 8); itemContainer.setPadding(32, 0, 32, 8);
itemContainer.addView(item.createView(context)); View view = item.createView(context);
itemContainer.addView(view);
item.view = view;
views.add(itemContainer); views.add(itemContainer);
} }
@@ -9,13 +9,14 @@ import static com.ridgebotics.ridgescout.utility.SharePrompt.shareContent;
import android.content.Context; import android.content.Context;
import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter; import com.ridgebotics.ridgescout.scoutingData.ScoutingDataWriter;
import com.ridgebotics.ridgescout.types.data.dataType; import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.types.frcMatch; import com.ridgebotics.ridgescout.types.frcMatch;
import com.ridgebotics.ridgescout.types.frcTeam; import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.types.input.inputType; import com.ridgebotics.ridgescout.types.input.FieldType;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
// Static class to export matches to a string.
public class CSVExport { public class CSVExport {
private static String[] alliances = {"red", "blue"}; private static String[] alliances = {"red", "blue"};
@@ -56,21 +57,21 @@ public class CSVExport {
data += (teamNum + ","); data += (teamNum + ",");
String filename = evcode+"-"+matchNum+"-"+alliance+"-"+alliancePos+"-"+teamNum+".matchscoutdata"; String filename = evcode+"-"+matchNum+"-"+alliance+"-"+alliancePos+"-"+teamNum+".matchscoutdata";
if(!fileEditor.fileExist(filename)){ if(!FileEditor.fileExist(filename)){
data += ("null,".repeat(match_latest_values.length)); data += ("null,".repeat(match_latest_values.length));
}else{ }else{
try { try {
String tempData = ""; String tempData = "";
ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, DataManager.match_values, DataManager.match_transferValues); ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, DataManager.match_values, DataManager.match_transferValues);
dataType[] matchData = psdr.data.array; RawDataType[] matchData = psdr.data.array;
inputType[] types = psdr.data.values[psdr.data.values.length-1]; FieldType[] types = psdr.data.values[psdr.data.values.length-1];
for (int i = 0; i < types.length; i++) { for (int i = 0; i < types.length; i++) {
tempData += (safeCSV(types[i].toString(matchData[i])) + ","); tempData += (safeCSV(types[i].toString(matchData[i])) + ",");
} }
data += tempData; data += tempData;
} catch (Exception e){ } catch (Exception e){
e.printStackTrace(); e.printStackTrace();
data += ("null,".repeat(pit_latest_values.length)); data += ("null,".repeat(match_latest_values.length));
} }
} }
@@ -108,14 +109,14 @@ public class CSVExport {
data += (team.startingYear + ","); data += (team.startingYear + ",");
String filename = evcode+"-"+team.teamNumber+".pitscoutdata"; String filename = evcode+"-"+team.teamNumber+".pitscoutdata";
if(!fileEditor.fileExist(filename)){ if(!FileEditor.fileExist(filename)){
data += ("null,".repeat(pit_latest_values.length)); data += ("null,".repeat(pit_latest_values.length));
}else{ }else{
try { try {
String tempData = ""; String tempData = "";
ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, DataManager.pit_values, DataManager.pit_transferValues); ScoutingDataWriter.ParsedScoutingDataResult psdr = ScoutingDataWriter.load(filename, DataManager.pit_values, DataManager.pit_transferValues);
dataType[] teamData = psdr.data.array; RawDataType[] teamData = psdr.data.array;
inputType[] types = psdr.data.values[psdr.data.values.length-1]; FieldType[] types = psdr.data.values[psdr.data.values.length-1];
for (int i = 0; i < types.length; i++) { for (int i = 0; i < types.length; i++) {
tempData += (safeCSV(types[i].toString(teamData[i])) + ","); tempData += (safeCSV(types[i].toString(teamData[i])) + ",");
} }
@@ -1,38 +1,35 @@
package com.ridgebotics.ridgescout.ui.transfer; package com.ridgebotics.ridgescout.ui.transfer;
//import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode; import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import static com.ridgebotics.ridgescout.utility.fileEditor.baseDir; import static com.ridgebotics.ridgescout.utility.FileEditor.baseDir;
import android.util.Log;
import com.ridgebotics.ridgescout.ui.data.FieldEditorHelper;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.SettingsManager;
import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPCmd;
import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TimeZone;
// This is now deprecated
// Class to synchronise data over FTP.
public class FTPSync extends Thread { public class FTPSync extends Thread {
public static final String remoteBasePath = "/RidgeScout/"; public static final String remoteBasePath = "/RidgeScout/";
public static final String timestampsFilename = "timestamps"; public static final String timestampsFilename = "timestamps";
@@ -122,7 +119,7 @@ public class FTPSync extends Thread {
public void run() { public void run() {
isRunning = true; isRunning = true;
boolean sendMetaFiles = settingsManager.getFTPSendMetaFiles(); boolean sendMetaFiles = SettingsManager.getFTPSendMetaFiles();
// Meta files // Meta files
List<String> meta_string_array = Arrays.asList( List<String> meta_string_array = Arrays.asList(
@@ -134,7 +131,7 @@ public class FTPSync extends Thread {
try { try {
// Login to FTP // Login to FTP
ftpClient = new FTPClient(); ftpClient = new FTPClient();
InetAddress address = InetAddress.getByName(settingsManager.getFTPServer()); InetAddress address = InetAddress.getByName(SettingsManager.getFTPServer());
ftpClient.connect(address); ftpClient.connect(address);
ftpClient.login("anonymous", null); ftpClient.login("anonymous", null);
ftpClient.enterLocalPassiveMode(); ftpClient.enterLocalPassiveMode();
@@ -162,13 +159,13 @@ public class FTPSync extends Thread {
if (remoteTimestamp == null || after(localTimeStamp, remoteTimestamp)) { if (remoteTimestamp == null || after(localTimeStamp, remoteTimestamp)) {
uploadFile(localFile); uploadFile(localFile);
System.out.println("Uploaded" + localFile.getName()); Log.i(getClass().toString(), "Uploaded" + localFile.getName());
setLocalFileTimestamp(localFile, curSyncTime); setLocalFileTimestamp(localFile, curSyncTime);
remoteTimestamps.put(localFile.getName(), curSyncTime); remoteTimestamps.put(localFile.getName(), curSyncTime);
upCount++; upCount++;
}else{ }else{
System.out.println("Did not upload"); Log.i(getClass().toString(), "Did not upload");
} }
} }
} }
@@ -197,24 +194,24 @@ public class FTPSync extends Thread {
if (!localFile.exists() || (after(remoteTimestamp, localTimeStamp) && !localTimeStamp.equals(remoteTimestamp))) { if (!localFile.exists() || (after(remoteTimestamp, localTimeStamp) && !localTimeStamp.equals(remoteTimestamp))) {
downloadFile(remoteFile, localFile); downloadFile(remoteFile, localFile);
System.out.println("Downloaded " + localFile.getName()); Log.i(getClass().toString(), "Downloaded " + localFile.getName());
if(!localFile.exists()) System.out.println("Not exist"); if(!localFile.exists()) Log.i(getClass().toString(), "Not exist");
else if(after(remoteTimestamp, localTimeStamp)) System.out.println("Before: " + (localTimeStamp.getTime()-remoteTimestamp.getTime())); else if(after(remoteTimestamp, localTimeStamp)) Log.i(getClass().toString(), "Before: " + (localTimeStamp.getTime()-remoteTimestamp.getTime()));
// Date d = getUtcTimestamp(remoteFile); // Date d = getUtcTimestamp(remoteFile);
setLocalFileTimestamp(localFile, remoteTimestamps.get(localFile.getName())); setLocalFileTimestamp(localFile, remoteTimestamps.get(localFile.getName()));
// remoteTimestamps.put(remoteFile, curSyncTime); // remoteTimestamps.put(remoteFile, curSyncTime);
downCount++; downCount++;
}else{ }else{
System.out.println("Did not download"); Log.i(getClass().toString(), "Did not download");
} }
} }
setTimestamps(remoteTimestamps); setTimestamps(remoteTimestamps);
} catch (Exception e) { } catch (Exception e) {
AlertManager.error(e); AlertManager.error("Failed Syncing!", e);
onResult.onResult(true, upCount, downCount); onResult.onResult(true, upCount, downCount);
setUpdateIndicator("ERROR!"); setUpdateIndicator("ERROR!");
} finally { } finally {
@@ -235,12 +232,12 @@ public class FTPSync extends Thread {
bb.addLong(timestamps.get(filenames[i]).getTime()); bb.addLong(timestamps.get(filenames[i]).getTime());
} }
fileEditor.writeFile(timestampsFilename, bb.build()); FileEditor.writeFile(timestampsFilename, bb.build());
uploadFile(new File(baseDir + timestampsFilename)); uploadFile(new File(baseDir + timestampsFilename));
return true; return true;
} catch (ByteBuilder.buildingException | IOException e) { } catch (ByteBuilder.buildingException | IOException e) {
e.printStackTrace(); AlertManager.error("Failed Syncing!", e);
return false; return false;
} }
} }
@@ -249,7 +246,7 @@ public class FTPSync extends Thread {
try { try {
downloadFile(timestampsFilename, new File(baseDir + timestampsFilename)); downloadFile(timestampsFilename, new File(baseDir + timestampsFilename));
byte[] data = fileEditor.readFile(timestampsFilename); byte[] data = FileEditor.readFile(timestampsFilename);
if(data == null || data.length == 0) if(data == null || data.length == 0)
return new HashMap<>(); return new HashMap<>();
@@ -268,7 +265,7 @@ public class FTPSync extends Thread {
return output; return output;
}catch (IOException | BuiltByteParser.byteParsingExeption e){ }catch (IOException | BuiltByteParser.byteParsingExeption e){
AlertManager.error(e); AlertManager.error("Failed Syncing!", e);
return new HashMap<>(); return new HashMap<>();
} }
} }
@@ -6,13 +6,13 @@ import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import com.ridgebotics.ridgescout.MainActivity; import com.ridgebotics.ridgescout.MainActivity;
import com.ridgebotics.ridgescout.types.file; import com.ridgebotics.ridgescout.types.ScoutingFile;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.SharePrompt; import com.ridgebotics.ridgescout.utility.SharePrompt;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@@ -20,28 +20,8 @@ import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
// Class to create the share and receive popups to transfer scouting data.
public class FileBundle { public class FileBundle {
private static final Intent FILE_SELECT_CODE = new Intent();
public static void send(String[] files, Context c){
try {
ByteBuilder b = new ByteBuilder();
for(int i = 0; i < files.length; i++){
if(!fileEditor.fileExist(files[i])) continue;
// byte[] data = fileEditor.readFile(files[i]);
file f = new file(files[i]);
b.addRaw(file.typecode, f.encode());
}
byte[] data = b.build();
send(data, c);
} catch (ByteBuilder.buildingException e) {
AlertManager.error(e);
}
}
public static void send(byte[] data, Context c){ public static void send(byte[] data, Context c){
String filename = DataManager.getevcode() + "-" + System.currentTimeMillis() + ".scoutbundle"; String filename = DataManager.getevcode() + "-" + System.currentTimeMillis() + ".scoutbundle";
SharePrompt.shareContent(c, filename, data, "application/ridgescout"); SharePrompt.shareContent(c, filename, data, "application/ridgescout");
@@ -58,6 +38,7 @@ public class FileBundle {
MainActivity.setResultRelay(new MainActivity.activityResultRelay() { MainActivity.setResultRelay(new MainActivity.activityResultRelay() {
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data == null) return;
Uri uri = data.getData(); Uri uri = data.getData();
if(uri == null) return; if(uri == null) return;
@@ -90,18 +71,18 @@ public class FileBundle {
for(int i = 0; i < parsedObjectList.size(); i++){ for(int i = 0; i < parsedObjectList.size(); i++){
BuiltByteParser.parsedObject pa = parsedObjectList.get(i); BuiltByteParser.parsedObject pa = parsedObjectList.get(i);
if(pa.getType() != file.typecode) continue; if(pa.getType() != ScoutingFile.typecode) continue;
file f = file.decode((byte[]) pa.get()); ScoutingFile f = ScoutingFile.decode((byte[]) pa.get());
if(f == null) continue; if(f == null) continue;
filenames.add(f.filename); filenames.add(f.filename);
fileEditor.writeFile(f.filename, f.data); FileEditor.writeFile(f.filename, f.data);
} }
AlertManager.alert("Saved", AlertManager.alert("Saved",
String.join("\n", filenames)); String.join("\n", filenames));
}catch (BuiltByteParser.byteParsingExeption e){ }catch (Exception e){
AlertManager.error(e); AlertManager.error("Failed saving files!", e);
} }
} }
} }
@@ -1,5 +1,7 @@
package com.ridgebotics.ridgescout.ui.transfer; package com.ridgebotics.ridgescout.ui.transfer;
import static com.ridgebotics.ridgescout.utility.Colors.fileselector_selected_color;
import static com.ridgebotics.ridgescout.utility.Colors.fileselector_unselected_color;
import static com.ridgebotics.ridgescout.utility.DataManager.evcode; import static com.ridgebotics.ridgescout.utility.DataManager.evcode;
import android.os.Bundle; import android.os.Bundle;
@@ -17,19 +19,18 @@ import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentTransferFileSelectorBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferFileSelectorBinding;
import com.ridgebotics.ridgescout.types.file; import com.ridgebotics.ridgescout.types.ScoutingFile;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.ByteBuilder; import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.ridgebotics.ridgescout.utility.DataManager; import com.ridgebotics.ridgescout.utility.DataManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
// Class to show a file browseer
public class FileSelectorFragment extends Fragment { public class FileSelectorFragment extends Fragment {
private static final int background_color = 0x5000ff00;
private static final int unselected_background_color = 0x2000ff00;
private static on_file_select onSelect = files -> {}; private static on_file_select onSelect = files -> {};
@@ -51,7 +52,7 @@ public class FileSelectorFragment extends Fragment {
evcode+".eventdata" evcode+".eventdata"
}; };
String[] files = fileEditor.getEventFiles(evcode); String[] files = FileEditor.getEventFiles(evcode);
Boolean[] selected_arr = new Boolean[files.length]; Boolean[] selected_arr = new Boolean[files.length];
Arrays.fill(selected_arr, Boolean.TRUE); Arrays.fill(selected_arr, Boolean.TRUE);
@@ -67,7 +68,7 @@ public class FileSelectorFragment extends Fragment {
tr.setPadding(20,20,20,20); tr.setPadding(20,20,20,20);
binding.fileSelectorTable.addView(tr); binding.fileSelectorTable.addView(tr);
tr.setBackgroundColor(background_color); tr.setBackgroundColor(fileselector_selected_color);
CheckBox checkBox = new CheckBox(getContext()); CheckBox checkBox = new CheckBox(getContext());
checkBox.setChecked(true); checkBox.setChecked(true);
@@ -83,7 +84,14 @@ public class FileSelectorFragment extends Fragment {
boolean sel = !selected_arr[fi]; boolean sel = !selected_arr[fi];
selected_arr[fi] = sel; selected_arr[fi] = sel;
tr.setBackgroundColor(sel ? background_color : unselected_background_color); tr.setBackgroundColor(sel ? fileselector_selected_color : fileselector_unselected_color);
((CheckBox) tr.getChildAt(0)).setChecked(sel);
});
checkBox.setOnClickListener(view -> {
boolean sel = !selected_arr[fi];
selected_arr[fi] = sel;
tr.setBackgroundColor(sel ? fileselector_selected_color : fileselector_unselected_color);
((CheckBox) tr.getChildAt(0)).setChecked(sel); ((CheckBox) tr.getChildAt(0)).setChecked(sel);
}); });
} }
@@ -97,7 +105,7 @@ public class FileSelectorFragment extends Fragment {
for(int i = 0; i < files.length; i++){ for(int i = 0; i < files.length; i++){
TableRow child = (TableRow) binding.fileSelectorTable.getChildAt(i); TableRow child = (TableRow) binding.fileSelectorTable.getChildAt(i);
child.setBackgroundColor(background_color); child.setBackgroundColor(fileselector_selected_color);
boolean sel = is_in_search_param(files[i], search_param, match_num_nums); boolean sel = is_in_search_param(files[i], search_param, match_num_nums);
child.setVisibility(sel ? View.VISIBLE : View.GONE); child.setVisibility(sel ? View.VISIBLE : View.GONE);
((CheckBox) child.getChildAt(0)).setChecked(sel); ((CheckBox) child.getChildAt(0)).setChecked(sel);
@@ -188,8 +196,21 @@ public class FileSelectorFragment extends Fragment {
ByteBuilder b = new ByteBuilder(); ByteBuilder b = new ByteBuilder();
for(int i = 0; i < filenames.size(); i++){ for(int i = 0; i < filenames.size(); i++){
file f = new file(filenames.get(i)); ScoutingFile f = new ScoutingFile(filenames.get(i));
b.addRaw(file.typecode, f.encode());
if(!FileEditor.fileExist(f.filename)) {
AlertManager.addSimpleError("File " + f.filename + " Does not exist!");
continue;
};
byte[] bytes = f.encode();
if(bytes == null || bytes.length == 0) {
AlertManager.addSimpleError("File " + f.filename + " Has no data!");
continue;
};
b.addRaw(ScoutingFile.typecode, bytes);
} }
return b.build(); return b.build();
@@ -0,0 +1,369 @@
package com.ridgebotics.ridgescout.ui.transfer;
import static com.ridgebotics.ridgescout.utility.FileEditor.baseDir;
import android.util.Log;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.ByteBuilder;
import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.utility.HttpGetFile;
import com.ridgebotics.ridgescout.utility.HttpPutFile;
import com.ridgebotics.ridgescout.utility.RequestTask;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
// This is now deprsicated
// Class to syncronise data over FTP.
public class HttpSync extends Thread {
public static final String timestampsFilename = "timestamps";
private static final long millisTolerance = 1000;
private boolean after(Date a, Date b){
return a.getTime() - b.getTime() > millisTolerance;
}
public interface onResult {
void onResult(boolean error, int upCount, int downCount);
}
public interface UpdateIndicator {
void onText(String text);
}
private static UpdateIndicator updateIndicator = text -> {};
public static String text = "";
private static void setUpdateIndicator(String m_text){
text = m_text;
updateIndicator.onText(m_text);
}
public static void setOnUpdateIndicator(UpdateIndicator m_updateIndicator){
updateIndicator = m_updateIndicator;
}
private static onResult onResult = (error, upCount, downCount) -> {};
public static void setOnResult(onResult result){
onResult = result;
}
private static boolean isRunning = false;
public static boolean getIsRunning(){return isRunning;}
public static void sync(){
// DataManager.reload_event();
HttpSync sync = new HttpSync();
sync.start();
}
private int upCount = 0;
private int downCount = 0;
private class TransferFile {
public String filename;
public Date updated;
public String checksum;
}
private List<TransferFile> localFiles = new ArrayList<>();
private List<TransferFile> remoteFiles = new ArrayList<>();
private void await() {
while(!runningRequest.get()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
AtomicBoolean runningRequest = new AtomicBoolean(false);
public void run() {
isRunning = true;
boolean sendMetaFiles = SettingsManager.getFTPSendMetaFiles();
String serverIP = SettingsManager.getFTPServer();
String serverKey = SettingsManager.getFTPKey();
setUpdateIndicator("Getting Metadata...");
// Load metadata from server
getRemoteFileMetadata(serverIP, serverKey);
if(!isRunning){
setUpdateIndicator("Error Connecting");
onResult.onResult(true, upCount, downCount);
return;
}
getLocalFileMetadata();
// Wait for metadata request to finish
setUpdateIndicator("Uploading 0%");
for(int i = 0; i < localFiles.size(); i++){
TransferFile localFile = localFiles.get(i);
TransferFile remoteFile = findInFileArray(remoteFiles, localFile.filename);
if(
(
sendMetaFiles || !(
localFile.filename.endsWith(".fields")
)
)
&& (remoteFile == null ||
(
!Objects.equals(localFile.checksum, remoteFile.checksum) &&
after(localFile.updated, remoteFile.updated)
)
)) {
uploadFile(localFile, serverIP, serverKey);
// await();
Log.d(getClass().toString(), "LocalFile: " + localFile.filename + ", " + localFile.checksum + ", " + localFile.updated + ": Uploaded");
upCount++;
}else {
Log.d(getClass().toString(), "LocalFile: " + localFile.filename + ", " + localFile.checksum + ", " + localFile.updated + ": Not uploaded");
}
setUpdateIndicator("Uploading " + (Math.floor((double) (i * 1000) / localFiles.size()) / 10) + "%");
}
setUpdateIndicator("Downloading 0%");
for(int i = 0; i < remoteFiles.size(); i++){
TransferFile remoteFile = remoteFiles.get(i);
TransferFile localFile = findInFileArray(localFiles, remoteFile.filename);
if(localFile == null ||
(
!Objects.equals(localFile.checksum, remoteFile.checksum) &&
after(remoteFile.updated, localFile.updated) &&
!localFile.updated.equals(remoteFile.updated)
)
) {
downloadFile(remoteFile, serverIP);
// await();
Log.d(getClass().toString(), "RemoteFile: " + remoteFile.filename + ", " + remoteFile.checksum + ", " + remoteFile.updated + ": Downloaded");
downCount++;
} else {
Log.d(getClass().toString(), "RemoteFile: " + remoteFile.filename + ", " + remoteFile.checksum + ", " + remoteFile.updated + ": Not downloaded");
}
setUpdateIndicator("Downloading " + (Math.floor((double) (i * 1000) / remoteFiles.size()) / 10) + "%");
}
setUpdateIndicator("Finished, " + upCount + " Up, " + downCount + " Down");
onResult.onResult(false, upCount, downCount);
isRunning = false;
}
private TransferFile findInFileArray(List<TransferFile> files, String filename){
for(TransferFile file : files) {
if(file.filename.equals(filename))
return file;
}
return null;
}
private Date getLocalFileUtcTimestamp(File file) {
return new Date(file.lastModified());
}
public static String getSHA256Hash(String filePath) throws IOException, NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
FileInputStream fis = new FileInputStream(filePath);
byte[] byteArray = new byte[1024];
int bytesCount = 0;
while ((bytesCount = fis.read(byteArray)) != -1) {
digest.update(byteArray, 0, bytesCount);
}
fis.close();
byte[] bytes = digest.digest();
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
private void getLocalFileMetadata() {
File localDir = new File(baseDir);
File[] localFileNames = localDir.listFiles();
assert localFileNames != null;
for (int i = 0; i < localFileNames.length; i++) {
File file = localFileNames[i];
if(file.isDirectory()) continue;
// Remove timestamts file
if(file.getName().equals(timestampsFilename)) continue;
TransferFile tf = new TransferFile();
tf.filename = file.getName();
tf.updated = getLocalFileUtcTimestamp(file);
try {
tf.checksum = getSHA256Hash(file.getPath());
} catch (Exception e) {
}
localFiles.add(tf);
}
}
// Send request to server and retrieve metadata
private void getRemoteFileMetadata(String serverURL, String serverKey) {
final RequestTask rq = new RequestTask();
runningRequest.set(false);
rq.onResult(metadata -> {
try {
JSONObject j = new JSONObject(metadata);
for (Iterator<String> it = j.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject obj = j.getJSONObject(key);
TransferFile tf = new TransferFile();
tf.filename = key;
tf.updated = new Date(Long.parseLong(obj.getString("modified")));
tf.checksum = obj.getString("sha256");
remoteFiles.add(tf);
}
}catch(JSONException | NullPointerException e ) {
AlertManager.error(e);
isRunning = false;
}
runningRequest.set(true);
return null;
});
rq.execute((serverURL + "/api/metadata"), "api_key: " + serverKey);
await();
}
// private boolean setTimestamps(Map<String, Date> timestamps){
// try {
// ByteBuilder bb = new ByteBuilder();
// String[] filenames = timestamps.keySet().toArray(new String[0]);
//
// for(int i = 0; i < filenames.length; i++){
// bb.addString(filenames[i]);
// bb.addLong(timestamps.get(filenames[i]).getTime());
// }
//
// FileEditor.writeFile(timestampsFilename, bb.build());
//
// uploadFile(new File(baseDir + timestampsFilename));
// return true;
// } catch (ByteBuilder.buildingException | IOException e) {
// AlertManager.error("Failed Syncing!", e);
// return false;
// }
// }
//
// private Map<String, Date> getTimestamps() {
// try {
// downloadFile(timestampsFilename, new File(baseDir + timestampsFilename));
//
// byte[] data = FileEditor.readFile(timestampsFilename);
//
// if(data == null || data.length == 0)
// return new HashMap<>();
//
// BuiltByteParser bbp = new BuiltByteParser(data);
// List<BuiltByteParser.parsedObject> pa = bbp.parse();
//
// Map<String, Date> output = new HashMap<>();
// for(int i = 0; i < pa.size(); i+=2){
//// System.out.println((long) pa.get(i).get());
// output.put(
// (String) pa.get(i).get(),
// new Date((long) pa.get(i+1).get())
// );
// }
// return output;
//
// }catch (IOException | BuiltByteParser.byteParsingExeption e){
// AlertManager.error("Failed Syncing!", e);
// return new HashMap<>();
// }
// }
void uploadFile(TransferFile tf, String serverURL, String apiKey) {
runningRequest.set(false);
HttpPutFile uploadTask = new HttpPutFile(serverURL + "/api/" + tf.filename, new File(baseDir + tf.filename), new HttpPutFile.UploadCallback() {
@Override
public void onResult(String error) {
if(error != null)
AlertManager.error(error);
runningRequest.set(true);
}
}, new String[]{
"api_key: " + apiKey,
("modified: " + tf.updated.getTime())
}); // Pass auth token if needed
uploadTask.execute();
await();
}
private void setLocalFileTimestamp(File file, Date date) {
file.setLastModified(date.getTime());
}
void downloadFile(TransferFile tf, String serverURL) {
runningRequest.set(false);
File f = new File(baseDir + tf.filename);
HttpGetFile uploadTask = new HttpGetFile(serverURL + "/api/" + tf.filename, f, new HttpGetFile.DownloadCallback() {
@Override
public void onResult(String error) {
if(error != null)
AlertManager.error(error);
else
setLocalFileTimestamp(f, tf.updated);
runningRequest.set(true);
}
}); // Pass auth token if needed
uploadTask.execute();
await();
}
}
@@ -1,5 +1,13 @@
package com.ridgebotics.ridgescout.ui.transfer; package com.ridgebotics.ridgescout.ui.transfer;
import static androidx.navigation.fragment.FragmentKt.findNavController;
import static com.ridgebotics.ridgescout.utility.Colors.tba_blue;
import static com.ridgebotics.ridgescout.utility.Colors.tba_red;
import static com.ridgebotics.ridgescout.utility.Colors.tba_toggle_background;
import static com.ridgebotics.ridgescout.utility.FileEditor.TBAAddress;
import static com.ridgebotics.ridgescout.utility.FileEditor.TBAHeader;
import android.app.ProgressDialog;
import android.os.Bundle; import android.os.Bundle;
import android.view.Gravity; import android.view.Gravity;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@@ -14,136 +22,59 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.databinding.FragmentTransferTbaBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferTbaBinding;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.RequestTask;
import com.ridgebotics.ridgescout.types.frcEvent; import com.ridgebotics.ridgescout.types.frcEvent;
import com.ridgebotics.ridgescout.types.frcMatch; import com.ridgebotics.ridgescout.types.frcMatch;
import com.ridgebotics.ridgescout.types.frcTeam; import com.ridgebotics.ridgescout.types.frcTeam;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.ImageRequestTask;
import com.ridgebotics.ridgescout.utility.JSONUtil; import com.ridgebotics.ridgescout.utility.JSONUtil;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.RequestTask;
import com.ridgebotics.ridgescout.utility.FileEditor;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
public class TBAFragment extends Fragment { // Class to download data from a specific event and encode it.
private static final String TBAAddress = "https://www.thebluealliance.com/api/v3/"; public class TBAEventFragment extends Fragment {
private static final String TBAHeader = "X-TBA-Auth-Key: tjEKSZojAU2pgbs2mBt06SKyOakVhLutj3NwuxLTxPKQPLih11aCIwRIVFXKzY4e";
private android.widget.TableLayout Table; private TableLayout Table;
private FragmentTransferTbaBinding binding; private FragmentTransferTbaBinding binding;
private final int year = settingsManager.getYearNum(); private final int year = SettingsManager.getYearNum();
private ProgressDialog loadingDialog;
private static JSONObject eventData = null;
public static void setEventData(JSONObject j){
eventData = j;
}
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) { @Nullable Bundle savedInstanceState) {
binding = FragmentTransferTbaBinding.inflate(inflater, container, false); binding = FragmentTransferTbaBinding.inflate(inflater, container, false);
final String matchKey;
try {
matchKey = eventData.getString("key");
} catch (JSONException e) {
AlertManager.error("Failed loading event key!", e);
return binding.getRoot();
}
Table = binding.matchTable; Table = binding.matchTable;
Table.setStretchAllColumns(true); Table.setStretchAllColumns(true);
TableRow tr = new TableRow(getContext()); startLoading("Loading Teams and Matches...");
addTableText(tr, "Loading Events...");
Table.addView(tr);
final RequestTask rq = new RequestTask();
rq.onResult(s -> {
if(s == null || s.isEmpty()) {
AlertManager.error("Could not fetch event!");
return null;
}
eventTable(s);
return null;
});
rq.execute(TBAAddress + "events/"+year, TBAHeader);
return binding.getRoot();
}
private void addTableText(TableRow tr, String textStr){
TextView text = new TextView(getContext());
text.setTextSize(18);
text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); // Text align center
text.setText(textStr);
tr.addView(text);
}
public void eventTable(String dataString){
Table.removeAllViews();
Table.setStretchAllColumns(true);
Table.bringToFront();
Date currentTime = Calendar.getInstance().getTime();
try {
JSONArray data = new JSONArray(dataString);
Table.setStretchAllColumns(true);
Table.bringToFront();
boolean toggle = false;
for(int i=0;i<data.length();i++){
TableRow tr = new TableRow(getContext());
TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT
);
rowParams.setMargins(20,20,20,20);
tr.setLayoutParams(rowParams);
tr.setPadding(20,20,20,20);
tr.setBackgroundColor(0x30000000);
JSONObject j = data.getJSONObject(i);
String matchKey = j.getString("key");
String name = j.getString("short_name");
// Sometimes, a short name is not present on TBA Events
if(name.isEmpty()){
name = j.getString("name");
}
TextView tv = new TextView(getContext());
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setTextSize(12);
tv.setText(j.getString("key"));
tr.addView(tv);
tv = new TextView(getContext());
tv.setTextSize(18);
tv.setText(name);
tr.addView(tv);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date startDate = format.parse(j.getString("start_date"));
Date endDate = format.parse(j.getString("end_date"));
if(currentTime.after(endDate)){
tr.setBackgroundColor(0x30FF0000);
}else if(currentTime.before(startDate)){
tr.setBackgroundColor(0x3000FF00);
}else if(currentTime.after(startDate) && currentTime.before(endDate)){
tr.setBackgroundColor(0x30FFFF00);
}
} catch (Exception e) {
AlertManager.error(e);
}
tr.setOnClickListener(v -> {
Table.removeAllViews(); Table.removeAllViews();
Table.setStretchAllColumns(true); Table.setStretchAllColumns(true);
Table.bringToFront(); Table.bringToFront();
@@ -160,39 +91,25 @@ public class TBAFragment extends Fragment {
final RequestTask rq1 = new RequestTask(); final RequestTask rq1 = new RequestTask();
rq1.onResult(matchesStr -> { rq1.onResult(matchesStr -> {
matchTable(matchesStr, teamsStr, j); matchTable(matchesStr, teamsStr, eventData);
stopLoading();
return null; return null;
}); });
rq1.execute((TBAAddress + "event/" + matchKey + "/matches"), TBAHeader); rq1.execute((TBAAddress + "event/" + matchKey + "/matches"), TBAHeader);
return null; return null;
}); });
rq.execute((TBAAddress + "event/" + matchKey + "/teams"), TBAHeader); rq.execute((TBAAddress + "event/" + matchKey + "/teams"), TBAHeader);
});
// tr.addView(cl); return binding.getRoot();
Table.addView(tr, rowParams);
toggle = !toggle;
}
}catch (JSONException j){
AlertManager.alert("Error", "Invalid JSON");
}
} }
static class matchComparator implements Comparator<JSONObject> private void addTableText(TableRow tr, String textStr){
{ TextView text = new TextView(getContext());
text.setTextSize(18);
public int compare(JSONObject a, JSONObject b) text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); // Text align center
{ text.setText(textStr);
try { tr.addView(text);
return a.getInt("match_number") - b.getInt("match_number");
}catch (JSONException j){
return 0;
} }
}
}
public void matchTable(String matchesString, String teamsString, JSONObject eventData){ public void matchTable(String matchesString, String teamsString, JSONObject eventData){
Table.removeAllViews(); Table.removeAllViews();
@@ -347,11 +264,7 @@ public class TBAFragment extends Fragment {
final ArrayList<frcMatch> matchesOBJ = new ArrayList<>(); final ArrayList<frcMatch> matchesOBJ = new ArrayList<>();
btn.setOnClickListener(v -> { btn.setOnClickListener(v -> {
if(saveData(matchesOBJ, teamData, eventData)){ saveData(matchesOBJ, teamData, eventData);
AlertManager.alert("Info", "Saved!");
}else{
AlertManager.alert("Error", "Error saving files.");
}
}); });
@@ -412,7 +325,7 @@ public class TBAFragment extends Fragment {
tr = new TableRow(getContext()); tr = new TableRow(getContext());
if (toggle) { if (toggle) {
tr.setBackgroundColor(0x30000000); tr.setBackgroundColor(tba_toggle_background);
} }
addTableText(tr, String.valueOf(matchCount)); addTableText(tr, String.valueOf(matchCount));
@@ -431,12 +344,12 @@ public class TBAFragment extends Fragment {
String str = redAlliance.getString(b).substring(3); String str = redAlliance.getString(b).substring(3);
redKeys[b] = Integer.parseInt(str); redKeys[b] = Integer.parseInt(str);
text.setText(str); text.setText(str);
text.setBackgroundColor(0x50ff0000); text.setBackgroundColor(tba_red);
}else{ }else{
String str = blueAlliance.getString(b-3).substring(3); String str = blueAlliance.getString(b-3).substring(3);
blueKeys[b-3] = Integer.parseInt(str); blueKeys[b-3] = Integer.parseInt(str);
text.setText(str); text.setText(str);
text.setBackgroundColor(0x500000ff); text.setBackgroundColor(tba_blue);
} }
} }
@@ -461,24 +374,26 @@ public class TBAFragment extends Fragment {
// }); // });
}catch (JSONException j){ }catch (JSONException j){
AlertManager.error(j); AlertManager.error("Failed Downloading", j);
AlertManager.alert("Error", "Invalid JSON"); stopLoading();
} }
} }
private boolean saveData(ArrayList<frcMatch> matchData, JSONArray teamData, JSONObject eventData){ private boolean saveData(ArrayList<frcMatch> matchData, JSONArray teamData, JSONObject eventData){
startLoading("Saving data...");
Thread t = new Thread(() -> {
try { try {
final String matchKey = eventData.getString("key"); final String matchKey = eventData.getString("key");
String matchName = eventData.getString("short_name"); String matchName = eventData.getString("short_name");
// Sometimes, a short name is not present on TBA Events // Sometimes, a short name is not present on TBA Events
if(matchName.isEmpty()){ if (matchName.isEmpty()) {
matchName = eventData.getString("name"); matchName = eventData.getString("name");
} }
ArrayList<frcTeam> teams = new ArrayList<>(); ArrayList<frcTeam> teams = new ArrayList<>();
for(int i=0;i<teamData.length();i++){ for (int i = 0; i < teamData.length(); i++) {
frcTeam teamObj = new frcTeam(); frcTeam teamObj = new frcTeam();
JSONObject team = teamData.getJSONObject(i); JSONObject team = teamData.getJSONObject(i);
@@ -490,7 +405,20 @@ public class TBAFragment extends Fragment {
teamObj.country = team.getString("country"); teamObj.country = team.getString("country");
teamObj.startingYear = team.getInt("rookie_year"); teamObj.startingYear = team.getInt("rookie_year");
ImageRequestTask imageRequestTask = new ImageRequestTask();
imageRequestTask.onResult(bitmap -> {
teamObj.bitmap = bitmap;
teamObj.teamColor = frcTeam.findPrimaryColor(bitmap);
teams.add(teamObj); teams.add(teamObj);
return null;
});
imageRequestTask.execute("https://www.thebluealliance.com/avatar/" + year + "/frc" + teamObj.teamNumber + ".png");
}
while (teams.size() != teamData.length()) {
Thread.sleep(100);
} }
frcEvent event = new frcEvent(); frcEvent event = new frcEvent();
@@ -499,11 +427,35 @@ public class TBAFragment extends Fragment {
event.teams = teams; event.teams = teams;
event.matches = matchData; event.matches = matchData;
return fileEditor.setEvent(event); FileEditor.setEvent(event);
}catch (JSONException j){ AlertManager.toast("Saved!");
getActivity().runOnUiThread(() -> findNavController(this).navigate(R.id.action_navigation_tba_event_to_navigation_transfer));
stopLoading();
}catch(Exception j) {
AlertManager.error(j); AlertManager.error(j);
AlertManager.alert("Error", "Invalid JSON"); stopLoading();
}
});
t.start();
return false; return false;
} }
private void startLoading(String title){
getActivity().runOnUiThread(() -> {
if(loadingDialog != null && loadingDialog.isShowing())
loadingDialog.dismiss();
loadingDialog = ProgressDialog.show(getActivity(), title, "Please wait...");
});
}
private void stopLoading(){
getActivity().runOnUiThread(() -> {
if (loadingDialog != null)
loadingDialog.cancel();
loadingDialog = null;
});
} }
} }
@@ -0,0 +1,227 @@
package com.ridgebotics.ridgescout.ui.transfer;
import static androidx.navigation.fragment.FragmentKt.findNavController;
import static com.ridgebotics.ridgescout.utility.Colors.tba_current;
import static com.ridgebotics.ridgescout.utility.Colors.tba_next;
import static com.ridgebotics.ridgescout.utility.Colors.tba_previous;
import static com.ridgebotics.ridgescout.utility.FileEditor.TBAAddress;
import static com.ridgebotics.ridgescout.utility.FileEditor.TBAHeader;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.databinding.FragmentTransferTbaBinding;
import com.ridgebotics.ridgescout.ui.views.TBAEventOption;
import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.RequestTask;
import com.ridgebotics.ridgescout.utility.SettingsManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
// Class to select an event from TBA and redirect to TBAEventFragment.java.
public class TBASelectorFragment extends Fragment {
private android.widget.TableLayout Table;
private FragmentTransferTbaBinding binding;
private final int year = SettingsManager.getYearNum();
private ProgressDialog loadingDialog;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentTransferTbaBinding.inflate(inflater, container, false);
Table = binding.matchTable;
Table.setStretchAllColumns(true);
TableRow tr = new TableRow(getContext());
addTableText(tr, "Loading Events...");
Table.addView(tr);
startLoading("Loading Events...");
final RequestTask rq = new RequestTask();
rq.onResult(s -> {
if(s == null || s.isEmpty()) {
AlertManager.error("Could not fetch event!");
stopLoading();
return null;
}
eventTable(s);
return null;
});
rq.execute(TBAAddress + "events/"+year, TBAHeader);
return binding.getRoot();
}
private void addTableText(TableRow tr, String textStr){
TextView text = new TextView(getContext());
text.setTextSize(18);
text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); // Text align center
text.setText(textStr);
tr.addView(text);
}
public static int getEventTypeWeight(String type){
switch(type){
case "Preseason": return -3;
case "District": return -2;
case "Regional": return -1;
case "District Championship Division": return 0;
case "District Championship": return 1;
case "Championship Divison": return 2;
case "Championship Finals": return 3;
case "Offseason": return 4;
}
return 0;
}
public void eventTable(String dataString){
Table.removeAllViews();
Table.setStretchAllColumns(true);
Table.bringToFront();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date currentTime = Calendar.getInstance().getTime();
try {
JSONArray events = new JSONArray(dataString);
List<JSONObject> data = new ArrayList<>();
for(int i = 0; i < events.length(); i++){
data.add(events.getJSONObject(i));
}
// Sort events by date, and then type
data.sort((a, b) -> {
try {
// return (int) (currentTime.getTime() - format.parse(a.getString("start_date")).getTime())
// -
// (int) (currentTime.getTime() - format.parse(b.getString("start_date")).getTime());
int diff = format.parse(a.getString("start_date")).compareTo(format.parse(b.getString("start_date"))) * 10;
if(diff == 0){
diff = getEventTypeWeight(a.getString("event_type_string")) - getEventTypeWeight(b.getString("event_type_string"));
}
if(diff == 0){
diff = a.getString("key").compareTo(b.getString("key"));
}
return diff;
} catch (ParseException | JSONException e) {
AlertManager.error(e);
return 0;
}
});
boolean toggle = false;
for(int i=0;i<data.size();i++){
JSONObject j = data.get(i);
TBAEventOption row = new TBAEventOption(getContext());
// TableRow tr = new TableRow(getContext());
// TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
// TableRow.LayoutParams.WRAP_CONTENT,
// TableRow.LayoutParams.WRAP_CONTENT
// );
// rowParams.setMargins(20,20,20,20);
// tr.setLayoutParams(rowParams);
// tr.setPadding(20,20,20,20);
row.setBackgroundColor(0x30000000);
String name = j.getString("short_name");
// Sometimes, a short name is not present on TBA Events
if(name.isEmpty()){
name = j.getString("name");
}
String eventType = j.getString("event_type_string");
if(eventType.equals("District") || eventType.equals("Regional"))
eventType = "Week " + (j.getInt("week")+1) + " " + eventType;
row.setName(name);
row.setCode(j.getString("key"));
row.setType(eventType);
try {
Date startDate = format.parse(j.getString("start_date"));
Date endDate = format.parse(j.getString("end_date"));
if(currentTime.after(endDate)){
row.setColor(tba_previous);
}else if(currentTime.before(startDate)){
row.setColor(tba_next);
}else if(currentTime.after(startDate) && currentTime.before(endDate)){
row.setColor(tba_current);
}
} catch (Exception e) {
AlertManager.error("Failed finding start and end dates!", e);
stopLoading();
}
row.setOnClickListener(v -> {
TBAEventFragment.setEventData(j);
findNavController(this).navigate(R.id.action_navigation_tba_selector_to_navigation_tba_event);
});
// tr.addView(cl);
Table.addView(row);
toggle = !toggle;
}
stopLoading();
}catch (JSONException j){
AlertManager.error("Failed Downloading", j);
stopLoading();
}
}
private void startLoading(String title){
getActivity().runOnUiThread(() -> {
if(loadingDialog != null && loadingDialog.isShowing())
loadingDialog.dismiss();
loadingDialog = ProgressDialog.show(getActivity(), title, "Please wait...");
});
}
private void stopLoading(){
getActivity().runOnUiThread(() -> {
if (loadingDialog != null)
loadingDialog.cancel();
loadingDialog = null;
});
}
}
@@ -3,7 +3,6 @@ package com.ridgebotics.ridgescout.ui.transfer;
import static androidx.navigation.fragment.FragmentKt.findNavController; import static androidx.navigation.fragment.FragmentKt.findNavController;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@@ -15,15 +14,12 @@ import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.R; import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.settingsManager; import com.ridgebotics.ridgescout.utility.SettingsManager;
import com.ridgebotics.ridgescout.databinding.FragmentTransferBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferBinding;
import com.ridgebotics.ridgescout.ui.transfer.bluetooth.BluetoothSenderFragment; import com.ridgebotics.ridgescout.ui.transfer.bluetooth.BluetoothSenderFragment;
import com.ridgebotics.ridgescout.ui.transfer.codes.CodeGeneratorView; import com.ridgebotics.ridgescout.ui.transfer.codes.CodeGeneratorView;
import org.apache.commons.net.ftp.FTP; // Class to do transference.
import java.util.Date;
public class TransferFragment extends Fragment { public class TransferFragment extends Fragment {
private FragmentTransferBinding binding; private FragmentTransferBinding binding;
@@ -36,9 +32,6 @@ public class TransferFragment extends Fragment {
String evcode; String evcode;
private static final int background_color = 0x5000ff00;
private static final int unselected_background_color = 0x2000ff00;
// private Bundle b; // private Bundle b;
@Nullable @Nullable
@@ -50,35 +43,35 @@ public class TransferFragment extends Fragment {
binding = FragmentTransferBinding.inflate(inflater, container, false); binding = FragmentTransferBinding.inflate(inflater, container, false);
evcode = settingsManager.getEVCode(); evcode = SettingsManager.getEVCode();
binding.downloadButton.setOnClickListener(v -> { binding.downloadButton.setOnClickListener(v -> {
start_download(); start_download();
}); });
binding.TBAButton.setOnClickListener(v -> { binding.TBAButton.setOnClickListener(v -> {
findNavController(this).navigate(R.id.action_navigation_transfer_to_navigation_tba); findNavController(this).navigate(R.id.action_navigation_transfer_to_navigation_tba_selector);
}); });
if(!settingsManager.getWifiMode()) { if(!SettingsManager.getWifiMode()) {
binding.TBAButton.setEnabled(false); binding.TBAButton.setEnabled(false);
binding.SyncButton.setEnabled(false); binding.SyncButton.setEnabled(false);
} }
if(!settingsManager.getFTPEnabled()) { if(!SettingsManager.getFTPEnabled()) {
binding.SyncButton.setEnabled(false); binding.SyncButton.setEnabled(false);
} }
binding.SyncButton.setOnClickListener(v -> { binding.SyncButton.setOnClickListener(v -> {
binding.SyncButton.setEnabled(false); binding.SyncButton.setEnabled(false);
FTPSync.sync(); HttpSync.sync();
}); });
if(FTPSync.getIsRunning()) if(HttpSync.getIsRunning())
binding.SyncButton.setEnabled(false); binding.SyncButton.setEnabled(false);
FTPSync.setOnResult((error, upcount, downcount) -> { HttpSync.setOnResult((error, upcount, downcount) -> {
if (getActivity() != null) if (getActivity() != null)
getActivity().runOnUiThread(() -> { getActivity().runOnUiThread(() -> {
binding.SyncButton.setEnabled(true); binding.SyncButton.setEnabled(true);
@@ -86,8 +79,8 @@ public class TransferFragment extends Fragment {
}); });
}); });
binding.syncIndicator.setText(FTPSync.text); binding.syncIndicator.setText(HttpSync.text);
FTPSync.setOnUpdateIndicator(text -> {if(getActivity() != null) getActivity().runOnUiThread(() -> binding.syncIndicator.setText(text));}); HttpSync.setOnUpdateIndicator(text -> {if(getActivity() != null) getActivity().runOnUiThread(() -> binding.syncIndicator.setText(text));});
if(evcode.equals("unset")){ if(evcode.equals("unset")){
binding.noEventError.setVisibility(View.VISIBLE); binding.noEventError.setVisibility(View.VISIBLE);
@@ -11,6 +11,7 @@ import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentTransferSelectorBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferSelectorBinding;
// The transfer method selector
public class TransferSelectorFragment extends Fragment { public class TransferSelectorFragment extends Fragment {
// Declaring three blank funcs in one line lol // Declaring three blank funcs in one line lol
@@ -8,6 +8,7 @@ import android.bluetooth.BluetoothSocket;
import android.content.Context; import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
import android.util.Log;
import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
@@ -20,11 +21,10 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
// Helper class for bluetooth reciever.
public class BluetoothReceiver { public class BluetoothReceiver {
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String NAME = "BluetoothReceiverApp"; private static final String NAME = "BluetoothReceiverApp";
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_PERMISSIONS = 2;
private Context context; private Context context;
private BluetoothAdapter bluetoothAdapter; private BluetoothAdapter bluetoothAdapter;
@@ -140,7 +140,7 @@ public class BluetoothReceiver {
} catch (IOException e) { } catch (IOException e) {
if (e.getMessage() != null && e.getMessage().contains("bt socket closed, read return: -1")) { if (e.getMessage() != null && e.getMessage().contains("bt socket closed, read return: -1")) {
receiveddata.onConnectionStop(); receiveddata.onConnectionStop();
System.out.println("Bluetooth socket closed, treating as end of stream"); Log.i(getClass().toString(), "Bluetooth socket closed, treating as end of stream");
} else { } else {
throw e; throw e;
} }
@@ -1,6 +1,7 @@
package com.ridgebotics.ridgescout.ui.transfer.bluetooth; package com.ridgebotics.ridgescout.ui.transfer.bluetooth;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@@ -12,16 +13,17 @@ import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentTransferBluetoothReceiverBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferBluetoothReceiverBinding;
import com.ridgebotics.ridgescout.types.file; import com.ridgebotics.ridgescout.types.ScoutingFile;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.zip.DataFormatException; import java.util.zip.DataFormatException;
// Class to receive bluetooth transmissions from other devices
public class BluetoothReceiverFragment extends Fragment { public class BluetoothReceiverFragment extends Fragment {
private BluetoothReceiver bluetoothReceiver; private BluetoothReceiver bluetoothReceiver;
private Button startListeningButton; private Button startListeningButton;
@@ -68,12 +70,12 @@ public class BluetoothReceiverFragment extends Fragment {
statusTextView = binding.statusTextView; statusTextView = binding.statusTextView;
if (!bluetoothReceiver.isBluetoothSupported()) { if (!bluetoothReceiver.isBluetoothSupported()) {
AlertManager.error("Bluetooth is not supported on this device"); AlertManager.addSimpleError("Bluetooth is not supported on this device");
return binding.getRoot(); return binding.getRoot();
} }
if (!bluetoothReceiver.isBluetoothEnabled()) { if (!bluetoothReceiver.isBluetoothEnabled()) {
AlertManager.error("Please enable Bluetooth"); AlertManager.addSimpleError("Please enable Bluetooth");
} }
startListeningButton.setOnClickListener(v -> { startListeningButton.setOnClickListener(v -> {
@@ -97,7 +99,7 @@ public class BluetoothReceiverFragment extends Fragment {
recievedBytes = new ArrayList<>(); recievedBytes = new ArrayList<>();
} catch (IOException e) { } catch (IOException e) {
AlertManager.error("Failed to start listening: " + e.getMessage()); AlertManager.error("Failed to start listening", e);
} }
} }
@@ -108,15 +110,15 @@ public class BluetoothReceiverFragment extends Fragment {
startListeningButton.setEnabled(true); startListeningButton.setEnabled(true);
stopListeningButton.setEnabled(false); stopListeningButton.setEnabled(false);
} catch (IOException e) { } catch (IOException e) {
AlertManager.error("Failed to stop listening: " + e.getMessage()); AlertManager.error("Failed to stop listening: " + e.getMessage(), e);
} }
} }
private List<byte[]> recievedBytes; private List<byte[]> recievedBytes;
private void receiveData(byte[] data, int bytes) { private void receiveData(byte[] data, int bytes) {
byte[] newBytes = fileEditor.getByteBlock(data, 0, bytes); byte[] newBytes = FileEditor.getByteBlock(data, 0, bytes);
System.out.println("Recieved " + bytes + " Bytes over bluetooth!"); Log.i(getClass().toString(), "Recieved " + bytes + " Bytes over bluetooth!");
recievedBytes.add(newBytes); recievedBytes.add(newBytes);
} }
@@ -125,19 +127,19 @@ public class BluetoothReceiverFragment extends Fragment {
String result_filenames = ""; String result_filenames = "";
try { try {
byte[] resultBytes = fileEditor.combineByteArrays(recievedBytes); byte[] resultBytes = FileEditor.combineByteArrays(recievedBytes);
resultBytes = fileEditor.blockUncompress(resultBytes); resultBytes = FileEditor.blockUncompress(resultBytes);
BuiltByteParser bbp = new BuiltByteParser(resultBytes); BuiltByteParser bbp = new BuiltByteParser(resultBytes);
ArrayList<BuiltByteParser.parsedObject> result = bbp.parse(); ArrayList<BuiltByteParser.parsedObject> result = bbp.parse();
for (int i = 0; i < result.size(); i++) { for (int i = 0; i < result.size(); i++) {
if (result.get(i).getType() != file.typecode) continue; if (result.get(i).getType() != ScoutingFile.typecode) continue;
file f = file.decode((byte[]) result.get(i).get()); ScoutingFile f = ScoutingFile.decode((byte[]) result.get(i).get());
if (f != null) { if (f != null) {
System.out.println(f.filename); Log.i(getClass().toString(), f.filename);
if (f.write()) if (f.write())
result_filenames += f.filename + "\n"; result_filenames += f.filename + "\n";
} }
@@ -21,10 +21,9 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
// Helper class with sending bluetooth scouting data
public class BluetoothSender { public class BluetoothSender {
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_PERMISSIONS = 2;
private Context context; private Context context;
private BluetoothAdapter bluetoothAdapter; private BluetoothAdapter bluetoothAdapter;
@@ -17,12 +17,13 @@ import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentTransferBluetoothSenderBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferBluetoothSenderBinding;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Set; import java.util.Set;
// Class to send scouting data over bluetooth.
public class BluetoothSenderFragment extends Fragment { public class BluetoothSenderFragment extends Fragment {
private BluetoothSender bluetoothSender; private BluetoothSender bluetoothSender;
private ListView deviceListView; private ListView deviceListView;
@@ -101,10 +102,10 @@ public class BluetoothSenderFragment extends Fragment {
private void sendData() { private void sendData() {
try { try {
byte[] compressed = fileEditor.blockCompress(data_to_send); byte[] compressed = FileEditor.blockCompress(data_to_send, FileEditor.lengthHeaderBytes);
for(int i = 0; i < Math.ceil((double) compressed.length/1024); i++){ for(int i = 0; i < Math.ceil((double) compressed.length/1024); i++){
bluetoothSender.sendData(fileEditor.getByteBlock(compressed, i*1024, (i+1)*1024)); bluetoothSender.sendData(FileEditor.getByteBlock(compressed, i*1024, (i+1)*1024));
} }
bluetoothSender.close(); bluetoothSender.close();
@@ -17,7 +17,7 @@ import androidx.fragment.app.Fragment;
import com.ridgebotics.ridgescout.databinding.FragmentTransferCodeSenderBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferCodeSenderBinding;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.google.zxing.BarcodeFormat; import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType; import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter; import com.google.zxing.MultiFormatWriter;
@@ -30,6 +30,7 @@ import java.util.EnumMap;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
// Class to show the code transfer thing.
public class CodeGeneratorView extends Fragment { public class CodeGeneratorView extends Fragment {
private ImageView qrImage; private ImageView qrImage;
private SeekBar qrSpeedSlider; private SeekBar qrSpeedSlider;
@@ -76,7 +77,7 @@ public class CodeGeneratorView extends Fragment {
qrIndexN = binding.qrIndexN; qrIndexN = binding.qrIndexN;
qrIndexD = binding.qrIndexD; qrIndexD = binding.qrIndexD;
String compressed = new String(fileEditor.blockCompress(data), StandardCharsets.ISO_8859_1); String compressed = new String(FileEditor.blockCompress(data, FileEditor.lengthHeaderBytes), StandardCharsets.ISO_8859_1);
if(compressed.isEmpty()){ if(compressed.isEmpty()){
AlertManager.alert("Error!", "Empty data!"); AlertManager.alert("Error!", "Empty data!");
@@ -190,10 +191,10 @@ public class CodeGeneratorView extends Fragment {
try { try {
// alert("test", ""+Math.ceil((double)data.length()/(double)qrSize)); // alert("test", ""+Math.ceil((double)data.length()/(double)qrSize));
qrBitmaps.add(generateQrCode( qrBitmaps.add(generateQrCode(
fileEditor.byteToChar(fileEditor.internalDataVersion) + FileEditor.byteToChar(FileEditor.internalDataVersion, FileEditor.lengthHeaderBytes) +
String.valueOf(fileEditor.byteToChar(randID)) + String.valueOf(FileEditor.byteToChar(randID, FileEditor.lengthHeaderBytes)) +
fileEditor.byteToChar(i) + FileEditor.byteToChar(i, FileEditor.lengthHeaderBytes) +
fileEditor.byteToChar(qrCount - 1) + FileEditor.byteToChar(qrCount - 1, FileEditor.lengthHeaderBytes) +
data.substring(start, end) data.substring(start, end)
)); ));
// alert("title", ""+(qrCount-1)); // alert("title", ""+(qrCount-1));
@@ -2,6 +2,10 @@ package com.ridgebotics.ridgescout.ui.transfer.codes;
// From https://github.com/dlazaro66/QRCodeReaderView/blob/master/samples/src/main/java/com/example/qr_readerexample/PointsOverlayView.java // From https://github.com/dlazaro66/QRCodeReaderView/blob/master/samples/src/main/java/com/example/qr_readerexample/PointsOverlayView.java
import static com.ridgebotics.ridgescout.utility.Colors.code_scanned_color;
import static com.ridgebotics.ridgescout.utility.Colors.code_selected_color;
import static com.ridgebotics.ridgescout.utility.Colors.code_unscanned_color;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
@@ -13,6 +17,7 @@ import android.view.View;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
// Shows the progress of receiving data over codes.
public class CodeOverlayView extends View { public class CodeOverlayView extends View {
PointF[] points; PointF[] points;
@@ -37,7 +42,7 @@ public class CodeOverlayView extends View {
private void init() { private void init() {
paint = new Paint(); paint = new Paint();
paint.setColor(Color.YELLOW); paint.setColor(code_selected_color);
paint.setStyle(Paint.Style.FILL); paint.setStyle(Paint.Style.FILL);
} }
@@ -69,12 +74,12 @@ public class CodeOverlayView extends View {
final int num = barColors[i]; final int num = barColors[i];
int c = Color.RED; int c = code_unscanned_color;
if(num == 2){ if(num == 2){
c = Color.GREEN; c = code_scanned_color;
}else if(num == 1){ }else if(num == 1){
c = Color.YELLOW; c = code_selected_color;
} }
final Paint p = new Paint(); final Paint p = new Paint();
@@ -20,6 +20,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
// Background task for code scanning, to not slow down the scanner.
public class CodeScanTask extends AsyncTask<String, String, String>{ public class CodeScanTask extends AsyncTask<String, String, String>{
private Function<String, String> resultFunction = null; private Function<String, String> resultFunction = null;
private Bitmap image; private Bitmap image;
@@ -33,11 +33,10 @@ import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LifecycleOwner;
import com.ridgebotics.ridgescout.databinding.FragmentTransferCodeReceiverBinding; import com.ridgebotics.ridgescout.databinding.FragmentTransferCodeReceiverBinding;
import com.ridgebotics.ridgescout.databinding.FragmentTransferCodeSenderBinding; import com.ridgebotics.ridgescout.types.ScoutingFile;
import com.ridgebotics.ridgescout.types.file;
import com.ridgebotics.ridgescout.utility.AlertManager; import com.ridgebotics.ridgescout.utility.AlertManager;
import com.ridgebotics.ridgescout.utility.BuiltByteParser; import com.ridgebotics.ridgescout.utility.BuiltByteParser;
import com.ridgebotics.ridgescout.utility.fileEditor; import com.ridgebotics.ridgescout.utility.FileEditor;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@@ -48,7 +47,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
//public class scannerView extends androidx.appcompat.widget.AppCompatImageView { // Recieves data from the camera, scanning codes.
public class CodeScannerView extends Fragment { public class CodeScannerView extends Fragment {
private CodeOverlayView CodeOverlayView; private CodeOverlayView CodeOverlayView;
private Handler uiHandler; private Handler uiHandler;
@@ -120,10 +119,10 @@ public class CodeScannerView extends Fragment {
if(data != null){ if(data != null){
// alert("test", ""+fileEditor.byteFromChar(data.charAt(0))); // alert("test", ""+fileEditor.byteFromChar(data.charAt(0)));
compileData( compileData(
fileEditor.byteFromChar(data.charAt(0)), FileEditor.byteFromChar(data.charAt(0)),
fileEditor.byteFromChar(data.charAt(1)), FileEditor.byteFromChar(data.charAt(1)),
fileEditor.byteFromChar(data.charAt(2)), FileEditor.byteFromChar(data.charAt(2)),
(fileEditor.byteFromChar(data.charAt(3))+1), (FileEditor.byteFromChar(data.charAt(3))+1),
data.substring(4) data.substring(4)
); );
} }
@@ -284,8 +283,8 @@ public class CodeScannerView extends Fragment {
private int randID; private int randID;
private int prevQrIndex; private int prevQrIndex;
private void compileData(int dataVersion, int randID, int qrIndex, int qrCount, String qrData){ private void compileData(int dataVersion, int randID, int qrIndex, int qrCount, String qrData){
if(dataVersion != fileEditor.internalDataVersion){ if(dataVersion != FileEditor.internalDataVersion){
alert("Error", "Incorrect data version ("+dataVersion+" != "+fileEditor.internalDataVersion+")"); alert("Error", "Incorrect data version ("+dataVersion+" != "+ FileEditor.internalDataVersion+")");
return; return;
} }
@@ -321,7 +320,7 @@ public class CodeScannerView extends Fragment {
try { try {
byte[] compiledBytes = compiledString.getBytes(StandardCharsets.ISO_8859_1); byte[] compiledBytes = compiledString.getBytes(StandardCharsets.ISO_8859_1);
byte[] resultBytes = fileEditor.blockUncompress(compiledBytes); byte[] resultBytes = FileEditor.blockUncompress(compiledBytes);
String result_filenames = ""; String result_filenames = "";
@@ -330,8 +329,8 @@ public class CodeScannerView extends Fragment {
ArrayList<BuiltByteParser.parsedObject> result = bbp.parse(); ArrayList<BuiltByteParser.parsedObject> result = bbp.parse();
for(int i = 0; i < result.size(); i++){ for(int i = 0; i < result.size(); i++){
if(result.get(i).getType() != file.typecode) continue; if(result.get(i).getType() != ScoutingFile.typecode) continue;
file f = file.decode((byte[]) result.get(i).get()); ScoutingFile f = ScoutingFile.decode((byte[]) result.get(i).get());
if(f != null) if(f != null)
if(f.write()) if(f.write())
@@ -1,14 +1,9 @@
package com.ridgebotics.ridgescout.ui; package com.ridgebotics.ridgescout.ui.views;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.View; import android.view.View;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
@@ -18,6 +13,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
// Unused. AI-generated dynamic wallpaper for 2025 season.
public class BackgroundView extends View { public class BackgroundView extends View {
private List<Circle> circles; private List<Circle> circles;
private Paint whitePaint; private Paint whitePaint;
@@ -0,0 +1,108 @@
package com.ridgebotics.ridgescout.ui.views;
import static com.ridgebotics.ridgescout.utility.Colors.candlestick_color;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
// Shows the scale for a candlestick chart.
public class CandlestickHeader extends View {
private float absoluteMin = 0;
private float absoluteMax = 100;
// Number of scale marks to show
private final int SCALE_MARKS = 5;
// Padding and dimensions
private final int PADDING_LEFT = 50;
private final int PADDING_RIGHT = 50;
private final int PADDING_TOP = 10;
private final int PADDING_BOTTOM = 10;
private final int TICK_HEIGHT = 10;
private Paint linePaint;
private Paint textPaint;
public CandlestickHeader(Context context) {
super(context);
init();
}
public CandlestickHeader(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CandlestickHeader(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setColor(candlestick_color);
linePaint.setStrokeWidth(2f);
linePaint.setStyle(Paint.Style.STROKE);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(candlestick_color);
textPaint.setTextSize(30f);
textPaint.setTextAlign(Paint.Align.CENTER);
}
/**
* Set the scale range for the header
*
* @param absoluteMin Absolute minimum of the dataset
* @param absoluteMax Absolute maximum of the dataset
*/
public void setScale(float absoluteMin, float absoluteMax) {
this.absoluteMin = absoluteMin;
this.absoluteMax = absoluteMax;
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 600;
int desiredHeight = 80; // Height for the scale with labels
int width = resolveSize(desiredWidth, widthMeasureSpec);
int height = resolveSize(desiredHeight, heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
// Draw horizontal axis
float y = height - PADDING_BOTTOM;
canvas.drawLine(PADDING_LEFT, y, width - PADDING_RIGHT, y, linePaint);
// Calculate interval between scale marks
float availableWidth = width - PADDING_LEFT - PADDING_RIGHT;
float intervalValue = (absoluteMax - absoluteMin) / (SCALE_MARKS - 1);
float intervalPixels = availableWidth / (SCALE_MARKS - 1);
// Draw scale marks and labels
for (int i = 0; i < SCALE_MARKS; i++) {
float x = PADDING_LEFT + (intervalPixels * i);
float value = absoluteMin + (intervalValue * i);
// Draw tick mark
canvas.drawLine(x, y, x, y - TICK_HEIGHT, linePaint);
// Draw label
canvas.drawText(String.format("%.1f", value), x, y - TICK_HEIGHT - 10, textPaint);
}
}
}
@@ -0,0 +1,215 @@
package com.ridgebotics.ridgescout.ui.views;
import static com.ridgebotics.ridgescout.utility.Colors.candlestick_color;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.ridgebotics.ridgescout.types.data.RawDataType;
import com.ridgebotics.ridgescout.ui.data.DataProcessing;
import java.util.List;
// A single candlestick chart row.
public class CandlestickView extends View {
// Data points
private float min = 0;
private float max = 0;
private float lowerQuartile = 0;
private float upperQuartile = 0;
public float average = 0;
// Dataset absolute bounds for scaling
private float absoluteMin = 0;
private float absoluteMax = 100;
// Padding and dimensions
private final int PADDING_LEFT = 50;
private final int PADDING_RIGHT = 50;
private final int PADDING_TOP = 20;
private final int PADDING_BOTTOM = 20;
private final int CANDLESTICK_HEIGHT = 60;
private final int WHISKER_HEIGHT = 10;
// Paint objects
private Paint boxPaint;
private Paint whiskerPaint;
private Paint averagePaint;
private Paint textPaint;
public CandlestickView(Context context) {
super(context);
init();
}
public CandlestickView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CandlestickView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// Initialize paint objects
boxPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
boxPaint.setColor(candlestick_color);
boxPaint.setStyle(Paint.Style.STROKE);
boxPaint.setStrokeWidth(2f);
whiskerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
whiskerPaint.setColor(candlestick_color);
whiskerPaint.setStrokeWidth(2f);
whiskerPaint.setStyle(Paint.Style.STROKE);
averagePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
averagePaint.setColor(candlestick_color);
averagePaint.setStrokeWidth(3f);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(candlestick_color);
textPaint.setTextSize(30f);
}
/**
* Set data for the candlestick chart
*
* @param min Minimum value
* @param lowerQuartile Lower quartile value
* @param average Average value
* @param upperQuartile Upper quartile value
* @param max Maximum value
* @param absoluteMin Absolute minimum of the dataset
* @param absoluteMax Absolute maximum of the dataset
*/
public void setData(float min, float lowerQuartile, float average,
float upperQuartile, float max,
float absoluteMin, float absoluteMax) {
this.min = min;
this.lowerQuartile = lowerQuartile;
this.average = average;
this.upperQuartile = upperQuartile;
this.max = max;
this.absoluteMin = absoluteMin;
this.absoluteMax = absoluteMax;
// Request redraw
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 600;
int desiredHeight = CANDLESTICK_HEIGHT + PADDING_TOP + PADDING_BOTTOM;
int width = resolveSize(desiredWidth, widthMeasureSpec);
int height = resolveSize(desiredHeight, heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
// Calculate scaling factor for data points
float availableWidth = width - PADDING_LEFT - PADDING_RIGHT;
float scale = availableWidth / (absoluteMax - absoluteMin);
// Calculate vertical center of the view
int centerY = height / 2;
// Calculate scaled positions
float scaledMin = PADDING_LEFT + (min - absoluteMin) * scale;
float scaledLQ = PADDING_LEFT + (lowerQuartile - absoluteMin) * scale;
float scaledAvg = PADDING_LEFT + (average - absoluteMin) * scale;
float scaledUQ = PADDING_LEFT + (upperQuartile - absoluteMin) * scale;
float scaledMax = PADDING_LEFT + (max - absoluteMin) * scale;
// Draw the box (interquartile range)
if(lowerQuartile != upperQuartile) {
RectF box = new RectF(
scaledLQ,
centerY - CANDLESTICK_HEIGHT / 2,
scaledUQ,
centerY + CANDLESTICK_HEIGHT / 2);
canvas.drawRect(box, boxPaint);
}
// Draw whiskers (min to lower quartile and upper quartile to max)
// Left whisker
canvas.drawLine(scaledMin, centerY, scaledLQ, centerY, whiskerPaint);
canvas.drawLine(
scaledMin,
centerY - WHISKER_HEIGHT,
scaledMin,
centerY + WHISKER_HEIGHT,
whiskerPaint);
// Right whisker
canvas.drawLine(scaledUQ, centerY, scaledMax, centerY, whiskerPaint);
canvas.drawLine(
scaledMax,
centerY - WHISKER_HEIGHT,
scaledMax,
centerY + WHISKER_HEIGHT,
whiskerPaint);
// Draw average line
canvas.drawLine(
scaledAvg,
centerY - CANDLESTICK_HEIGHT / 2,
scaledAvg,
centerY + CANDLESTICK_HEIGHT / 2,
averagePaint);
// Draw labels
// canvas.drawText(String.format("%.1f", min), scaledMin - 20, centerY - CANDLESTICK_HEIGHT / 2 - 10, textPaint);
// canvas.drawText(String.format("%.1f", max), scaledMax - 20, centerY - CANDLESTICK_HEIGHT / 2 - 10, textPaint);
// canvas.drawText(String.format("%.1f", average), scaledAvg - 20, centerY + CANDLESTICK_HEIGHT / 2 + 30, textPaint);
}
public int teamNum;
public void fromTeamData(List<RawDataType> teamData, Integer teamNum, float absmin, float absmax){
this.teamNum = teamNum;
int[] tmp_loc_bounds = DataProcessing.getNumberBounds(teamData);
int locmin = tmp_loc_bounds[0];
int locmax = tmp_loc_bounds[1];
float avg = 0;
for(int i = 0; i < teamData.size(); i++){
avg += (int) teamData.get(i).get();
}
avg /= teamData.size();
float[] teamDataArray = new float[teamData.size()];
for(int i = 0; i < teamData.size(); i++){
teamDataArray[i] = (int) teamData.get(i).get();
}
float lowerQuartile = 0;
float upperQuartile = 0;
if(teamDataArray.length != 0) {
lowerQuartile = DataProcessing.calculatePercentile(teamDataArray, 25);
upperQuartile = DataProcessing.calculatePercentile(teamDataArray, 75);
}
Log.i(getClass().toString(), locmin + ", " + lowerQuartile + ", " + avg + ", " + upperQuartile + ", " + locmax);
setData(locmin, lowerQuartile, avg, upperQuartile, locmax, absmin, absmax);
}
}
@@ -1,29 +1,17 @@
package com.ridgebotics.ridgescout.ui; package com.ridgebotics.ridgescout.ui.views;
import android.content.Context; import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TableLayout; import android.widget.TableLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.divider.MaterialDivider; import com.google.android.material.divider.MaterialDivider;
import com.ridgebotics.ridgescout.R;
import java.util.ArrayList;
import java.util.List; import java.util.List;
// The notification view of a Custom dropdown notification
public class CustomSpinnerPopup extends TableLayout { public class CustomSpinnerPopup extends TableLayout {
public CustomSpinnerPopup(Context context) { public CustomSpinnerPopup(Context context) {
@@ -1,29 +1,22 @@
package com.ridgebotics.ridgescout.ui; package com.ridgebotics.ridgescout.ui.views;
import static android.app.PendingIntent.getActivity; import static android.app.PendingIntent.getActivity;
import static com.ridgebotics.ridgescout.utility.settingsManager.getEditor;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.ScrollView; import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import com.ridgebotics.ridgescout.R; import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.databinding.ViewCustomSpinnerBinding;
import java.util.ArrayList;
import java.util.List; import java.util.List;
// The dropdown element of a custom spinner view.
public class CustomSpinnerView extends LinearLayout { public class CustomSpinnerView extends LinearLayout {
public interface onClickListener { public interface onClickListener {
@@ -0,0 +1,66 @@
package com.ridgebotics.ridgescout.ui.views;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.types.input.FieldType;
public class FieldBorderedRow extends TableRow {
public FieldBorderedRow(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FieldBorderedRow(Context context) {
super(context);
init(context);
}
private ConstraintLayout box;
private View coloredBackground;
public void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_field_border_row, this, true);
box = findViewById(R.id.field_option_box);
coloredBackground = findViewById(R.id.field_option_background);
}
public void setColor(int color){
Drawable drawable = box.getBackground();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
float[] hsv = new float[3];
Color.colorToHSV(color,hsv);
coloredBackground.setBackgroundColor(
Color.HSVToColor(127, new float[]{
hsv[0],
Math.min(hsv[1], 0.75f),
Math.min(hsv[2], 0.5f)
})
);
}
public void fromField(FieldType field){
((TextView) findViewById(R.id.field_option_name)).setText(field.name);
((TextView) findViewById(R.id.field_option_type)).setText(field.get_type_name());
}
@Override
public void addView(View v){
box.addView(v);
}
}
@@ -0,0 +1,119 @@
package com.ridgebotics.ridgescout.ui.views;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.types.input.FieldType;
// Shows a display of the view in the view editor.
public class FieldDisplay extends ConstraintLayout {
public FieldDisplay(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FieldDisplay(Context context) {
super(context);
init(context);
}
private FieldType field;
public Button editButton;
// private View fieldView;
private ConstraintLayout box;
public View coloredBackground;
private LinearLayout fieldDisplayBox;
public void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_field_display, this, true);
box = findViewById(R.id.field_box);
fieldDisplayBox = findViewById(R.id.field_display_box);
coloredBackground = findViewById(R.id.field_background);
editButton = findViewById(R.id.button_edit);
}
private ToggleTitleView toggleTitleView;
private View fieldView;
public void setField(FieldType field){
this.field = field;
// titleText.setText(field.name);
// typeText.setText(field.get_type_name());
toggleTitleView = new ToggleTitleView(getContext());
toggleTitleView.setTitle(field.name);
toggleTitleView.setDescription(field.description);
fieldView = field.createView(getContext(), dataType -> 0);
fieldDisplayBox.removeAllViews();
fieldDisplayBox.addView(toggleTitleView);
fieldDisplayBox.addView(fieldView);
}
// public void setField(View newView){
// if(fieldView != null)
// box.removeView(fieldView);
// box.addView(newView);
// fieldView = newView;
// }
// public void fromTeam(frcTeam team){
// setTeamNumber(team.teamNumber);
// setTeamName(team.teamName);
//
// if(team.bitmap != null) {
// setTeamLogo(team.bitmap);
// }else{
// hideLogo();
// }
//
// setColor(team.getTeamColor());
// }
public void showButtons(){
findViewById(R.id.buttons).setVisibility(View.VISIBLE);
}
public void hideButtons(){
findViewById(R.id.buttons).setVisibility(View.GONE);
}
public FieldType getField(){
return field;
}
public void setColor(int color){
Drawable drawable = box.getBackground();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
float[] hsv = new float[3];
Color.colorToHSV(color,hsv);
coloredBackground.setBackgroundColor(
Color.HSVToColor(127, new float[]{
hsv[0],
Math.min(hsv[1] - 0.25f, 0.75f),
Math.min(hsv[2] - 0.25f, 0.5f)
})
);
}
}
@@ -1,4 +1,4 @@
package com.ridgebotics.ridgescout.ui.scouting; package com.ridgebotics.ridgescout.ui.views;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
@@ -13,7 +13,9 @@ import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import com.ridgebotics.ridgescout.R; import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.utility.SettingsManager;
// Custom view to display a field position.
public class FieldPosView extends FrameLayout { public class FieldPosView extends FrameLayout {
private int x = -1; private int x = -1;
private int y = -1; private int y = -1;
@@ -72,7 +74,14 @@ public class FieldPosView extends FrameLayout {
return false; return false;
}); });
switch(SettingsManager.getFieldImageIndex()){
case "2025":
setImageResource(R.drawable.field_2025); setImageResource(R.drawable.field_2025);
break;
case "2025 (Flipped)":
setImageResource(R.drawable.field_2025_flipped);
break;
}
} }
@@ -0,0 +1,91 @@
package com.ridgebotics.ridgescout.ui.views;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.types.frcTeam;
import org.w3c.dom.Text;
// A view for displaying information about a team.
public class MatchScoutingIndicator extends RelativeLayout {
public MatchScoutingIndicator(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MatchScoutingIndicator(Context context) {
super(context);
init(context);
}
public TextView match_indicator_alliance_pos_text;
public TextView match_indicator_bar_team_num;
public TextView match_indicator_matchnum;
public TextView match_indicator_username;
public ImageButton match_indicator_back_button;
public ImageButton match_indicator_next_button;
private ConstraintLayout box;
private View coloredBackground;
public void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_match_scouting_indicator, this, true);
match_indicator_back_button = findViewById(R.id.match_indicator_back_button);
match_indicator_next_button = findViewById(R.id.match_indicator_next_button);
match_indicator_alliance_pos_text = findViewById(R.id.match_indicator_alliance_pos_text);
match_indicator_username = findViewById(R.id.match_indicator_username);
match_indicator_matchnum = findViewById(R.id.match_indicator_matchnum);
match_indicator_bar_team_num = findViewById(R.id.match_indicator_bar_team_num);
box = findViewById(R.id.file_indicator_box);
coloredBackground = findViewById(R.id.match_indicator_background);
}
public void setUsername(String username){
match_indicator_username.setText(username);
}
public void setAlliancePos(String alliancePos){
match_indicator_alliance_pos_text.setText(alliancePos);
}
public void setMatchNum(String matchNum){
match_indicator_matchnum.setText(matchNum);
}
public void setTeamNum(String teamNum){
match_indicator_bar_team_num.setText(teamNum);
}
public void setColor(int color){
Drawable drawable = box.getBackground();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
float[] hsv = new float[3];
Color.colorToHSV(color,hsv);
coloredBackground.setBackgroundColor(
Color.HSVToColor(220, new float[]{
hsv[0],
Math.min(hsv[1], 0.75f),
Math.min(hsv[2], 0.5f)
})
);
}
}
@@ -1,14 +1,11 @@
package com.ridgebotics.ridgescout.ui.scouting; package com.ridgebotics.ridgescout.ui.views;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
@@ -0,0 +1,90 @@
package com.ridgebotics.ridgescout.ui.views;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ridgebotics.ridgescout.R;
// Class for custom view displaying an event in the TBASelector.java
public class TBAEventOption extends LinearLayout {
public TBAEventOption(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public TBAEventOption(Context context) {
super(context);
init(context);
}
private TextView eventCode;
private TextView eventName;
private TextView eventType;
private ConstraintLayout box;
private View coloredBackground;
public void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_tba_event, this, true);
eventCode = findViewById(R.id.tba_event_code);
eventName = findViewById(R.id.tba_event_name);
eventType = findViewById(R.id.tba_event_type);
box = findViewById(R.id.tba_event_box);
coloredBackground = findViewById(R.id.tba_event_background);
}
public void setCode(String code){
eventCode.setText(String.valueOf(code));
}
public void setName(String name){
eventName.setText(name);
}
public void setType(String name){
eventType.setText(name);
}
// public void fromTeam(frcTeam team){
// setTeamNumber(team.teamNumber);
// setTeamName(team.teamName);
//
// if(team.bitmap != null) {
// setTeamLogo(team.bitmap);
// }else{
// hideLogo();
// }
//
// setColor(team.getTeamColor());
// }
public void setColor(int color){
Drawable drawable = box.getBackground();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
float[] hsv = new float[3];
Color.colorToHSV(color,hsv);
coloredBackground.setBackgroundColor(
Color.HSVToColor(127, new float[]{
hsv[0],
Math.min(hsv[1], 0.75f),
Math.min(hsv[2], 0.5f)
})
);
}
}
@@ -1,4 +1,4 @@
package com.ridgebotics.ridgescout.ui.scouting; package com.ridgebotics.ridgescout.ui.views;
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
@@ -9,12 +9,15 @@ import android.widget.TextView;
import com.ridgebotics.ridgescout.R; import com.ridgebotics.ridgescout.R;
// Unused. This would be almost the same as the Fieldpos field, except it would support multiple positions.
public class TallyCounterView extends LinearLayout { public class TallyCounterView extends LinearLayout {
private int count = 0; private int count = 0;
private TextView countDisplay; private TextView countDisplay;
private Button minusButton; private Button minusButton;
private Button plusButton; private Button plusButton;
private OnCountChangedListener onCountChangedListener; private OnCountChangedListener onCountChangedListener;
private int min = 0;
private int max = -1;
public interface OnCountChangedListener { public interface OnCountChangedListener {
void onCountChanged(int newCount); void onCountChanged(int newCount);
@@ -45,20 +48,26 @@ public class TallyCounterView extends LinearLayout {
updateDisplay(); updateDisplay();
minusButton.setOnClickListener(v -> { minusButton.setOnClickListener(v -> {
if(count > 0) { if(count > min) {
count--; count--;
updateDisplay(); updateDisplay();
} }
}); });
plusButton.setOnClickListener(v -> { plusButton.setOnClickListener(v -> {
if(max == -1 || count < max){
count++; count++;
updateDisplay(); updateDisplay();
}
}); });
} }
private void updateDisplay() { private void updateDisplay() {
countDisplay.setText(String.valueOf(count)); countDisplay.setText(String.valueOf(count));
minusButton.setEnabled(count > min);
plusButton.setEnabled(max == -1 || count < max);
if (onCountChangedListener != null) { if (onCountChangedListener != null) {
onCountChangedListener.onCountChanged(count); onCountChangedListener.onCountChanged(count);
} }
@@ -69,6 +78,12 @@ public class TallyCounterView extends LinearLayout {
updateDisplay(); updateDisplay();
} }
public void setBounds(int min, int max){
this.min = min;
this.max = max;
updateDisplay();
}
public int getValue() { public int getValue() {
return count; return count;
} }
@@ -0,0 +1,109 @@
package com.ridgebotics.ridgescout.ui.views;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.types.frcTeam;
// A view for displaying information about a team.
public class TeamCard extends LinearLayout {
public TeamCard(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public TeamCard(Context context) {
super(context);
init(context);
}
private TextView teamNumber;
private TextView teamName;
private TextView teamDescription;
private ImageView teamLogo;
private ConstraintLayout box;
private View coloredBackground;
public void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_team_card, this, true);
teamNumber = findViewById(R.id.team_card_number);
teamName = findViewById(R.id.team_card_name);
teamLogo = findViewById(R.id.team_card_logo);
teamDescription = findViewById(R.id.team_card_description);
box = findViewById(R.id.team_card_box);
coloredBackground = findViewById(R.id.team_card_background);
}
public void setTeamNumber(int num){
teamNumber.setText(String.valueOf(num));
}
public void setTeamName(String name){
teamName.setText(name);
}
public void setTeamLogo(Bitmap bitmap){
teamLogo.setImageBitmap(bitmap);
}
public void setTeamDescription(String description){
teamDescription.setText(description);
}
public void hideLogo(){
teamLogo.setVisibility(View.GONE);
}
public void showLogo(){
teamLogo.setVisibility(View.VISIBLE);
}
public void fromTeam(frcTeam team){
setTeamNumber(team.teamNumber);
setTeamName(team.teamName);
if(team.bitmap != null) {
showLogo();
setTeamLogo(team.bitmap);
}else{
hideLogo();
}
setTeamDescription(team.getDescription());
setColor(team.getTeamColor());
}
public void setColor(int color){
Drawable drawable = box.getBackground();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
float[] hsv = new float[3];
Color.colorToHSV(color,hsv);
coloredBackground.setBackgroundColor(
Color.HSVToColor(127, new float[]{
hsv[0],
Math.min(hsv[1], 0.75f),
Math.min(hsv[2], 0.5f)
})
);
}
}
@@ -0,0 +1,100 @@
package com.ridgebotics.ridgescout.ui.views;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ridgebotics.ridgescout.R;
import com.ridgebotics.ridgescout.types.frcTeam;
// A view that acts as a row specifically to display a team and their icon in a list formmt.
public class TeamListOption extends LinearLayout {
public TeamListOption(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public TeamListOption(Context context) {
super(context);
init(context);
}
private TextView teamNumber;
private TextView teamName;
private ImageView teamLogo;
private ConstraintLayout box;
private View coloredBackground;
public void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_team_option, this, true);
teamNumber = findViewById(R.id.field_option_type);
teamName = findViewById(R.id.field_option_name);
teamLogo = findViewById(R.id.team_option_logo);
box = findViewById(R.id.team_option_box);
coloredBackground = findViewById(R.id.team_option_background);
}
public void setTeamNumber(int num){
teamNumber.setText(String.valueOf(num));
}
public void setTeamName(String name){
teamName.setText(name);
}
public void setTeamLogo(Bitmap bitmap){
teamLogo.setImageBitmap(bitmap);
}
public void hideLogo(){
teamLogo.setVisibility(View.GONE);
}
public void showLogo(){
teamLogo.setVisibility(View.VISIBLE);
}
public void fromTeam(frcTeam team){
setTeamNumber(team.teamNumber);
setTeamName(team.teamName);
if(team.bitmap != null) {
setTeamLogo(team.bitmap);
}else{
hideLogo();
}
setColor(team.getTeamColor());
}
public void setColor(int color){
Drawable drawable = box.getBackground();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
float[] hsv = new float[3];
Color.colorToHSV(color,hsv);
coloredBackground.setBackgroundColor(
Color.HSVToColor(127, new float[]{
hsv[0],
Math.min(hsv[1], 0.75f),
Math.min(hsv[2], 0.5f)
})
);
}
}
@@ -1,11 +1,14 @@
package com.ridgebotics.ridgescout.ui; package com.ridgebotics.ridgescout.ui.views;
import static com.ridgebotics.ridgescout.utility.Colors.toggletitle_black_background;
import static com.ridgebotics.ridgescout.utility.Colors.toggletitle_no_background;
import static com.ridgebotics.ridgescout.utility.Colors.toggletitle_unselected;
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@@ -14,6 +17,7 @@ import androidx.constraintlayout.widget.ConstraintLayout;
import com.ridgebotics.ridgescout.R; import com.ridgebotics.ridgescout.R;
// The enable and disable button for match and pit scouting
public class ToggleTitleView extends ConstraintLayout { public class ToggleTitleView extends ConstraintLayout {
public ToggleTitleView(@NonNull Context context, @Nullable AttributeSet attrs) { public ToggleTitleView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs); super(context, attrs);
@@ -52,6 +56,7 @@ public class ToggleTitleView extends ConstraintLayout {
else else
disable(); disable();
if(onToggleListener != null)
onToggleListener.onToggle(!checked); onToggleListener.onToggle(!checked);
}); });
} }
@@ -76,14 +81,14 @@ public class ToggleTitleView extends ConstraintLayout {
enabled = false; enabled = false;
toggle_title_checkbox.setChecked(false); toggle_title_checkbox.setChecked(false);
toggle_title_description.setVisibility(View.GONE); toggle_title_description.setVisibility(View.GONE);
setBackgroundColor(0xffff0000); setBackgroundColor(toggletitle_unselected);
titleView.setTextColor(0xff000000); titleView.setTextColor(toggletitle_black_background);
} }
public void enable(){ public void enable(){
enabled = true; enabled = true;
toggle_title_checkbox.setChecked(true); toggle_title_checkbox.setChecked(true);
toggle_title_description.setVisibility(View.VISIBLE); toggle_title_description.setVisibility(View.VISIBLE);
setBackgroundColor(0x00000000); setBackgroundColor(toggletitle_no_background);
titleView.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline5); titleView.setTextAppearance(com.google.android.material.R.style.TextAppearance_MaterialComponents_Headline5);
} }
@@ -1,69 +1,115 @@
package com.ridgebotics.ridgescout.utility; package com.ridgebotics.ridgescout.utility;
import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast; import android.widget.Toast;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
// Class to cause alerts and popups
public class AlertManager { public class AlertManager {
@SuppressLint("StaticFieldLeak")
public static Context context; public static Context context;
public static void init(Context c){ public static void init(Context c){
context = c; context = c;
} }
private static AlertDialog currentError;
private static final List<String> simpleErrorList = new ArrayList<>();
private static final List<String> errorList = new ArrayList<>();
public static void alert(String title, String content) { public static void alert(String title, String content) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() { ((Activity) context).runOnUiThread(() -> {
AlertDialog.Builder alert = new AlertDialog.Builder(context); AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage(content);
alert.setTitle(title); alert.setTitle(title);
alert.setMessage(content);
alert.setPositiveButton("OK", null); alert.setPositiveButton("OK", null);
alert.setCancelable(true); alert.setCancelable(true);
alert.create().show(); alert.create().show();
}
}); });
} }
public static void toast(String content) { public static void toast(String content) {
((Activity) context).runOnUiThread(new Runnable() { ((Activity) context).runOnUiThread(() -> Toast.makeText(context, content, Toast.LENGTH_LONG).show());
public void run() {
Toast.makeText(context, content, Toast.LENGTH_LONG).show();
} }
});
public static void addSimpleError(String error) {
simpleErrorList.add(error);
updateErrors();
} }
public static void error(String content) { public static void error(String content) {
((Activity) context).runOnUiThread(new Runnable() { errorList.add(content);
public void run() { updateErrors();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage(content);
alert.setTitle("Error!");
alert.setPositiveButton("OK", null);
alert.setCancelable(true);
alert.create().show();
} }
});
public static void error(String title, String content) {
simpleErrorList.add(title);
errorList.add(content);
updateErrors();
} }
public static void error(Exception e) { public static void error(Exception e) {
e.printStackTrace(); e.printStackTrace();
((Activity) context).runOnUiThread(() -> { // simpleErrorList.add(e.getMessage());
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw)); e.printStackTrace(new PrintWriter(sw));
AlertDialog.Builder alert = new AlertDialog.Builder(context); errorList.add(sw.getBuffer().toString());
alert.setMessage(sw.toString()); updateErrors();
alert.setTitle(e.getMessage()); }
alert.setPositiveButton("OK", null);
alert.setCancelable(true);
alert.create().show(); public static void error(String title, Exception e) {
simpleErrorList.add(title);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
errorList.add(sw.toString());
e.printStackTrace();
updateErrors();
}
public static void updateErrors(){
((Activity) context).runOnUiThread(() -> {
if(currentError != null && currentError.isShowing()){
DialogInterface tmp = currentError;
currentError = null;
tmp.dismiss();
}
AlertDialog.Builder alert = new AlertDialog.Builder(context);
if(!simpleErrorList.isEmpty())
alert.setTitle(simpleErrorList.get(0) + (simpleErrorList.size() > 1 ? "..." : ""));
else
alert.setTitle(errorList.size() + " Error" + (errorList.size() != 1 ? "s" : "") + "!");
if(simpleErrorList.size() > 1)
alert.setMessage(String.join("\n", simpleErrorList));
alert.setPositiveButton("OK", (dialogInterface, i) -> {if(currentError != null){errorList.clear(); simpleErrorList.clear();}});
String detailedErrors = String.join("\n\n\n\n\n", errorList);
if(!errorList.isEmpty())
alert.setNeutralButton("View Detailed Error" + (errorList.size() != 1 ? "s" : ""), (dialogInterface, i) -> alert("Details", detailedErrors));
// alert.setOnDismissListener((x) -> {if(currentError != null){errorList.clear(); simpleErrorList.clear();}});
alert.setCancelable(true);
currentError = alert.create();
currentError.show();
}); });
} }
@@ -3,14 +3,17 @@ package com.ridgebotics.ridgescout.utility;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
// Class to run a save function after a timeout of not calling the update function has been reached.
// Used for auto-saving in pit and match scouting.
public class AutoSaveManager { public class AutoSaveManager {
private static final long AUTO_SAVE_DELAY = 2000; // 2 seconds public static final long AUTO_SAVE_DELAY = 2000; // 2 seconds
private final Handler handler; private final Handler handler;
private final Runnable autoSaveRunnable; private final Runnable autoSaveRunnable;
private boolean isAutoSaveScheduled = false; private boolean isAutoSaveScheduled = false;
private final AutoSaveFunction autoSaveFunction; private final AutoSaveFunction autoSaveFunction;
public boolean isRunning = false; public boolean isRunning = false;
private long delay;
// Functional interface for the auto-save function // Functional interface for the auto-save function
@FunctionalInterface @FunctionalInterface
@@ -18,8 +21,9 @@ public class AutoSaveManager {
void save(); void save();
} }
public AutoSaveManager(AutoSaveFunction autoSaveFunction) { public AutoSaveManager(AutoSaveFunction autoSaveFunction, long delay) {
this.autoSaveFunction = autoSaveFunction; this.autoSaveFunction = autoSaveFunction;
this.delay = delay;
handler = new Handler(Looper.getMainLooper()); handler = new Handler(Looper.getMainLooper());
autoSaveRunnable = new Runnable() { autoSaveRunnable = new Runnable() {
@Override @Override
@@ -1,9 +1,11 @@
package com.ridgebotics.ridgescout.utility; package com.ridgebotics.ridgescout.utility;
import static com.ridgebotics.ridgescout.utility.FileEditor.lengthHeaderBytes;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
// Class to decode the raw types from any of the scouting files
public class BuiltByteParser { public class BuiltByteParser {
public static final Integer boolType = 0; public static final Integer boolType = 0;
public static final Integer intType = 1; public static final Integer intType = 1;
@@ -12,7 +14,7 @@ public class BuiltByteParser {
public static final Integer stringArrayType = 4; public static final Integer stringArrayType = 4;
public static final Integer longType = 5; public static final Integer longType = 5;
public class byteParsingExeption extends Exception { public static class byteParsingExeption extends Exception {
public byteParsingExeption() {} public byteParsingExeption() {}
public byteParsingExeption(String message) { public byteParsingExeption(String message) {
super(message); super(message);
@@ -76,26 +78,36 @@ public class BuiltByteParser {
byte[] bytes; byte[] bytes;
ArrayList<parsedObject> objects = new ArrayList<>(); ArrayList<parsedObject> objects = new ArrayList<>();
public BuiltByteParser(byte[] bytes){ public BuiltByteParser(byte[] bytes){
this.bytes = bytes; this.bytes = bytes;
} }
public ArrayList<parsedObject> parse() throws byteParsingExeption { public ArrayList<parsedObject> parse() throws byteParsingExeption {
if(bytes.length < 3){throw new byteParsingExeption("Invalid length");} try{
return parse(lengthHeaderBytes); // Try decoding with new format
}catch (byteParsingExeption e){
objects.clear(); // Clear previous attempt at decoding
return parse(lengthHeaderBytes - 1); // Try parsing with old format
}
}
private ArrayList<parsedObject> parse(final int size) throws byteParsingExeption {
if(bytes.length < size + 1){throw new byteParsingExeption("Invalid length");}
int curIndex = 0; int curIndex = 0;
while(true){ while(true){
// Log.i("t", String.valueOf(curIndex)); // Log.i("t", String.valueOf(curIndex));
final int length = fileEditor.fromBytes(fileEditor.getByteBlock(bytes, curIndex, curIndex+2), 2); final int length = FileEditor.fromBytes(FileEditor.getByteBlock(bytes, curIndex, curIndex+size), size);
final int type = bytes[curIndex+2] & 0xFF; final int type = bytes[curIndex+size] & 0xFF;
if(length == 0){ if(length == 0){
curIndex += 3; curIndex += size;
continue; continue;
} }
final byte[] block; final byte[] block;
try { try {
block = fileEditor.getByteBlock(bytes, curIndex + 3, curIndex + length + 3); block = FileEditor.getByteBlock(bytes, curIndex + size + 1, curIndex + length + size + 1);
} catch(Exception e){ } catch(Exception e){
throw new byteParsingExeption("Array out of bounds"); throw new byteParsingExeption("Array out of bounds");
} }
@@ -108,7 +120,7 @@ public class BuiltByteParser {
break; break;
case 1: case 1:
intObject io = new intObject(); intObject io = new intObject();
io.num = fileEditor.fromBytes(block, length); io.num = FileEditor.fromBytes(block, length);
objects.add(io); objects.add(io);
break; break;
case 2: case 2:
@@ -128,7 +140,7 @@ public class BuiltByteParser {
intArrayObject ia = new intArrayObject(); intArrayObject ia = new intArrayObject();
ia.arr = intArr; ia.arr = intArr;
System.out.println(Arrays.toString(intArr)); // System.out.println(Arrays.toString(intArr));lengthHeaderBytes
objects.add(ia); objects.add(ia);
break; break;
case 4: case 4:
@@ -148,7 +160,7 @@ public class BuiltByteParser {
break; break;
case 5: case 5:
longObject lo = new longObject(); longObject lo = new longObject();
lo.num = fileEditor.fromBytesLong(block, length); lo.num = FileEditor.fromBytesLong(block, length);
objects.add(lo); objects.add(lo);
break; break;
default: default:
@@ -158,7 +170,7 @@ public class BuiltByteParser {
break; break;
} }
curIndex += length + 3; curIndex += length + size + 1;
if(curIndex == bytes.length){ if(curIndex == bytes.length){
break; break;
@@ -1,8 +1,11 @@
package com.ridgebotics.ridgescout.utility; package com.ridgebotics.ridgescout.utility;
import static com.ridgebotics.ridgescout.utility.FileEditor.lengthHeaderBytes;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
// Class to encode the raw types from any of the scouting files
public class ByteBuilder { public class ByteBuilder {
public static final int bool_id = 0; public static final int bool_id = 0;
public static final int int_id = 1; public static final int int_id = 1;
@@ -56,7 +59,7 @@ public class ByteBuilder {
public byte getType(){return int_id;} public byte getType(){return int_id;}
public int length(){return precision;} public int length(){return precision;}
public byte[] build(){ public byte[] build(){
return fileEditor.toBytes(num, precision); return FileEditor.toBytes(num, precision, lengthHeaderBytes);
} }
} }
private int getLeastBytePrecision(int num){ private int getLeastBytePrecision(int num){
@@ -71,7 +74,7 @@ public class ByteBuilder {
public ByteBuilder addInt(int num, int precision) throws buildingException { public ByteBuilder addInt(int num, int precision) throws buildingException {
if(precision <= 0){throw new buildingException("Invalid precision: " + precision);} if(precision <= 0){throw new buildingException("Invalid precision: " + precision);}
if(precision > 65536){throw new buildingException("Precision too large (greter than 65536)");} if(precision > Math.pow(lengthHeaderBytes,8)){throw new buildingException("Precision too large (greter than 16777216)");}
if(precision < getLeastBytePrecision(num)){throw new buildingException("Precision too small");} if(precision < getLeastBytePrecision(num)){throw new buildingException("Precision too small");}
if(num > Integer.MAX_VALUE){throw new buildingException("Integer overflow");} if(num > Integer.MAX_VALUE){throw new buildingException("Integer overflow");}
@@ -96,7 +99,7 @@ public class ByteBuilder {
} }
public ByteBuilder addString(String str) throws buildingException { public ByteBuilder addString(String str) throws buildingException {
str = blankStrNull(str); str = blankStrNull(str);
if(str.length() > 65536){throw new buildingException("String too long (greater than 65536)");} if(str.length() > Math.pow(lengthHeaderBytes,8)){throw new buildingException("String too long (greater than 16777216)");}
stringType stringType = new stringType(); stringType stringType = new stringType();
// To get the length correctly, the string bytes need to be precalculated // To get the length correctly, the string bytes need to be precalculated
@@ -160,7 +163,7 @@ public class ByteBuilder {
public byte getType(){return long_id;} public byte getType(){return long_id;}
public int length(){return precision;} public int length(){return precision;}
public byte[] build(){ public byte[] build(){
return fileEditor.toBytes(num, precision); return FileEditor.toBytes(num, precision, lengthHeaderBytes);
} }
} }
private int getLeastBytePrecision(long num){ private int getLeastBytePrecision(long num){
@@ -175,7 +178,7 @@ public class ByteBuilder {
public ByteBuilder addLong(long num, int precision) throws buildingException { public ByteBuilder addLong(long num, int precision) throws buildingException {
if(precision <= 0){throw new buildingException("Invalid precision: " + precision);} if(precision <= 0){throw new buildingException("Invalid precision: " + precision);}
if(precision > 65536){throw new buildingException("Precision too large (greter than 65536)");} if(precision > Math.pow(lengthHeaderBytes,8)){throw new buildingException("Precision too large (greter than 16777216)");}
if(precision < getLeastBytePrecision(num)){throw new buildingException("Precision too small");} if(precision < getLeastBytePrecision(num)){throw new buildingException("Precision too small");}
if(num > Long.MAX_VALUE){throw new buildingException("Long overflow");} if(num > Long.MAX_VALUE){throw new buildingException("Long overflow");}
@@ -200,7 +203,7 @@ public class ByteBuilder {
} }
public ByteBuilder addRaw(int type, byte[] bytes) throws buildingException { public ByteBuilder addRaw(int type, byte[] bytes) throws buildingException {
if(bytes.length > 65536){throw new buildingException("Byte array length to long (greater than 65536)");} if(bytes.length > 16777216){throw new buildingException("Byte array length to long (greater than 16777216)");}
rawType rawType = new rawType(); rawType rawType = new rawType();
rawType.type = type; rawType.type = type;
@@ -213,7 +216,7 @@ public class ByteBuilder {
public byte[] build() throws buildingException { public byte[] build() throws buildingException {
if(bytesToBuild.size() == 0){throw new buildingException("Cannot build null data");} if(bytesToBuild.size() == 0){throw new buildingException("Cannot build null data");}
int length = bytesToBuild.size() * 3; int length = bytesToBuild.size() * (lengthHeaderBytes + 1);
for(byteType bt : bytesToBuild){ for(byteType bt : bytesToBuild){
length += bt.length(); length += bt.length();
} }
@@ -223,12 +226,13 @@ public class ByteBuilder {
for(byteType bt : bytesToBuild){ for(byteType bt : bytesToBuild){
byte[] blockLength = fileEditor.toBytes(bt.length(), 2); byte[] blockLength = FileEditor.toBytes(bt.length(), lengthHeaderBytes + 1, lengthHeaderBytes);
bytes[bytesFilled] = blockLength[0]; for(int i = 0; i < lengthHeaderBytes; i++) {
bytesFilled += 1; bytes[bytesFilled] = blockLength[i];
bytes[bytesFilled] = blockLength[1];
bytesFilled += 1; bytesFilled += 1;
}
bytes[bytesFilled] = bt.getType(); bytes[bytesFilled] = bt.getType();
bytesFilled += 1; bytesFilled += 1;
@@ -0,0 +1,81 @@
package com.ridgebotics.ridgescout.utility;
import android.graphics.Color;
// Constants for most of the colors in the entire app.
public class Colors {
// Lists and stuff
public static final int color_found = 0x7f00ff00;
public static final int color_rescout = 0x7f0000ff;
public static final int color_not_found = 0x7f7f0000;
public static final int background_color = 0x5000ff00;
public static final int unfocused_background_color = 0x50118811;
public static final int unsaved_color = 0x60ff0000;
public static final int saved_color = 0x6000ff00;
public static final int rescout_color = 0x600000ff;
// Data graphs
public static final int chart_background = 0xff252025;
public static final int chart_text = Color.WHITE;
public static final int[] checkbox_colors = {0x7f00ff00, 0x7f7f0000};
public static final int checkbox_data_color = Color.RED;;
public static final int checkbox_value_text_color = Color.BLACK;
public static final int dropdown_value_text_1 = Color.BLACK;
public static final int dropdown_value_text_2 = Color.RED;
public static final int fieldpos_data = Color.BLUE;
public static final int number_data = Color.BLUE;
public static final int slider_data = Color.BLUE;
public static final int tally_data = Color.BLUE;
public static final int text_data = Color.BLUE;
// Code scanner
public static final int code_scanned_color = Color.GREEN;
public static final int code_selected_color = Color.YELLOW;
public static final int code_unscanned_color = Color.RED;
// Toggle title
public static final int toggletitle_no_background = 0x00000000;
public static final int toggletitle_black_background = 0xff000000;
public static final int toggletitle_unselected = 0xffff0000;
// public static final int toggletitle_no_background = 0x00000000;
// Data fragment
public static final int datafragment_option_1 = 0xff509050;
public static final int datafragment_option_2 = 0xff307030;
// fileselector
public static final int fileselector_selected_color = 0x5000ff00;
public static final int fileselector_unselected_color = 0x50006600;
// TBA
public static final int tba_previous = 0x30FF0000;
public static final int tba_current = 0x50ff0000;
public static final int tba_next = 0x30FFFF00;
public static final int tba_red = 0x50ff0000;
public static final int tba_blue = 0x500000ff;
public static final int tba_toggle_background = 0x30000000;
// Candlestick
public static final int candlestick_color = Color.GREEN;
}
@@ -1,54 +1,127 @@
package com.ridgebotics.ridgescout.utility; package com.ridgebotics.ridgescout.utility;
import com.ridgebotics.ridgescout.scoutingData.fields; import com.ridgebotics.ridgescout.scoutingData.Fields;
import com.ridgebotics.ridgescout.scoutingData.transfer.transferType; import com.ridgebotics.ridgescout.scoutingData.transfer.TransferType;
import com.ridgebotics.ridgescout.types.frcEvent; import com.ridgebotics.ridgescout.types.frcEvent;
import com.ridgebotics.ridgescout.types.input.inputType; import com.ridgebotics.ridgescout.types.input.FieldType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Static class to hold loaded data, for ease of access.
public class DataManager { public class DataManager {
public static String evcode; public static String evcode;
public static frcEvent event; public static frcEvent event;
public static void reload_event(){ public static void reload_event(){
// if(event != null) return;
evcode = getevcode(); evcode = getevcode();
if(evcode.equals("unset")) return; if(evcode.equals("unset")) return;
event = frcEvent.decode(fileEditor.readFile(evcode + ".eventdata")); event = frcEvent.decode(FileEditor.readFile(evcode + ".eventdata"));
if(event == null) { if(event == null) {
AlertManager.error("Failed to load event!"); AlertManager.addSimpleError("Failed to load event!");
settingsManager.setEVCode("unset"); SettingsManager.setEVCode("unset");
evcode = "unset"; evcode = "unset";
}else{
reload_rescout_list();
reload_scout_notice();
AlertManager.toast("Reloaded event!");
} }
} }
public static String getevcode() { public static String getevcode() {
return settingsManager.getEVCode(); return SettingsManager.getEVCode();
} }
public static inputType[][] match_values; public static FieldType[][] match_values;
public static inputType[] match_latest_values; public static FieldType[] match_latest_values;
public static transferType[][] match_transferValues; public static TransferType[][] match_transferValues;
public static void reload_match_fields(){ public static void reload_match_fields(){
try { try {
match_values = fields.load(fields.matchFieldsFilename); match_values = Fields.load(Fields.matchFieldsFilename);
match_latest_values = match_values[match_values.length - 1]; match_latest_values = match_values[match_values.length - 1];
match_transferValues = transferType.get_transfer_values(match_values); match_transferValues = TransferType.get_transfer_values(match_values);
} catch (Exception e){ } catch (Exception e){
AlertManager.error(e); AlertManager.error("Error reading match fields", e);
} }
} }
public static inputType[][] pit_values; public static FieldType[][] pit_values;
public static inputType[] pit_latest_values; public static FieldType[] pit_latest_values;
public static transferType[][] pit_transferValues; public static TransferType[][] pit_transferValues;
public static void reload_pit_fields(){ public static void reload_pit_fields(){
try { try {
pit_values = fields.load(fields.pitsFieldsFilename); pit_values = Fields.load(Fields.pitsFieldsFilename);
pit_latest_values = pit_values[pit_values.length-1]; pit_latest_values = pit_values[pit_values.length-1];
pit_transferValues = transferType.get_transfer_values(pit_values); pit_transferValues = TransferType.get_transfer_values(pit_values);
} catch (Exception e){ } catch (Exception e){
AlertManager.error(e); AlertManager.error("Error reading pit fields", e);
}
}
public static List<String> rescout_list = new ArrayList<>();
public static void reload_rescout_list(){
if(!FileEditor.fileExist(evcode + ".rescout")) {rescout_list = new ArrayList<>(); return;}
byte[] file = FileEditor.readFile(evcode + ".rescout");
if(file == null) {rescout_list = new ArrayList<>(); return;}
try {
BuiltByteParser bbp = new BuiltByteParser(file);
rescout_list = new ArrayList<>(Arrays.asList((String[]) (bbp.parse().get(0).get())));
} catch (Exception e){
AlertManager.error("Error loading scout fields", e);
rescout_list = new ArrayList<>();
}
}
public static void save_rescout_list() {
try {
if(rescout_list.size() == 0){
FileEditor.deleteFile(evcode + ".rescout");
return;
}
ByteBuilder bb = new ByteBuilder();
bb.addStringArray(rescout_list.toArray(new String[0]));
FileEditor.writeFile(evcode + ".rescout", bb.build());
} catch (Exception e){
AlertManager.error("Error saving scout fields", e);
}
}
public static String scoutNotice = "";
public static void reload_scout_notice(){
if(!FileEditor.fileExist(evcode + ".scoutnotice")) {scoutNotice = ""; return;}
byte[] file = FileEditor.readFile(evcode + ".scoutnotice");
if(file == null) {scoutNotice = ""; return;}
try {
BuiltByteParser bbp = new BuiltByteParser(file);
scoutNotice = (String) (bbp.parse().get(0).get());
} catch (Exception e){
AlertManager.error("Error loading scout notice", e);
rescout_list = new ArrayList<>();
}
}
public static void save_scout_notice() {
try {
if(scoutNotice.isEmpty()){
FileEditor.deleteFile(evcode + ".scoutnotice");
return;
}
ByteBuilder bb = new ByteBuilder();
bb.addString(scoutNotice);
FileEditor.writeFile(evcode + ".scoutnotice", bb.build());
} catch (Exception e){
AlertManager.error("Error saving scout notice", e);
} }
} }
} }
@@ -15,24 +15,27 @@ import java.io.IOException;
import java.nio.BufferOverflowException; import java.nio.BufferOverflowException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.TimeZone;
import java.util.zip.DataFormatException; import java.util.zip.DataFormatException;
import java.util.zip.Deflater; import java.util.zip.Deflater;
import java.util.zip.Inflater; import java.util.zip.Inflater;
public final class fileEditor { // Helper class for binary editing
public final class FileEditor {
public final static String baseDir = "/data/data/com.ridgebotics.ridgescout/"; public final static String baseDir = "/data/data/com.ridgebotics.ridgescout/";
public static final byte internalDataVersion = 0x01; public static final byte internalDataVersion = 0x01;
public static final int maxCompressedBlockSize = 4096; public static final int maxCompressedBlockSize = 4096;
public static final int lengthHeaderBytes = 3;
public static final String TBAAddress = "https://www.thebluealliance.com/api/v3/";
public static final String TBAHeader = "X-TBA-Auth-Key: tjEKSZojAU2pgbs2mBt06SKyOakVhLutj3NwuxLTxPKQPLih11aCIwRIVFXKzY4e";
// private TimeZone localTimeZone = TimeZone.getDefault(); // private TimeZone localTimeZone = TimeZone.getDefault();
@@ -49,14 +52,14 @@ public final class fileEditor {
} }
public static char byteToChar(int num){ public static char byteToChar(int num, int headerSize){
return new String(toBytes(num, 1), StandardCharsets.ISO_8859_1).charAt(0); return new String(toBytes(num, 1, headerSize), StandardCharsets.ISO_8859_1).charAt(0);
} }
public static byte[] toBytes(int num, int byteCount){ public static byte[] toBytes(int num, int byteCount, int headerSize){
if(num > (Math.pow(2,byteCount*8)-1)){ if(num > (Math.pow(headerSize,byteCount*8)-1)){
throw new BufferOverflowException(); throw new BufferOverflowException();
} }
byte[] bytes = new byte[byteCount]; byte[] bytes = new byte[byteCount];
@@ -66,8 +69,8 @@ public final class fileEditor {
return bytes; return bytes;
} }
public static byte[] toBytes(long num, int byteCount){ public static byte[] toBytes(long num, int byteCount, int headerSize){
if(num > (Math.pow(2,byteCount*8)-1)){ if(num > (Math.pow(headerSize,byteCount*8)-1)){
throw new BufferOverflowException(); throw new BufferOverflowException();
} }
byte[] bytes = new byte[byteCount]; byte[] bytes = new byte[byteCount];
@@ -131,21 +134,21 @@ public final class fileEditor {
return outputStream.toByteArray(); return outputStream.toByteArray();
} }
public static byte[] blockCompress(byte[] inputData) { public static byte[] blockCompress(byte[] inputData, int headerSize) {
List<byte[]> compiledData = new ArrayList<>(); List<byte[]> compiledData = new ArrayList<>();
for(int i=0;i<Math.ceil((double) inputData.length / fileEditor.maxCompressedBlockSize);i++){ for(int i = 0; i<Math.ceil((double) inputData.length / FileEditor.maxCompressedBlockSize); i++){
final int start = i*fileEditor.maxCompressedBlockSize; final int start = i* FileEditor.maxCompressedBlockSize;
int end = ((i+1)*fileEditor.maxCompressedBlockSize); int end = ((i+1)* FileEditor.maxCompressedBlockSize);
if(end > inputData.length) { if(end > inputData.length) {
end = inputData.length; end = inputData.length;
} }
byte[] dataBlock = fileEditor.getByteBlock(inputData, start, end); byte[] dataBlock = FileEditor.getByteBlock(inputData, start, end);
final byte[] compressedBlock = fileEditor.compress(dataBlock); final byte[] compressedBlock = FileEditor.compress(dataBlock);
compiledData.add(fileEditor.toBytes(compressedBlock.length, 2)); compiledData.add(FileEditor.toBytes(compressedBlock.length, 2, headerSize));
compiledData.add(compressedBlock); compiledData.add(compressedBlock);
} }
return combineByteArrays(compiledData); return combineByteArrays(compiledData);
@@ -156,11 +159,11 @@ public final class fileEditor {
int curIndex = 0; int curIndex = 0;
while (curIndex < data.length) { while (curIndex < data.length) {
final int blockLength = fileEditor.fromBytes(fileEditor.getByteBlock(data, curIndex, curIndex + 2), 2); final int blockLength = FileEditor.fromBytes(FileEditor.getByteBlock(data, curIndex, curIndex + 2), 2);
uncompressedData.add( uncompressedData.add(
decompress( decompress(
fileEditor.getByteBlock(data, curIndex + 2, curIndex + blockLength + 2) FileEditor.getByteBlock(data, curIndex + 2, curIndex + blockLength + 2)
) )
); );
@@ -262,6 +265,14 @@ public final class fileEditor {
} }
} }
public static boolean deleteFile(String filepath){
if(!fileExist(filepath)){
return true;
}
File file = new File(baseDir + filepath);
return file.delete();
}
public static boolean fileExist(String path){ public static boolean fileExist(String path){
File f = new File(baseDir + path); File f = new File(baseDir + path);
return f.exists() && !f.isDirectory(); return f.exists() && !f.isDirectory();
@@ -308,8 +319,8 @@ public final class fileEditor {
public static boolean setEvent(frcEvent event){ public static boolean setEvent(frcEvent event){
final String filename = (event.eventCode + ".eventdata"); final String filename = (event.eventCode + ".eventdata");
if(settingsManager.getEVCode().equals("unset")){ if(SettingsManager.getEVCode().equals("unset")){
settingsManager.setEVCode(event.eventCode); SettingsManager.setEVCode(event.eventCode);
} }
return writeFile(filename, event.encode()); return writeFile(filename, event.encode());
@@ -394,15 +405,20 @@ public final class fileEditor {
} }
}); });
} catch (Exception e){ } catch (Exception e){
e.printStackTrace(); AlertManager.error(e);
} }
return filenames; return filenames;
} }
// https://stackoverflow.com/questions/7620401/how-to-convert-image-file-data-in-a-byte-array-to-a-bitmap
// public static String imageToBitMap(byte[] data) throws IOException {
// Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
// return bitmap;
// ByteArrayOutputStream blob = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
// }
public static boolean setTeams(Context context, String key, ArrayList<frcTeam> teams){ public static boolean setTeams(Context context, String key, ArrayList<frcTeam> teams){
@@ -0,0 +1,168 @@
package com.ridgebotics.ridgescout.utility;
import android.os.AsyncTask;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetFile extends AsyncTask<Void, Integer, File> {
public interface DownloadCallback {
void onResult(String error);
}
private String downloadUrl;
private File destinationFile;
private DownloadCallback callback;
private String errorMessage;
public HttpGetFile(String downloadUrl, File destinationFile, DownloadCallback callback) {
this.downloadUrl = downloadUrl;
this.destinationFile = destinationFile;
this.callback = callback;
}
@Override
protected File doInBackground(Void... voids) {
HttpURLConnection connection = null;
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
URL url = new URL(downloadUrl);
connection = (HttpURLConnection) url.openConnection();
// Configure connection for GET request
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setConnectTimeout(30000); // 30 seconds
connection.setReadTimeout(60000); // 60 seconds
connection.connect();
// Check response code
int responseCode = connection.getResponseCode();
if (responseCode < 200 || responseCode >= 300) {
String errorResponse = readErrorResponse(connection);
errorMessage = "Download failed. Response code: " + responseCode +
(errorResponse != null ? ". Error: " + errorResponse : "");
return null;
}
// Get file size for progress tracking
long fileSize = connection.getContentLengthLong();
if (fileSize == -1) {
fileSize = connection.getContentLength(); // fallback for older API
}
inputStream = connection.getInputStream();
// Create destination file and directories if needed
if (destinationFile.getParentFile() != null && !destinationFile.getParentFile().exists()) {
if (!destinationFile.getParentFile().mkdirs()) {
errorMessage = "Failed to create destination directory: " + destinationFile.getParentFile().getAbsolutePath();
return null;
}
}
outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[8192];
long downloadedBytes = 0;
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
if (isCancelled()) {
deletePartialFile();
return null;
}
outputStream.write(buffer, 0, bytesRead);
downloadedBytes += bytesRead;
// Update progress if file size is known
if (fileSize > 0) {
int progress = (int) ((downloadedBytes * 100) / fileSize);
publishProgress(progress);
}
}
outputStream.flush();
// Log.d(TAG, "Download successful. File saved to: " + destinationFile.getAbsolutePath());
return destinationFile;
} catch (Exception e) {
AlertManager.error(e);
errorMessage = "Download error: " + e.getMessage();
// Log.e(TAG, errorMessage, e);
deletePartialFile();
return null;
} finally {
closeResources(inputStream, outputStream, connection);
}
}
@Override
protected void onPostExecute(File result) {
if (callback != null) {
callback.onResult(errorMessage);
}
}
@Override
protected void onCancelled() {
deletePartialFile();
if (callback != null) {
callback.onResult("Download cancelled");
}
}
private String readErrorResponse(HttpURLConnection connection) {
try {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
} catch (IOException e) {
AlertManager.error(e);
// Log.e(TAG, "Error reading error response", e);
}
return null;
}
private void deletePartialFile() {
if (destinationFile != null && destinationFile.exists()) {
if (destinationFile.delete()) {
// Log.d(TAG, "Partial download file deleted");
} else {
// Log.w(TAG, "Failed to delete partial download file");
}
}
}
private void closeResources(InputStream inputStream, OutputStream outputStream, HttpURLConnection connection) {
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
AlertManager.error(e);
// Log.e(TAG, "Error closing input stream", e);
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
AlertManager.error(e);
// Log.e(TAG, "Error closing output stream", e);
}
if (connection != null) {
connection.disconnect();
}
}
}
@@ -0,0 +1,161 @@
package com.ridgebotics.ridgescout.utility;
import android.os.AsyncTask;
//import android.util.Log;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPutFile extends AsyncTask<Void, Integer, Boolean> {
// private static final String TAG = "FileUploadTask";
public interface UploadCallback {
void onResult(String error);
}
private String uploadUrl;
private File fileToUpload;
private UploadCallback callback;
private String errorMessage;
private String[] headers;
public HttpPutFile(String uploadUrl, File fileToUpload, UploadCallback callback, String[] headers) {
this.uploadUrl = uploadUrl;
this.fileToUpload = fileToUpload;
this.callback = callback;
this.headers = headers;
}
@Override
protected Boolean doInBackground(Void... voids) {
HttpURLConnection connection = null;
InputStream fileInputStream = null;
OutputStream outputStream = null;
try {
if (!fileToUpload.exists()) {
errorMessage = "File does not exist: " + fileToUpload.getAbsolutePath();
return false;
}
URL url = new URL(uploadUrl);
connection = (HttpURLConnection) url.openConnection();
// Configure connection for PUT request
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Content-Length", String.valueOf(fileToUpload.length()));
connection.setConnectTimeout(30000); // 30 seconds
connection.setReadTimeout(60000); // 60 seconds
for(int i = 0; i < headers.length; i++){
String[] split = headers[i].split(": ");
connection.setRequestProperty(split[0], split[1]);
}
connection.connect();
outputStream = connection.getOutputStream();
fileInputStream = new FileInputStream(fileToUpload);
byte[] buffer = new byte[8192];
long totalBytes = fileToUpload.length();
long uploadedBytes = 0;
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
if (isCancelled()) {
return false;
}
outputStream.write(buffer, 0, bytesRead);
uploadedBytes += bytesRead;
// Update progress
int progress = (int) ((uploadedBytes * 100) / totalBytes);
publishProgress(progress);
}
outputStream.flush();
// Check response code
int responseCode = connection.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
// Log.d(TAG, "Upload successful. Response code: " + responseCode);
return true;
} else {
// Read error response if available
String errorResponse = readErrorResponse(connection);
errorMessage = "Upload failed. Response code: " + responseCode +
(errorResponse != null ? ". Error: " + errorResponse : "");
return false;
}
} catch (Exception e) {
AlertManager.error(e);
errorMessage = "Upload error: " + e.getMessage();
// Log.e(TAG, errorMessage, e);
return false;
} finally {
closeResources(fileInputStream, outputStream, connection);
}
}
@Override
protected void onPostExecute(Boolean success) {
if (callback != null) {
callback.onResult(errorMessage);
}
}
@Override
protected void onCancelled() {
if (callback != null) {
callback.onResult("Upload cancelled");
}
}
private String readErrorResponse(HttpURLConnection connection) {
try {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
} catch (IOException e) {
AlertManager.error(e);
// Log.e(TAG, "Error reading error response", e);
}
return null;
}
private void closeResources(InputStream inputStream, OutputStream outputStream, HttpURLConnection connection) {
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
AlertManager.error(e);
// Log.e(TAG, "Error closing input stream", e);
}
try {
if (outputStream != null) outputStream.close();
} catch (IOException e) {
AlertManager.error(e);
// Log.e(TAG, "Error closing output stream", e);
}
if (connection != null) {
connection.disconnect();
}
}
}
@@ -0,0 +1,58 @@
package com.ridgebotics.ridgescout.utility;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.function.Function;
import javax.net.ssl.HttpsURLConnection;
// Class to retrieve team icon from TBA
// https://stackoverflow.com/questions/37510411/download-an-image-into-bitmap-file-in-android
public class ImageRequestTask extends AsyncTask<String, Void, Bitmap> {
Function<Bitmap, Void> resultFunction = null;
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (FileNotFoundException e) {
return null;
} catch (IOException e){
AlertManager.error("Error downloading image " + src, e);
return null;
}
}
@Override
protected Bitmap doInBackground(String... params) {
return getBitmapFromURL(params[0]);
}
public void onResult(Function<Bitmap, Void> func) {
this.resultFunction = func;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(resultFunction != null){
resultFunction.apply(result);
}
}
}
@@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
// Literally just sorting json
public class JSONUtil { public class JSONUtil {
public static JSONArray sort(JSONArray array, Comparator c){ public static JSONArray sort(JSONArray array, Comparator c){
List asList = new ArrayList(array.length()); List asList = new ArrayList(array.length());
@@ -1,158 +0,0 @@
package com.ridgebotics.ridgescout.utility;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.view.MotionEvent;
import android.widget.TableLayout;
public class ReorderableTableLayout extends TableLayout {
private boolean reorderingEnabled = false;
private int draggedRowIndex = -1;
private float lastY;
private List<View> rows;
private List<Integer> reorderedIndices;
private int rowHeight;
public ReorderableTableLayout(Context context) {
super(context);
init();
}
public ReorderableTableLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
rows = new ArrayList<>();
reorderedIndices = new ArrayList<>();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!reorderingEnabled) {
return super.onInterceptTouchEvent(ev);
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastY = ev.getY();
draggedRowIndex = getRowIndexAtY(lastY);
if (draggedRowIndex != -1) {
View draggedRow = getChildAt(draggedRowIndex);
rowHeight = draggedRow.getHeight();
saveOriginalOrder();
return true;
}
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public void addView(View child) {
super.addView(child);
reorderedIndices.add(reorderedIndices.size());
}
@Override
public void removeAllViews() {
super.removeAllViews();
reorderedIndices.clear();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!reorderingEnabled || draggedRowIndex == -1) {
return super.onTouchEvent(event);
}
float currentY = event.getY();
int targetIndex = getRowIndexAtY(currentY);
View child = getChildAt(targetIndex);
if(child != null)
getChildAt(targetIndex).callOnClick();
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (targetIndex != -1 && targetIndex != draggedRowIndex) {
updateRowOrder(draggedRowIndex, targetIndex);
draggedRowIndex = targetIndex;
}
lastY = currentY;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
draggedRowIndex = -1;
break;
}
return true;
}
private int getRowIndexAtY(float y) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (y >= child.getTop() && y <= child.getBottom()) {
return i;
}
}
return -1;
}
private void saveOriginalOrder() {
rows.clear();
for (int i = 0; i < getChildCount(); i++) {
rows.add(getChildAt(i));
}
}
public void updateRowOrder(int fromIndex, int toIndex) {
saveOriginalOrder();
if (fromIndex < toIndex) {
for (int i = fromIndex; i < toIndex; i++) {
Collections.swap(rows, i, i + 1);
Collections.swap(reorderedIndices, i, i + 1);
}
} else {
for (int i = fromIndex; i > toIndex; i--) {
Collections.swap(rows, i, i - 1);
Collections.swap(reorderedIndices, i, i - 1);
}
}
removeAllViewsInLayout();
for (View view : rows) {
addViewInLayout(view, -1, view.getLayoutParams(), true);
}
requestLayout();
invalidate();
}
public void setReorderingEnabled(boolean enabled) {
reorderingEnabled = enabled;
}
public List<Integer> getReorderedIndexes() {
return reorderedIndices;
}
public void removeElement(int unshuffledindex){
System.out.println(Arrays.toString(new List[]{reorderedIndices}));
reorderedIndices.remove(unshuffledindex);
for (int i = 0; i < reorderedIndices.size(); i++) {
if(reorderedIndices.get(i) > unshuffledindex)
reorderedIndices.set(i, reorderedIndices.get(i) - 1);
}
System.out.println(Arrays.toString(new List[]{reorderedIndices}));
}
}
@@ -12,6 +12,8 @@ import java.util.function.Function;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
// Class to send an http request
// Used for TBA
public class RequestTask extends AsyncTask<String, String, String> { public class RequestTask extends AsyncTask<String, String, String> {
private Function<String, String> resultFunction = null; private Function<String, String> resultFunction = null;
@@ -36,7 +38,7 @@ public class RequestTask extends AsyncTask<String, String, String> {
return null; // See documentation for more info on response handling return null; // See documentation for more info on response handling
} }
} catch (IOException e) { } catch (IOException e) {
AlertManager.error(e); AlertManager.error("Failed to download!", e);
} }
return null; return null;
} }
@@ -7,6 +7,8 @@ import org.tensorflow.lite.task.text.nlclassifier.NLClassifier;
import java.util.List; import java.util.List;
// Class that runs a sentiment analysis model of a string
// This would be very cool if it was useful at all.
public class SentimentAnalysis { public class SentimentAnalysis {
private static NLClassifier textClassifier; private static NLClassifier textClassifier;
@@ -0,0 +1,159 @@
package com.ridgebotics.ridgescout.utility;
import android.content.SharedPreferences;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
// Helper class for loading settings from android SharedPreferences
public class SettingsManager {
public static SharedPreferences prefs;
public static SharedPreferences.Editor editor;
public static final String TeamNumKey = "team_num";
public static final String UnameKey = "username";
public static final String SelEVCodeKey = "selected_event_code";
public static final String YearNumKey = "year_num";
public static final String FieldImageKey = "field_image";
public static final String MatchNumKey = "match_num";
public static final String AllyPosKey = "alliance_pos";
public static final String WifiModeKey = "wifi_mode";
public static final String DataModeKey = "data_view_mode";
public static final String TeamsDataModeKey = "teams_data_view_mode";
public static final String BtUUIDKey = "bt_uuid";
public static final String FTPEnabled = "ftp_enabled";
public static final String FTPServer = "ftp_server";
public static final String FTPKey = "ftp_key";
public static final String FTPSendMetaFiles = "ftp_send_meta_files";
public static final String EnableQuickAllianceChangeKey = "enable_quick_alliance_change";
public static final String CustomEventsKey = "enable_custom_event";
public static final String ScoutingReportKey = "scouting_report";
public static final String ScoutingReportIndexKey = "scouting_report_index";
public static Map defaults = getDefaults();
private static Map getDefaults(){
Map<String, Object> hm = new HashMap<>();
hm.put(TeamNumKey, 4388);
hm.put(UnameKey, "Username");
hm.put(SelEVCodeKey, "unset");
hm.put(WifiModeKey, false);
hm.put(YearNumKey, 2025);
hm.put(FieldImageKey, "2025");
hm.put(MatchNumKey, 0);
hm.put(AllyPosKey, "red-1");
hm.put(DataModeKey, 0);
hm.put(TeamsDataModeKey, 0);
hm.put(BtUUIDKey, UUID.randomUUID().toString());
hm.put(FTPEnabled, false);
hm.put(FTPServer, "http://127.0.0.1:8080");
hm.put(FTPKey, "5uper_5ecure_k3y");
hm.put(FTPSendMetaFiles, false);
hm.put(EnableQuickAllianceChangeKey, false);
hm.put(CustomEventsKey, false);
hm.put(ScoutingReportKey, "");
hm.put(ScoutingReportIndexKey, 0);
return hm;
}
public static SharedPreferences.Editor getEditor(){
if(editor == null) editor = prefs.edit();
return editor;
}
public static void resetSettings(){
getEditor() .putInt(TeamNumKey, (int) defaults.get( TeamNumKey )).apply();
getEditor() .putString(UnameKey, (String) defaults.get( UnameKey )).apply();
getEditor() .putString(SelEVCodeKey,(String) defaults.get( SelEVCodeKey)).apply();
getEditor().putBoolean(WifiModeKey, (boolean) defaults.get( WifiModeKey )).apply();
getEditor() .putInt(YearNumKey, (int) defaults.get( YearNumKey )).apply();
getEditor() .putString(FieldImageKey, (String) defaults.get( FieldImageKey )).apply();
getEditor() .putInt(MatchNumKey, (int) defaults.get( MatchNumKey )).apply();
getEditor() .putString(AllyPosKey, (String) defaults.get( AllyPosKey )).apply();
getEditor() .putInt(DataModeKey, (int) defaults.get( DataModeKey )).apply();
getEditor() .putInt(TeamsDataModeKey, (int) defaults.get( TeamsDataModeKey )).apply();
getEditor() .putString(BtUUIDKey, (String) defaults.get( BtUUIDKey )).apply();
getEditor().putBoolean(FTPEnabled, (boolean) defaults.get( FTPEnabled )).apply();
getEditor() .putString(FTPServer, (String) defaults.get( FTPServer )).apply();
getEditor().putBoolean(FTPSendMetaFiles, (boolean) defaults.get( FTPSendMetaFiles )).apply();
getEditor().putBoolean(EnableQuickAllianceChangeKey, (boolean) defaults.get( EnableQuickAllianceChangeKey )).apply();
getEditor().putBoolean(CustomEventsKey, (boolean) defaults.get( CustomEventsKey )).apply();
}
public static int getTeamNum(){return prefs.getInt( TeamNumKey, (int) defaults.get(TeamNumKey));}
public static void setTeamNum(int num){ getEditor().putInt( TeamNumKey,num).apply();}
public static String getUsername(){return prefs.getString( UnameKey, (String) defaults.get(UnameKey));}
public static void setUsername(String str){ getEditor().putString( UnameKey,str).apply();}
public static String getEVCode(){return prefs.getString( SelEVCodeKey, (String) defaults.get(SelEVCodeKey));}
public static void setEVCode(String str){ getEditor().putString( SelEVCodeKey,str).apply();}
public static boolean getWifiMode(){return prefs.getBoolean( WifiModeKey, (boolean) defaults.get(WifiModeKey));}
public static void setWifiMode(boolean bool){getEditor().putBoolean( WifiModeKey,bool).apply();}
public static int getYearNum(){return prefs.getInt( YearNumKey, (int) defaults.get(YearNumKey));}
public static void setYearNum(int num){ getEditor().putInt( YearNumKey,num).apply();}
public static String getFieldImageIndex(){return prefs.getString( FieldImageKey, (String) defaults.get(FieldImageKey));}
public static void setFieldImageIndex(String str){ getEditor().putString( FieldImageKey,str).apply();}
public static int getMatchNum(){return prefs.getInt( MatchNumKey, (int) defaults.get(MatchNumKey));}
public static void setMatchNum(int num){ getEditor().putInt( MatchNumKey,num).apply();}
public static String getAllyPos(){return prefs.getString( AllyPosKey, (String) defaults.get(AllyPosKey));}
public static void setAllyPos(String str){ getEditor().putString( AllyPosKey,str).apply();}
public static int getDataMode(){return prefs.getInt( DataModeKey, (int) defaults.get(DataModeKey));}
public static void setDataMode(int num){ getEditor().putInt( DataModeKey,num).apply();}
public static int getTeamsDataMode(){return prefs.getInt( TeamsDataModeKey, (int) defaults.get(TeamsDataModeKey));}
public static void setTeamsDataMode(int num){ getEditor().putInt( TeamsDataModeKey,num).apply();}
public static String getBtUUID(){return prefs.getString( BtUUIDKey, (String) defaults.get(BtUUIDKey));}
public static void setBtUUID(String str){ getEditor().putString( BtUUIDKey,str).apply();}
public static boolean getFTPEnabled(){return prefs.getBoolean( FTPEnabled, (boolean) defaults.get(FTPEnabled));}
public static void setFTPEnabled(boolean bool){getEditor().putBoolean( FTPEnabled,bool).apply();}
public static String getFTPServer(){return prefs.getString( FTPServer, (String) defaults.get(FTPServer));}
public static void setFTPServer(String str){ getEditor().putString( FTPServer,str).apply();}
public static String getFTPKey(){return prefs.getString( FTPKey, (String) defaults.get(FTPKey));}
public static void setFTPKey(String str){ getEditor().putString( FTPKey,str).apply();}
public static boolean getFTPSendMetaFiles(){return prefs.getBoolean(FTPSendMetaFiles, (boolean) defaults.get(FTPSendMetaFiles));}
public static void setFTPSendMetaFiles(boolean bool){getEditor().putBoolean(FTPSendMetaFiles,bool).apply();}
public static boolean getEnableQuickAlliancePosChange(){return prefs.getBoolean(EnableQuickAllianceChangeKey, (boolean) defaults.get(EnableQuickAllianceChangeKey));}
public static void setEnableQuickAlliancePosChange(boolean bool){getEditor().putBoolean(EnableQuickAllianceChangeKey,bool).apply();}
public static boolean getCustomEvents(){return prefs.getBoolean(CustomEventsKey, (boolean) defaults.get(FTPSendMetaFiles));}
public static void setCustomEvents(boolean bool){getEditor().putBoolean(CustomEventsKey,bool).apply();}
public static String getScoutingReport(String eventCode, int matchNum){return prefs.getString(ScoutingReportKey+"_"+eventCode+"_"+matchNum, (String) defaults.get(ScoutingReportKey));}
public static void setScoutingReport(String eventCode, int matchNum, String data){getEditor().putString(ScoutingReportKey+"_"+eventCode+"_"+matchNum,data).apply();}
public static int getReportMatchIndex(String eveode){return prefs.getInt( ScoutingReportIndexKey+"_"+eveode, (int) defaults.get(ScoutingReportIndexKey));}
public static void setReportIndex(int num, String evcode){ getEditor().putInt( ScoutingReportIndexKey+"_"+evcode,num).apply();}
}
@@ -10,6 +10,7 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
// Class to cause the share popup.
public class SharePrompt { public class SharePrompt {
public static void shareContent(Context context, String fileName, String content, String mimeType) { public static void shareContent(Context context, String fileName, String content, String mimeType) {
shareContent(context, fileName, content.getBytes(), mimeType); shareContent(context, fileName, content.getBytes(), mimeType);
@@ -1,114 +0,0 @@
package com.ridgebotics.ridgescout.utility;
import android.content.SharedPreferences;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class settingsManager {
public static SharedPreferences prefs;
public static SharedPreferences.Editor editor;
public static final String UnameKey = "username";
public static final String SelEVCodeKey = "selected_event_code";
public static final String YearNumKey = "year_num";
public static final String WifiModeKey = "wifi_mode";
public static final String MatchNumKey = "match_num";
public static final String AllyPosKey = "alliance_pos";
public static final String DataModeKey = "data_view_mode";
public static final String BtUUIDKey = "bt_uuid";
public static final String FTPEnabled = "ftp_enabled";
public static final String FTPServer = "ftp_server";
public static final String FTPSendMetaFiles = "ftp_send_meta_files";
public static final String CustomEventsKey = "enable_custom_event";
public static Map defaults = getDefaults();
private static Map getDefaults(){
Map<String, Object> hm = new HashMap<>();
hm.put(UnameKey, "Username");
hm.put(SelEVCodeKey, "unset");
hm.put(WifiModeKey, false);
hm.put(YearNumKey, 2025);
hm.put(MatchNumKey, 0);
hm.put(AllyPosKey, "red-1");
hm.put(DataModeKey, 0);
hm.put(BtUUIDKey, UUID.randomUUID().toString());
hm.put(FTPEnabled, false);
hm.put(FTPServer, "0.0.0.0");
hm.put(FTPSendMetaFiles, false);
hm.put(CustomEventsKey, false);
return hm;
}
public static SharedPreferences.Editor getEditor(){
if(editor == null) editor = prefs.edit();
return editor;
}
public static void resetSettings(){
getEditor() .putString(UnameKey, (String) defaults.get( UnameKey )).apply();
getEditor() .putString(SelEVCodeKey,(String) defaults.get( SelEVCodeKey)).apply();
getEditor().putBoolean(WifiModeKey, (boolean) defaults.get( WifiModeKey )).apply();
getEditor() .putInt(YearNumKey, (int) defaults.get( YearNumKey )).apply();
getEditor() .putInt(MatchNumKey, (int) defaults.get( MatchNumKey )).apply();
getEditor() .putString(AllyPosKey, (String) defaults.get( AllyPosKey )).apply();
getEditor() .putInt(DataModeKey, (int) defaults.get( DataModeKey )).apply();
getEditor() .putString(BtUUIDKey, (String) defaults.get( BtUUIDKey )).apply();
getEditor().putBoolean(FTPEnabled, (boolean) defaults.get( FTPEnabled )).apply();
getEditor() .putString(FTPServer, (String) defaults.get( FTPServer )).apply();
getEditor().putBoolean(FTPSendMetaFiles, (boolean) defaults.get( FTPSendMetaFiles )).apply();
getEditor().putBoolean(CustomEventsKey, (boolean) defaults.get( CustomEventsKey )).apply();
}
// IDK why I decided to format these functions like this. It looks cool though.
public static String getUsername(){return prefs.getString( UnameKey, (String) defaults.get(UnameKey));}
public static void setUsername(String str){ getEditor().putString( UnameKey,str).apply();}
public static String getEVCode(){return prefs.getString( SelEVCodeKey, (String) defaults.get(SelEVCodeKey));}
public static void setEVCode(String str){ getEditor().putString( SelEVCodeKey,str).apply();}
public static boolean getWifiMode(){return prefs.getBoolean( WifiModeKey, (boolean) defaults.get(WifiModeKey));}
public static void setWifiMode(boolean bool){getEditor().putBoolean( WifiModeKey,bool).apply();}
public static int getYearNum(){return prefs.getInt( YearNumKey, (int) defaults.get(YearNumKey));}
public static void setYearNum(int num){ getEditor().putInt( YearNumKey,num).apply();}
public static int getMatchNum(){return prefs.getInt( MatchNumKey, (int) defaults.get(MatchNumKey));}
public static void setMatchNum(int num){ getEditor().putInt( MatchNumKey,num).apply();}
public static String getAllyPos(){return prefs.getString( AllyPosKey, (String) defaults.get(AllyPosKey));}
public static void setAllyPos(String str){ getEditor().putString( AllyPosKey,str).apply();}
public static int getDataMode(){return prefs.getInt( DataModeKey, (int) defaults.get(DataModeKey));}
public static void setDataMode(int num){ getEditor().putInt( DataModeKey,num).apply();}
public static String getBtUUID(){return prefs.getString( BtUUIDKey, (String) defaults.get(BtUUIDKey));}
public static void setBtUUID(String str){ getEditor().putString( BtUUIDKey,str).apply();}
public static boolean getFTPEnabled(){return prefs.getBoolean( FTPEnabled, (boolean) defaults.get(FTPEnabled));}
public static void setFTPEnabled(boolean bool){getEditor().putBoolean( FTPEnabled,bool).apply();}
public static String getFTPServer(){return prefs.getString( FTPServer, (String) defaults.get(FTPServer));}
public static void setFTPServer(String str){ getEditor().putString( FTPServer,str).apply();}
public static boolean getFTPSendMetaFiles(){return prefs.getBoolean(FTPSendMetaFiles, (boolean) defaults.get(FTPSendMetaFiles));}
public static void setFTPSendMetaFiles(boolean bool){getEditor().putBoolean(FTPSendMetaFiles,bool).apply();}
public static boolean getCustomEvents(){return prefs.getBoolean(CustomEventsKey, (boolean) defaults.get(FTPSendMetaFiles));}
public static void setCustomEvents(boolean bool){getEditor().putBoolean(CustomEventsKey,bool).apply();}
}
BIN
View File
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Some files were not shown because too many files have changed in this diff Show More