Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Mar 21st, 2010 | Syntax: Java 5 | Size: 9.64 KB | Hits: 83 | Expires: Never
Copy text to clipboard
  1. package cam;
  2.  
  3. import java.net.*;
  4. import java.io.*;
  5.  
  6. public class Camera {
  7.        
  8.         String name = null;
  9.         int[] ipv4adr = null;
  10.         String ipName = null;
  11.         int port = 0;
  12.         String authentication = null;
  13.         /* Used for debugging. If true, more info is output to console */
  14.         private final static boolean DEBUG = true;
  15.  
  16.         /* Constructors */
  17.        
  18.         public Camera() {}
  19.  
  20.         public Camera(int[] ipv4adr, int port, String authentication) {
  21.                 this.ipv4adr = ipv4adr;
  22.                 this.port = port;
  23.                 this.authentication = utils.Base64.encode(authentication);
  24.                 name = getName();
  25.         }
  26.  
  27.         public Camera(String ipName, int[] ipv4adr, int port, String authentication) {
  28.                 this.ipName = ipName;
  29.                 this.ipv4adr = ipv4adr;
  30.                 this.port = port;
  31.                 this.authentication = utils.Base64.encode(authentication);
  32.                 name = getName();
  33.         }
  34.        
  35.         /* Methods */
  36.        
  37.         /**
  38.          * Send a simple request using the cameras CGI interface
  39.          * @param       request request-string according to cameras CGI interface
  40.          * @return      String representation of camera built-in server response
  41.          */
  42.         public String getResponse(String request) {
  43.                 String response = null;
  44.                 /* Return null if IP address is uninitialized */
  45.                 if((ipv4adr == null && ipName == null) || port == 0)
  46.                         return response;
  47.                
  48.                 /* setup request-string */
  49.                 String requestURL = getBaseURLString();
  50.                 requestURL += request;
  51.                 /* Create a URL object */
  52.                 URL url = null;
  53.                 try {
  54.                         url = new URL(requestURL);
  55.                 }
  56.                 catch (MalformedURLException e) {
  57.                         System.out.println(e);
  58.                         return response;
  59.                 }
  60.                
  61.                
  62.                 if(DEBUG) System.out.println("url is:" + url);
  63.                
  64.                 /* Setup connection, also sends the request which is incorporated in the URL */
  65.                 InputStream inStream = null;
  66.                 URLConnection con = null;
  67.                 try {
  68.                         con = url.openConnection();
  69.                         con.connect();
  70.                         inStream = con.getInputStream();
  71.                 }
  72.                 catch (IOException e) {
  73.                         System.out.println(e);
  74.                         inStream = null;
  75.                         return response;
  76.                 }
  77.                 /* Get response */
  78.                 byte[] resBytes = new byte[1024];
  79.                 int count = 0;
  80.                 try {
  81.                         count = inStream.read(resBytes, 0, resBytes.length);
  82.                 }
  83.                 catch (IOException e) {
  84.                         System.out.println(e);
  85.                         return response;
  86.                 }
  87.                 response = "";
  88.                 /* Convert byte-response to String */
  89.                 for(int i = 0; i < count; i++)
  90.                         response += (char) resBytes[i];
  91.                 try {
  92.                         inStream.close();
  93.                 } catch (IOException e) {
  94.                         System.out.println(e);
  95.                 }
  96.                 inStream = null;
  97.                
  98.                 return response.trim();
  99.         }
  100.        
  101.         /**
  102.          * Get camera name using socket if necessary to get it from camera
  103.          * @return      Camera name
  104.          */
  105.         public String getName() {
  106.                 if(name != null)
  107.                         return name;
  108.                 if((ipv4adr == null) || (port == 0))
  109.                         return null;
  110.  
  111.                 ConnectionWrapper camConn = null;
  112.                 if(ipName == null)
  113.                         camConn = new ConnectionWrapper(ipv4adr, port);
  114.                 else
  115.                         camConn = new ConnectionWrapper(ipName, port);
  116.  
  117.                 String requestString =  "GET /Get?Func=CameraName&Kind=1 HTTP/1.1\r\n" +
  118.                                                                 "Host: "+ getIPAsString() +"\r\n" +
  119.                                                                 "Authorization: Basic " + authentication + "\r\n" +
  120.                                                                 "\r\n";
  121.                 if(DEBUG) System.out.println("Request:\n" + requestString);
  122.                 byte[] requestBytes = requestString.getBytes();
  123.                 try {
  124.                         camConn.outStream.write(requestBytes, 0, requestBytes.length);
  125.                 }
  126.                 catch (IOException e) {
  127.                         System.out.println("Failed to write to stream:\n" + e);
  128.                         camConn.close();
  129.                         return name;
  130.                 }
  131.                 byte[] responseBytes = new byte[1024];
  132.                 int count = 0;
  133.                 try {
  134.                         count = camConn.inStream.read(responseBytes, 0, responseBytes.length); // Receive "HTTP/1.0 200 OK" packet
  135.                         if(new String(responseBytes, 0, count).indexOf("HTTP/1.0 200 OK") != -1 )
  136.                                 count = camConn.inStream.read(responseBytes, 0, responseBytes.length);
  137.                 }
  138.                 catch (Exception e) {
  139.                         System.out.println(e);
  140.                         camConn.close();
  141.                         return name;
  142.                 }
  143.                 String temp = new String(responseBytes, 0, count);
  144.                 //System.out.println("Response:\n" + temp);
  145.                 String finder = "Data:";
  146.                 int nameIndex = ( temp.indexOf(finder) + finder.length() );
  147.                 name = temp.substring(nameIndex, temp.indexOf('\r', nameIndex));
  148.                
  149.                 camConn.close();
  150.                
  151.                 return  name;
  152.         }
  153.        
  154.         /**
  155.          * Connects to camera, and captures an MJPEG stream (sequence of JPEG images), untrimmed (some content
  156.          * info and boundary info included). Needs to be extended/altered with trimming and length control.
  157.          */
  158.         public void getMJPEGStream(long durationSeconds) {
  159.                 // Return if uninitialized
  160.                 if((ipv4adr == null && ipName == null) || (port == 0) || (authentication == null))
  161.                         return;
  162.                 // Set up connection and streams, prepare CGI-request to camera
  163.                 ConnectionWrapper camConn = null;
  164.                 if(ipName == null)
  165.                         camConn = new ConnectionWrapper(ipv4adr, port);
  166.                 else
  167.                         camConn = new ConnectionWrapper(ipName, port);
  168.  
  169.                 InputStream mjpegStream = camConn.inStream;
  170.                 String requestString =  "GET /nphMotionJpeg?Resolution=320x240&Quality=Standard HTTP/1.1\r\n" +
  171.                                                                 "Host: "+ getIPAsString() +"\r\n" +
  172.                                                                 "Authorization: Basic " + authentication + "\r\n" +
  173.                                                                 "\r\n";
  174.                 if(DEBUG) System.out.print("Request:\n" + requestString);
  175.                 byte[] requestBytes = requestString.getBytes();
  176.                 // Output-file
  177.                 FileOutputStream fstream = null;
  178.                 try {
  179.                         fstream = new FileOutputStream("mjpeg_" + name + "_" + utils.Timestamp.getStringTime() + ".mjpeg");
  180.                 }
  181.                 catch (FileNotFoundException e) {
  182.                         System.out.println(e);
  183.                 }
  184.                 // Array to store bytes read from network-stream
  185.                 byte[] streamBytes = new byte[4096];
  186.                 int count = 0;
  187.                 // Send request to camera
  188.                 try {
  189.                         camConn.outStream.write(requestBytes, 0, requestBytes.length);
  190.                 }
  191.                 catch (IOException e) {
  192.                         System.out.println(e);
  193.                         camConn.close();
  194.                 }
  195.                 // First packet is "HTTP/1.0 200 OK\r\n". Can be dismissed.
  196.                 try {
  197.                         while(mjpegStream.available() <= 0) ;
  198.                         count = mjpegStream.read(streamBytes, 0, streamBytes.length);
  199.                         if(DEBUG) System.out.println("Read " + count + " trimmable bytes from camera stream during stream initialization");
  200.                 } catch (IOException e) {
  201.                         System.out.println(e);
  202.                 }
  203.                 // When to stop reading from stream
  204.                 long endTime = System.currentTimeMillis() + (durationSeconds * 1000);
  205.                 while(System.currentTimeMillis() < endTime) {
  206.                         try {
  207.                                 while(mjpegStream.available() <= 0) ; // This might be dangerous when reading stream for long time
  208.                                 count = mjpegStream.read(streamBytes, 0, streamBytes.length);
  209.                                 fstream.write(streamBytes, 0, count);
  210.                                 if(DEBUG) System.out.println("Read " + count + " bytes from camera stream");
  211.                         } catch (IOException e) {
  212.                                 System.out.println(e);
  213.                         }
  214.                 }
  215.                 camConn.close();
  216.                 try {
  217.                         fstream.close();
  218.                 } catch (IOException e) {
  219.                         System.out.println(e);
  220.                 }
  221.         }
  222.  
  223.         /**
  224.          * Connects to camera, and captures an MPEG4 stream, with or without sound.
  225.          */
  226.         public void getMPEG4Stream(long durationSeconds) {
  227.                 // Return if uninitialized
  228.                 if((ipv4adr == null && ipName == null) || (port == 0) || (authentication == null))
  229.                         return;
  230.                 // Set up connection and streams, prepare CGI-request to camera
  231.                 ConnectionWrapper camConn = null;
  232.                 if(ipName == null)
  233.                         camConn = new ConnectionWrapper(ipv4adr, port);
  234.                 else
  235.                         camConn = new ConnectionWrapper(ipName, port);
  236.  
  237.                 InputStream mjpegStream = camConn.inStream;
  238.                 // Format is <rtpOverHttp?Url=nphMpeg4/audio-resol>
  239.                 String requestString =  "GET /rtpOverHttp?Url=nphMpeg4/nil-320x240 HTTP/1.1\r\n" +
  240.                                                                 "Host: "+ getIPAsString() +"\r\n" +
  241.                                                                 "Authorization: Basic " + authentication + "\r\n" +
  242.                                                                 "\r\n";
  243.                 if(DEBUG) System.out.print("Request:\n" + requestString);
  244.                 byte[] requestBytes = requestString.getBytes();
  245.                 // Output-file
  246.                 FileOutputStream fstream = null;
  247.                 try {
  248.                         fstream = new FileOutputStream("mpeg4_" + name + "_" + utils.Timestamp.getStringTime() + ".mpeg4");
  249.                 }
  250.                 catch (FileNotFoundException e) {
  251.                         System.out.println(e);
  252.                 }
  253.                 // Array to store bytes read from network-stream
  254.                 byte[] streamBytes = new byte[4096];
  255.                 int count = 0;
  256.                 // Send request to camera
  257.                 try {
  258.                         camConn.outStream.write(requestBytes, 0, requestBytes.length);
  259.                 }
  260.                 catch (IOException e) {
  261.                         System.out.println(e);
  262.                         camConn.close();
  263.                 }
  264.                 // First 2 packets are "HTTP/1.0 200 OK\r\n" and "Content-type: video/x-pcc-nwc-rtp\r\n\r\n". Can be dismissed.
  265.                 for(int i = 0; i < 2; i++) {
  266.                         try {
  267.                                 while(mjpegStream.available() <= 0) ;
  268.                                 count = mjpegStream.read(streamBytes, 0, streamBytes.length);
  269.                                 if(DEBUG) System.out.println("Read " + count + " trimmable bytes from camera stream during stream initialization");
  270.                         } catch (IOException e) {
  271.                                 System.out.println(e);
  272.                         }
  273.                 }
  274.                 // When to stop reading from stream
  275.                 long endTime = System.currentTimeMillis() + (durationSeconds * 1000);
  276.                 while(System.currentTimeMillis() < endTime) {
  277.                         try {
  278.                                 while(mjpegStream.available() <= 0) ; // This might be dangerous when reading stream for long time
  279.                                 count = mjpegStream.read(streamBytes, 0, streamBytes.length);
  280.                                 fstream.write(streamBytes, 0, count);
  281.                                 if(DEBUG) System.out.println("Read " + count + " bytes from camera stream");
  282.                         } catch (IOException e) {
  283.                                 System.out.println(e);
  284.                         }
  285.                 }
  286.                 camConn.close();
  287.                 try {
  288.                         fstream.close();
  289.                 } catch (IOException e) {
  290.                         System.out.println(e);
  291.                 }
  292.         }
  293.        
  294.         /**
  295.          *  Method to return base URL string in
  296.          *  format "http://ipName:port/"
  297.          *  or "http://ip[0].ip[1].ip[2].ip[3]:port/"
  298.          *  @return     Base URL
  299.          */
  300.         private String getBaseURLString() {
  301.                 String s = "http://";
  302.                 if(ipName == null)
  303.                         s += getIPAsString();
  304.                 else
  305.                         s += ipName;
  306.                 s += ":" + port + "/";
  307.                 return s;
  308.         }
  309.        
  310.         /**
  311.          * Get IP address as a string in format ip[0].ip[1].ip[2].ip[3]
  312.          * @return      IP address
  313.          */
  314.         private String getIPAsString() {
  315.                 String s = "";
  316.                 for(int i = 0; i < 4; i++) {
  317.                         s += ipv4adr[i];
  318.                         if(i < 3) s += ".";
  319.                 }
  320.                 return s;
  321.         }
  322. }