-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParityDataLinkLayer.java
More file actions
266 lines (207 loc) · 8.21 KB
/
ParityDataLinkLayer.java
File metadata and controls
266 lines (207 loc) · 8.21 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
// =============================================================================
/**
* A data link layer that uses start/stop tags and byte packing to frame the
* data, and that uses a single parity bit to perform error detection.
*
* @author Scott F. H. Kaplan -- http://www.cs.amherst.edu/~sfkaplan
* @date 2008 March 03
* @version %I% %G%
**/
public class ParityDataLinkLayer extends DataLinkLayer {
// =============================================================================
// =========================================================================
/**
* The constructor. Make a new parity-checking data link layer.
*
* @param physicalLayer
* The physical layer through which this data link layer should
* communicate.
**/
public ParityDataLinkLayer(PhysicalLayer physicalLayer) {
// Initialize the layer.
initialize(physicalLayer);
} // ParityDataLinkLayer
// =========================================================================
// =========================================================================
/**
* Accept a buffer of data to send. Send it as divided into multiple frames
* of a fixed, maximum size. Add a parity bit for error checking to each
* frame. Call the physical layer to actually send each frame.
*
* @param data
* An array of bytes to be framed and transmitted.
**/
public void send(byte[] data) {
// Calculate the number of frames needed to transmit this data.
int numberFrames = (int) Math
.ceil((double) data.length / _maxFrameSize);
// Construct each frame and send it.
for (int frameNumber = 0; frameNumber < numberFrames; frameNumber++) {
int beginIndex = _maxFrameSize * frameNumber;
int endIndex = _maxFrameSize * (frameNumber + 1);
if (endIndex > data.length) {
endIndex = data.length;
}
byte[] frame = constructFrame(data, beginIndex, endIndex);
physicalLayer.send(frame);
}
} // send (byte[] data)
// =========================================================================
// =========================================================================
/**
* Create a single frame to be transmitted.
*
* @param data
* The original buffer of data from which to extract a frame's
* worth.
* @param begin
* The starting index from the original data buffer.
* @param end
* The ending index from the original frame buffer.
* @return A byte array that contains an entirely constructed frame.
**/
private byte[] constructFrame(byte[] data, int begin, int end) {
// Allocate an array of bytes large enough to hold the largest possible
// frame (tags and parity byte included).
byte[] framedData = new byte[(_maxFrameSize * 2) + 3];
// Begin with the start tag.
int frameIndex = 0;
framedData[frameIndex++] = _startTag;
// Add each byte of original data.
for (int dataIndex = begin; dataIndex < end; dataIndex++) {
// If the current data byte is itself a metadata tag, then preceed
// it with an escape tag.
byte currentByte = data[dataIndex];
if ((currentByte == _startTag) || (currentByte == _stopTag)
|| (currentByte == _escapeTag)) {
framedData[frameIndex++] = _escapeTag;
}
// Add the data byte itself.
framedData[frameIndex++] = currentByte;
}
// Calculate the parity bit (which is placed in its own byte).
framedData[frameIndex++] = calculateParity(data, begin, end);
// End with a stop tag.
framedData[frameIndex++] = _stopTag;
// Copy the complete frame into a buffer of the exact desired
// size.
byte[] finalFrame = new byte[frameIndex];
for (int i = 0; i < frameIndex; i++) {
finalFrame[i] = framedData[i];
}
return finalFrame;
} // constructFrame (byte[] data, int begin, int end)
// =========================================================================
// =========================================================================
/**
* Calculate the parity of the sequence of bytes.
*
* @param data
* A buffer of bytes.
* @param begin
* The starting index of the bytes to examine.
* @param end
* The ending index of the bytes to examine.
* @return The parity (0 or 1) for this group of bytes.
**/
private byte calculateParity(byte[] data, int begin, int end) {
// Create a bit vector from the bytes specified.
BitVector bits = new BitVector(data, begin, end);
// Iterate over the bit vector, counting the bits whose value is 1.
int ones = 0;
for (int i = 0; i < bits.length(); i++) {
ones += (bits.getBit(i) ? 1 : 0);
}
// Return the parity.
return (byte) (ones % 2);
} // calculateParity (byte[] data, int begin, int end)
// =========================================================================
// =========================================================================
/**
* Determine whether the buffered data forms a complete frame.
*
* @return Whether a complete buffer has arrived.
**/
protected boolean receivedCompleteFrame() {
// Any frame with less than two bytes cannot be complete, since even the
// empty frame contains a start and a stop tag.
if (bufferIndex < 2) {
return false;
}
// A frame is complete iff the byte received is an non-escaped stop tag.
return ((incomingBuffer[bufferIndex - 1] == _stopTag) && (incomingBuffer[bufferIndex - 2] != _escapeTag));
} // receivedCompleteFrame
// =========================================================================
// =========================================================================
/**
* Remove the framing metadata and return the original data.
*
* @return The data carried in this frame; <tt>null</tt> if the data was not
* successfully received.
**/
protected byte[] processFrame() {
// Allocate sufficient space to hold the original data, which
// does not need space for the start/stop tags.
byte[] originalData = new byte[bufferIndex - 3];
// Check the start tag.
int frameIndex = 0;
if (incomingBuffer[frameIndex++] != _startTag) {
System.err.println("ParityDLL: Missing start tag!");
return null;
}
// Loop through the frame, extracting the bytes. Look ahead to find the
// stop tag (making sure it is not escaped), because the byte before
// that is the parity byte.
int originalIndex = 0;
while ((incomingBuffer[frameIndex + 1] != _stopTag)
|| (incomingBuffer[frameIndex] == _escapeTag)) {
// If the next original byte is escape-tagged, then skip
// the tag so that only the real data is extracted.
if (incomingBuffer[frameIndex] == _escapeTag) {
frameIndex++;
}
// Copy the original byte.
originalData[originalIndex++] = incomingBuffer[frameIndex++];
}
// Allocate a space that is only as large as the original
// message and then copy the original data into it.
byte[] finalData = new byte[originalIndex];
for (int i = 0; i < originalIndex; i++) {
finalData[i] = originalData[i];
}
// Calculate the parity of the extracted data and compare it to the
// received parity bit. If there's a mismatch, return null.
byte parity = calculateParity(originalData, 0, originalIndex);
if (parity != incomingBuffer[frameIndex]) {
System.err.print("ParityDLL message: ");
for (int i = 0; i < finalData.length; i++) {
System.err.print((char) finalData[i]);
}
System.err.println(" <= Parity mismatch!");
finalData = null;
}
return finalData;
} // processFrame
// =========================================================================
// =========================================================================
// DATA MEMBERS
/**
* The tag that marks the beginning of a frame.
**/
final byte _startTag = (byte) '{';
/**
* The tag that marks the end of a frame.
**/
final byte _stopTag = (byte) '}';
/**
* The tag that marks the following byte as data (and not metadata).
**/
final byte _escapeTag = (byte) '\\';
/**
* The maximum number of data (not metadata) bytes in a frame.
**/
final int _maxFrameSize = 8;
// =========================================================================
// =============================================================================
} // class ParityDataLinkLayer
// =============================================================================