RobotCore 1.0
WPILib port to raspberry Pi
Loading...
Searching...
No Matches
PiCamera.java
1/*
2 * Copyright (C) 2020 John H. Gaby
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, version 3 of the License.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * Contact: robotics@gabysoft.com
17 */
18
19package robotCore;
20
21import java.io.FileNotFoundException;
22import java.io.PrintWriter;
23import java.util.ArrayList;
24import java.util.Timer;
25import java.util.TimerTask;
26
27import org.wpilib.hardware.hal.HALUtil;
28
29
44public class PiCamera implements Network.NetworkReceiver {
50 public class PiCameraStats {
51 public int m_averageDelay = 0;
52 public int m_maxDelay = 0;
53 public int m_minDelay = Integer.MAX_VALUE;
54 public int m_lostFrames;
55 public long m_time;
56
57 public PiCameraStats(int avgDelay, int maxDelay, int minDelay, int lostFrames, long time) {
58 m_averageDelay = avgDelay;
59 m_maxDelay = maxDelay;
60 m_minDelay = minDelay;
61 m_lostFrames = lostFrames;
62 m_time = time;
63 }
64 }
65
70 public class PiCameraPoint {
71 public int m_x;
72 public int m_y;
73
74 public PiCameraPoint(int x, int y) {
75 m_x = x;
76 m_y = y;
77 }
78 }
79
84 public class PiCameraRect {
85 public int m_left;
86 public int m_top;
87 public int m_right;
88 public int m_bottom;
89
90 public PiCameraRect(int left, int top, int right, int bottom) {
91 m_left = left;
92 m_top = top;
93 m_right = right;
94 m_bottom = bottom;
95 }
96 }
97
102 public class PiCameraRegion {
103 public int m_color;
104 public int m_topLeft;
105 public int m_topRight;
107
109 public PiCameraRegion(int color, int left, int top, int right, int bottom, int topLeft, int topRight) {
110 m_color = color;
111 m_topLeft = topLeft;
112 m_topRight = topRight;
113 m_bounds = new PiCameraRect(left, top, right, bottom);
114 }
116 }
117
125 public class PiCameraRegions {
126 public int m_targetVertPos;
127 public int m_targetHorzPos;
128 public int m_frameNo;
129 public int m_width;
130 public int m_height;
131 public int m_lostFrames;
132 public int m_profile;
133 public long m_captureTime;
134 public int m_procTime;
135 public ArrayList<PiCameraRegion> m_regions = new ArrayList<PiCameraRegion>();
136
138 protected PiCameraRegions(int frameNo, int targetVertPos, int targetHorzPos, int width, int height, int lostFrames,
139 long captureTime, int procTime, int profile) {
140 Logger.log("PiCamera", -1, String.format("PiCameraRegions(): width = %d, height = %d", width, height));
141
142 m_frameNo = frameNo;
143 m_targetVertPos = targetVertPos;
144 m_targetHorzPos = targetHorzPos;
145 m_width = width;
146 m_height = height;
147 m_lostFrames = lostFrames;
148 m_profile = profile;
149 m_captureTime = captureTime;
150 m_procTime = procTime;
151 }
152
153 protected void addRegion(int color, int left, int top, int right, int bottom, int topLeft, int topRight) {
154 m_regions.add(new PiCameraRegion(color, left, top, right, bottom, topLeft, topRight));
155 }
157
162 public int getRegionCount() {
163 return (m_regions.size());
164 }
165
171 public PiCameraRegion getRegion(int region) {
172
173 if ((region >= 0) && (region < m_regions.size())) {
174
175 return (m_regions.get(region));
176 }
177 // System.out.println(region);
178 // Logger.Log("PiCamera", 2, "" + region);
179 return (null);
180 }
181 }
182
183 private static final int k_syncRetry = 5000;
184 private static final int k_syncFirst = 1000;
185
186 private Network m_network = null;
187 private PiCameraRegions m_regions = null;
188 private PiCameraRegions m_nextRegions = null;
189 private long m_syncTime;
190 private int m_averageDelayCount = 0;
191 private int m_averageDelayMax = 30;
192 private int m_averageDelaySum = 0;
193 private int m_averageDelay = 0;
194 private int m_maxDelay = 0;
195 private int m_minDelay = Integer.MAX_VALUE;
196 private int m_lostFrames;
197 private int m_lastLostFrame = 0;
198 private long m_startTime = 0;
199 private boolean m_connected = false;
200 private Timer m_watchdogTimer = new Timer();
201 private long m_lastMessage;
202 private static final int k_timeout = 5000;
203
204 public PiCamera() {
205 m_watchdogTimer.scheduleAtFixedRate(new TimerTask() {
206
207 @Override
208 public void run() {
209 if (m_connected) {
210 Logger.log("PiCamera", -1, "WatchDog");
211
212 m_network.sendMessage("k");
213
214 if (m_lastMessage + k_timeout < HALUtil.getMonotonicMilliseconds()) {
215 Logger.log("PiCamera", 3, "Network timeout");
216 m_network.closeConnection();
217 }
218 }
219 }
220 }, 1000, 1000);
221 }
222
227 public boolean isConnected() {
228 return (m_connected);
229 }
230
232 public static int[] parseIntegers(String str, int count) {
233 int[] args = new int[count];
234 int i = 0;
235
236 String[] tokens = str.trim().split(" ");
237
238 for (String token : tokens) {
239 try {
240 args[i] = Integer.parseInt(token);
241
242 } catch (NumberFormatException nfe) {
243 break;
244 }
245
246 if (++i >= count) {
247 break;
248 }
249 }
250
251 if (i == count) {
252 return (args);
253 }
254
255 return (null);
256 }
257
258 public static long[] parseLong(String str, int count) {
259 long[] args = new long[count];
260 int i = 0;
261
262 String[] tokens = str.trim().split(" ");
263
264 for (String token : tokens) {
265 try {
266 args[i] = Long.parseLong(token);
267
268 } catch (NumberFormatException nfe) {
269 break;
270 }
271
272 if (++i >= count) {
273 break;
274 }
275 }
276
277 if (i == count) {
278 return (args);
279 }
280
281 return (null);
282 }
283
284 long m_pingTime = 0;
285
286 public void Ping() {
287 m_pingTime = getTimeMs();
288
289 m_network.sendMessage("p");
290 }
292
300 public void dumpFrames(int count) {
301 Logger.log("PiCamera", 1, String.format("DumpFrames(%d)", count));
302 m_network.sendMessage(String.format("d %d", count));
303 }
304
305 PrintWriter m_log = null;
306 long m_logTime = 0;
307
313 public void startLogging(String path) {
314 synchronized (this) {
315 if (m_log != null) {
316 m_log.close();
317 m_log = null;
318 }
319
320 try {
321 m_log = new PrintWriter(path);
322 m_logTime = HALUtil.getMonotonicMilliseconds();
323 m_lastLostFrame = m_lostFrames;
324 m_minDelay = Integer.MAX_VALUE;
325 m_maxDelay = 0;
326
327 m_log.println("time,frame,#Regions,lost,cap delay,proc delay,left,top,right,bottom");
328 } catch (FileNotFoundException e) {
329 e.printStackTrace();
330 }
331 }
332 }
333
338 public void endLogging() {
339 synchronized (this) {
340 if (m_log != null) {
341 m_log.close();
342 m_log = null;
343 }
344 }
345 }
346
353 public void setLight(int value) {
354 m_network.sendMessage(String.format("L %d", value));
355 }
356
357 // public void SendJpeg(boolean send)
358 // {
359 // m_network.SendMessage("J" + (send ? "y" : "n"));
360 // }
361
367 public void setProfile(int profile) {
368 if ((profile >= 0) && (profile < 4)) {
369 m_network.sendMessage(String.format("P %d", profile));
370 }
371 }
372
378 public void startPiLog() {
379 m_network.sendMessage("ls");
380 }
381
386 public void endPiLog() {
387 m_network.sendMessage("le");
388 }
389
396 public void connect(String host, int port) {
397 m_network = new Network();
398
399 m_startTime = HALUtil.getMonotonicMilliseconds();
400
401 m_network.connect(this, host, port);
402
403 }
404
405 private void timeSync() {
406 long time = getTimeMs();
407 if (time > m_syncTime) {
408 Logger.log("PiCamera", -1, "TimeSync()");
409
410 m_network.sendMessage(String.format("T1 %d", getTimeMs()));
411
412 m_syncTime = time + k_syncRetry;
413 }
414
415 }
416
417 private void processCameraFrame(String args) {
418 long a[] = parseLong(args, 9);
419
420 if (a != null) {
421 m_nextRegions = new PiCameraRegions((int) a[0], (int) a[1], (int) a[2], (int) a[3], (int) a[4], (int) a[5],
422 a[6], (int) a[7], (int) a[8]);
423
424 int delay = (int) (HALUtil.getMonotonicMilliseconds() - m_nextRegions.m_captureTime);
425 int averageDelay = -1;
426
427 m_averageDelaySum += delay;
428 if (++m_averageDelayCount >= m_averageDelayMax) {
429 averageDelay = m_averageDelaySum / m_averageDelayCount;
430
431 m_averageDelayCount = 0;
432 m_averageDelaySum = 0;
433 }
434
435 synchronized (this) {
436 if (averageDelay > 0) {
437 m_averageDelay = averageDelay;
438 }
439
440 if (delay > m_maxDelay) {
441 m_maxDelay = delay;
442 }
443 if (delay < m_minDelay) {
444 m_minDelay = delay;
445 }
446
447 m_lostFrames = (int) a[5];
448 }
449 }
450 }
451
457 synchronized (this) {
458 return (new PiCameraStats(m_averageDelay, m_maxDelay, m_minDelay, m_lostFrames - m_lastLostFrame,
459 HALUtil.getMonotonicMilliseconds() - m_startTime));
460 }
461 }
462
467 public void clearStats() {
468 synchronized (this) {
469 m_maxDelay = 0;
470 m_minDelay = Integer.MAX_VALUE;
471 m_lostFrames = 0;
472 m_startTime = HALUtil.getMonotonicMilliseconds();
473 }
474 }
475
476 private void processCameraRegion(String args) {
477 int a[] = parseIntegers(args, 7);
478
479 if ((a != null) && (m_nextRegions != null)) {
480 m_nextRegions.addRegion(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
481 }
482 }
483
484 private void logFrame() {
485 long curTime = HALUtil.getMonotonicMilliseconds();
486 int size = m_regions.m_regions.size();
487
488 m_log.print(String.format("%d,%d,%d,%d,%d,%d", curTime - m_logTime, m_regions.m_frameNo, size,
489 m_regions.m_lostFrames, curTime - m_regions.m_captureTime, m_regions.m_procTime));
490
491 if (size > 0) {
492 PiCameraRegion region = m_regions.m_regions.get(0);
493
494 m_log.print(String.format(",%d,%d,%d,%d", region.m_bounds.m_left, region.m_bounds.m_top,
495 region.m_bounds.m_right, region.m_bounds.m_bottom));
496 }
497
498 m_log.println("");
499
500 if ((m_regions.m_frameNo % 30) == 0) {
501 m_log.flush(); // flush every 30 frames
502 }
503 }
504
505 private void processCameraEnd(String args) {
506 synchronized (this) {
507 m_regions = m_nextRegions;
508 m_nextRegions = null;
509
510 if (m_log != null) {
511 logFrame();
512 }
513 }
514
515 timeSync();
516 }
517
526 synchronized (this) {
527 return (m_regions);
528 }
529
530 }
531
532 private long getTimeMs() {
533 return HALUtil.getMonotonicMilliseconds();
534 }
535
536 private void processTimeSync() {
537 Logger.log("PiCamera", -1, "ProcessTimeSync()");
538
539 long time = getTimeMs();
540
541 m_network.sendMessage(String.format("T2 %d", time));
542 }
543
545 @Override
546 public void processData(String data) {
547 Logger.log("PiCamera", -1, String.format("Data: %s", data));
548
549 m_lastMessage = HALUtil.getMonotonicMilliseconds();
550
551 switch (data.charAt(0)) {
552 case 'F':
553 processCameraFrame(data.substring(1).trim());
554 break;
555
556 case 'R':
557 processCameraRegion(data.substring(1).trim());
558 break;
559
560 case 'E':
561 processCameraEnd(data.substring(1).trim());
562 break;
563
564 case 'p':
565 Logger.log("PiCamera", 3, String.format("Ping = %d", getTimeMs() - m_pingTime));
566 break;
567
568 case 'T': // sync
569 processTimeSync();
570 break;
571
572 default:
573 Logger.log("PiCamera", 3, String.format("Invalid command: %s", data));
574 break;
575 }
576 }
577
578 @Override
579 public void disconnected() {
580 m_connected = false;
581 }
582
583 @Override
584 public void connected() {
585 m_connected = true;
586
587 m_syncTime = getTimeMs() + k_syncFirst;
588 m_lastMessage = m_syncTime;
589 }
591}
The Logger class provides a mechanism to log messages.
Definition Logger.java:54
static void log(String tag, int level, String message, boolean noLogToConsole)
Definition Logger.java:161
The Network class handles network connections.
Definition Network.java:45
void closeConnection()
Definition Network.java:167
void sendMessage(String message)
Definition Network.java:129
int m_x
Specifies the horizontal position in pixels from the left.
Definition PiCamera.java:71
int m_y
Specifies the vertical position in pixels from the top.
Definition PiCamera.java:72
The PiCameraRect specifies an rectangular region.
Definition PiCamera.java:84
int m_bottom
Specifies the bottom edge of the region in pixels.
Definition PiCamera.java:88
int m_left
Specifies the left edge of the region in pixels.
Definition PiCamera.java:85
int m_top
Specifies the top edge of the region in pixels.
Definition PiCamera.java:86
int m_right
Specifies the right edge of the region in pixels.
Definition PiCamera.java:87
The PiCameraRegion specifies a single detected region.
PiCameraRect m_bounds
Specifies the bounding rectangle for the region.
int m_topLeft
Not currently used.
int m_topRight
Not currently used.
int m_color
Specifies the region color [0..3].
The PiCameraRegions specifies list of detected regions.
int m_targetHorzPos
Specifies the horizontal target position as set by the ImageViewer.
int m_height
Specifies the height of the camera image (e.g. 480).
int m_width
Specifies the width of the camera image (e.g. 640).
PiCameraRegion getRegion(int region)
int m_procTime
Specifies the time required to process this image in ms.
long m_captureTime
Specifies the time at which the image was acquired in ms.
int m_lostFrames
Specifies the number of lost frames.
int m_frameNo
Specifies the frame #.
int m_targetVertPos
Specifies the vertical target position as set by the ImageViewer.
int m_profile
Specifies which capture profile is in effect.
The PiCameraStats class collects the current camera performance statistics.
Definition PiCamera.java:50
int m_lostFrames
Specifies the number of lost frames.
Definition PiCamera.java:54
long m_time
Specifies the elapsed time.
Definition PiCamera.java:55
int m_averageDelay
Specifies the average frame delay.
Definition PiCamera.java:51
int m_maxDelay
Specifies the max frame delay.
Definition PiCamera.java:52
int m_minDelay
Specifies the min frame delay.
Definition PiCamera.java:53
The PiCamera class handles communication with the Raspberry Pi Camera.
Definition PiCamera.java:44
PiCameraRegions getRegions()
boolean isConnected()
void startLogging(String path)
PiCameraStats getStats()
void dumpFrames(int count)
void setProfile(int profile)
void connect(String host, int port)
void setLight(int value)
The NetworkReceiver interface provides a callback for received data on a network connection.
Definition Network.java:68
void processData(String command)