-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathBinaryPacket.java
More file actions
1024 lines (849 loc) · 36.7 KB
/
BinaryPacket.java
File metadata and controls
1024 lines (849 loc) · 36.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.font.FontRenderContext;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
/**
* A class for describing and processing binary packets.
*
* The data structure of a binary packet can be defined interactively by the user, or by loading a layout file.
*
*
* When defined by loading a layout file, Controller.openLayout() will:
* 1. Call BinaryPacket.clear() to start over fresh.
* 2. Repeatedly call BinaryPacket.insertField() to define each of the fields.
* 3. Optionally call BinaryPacket.insertChecksum() if a checksum field is used.
* 4. Call Controller.connectToSerialPort(), which will call BinaryPacket.startReceivingData().
* 5. Create the charts.
*
*
* When defined by user interaction:
* 1. The ControlsRegion gets the possible packet types from Controller.getPacketTypes(), and one of them is an object of this class.
* 2. The user clicks Connect in the ControlsRegion, which calls Controller.connectToSerialPort().
* 3. If a successful connection occurs, BinaryPacket.showDataStructureWindow() is called.
* 4. That window lets the user define the binary packet data structure by calling methods of this class:
*
* To modify or query the data structure:
* insertField()
* removeField()
* insertChecksum()
* removeChecksum()
* clear()
* isFull()
* isEmpty()
*
* To visualize the data structure with a JTable:
* getRowCount()
* getCellContents()
*
* To list possibilities for the user:
* getFirstAvailableOffset()
* getBinaryFieldProcessors()
* getBinaryChecksumProcessors()
*
* 5. When use user clicks Done in the BinaryDataStructureWindow, Controller.connectToSerialPort() will call BinaryPacket.startReceivingData().
* 6. The user can then interactively create the charts.
*/
public class BinaryPacket implements Packet {
private byte syncWord;
public BinaryChecksumProcessor checksumProcessor;
public int checksumProcessorOffset;
private int packetSize; // total byte count: includes sync word, fields, and checksum field
private Thread thread;
/**
* Creates an object with a default sync word, but no fields, and no checksum processor.
*/
public BinaryPacket() {
syncWord = (byte) 0xAA;
Controller.removeAllDatasets();
checksumProcessor = null;
checksumProcessorOffset = -1;
packetSize = 1; // the syncWord
thread = null;
}
/**
* Description shown in the packetTypeCombobox in the ControlsRegion.
*/
@Override public String toString() {
return Communication.PACKET_TYPE_BINARY;
}
/**
* Adds a field to the data structure if possible.
*
* @param byteOffset Binary packet byte offset.
* @param processor BinaryProcessor for the raw samples in the Binary packet.
* @param name Descriptive name of what the samples represent.
* @param color Color to use when visualizing the samples.
* @param unit Descriptive name of how the samples are quantified.
* @param conversionFactorA This many unprocessed LSBs...
* @param conversionFactorB ... equals this many units.
* @return null on success, or a user-friendly String describing why the field could not be added.
*/
public String insertField(int byteOffset, BinaryFieldProcessor processor, String name, Color color, String unit, float conversionFactorA, float conversionFactorB) {
if(byteOffset == 0)
return "Error: Can not place a field that overlaps the sync word.";
if(isFull())
return "Error: The packet is full.";
if(checksumProcessor != null)
if(byteOffset + processor.getByteCount() - 1 >= checksumProcessorOffset)
return "Error: Can not place a field that overlaps the checksum or is placed after the checksum.";
// check for overlap with existing fields
int proposedStartByte = byteOffset;
int proposedEndByte = proposedStartByte + processor.getByteCount() - 1;
for(Dataset dataset : Controller.getAllDatasets()) {
int existingStartByte = dataset.location;
int existingEndByte = existingStartByte + dataset.processor.getByteCount() - 1;
if(proposedStartByte >= existingStartByte && proposedStartByte <= existingEndByte)
return "Error: Can not place a field that overlaps an existing field."; // starting inside existing range
if(proposedEndByte >= existingStartByte && proposedEndByte <= existingEndByte)
return "Error: Can not place a field that overlaps an existing field."; // ending inside existing range
if(existingStartByte >= proposedStartByte && existingEndByte <= proposedEndByte)
return "Error: Can not place a field that overlaps an existing field."; // encompassing existing range
}
// add the field
Controller.insertDataset(byteOffset, processor, name, color, unit, conversionFactorA, conversionFactorB);
// update packetSize
int newPacketSize = 1;
for(Dataset dataset : Controller.getAllDatasets()) {
int endByte = dataset.location + dataset.processor.getByteCount() - 1;
if(endByte + 1 > newPacketSize)
newPacketSize = endByte + 1;
}
if(newPacketSize > packetSize)
packetSize = newPacketSize;
// no errors
return null;
}
/**
* Removes a field from the data structure if possible.
*
* @param byteOffset The field at this offset will be removed.
* @return null on success, or a user-friendly String describing why the field could not be added.
*/
public String removeField(int byteOffset) {
if(byteOffset == 0)
return "Error: Can not remove the sync word.";
boolean success = Controller.removeDataset(byteOffset);
if(!success)
return "Error: No field exists at that location.";
// update packetSize if there is no checksum
if(checksumProcessor == null) {
int newPacketSize = 1;
for(Dataset dataset : Controller.getAllDatasets()) {
int endByte = dataset.location + dataset.processor.getByteCount() - 1;
if(endByte + 1 > newPacketSize)
newPacketSize = endByte + 1;
}
packetSize = newPacketSize;
}
// no errors
return null;
}
/**
* Adds a checksum field to the data structure if possible.
*
* @param byteOffset Binary packet byte offset.
* @param processor The type of checksum field.
* @return null on success, or a user-friendly String describing why the checksum field could not be added.
*/
public String insertChecksum(int byteOffset, BinaryChecksumProcessor processor) {
if(checksumProcessor != null)
return "Error: A checksum field already exists.";
if(byteOffset == 0)
return "Error: A checksum field can not overlap with the sync word.";
if(byteOffset < packetSize)
return "Error: A checksum field can not be placed in front of existing fields.";
if((byteOffset - 1) % processor.getByteCount() != 0)
return "Error: The checksum must be aligned. The number of bytes before the checksum, not counting the sync word, must be a multiple of " + processor.getByteCount() + " for this checksum type.";
// add the checksum processor
checksumProcessor = processor;
checksumProcessorOffset = byteOffset;
// update packetSize
packetSize = byteOffset + processor.getByteCount();
// no errors
return null;
}
/**
* Removes the checksum field from the data structure if possible.
*
* @return null on success, or a user-friendly String describing why the checksum field could not be removed.
*/
public String removeChecksum() {
if(checksumProcessor == null)
return "Error: There was no checksum processor to remove.";
// remove the checksum processor
checksumProcessor = null;
checksumProcessorOffset = -1;
// update packetSize
int newPacketSize = 1;
for(Dataset dataset : Controller.getAllDatasets()) {
int endByte = dataset.location + dataset.processor.getByteCount() - 1;
if(endByte + 1 > newPacketSize)
newPacketSize = endByte + 1;
}
packetSize = newPacketSize;
// no errors
return null;
}
/**
* Removes the checksum and all fields from the data structure, leaving just the sync word.
*/
@Override public void clear() {
Controller.removeAllDatasets();
checksumProcessor = null;
packetSize = 1; // the syncWord
}
/**
* Checks if more fields can be added.
*
* @return True if a checksum processor exists and every byte before it is occupied, false if more fields or a checksum processor can be added
*/
public boolean isFull() {
if(checksumProcessor == null)
return false;
// check which bytes before the checksum are occupied
boolean[] byteUsed = new boolean[packetSize - checksumProcessor.getByteCount()];
byteUsed[0] = true; // the syncWord
for(Dataset dataset : Controller.getAllDatasets()) {
int start = dataset.location;
int end = start + dataset.processor.getByteCount() - 1;
for (int i = start; i <= end; i++)
byteUsed[i] = true;
}
// check if all of those bytes are occupied
boolean everyByteUsed = true;
for(int i = 0; i < byteUsed.length; i++)
if(byteUsed[i] == false)
everyByteUsed = false;
if(everyByteUsed)
return true;
else
return false;
}
/**
* Check if the data structure is empty.
*
* @return True if there is just a sync word, false otherwise.
*/
public boolean isEmpty() {
if(packetSize == 1)
return true;
else
return false;
}
/**
* Gets the number of rows that should be shown in the BinaryDataStructureWindow's JTable.
* This would be the number of fields, +1 for the sync word, +1 if a checksum field has been defined.
*
* @return The number of rows.
*/
public int getRowCount() {
int count = 1; // the syncWord
count += Controller.getDatasetsCount();
if(checksumProcessor != null)
count++;
return count;
}
/**
* Gets the text to show in a specific cell in the BinaryDataStructureWindow's JTable.
*
* Column 0 = byte offset, data type
* Column 1 = name
* Column 2 = color
* Column 3 = unit
* Column 4 = conversion ratio
*
* @param column The column.
* @param row The row.
* @return The contents of the cell.
*/
public String getCellContents(int column, int row) {
// the first row is always the sync word
if(row == 0) {
if(column == 0) return "0, [Sync Word]";
else if(column == 1) return String.format("0x%02X", syncWord);
else return "";
}
// subsequent rows are the fields
row--;
int count = Controller.getDatasetsCount();
if(row < count) {
Dataset dataset = Controller.getDatasetByIndex(row);
if(column == 0) return dataset.location + ", " + dataset.processor.toString();
else if(column == 1) return dataset.name;
else if(column == 2) return "<html><font color=\"rgb(" + dataset.color.getRed() + "," + dataset.color.getGreen() + "," + dataset.color.getBlue() + ")\">\u25B2</font></html>";
else if(column == 3) return dataset.unit;
else if(column == 4) return String.format("%3.3f LSBs = %3.3f %s", dataset.conversionFactorA, dataset.conversionFactorB, dataset.unit);
else return "";
}
// last row is the checksum if it exists
if(checksumProcessor != null) {
if(column == 0) return checksumProcessorOffset + ", [Checksum]";
else if(column == 1) return checksumProcessor.toString();
else return "";
}
// this should never happen
return "";
}
/**
* @return The first unoccupied byte offset, or -1 if they are all occupied.
*/
public int getFirstAvailableOffset() {
// the packet is empty
if(packetSize == 1)
return 1;
// the packet is full
if(isFull())
return -1;
// check which bytes before the checksum are occupied
int size = packetSize;
if(checksumProcessor != null)
size -= checksumProcessor.getByteCount();
boolean[] byteUsed = new boolean[size];
byteUsed[0] = true; // the syncWord
for(Dataset dataset : Controller.getAllDatasets()) {
int start = dataset.location;
int end = start + dataset.processor.getByteCount() - 1;
for (int i = start; i <= end; i++)
byteUsed[i] = true;
}
// if the packet is sparse, return the first unused byte
for(int i = 0; i < byteUsed.length; i++)
if(byteUsed[i] == false)
return i;
// if the packet is not sparse, return the current packet size
return packetSize;
}
/**
* @return An array of BinaryFieldProcessors that each describe their data type and can convert raw bytes into a number.
*/
static public BinaryFieldProcessor[] getBinaryFieldProcessors() {
BinaryFieldProcessor[] processors = new BinaryFieldProcessor[8];
processors[0] = new BinaryFieldProcessor() {
@Override public String toString() { return "uint16 LSB First"; }
@Override public int getByteCount() { return 2; }
@Override public float extractValue(byte[] rawBytes) { return (float) (((0xFF & rawBytes[0]) << 0) |
((0xFF & rawBytes[1]) << 8));}
};
processors[1] = new BinaryFieldProcessor() {
@Override public String toString() { return "uint16 MSB First"; }
@Override public int getByteCount() { return 2; }
@Override public float extractValue(byte[] rawBytes) { return (float) (((0xFF & rawBytes[1]) << 0) |
((0xFF & rawBytes[0]) << 8));}
};
processors[2] = new BinaryFieldProcessor() {
@Override public String toString() { return "float32 LSB First"; }
@Override public int getByteCount() { return 4; }
@Override public float extractValue(byte[] bytes) { return Float.intBitsToFloat(((0xFF & bytes[0]) << 0) |
((0xFF & bytes[1]) << 8) |
((0xFF & bytes[2]) << 16) |
((0xFF & bytes[3]) << 24));}
};
processors[3] = new BinaryFieldProcessor() {
@Override public String toString() { return "float32 MSB First"; }
@Override public int getByteCount() { return 4; }
@Override public float extractValue(byte[] bytes) { return Float.intBitsToFloat(((0xFF & bytes[3]) << 0) |
((0xFF & bytes[2]) << 8) |
((0xFF & bytes[1]) << 16) |
((0xFF & bytes[0]) << 24));}
};
processors[4] = new BinaryFieldProcessor() {
@Override public String toString() { return "uint32 LSB First"; }
@Override public int getByteCount() { return 4; }
@Override public float extractValue(byte[] rawBytes) { return (float) (((0xFF & rawBytes[0]) << 0) |
((0xFF & rawBytes[1]) << 8) |
((0xFF & rawBytes[2]) << 16) |
((0xFF & rawBytes[3]) << 24));}
};
processors[5] = new BinaryFieldProcessor() {
@Override public String toString() { return "uint32 MSB First"; }
@Override public int getByteCount() { return 4; }
@Override public float extractValue(byte[] rawBytes) { return (float) (((0xFF & rawBytes[3]) << 0) |
((0xFF & rawBytes[2]) << 8) |
((0xFF & rawBytes[1]) << 16) |
((0xFF & rawBytes[0]) << 24));}
};
processors[6] = new BinaryFieldProcessor() {
@Override public String toString() { return "int16 LSB First"; }
@Override public int getByteCount() { return 2; }
@Override public float extractValue(byte[] rawBytes) { return (float) ((rawBytes[0] << 0) |
(rawBytes[1] << 8));}
};
processors[7] = new BinaryFieldProcessor() {
@Override public String toString() { return "int16 MSB First"; }
@Override public int getByteCount() { return 2; }
@Override public float extractValue(byte[] rawBytes) { return (float) ((rawBytes[1] << 0) |
(rawBytes[0] << 8));}
};
return processors;
}
/**
* @return An array of BinaryChecksumProcessors that each describe their type and can test for a valid checksum.
*/
static public BinaryChecksumProcessor[] getBinaryChecksumProcessors() {
BinaryChecksumProcessor[] processors = new BinaryChecksumProcessor[1];
processors[0] = new BinaryChecksumProcessor() {
@Override public String toString() { return "uint16 Checksum LSB First"; }
@Override public int getByteCount() { return 2; }
@Override public boolean testChecksum(byte[] bytes, int length) {
// sanity check: a 16bit checksum requires an even number of bytes
if(length % 2 != 0)
return false;
// calculate the sum
int wordCount = (length - getByteCount()) / 2; // 16bit words
int sum = 0;
int lsb = 0;
int msb = 0;
for(int i = 0; i < wordCount; i++) {
lsb = 0xFF & bytes[i*2];
msb = 0xFF & bytes[i*2 + 1];
sum += (msb << 8 | lsb);
}
// extract the reported checksum
lsb = 0xFF & bytes[wordCount*2];
msb = 0xFF & bytes[wordCount*2 + 1];
int checksum = (msb << 8 | lsb);
// test
sum %= 65536;
if(sum == checksum)
return true;
else
return false;
}
};
return processors;
}
/**
* Spawns a new thread that listens for incoming data, processes it, and populates the datasets.
* This method should only be called after the data structure has been defined and a connection has been made.
*
* @param stream The data to process.
*/
@Override public void startReceivingData(InputStream stream) {
thread = new Thread(() -> {
byte[] rx_buffer = new byte[packetSize];
BufferedInputStream bStream = new BufferedInputStream(stream, 2 * packetSize);
while(true) {
try {
// wait for data to arrive
while(bStream.available() < packetSize)
Thread.sleep(1);
// wait for the sync word
bStream.read(rx_buffer, 0, 1);
while(rx_buffer[0] != syncWord)
bStream.read(rx_buffer, 0, 1);
// get rest of packet after the sync word
bStream.read(rx_buffer, 0, packetSize - 1); // -1 for syncWord
// test checksum if enabled
boolean checksumPassed = true;
if(checksumProcessor != null)
checksumPassed = checksumProcessor.testChecksum(rx_buffer, packetSize - 1); // -1 for syncWord
if(!checksumPassed) {
NotificationsController.showVerboseForSeconds("Checksum failed.", 1, false);
continue;
}
// extract raw numbers and insert them into the datasets
for(Dataset dataset : Controller.getAllDatasets()) {
BinaryFieldProcessor processor = dataset.processor;
int byteOffset = dataset.location;
int byteCount = processor.getByteCount();
byte[] buffer = new byte[byteCount];
for(int i = 0; i < byteCount; i++)
buffer[i] = rx_buffer[byteOffset + i - 1]; // -1 for syncWord
float rawNumber = processor.extractValue(buffer);
dataset.add(rawNumber);
}
} catch(IOException | InterruptedException e) {
// stop and end this thread
try { bStream.close(); } catch(IOException e2) { }
NotificationsController.showVerboseForSeconds("The Binary Packet Processor thread is stopping.", 5, false);
return;
}
}
});
thread.setPriority(Thread.MAX_PRIORITY);
thread.setName("Binary Packet Processor");
thread.start();
}
/**
* Stops the Binary Packet Processor thread.
*/
@Override public void stopReceivingData() {
if(thread != null && thread.isAlive()) {
thread.interrupt();
while(thread.isAlive()); // wait
}
}
/**
* Displays a window for the user to interactively define the binary packet's data structure.
*
* @param parentWindow Window to center over.
* @param testMode True for test mode (disables editing), false for normal mode.
*/
@Override public void showDataStructureWindow(JFrame parentWindow, boolean testMode) {
new BinaryDataStructureWindow(parentWindow, this, testMode);
}
/**
* Window where the user defines the binary packet data structure.
*/
@SuppressWarnings("serial")
private class BinaryDataStructureWindow extends JDialog {
JTextField nameTextfield;
JButton colorButton;
JTextField unitTextfield;
JTextField conversionFactorAtextfield;
JTextField conversionFactorBtextfield;
JLabel unitLabel;
JButton addButton;
JButton resetButton;
JButton doneButton;
JTable dataStructureTable;
JScrollPane scrollableDataStructureTable;
/**
* Creates a new window where the user can define the binary data structure.
*
* @param parentWindow The window to center this BinaryDataStructureWindow over.
* @param packet A BinaryPacket representing the data structure.
* @param testMode If true, the user will only be able to view, not edit, the data structure.
*/
public BinaryDataStructureWindow(JFrame parentWindow, BinaryPacket packet, boolean testMode) {
super();
setTitle(testMode ? "Binary Packet Data Structure (Not Editable in Test Mode)" : "Binary Packet Data Structure");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
// all JTextFields let the user press enter to add the row
ActionListener pressEnterToAddRow = new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
addButton.doClick();
}
};
// user specifies the offset (first byte) of a field
JTextField offsetTextfield = new JTextField(Integer.toString(packet.getFirstAvailableOffset()), 3);
offsetTextfield.addActionListener(pressEnterToAddRow);
offsetTextfield.addFocusListener(new FocusListener() {
@Override public void focusLost(FocusEvent fe) {
try {
offsetTextfield.setText(offsetTextfield.getText().trim());
Integer.parseInt(offsetTextfield.getText());
} catch(Exception e) {
offsetTextfield.setText(Integer.toString(packet.getFirstAvailableOffset()));
if(packet.isFull())
addButton.setEnabled(false);
}
}
@Override public void focusGained(FocusEvent fe) {
offsetTextfield.selectAll();
}
});
// user specifies the processor of a field (the processor converts raw bytes into numbers, or evaluates checksums)
JComboBox<Object> processorCombobox = new JComboBox<Object>();
for(BinaryFieldProcessor processor : BinaryPacket.getBinaryFieldProcessors())
processorCombobox.addItem(processor);
for(BinaryChecksumProcessor processor : BinaryPacket.getBinaryChecksumProcessors())
processorCombobox.addItem(processor);
processorCombobox.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent ae) {
if(processorCombobox.getSelectedItem() instanceof BinaryFieldProcessor) {
nameTextfield.setEnabled(true);
colorButton.setEnabled(true);
unitTextfield.setEnabled(true);
conversionFactorAtextfield.setEnabled(true);
conversionFactorBtextfield.setEnabled(true);
} else if(processorCombobox.getSelectedItem() instanceof BinaryChecksumProcessor) {
nameTextfield.setEnabled(false);
nameTextfield.setText("");
colorButton.setEnabled(false);
unitTextfield.setEnabled(false);
unitTextfield.setText("");
unitLabel.setText("");
conversionFactorAtextfield.setEnabled(false);
conversionFactorAtextfield.setText("1.0");
conversionFactorBtextfield.setEnabled(false);
conversionFactorBtextfield.setText("1.0");
}
}
});
// user specifies the name of a field
nameTextfield = new JTextField("", 15);
nameTextfield.addActionListener(pressEnterToAddRow);
nameTextfield.addFocusListener(new FocusListener() {
@Override public void focusLost(FocusEvent e) {
nameTextfield.setText(nameTextfield.getText().trim());
}
@Override public void focusGained(FocusEvent e) {
nameTextfield.selectAll();
}
});
// user specifies the color of a field
colorButton = new JButton("\u25B2");
colorButton.setForeground(Controller.getDefaultLineColor());
colorButton.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(BinaryDataStructureWindow.this, "Pick a Color for " + nameTextfield.getText(), Color.BLACK);
if(color != null)
colorButton.setForeground(color);
}
});
// user specifies the unit of a field
unitTextfield = new JTextField("", 15);
unitTextfield.addActionListener(pressEnterToAddRow);
unitTextfield.addFocusListener(new FocusListener() {
@Override public void focusLost(FocusEvent arg0) {
unitTextfield.setText(unitTextfield.getText().trim());
unitLabel.setText(unitTextfield.getText());
}
@Override public void focusGained(FocusEvent arg0) {
unitTextfield.selectAll();
}
});
unitTextfield.addKeyListener(new KeyListener() {
@Override public void keyReleased(KeyEvent ke) {
unitTextfield.setText(unitTextfield.getText().trim());
unitLabel.setText(unitTextfield.getText());
}
@Override public void keyPressed(KeyEvent ke) { }
@Override public void keyTyped(KeyEvent ke) { }
});
// user specifies the conversion ratio of a field as "x LSBs = x [Units]"
conversionFactorAtextfield = new JTextField("1.0", 4);
conversionFactorAtextfield.addActionListener(pressEnterToAddRow);
conversionFactorAtextfield.addFocusListener(new FocusListener() {
@Override public void focusLost(FocusEvent arg0) {
try {
conversionFactorAtextfield.setText(conversionFactorAtextfield.getText().trim());
double value = Double.parseDouble(conversionFactorAtextfield.getText());
if(value == 0.0 || value == Double.NaN || value == Double.POSITIVE_INFINITY || value == Double.NEGATIVE_INFINITY) throw new Exception();
} catch(Exception e) {
conversionFactorAtextfield.setText("1.0");
}
}
@Override public void focusGained(FocusEvent arg0) {
conversionFactorAtextfield.selectAll();
}
});
conversionFactorBtextfield = new JTextField("1.0", 4);
conversionFactorBtextfield.addActionListener(pressEnterToAddRow);
conversionFactorBtextfield.addFocusListener(new FocusListener() {
@Override public void focusLost(FocusEvent arg0) {
try {
conversionFactorBtextfield.setText(conversionFactorBtextfield.getText().trim());
double value = Double.parseDouble(conversionFactorBtextfield.getText());
if(value == 0.0 || value == Double.NaN || value == Double.POSITIVE_INFINITY || value == Double.NEGATIVE_INFINITY) throw new Exception();
} catch(Exception e) {
conversionFactorBtextfield.setText("1.0");
}
}
@Override public void focusGained(FocusEvent arg0) {
conversionFactorBtextfield.selectAll();
}
});
unitLabel = new JLabel("_______________");
unitLabel.setMinimumSize(unitLabel.getPreferredSize());
unitLabel.setPreferredSize(unitLabel.getPreferredSize());
unitLabel.setHorizontalAlignment(JLabel.LEFT);
unitLabel.setText("");
// user clicks Add to insert a new field into the data structure if possible
addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
int location = Integer.parseInt(offsetTextfield.getText());
Object processor = processorCombobox.getSelectedItem();
String name = nameTextfield.getText().trim();
Color color = colorButton.getForeground();
String unit = unitTextfield.getText();
float conversionFactorA = Float.parseFloat(conversionFactorAtextfield.getText());
float conversionFactorB = Float.parseFloat(conversionFactorBtextfield.getText());
if(processor instanceof BinaryFieldProcessor) {
if(name.equals("")) {
JOptionPane.showMessageDialog(BinaryDataStructureWindow.this, "A name is required.", "Error: Name Required", JOptionPane.ERROR_MESSAGE);
return;
}
String errorMessage = packet.insertField(location, (BinaryFieldProcessor) processor, name, color, unit, conversionFactorA, conversionFactorB);
dataStructureTable.revalidate();
dataStructureTable.repaint();
if(errorMessage != null) {
JOptionPane.showMessageDialog(BinaryDataStructureWindow.this, errorMessage, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(packet.isFull()) {
offsetTextfield.setEnabled(false);
processorCombobox.setEnabled(false);
nameTextfield.setEnabled(false);
colorButton.setEnabled(false);
unitTextfield.setEnabled(false);
conversionFactorAtextfield.setEnabled(false);
conversionFactorBtextfield.setEnabled(false);
addButton.setEnabled(false);
} else {
int newLocation = packet.getFirstAvailableOffset();
offsetTextfield.setText(Integer.toString(newLocation));
nameTextfield.requestFocus();
nameTextfield.selectAll();
}
} else if(processor instanceof BinaryChecksumProcessor) {
String errorMessage = packet.insertChecksum(location, (BinaryChecksumProcessor) processor);
dataStructureTable.revalidate();
dataStructureTable.repaint();
if(errorMessage != null) {
JOptionPane.showMessageDialog(BinaryDataStructureWindow.this, errorMessage, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(packet.isFull()) {
offsetTextfield.setEnabled(false);
processorCombobox.setEnabled(false);
nameTextfield.setEnabled(false);
colorButton.setEnabled(false);
unitTextfield.setEnabled(false);
conversionFactorAtextfield.setEnabled(false);
conversionFactorBtextfield.setEnabled(false);
addButton.setEnabled(false);
} else {
int newLocation = packet.getFirstAvailableOffset();
offsetTextfield.setText(Integer.toString(newLocation));
nameTextfield.requestFocus();
nameTextfield.selectAll();
processorCombobox.setSelectedIndex(0);
}
}
}
});
// user clicks Reset to remove all fields from the data structure
resetButton = new JButton("Reset");
resetButton.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent arg0) {
packet.clear();
dataStructureTable.revalidate();
dataStructureTable.repaint();
offsetTextfield.setEnabled(true);
processorCombobox.setEnabled(true);
nameTextfield.setEnabled(true);
colorButton.setEnabled(true);
unitTextfield.setEnabled(true);
conversionFactorAtextfield.setEnabled(true);
conversionFactorBtextfield.setEnabled(true);
addButton.setEnabled(true);
offsetTextfield.setText(Integer.toString(packet.getFirstAvailableOffset()));
nameTextfield.requestFocus();
nameTextfield.selectAll();
processorCombobox.setSelectedIndex(0);
}
});
// user clicks Done when the data structure is complete
doneButton = new JButton("Done");
doneButton.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
if(packet.isEmpty()) {
JOptionPane.showMessageDialog(BinaryDataStructureWindow.this, "Error: At least one field is required.", "Error", JOptionPane.ERROR_MESSAGE);
} else {
dispose();
}
}
});
JPanel dataEntryPanel = new JPanel();
dataEntryPanel.setBorder(new EmptyBorder(5, 5, 0, 5));
dataEntryPanel.add(new JLabel("Byte Offset"));
dataEntryPanel.add(offsetTextfield);
dataEntryPanel.add(Box.createHorizontalStrut(20));
dataEntryPanel.add(processorCombobox);
dataEntryPanel.add(Box.createHorizontalStrut(20));
dataEntryPanel.add(new JLabel("Name"));
dataEntryPanel.add(nameTextfield);
dataEntryPanel.add(Box.createHorizontalStrut(20));
dataEntryPanel.add(new JLabel("Color"));
dataEntryPanel.add(colorButton);
dataEntryPanel.add(Box.createHorizontalStrut(20));
dataEntryPanel.add(new JLabel("Unit"));
dataEntryPanel.add(unitTextfield);
dataEntryPanel.add(Box.createHorizontalStrut(80));
dataEntryPanel.add(conversionFactorAtextfield);
dataEntryPanel.add(new JLabel(" LSBs = "));
dataEntryPanel.add(conversionFactorBtextfield);
dataEntryPanel.add(unitLabel);
dataEntryPanel.add(Box.createHorizontalStrut(80));
dataEntryPanel.add(addButton);
dataEntryPanel.add(Box.createHorizontalStrut(20));
dataEntryPanel.add(resetButton);
dataEntryPanel.add(Box.createHorizontalStrut(20));
dataEntryPanel.add(doneButton);
dataStructureTable = new JTable(new AbstractTableModel() {
@Override public String getColumnName(int column) {
if(column == 0) return "Byte Offset, Data Type";
else if(column == 1) return "Name";
else if(column == 2) return "Color";
else if(column == 3) return "Unit";
else if(column == 4) return "Conversion Ratio";
else return "Error";
}
@Override public Object getValueAt(int row, int column) {
return packet.getCellContents(column, row);
}
@Override public int getRowCount() {
return packet.getRowCount();
}
@Override public int getColumnCount() {
return 5;
}
});
scrollableDataStructureTable = new JScrollPane(dataStructureTable);
JPanel tablePanel = new JPanel(new GridLayout(1, 1));
tablePanel.setBorder(new EmptyBorder(5, 5, 5, 5));
tablePanel.add(scrollableDataStructureTable, BorderLayout.CENTER);
dataStructureTable.setRowHeight((int) tablePanel.getFont().getStringBounds("Abcdefghijklmnopqrstuvwxyz", new FontRenderContext(null, true, true)).getHeight()); // fixes display scaling issue
add(dataEntryPanel, BorderLayout.NORTH);
add(tablePanel, BorderLayout.CENTER);
pack();
setMinimumSize(new Dimension(getPreferredSize().width, 500));
setLocationRelativeTo(parentWindow);
nameTextfield.requestFocus();
if(packet.isFull()) {
offsetTextfield.setEnabled(false);
processorCombobox.setEnabled(false);
nameTextfield.setEnabled(false);
colorButton.setEnabled(false);
unitTextfield.setEnabled(false);
conversionFactorAtextfield.setEnabled(false);
conversionFactorBtextfield.setEnabled(false);
addButton.setEnabled(false);
resetButton.setEnabled(true);