################################################################
# MBARI Benthic Rover
#
# Interface to onboard video server
#
# History:
#
#   29-Nov-06   RGH   V1.0 - basic functionality
#
################################################################

require 'monitor'
require 'rover_environment'
require 'rover_utils'

class Video < Monitor
  include LogHelper
  
  # Define cameras by name: NAME = channel_number
  #
  CHAMBER_1 = 1
  
  # Default configuration - video server at 192.168.0.90
  #
  def initialize ip = '192.168.0.90'
    super()
    syslog "#\n# Video server data log\n#"

    @ip = ip
  
  end

#################################################################
# Capture image and place the image file in the images directory.
# The target filename is constructed using the given prefix
# supplmented with a suffix that virtually guarantees a unique
# filename.
#
# Thread syncronization is implemented here via MonitorMixin
#
# camera_id - video channel number (1 to 4)
# prefix - use to label the file (e.g., "measurement_site")
#
#################################################################

  def captureImage(camera_id, prefix)
    self.synchronize do
  
      # Take an image. If successful copy file to image directory
      #
      if (frameGrab(camera_id))
        return moveImage(prefix)
      end
      
      return false
    end
  end


#~~~~~~~~~~~~~~~~~~~~~~ PRIVATE METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~

private

#################################################################
# Capture image from camera. The image file is placed in the
# current directory and named image.jpg
#
# camera_id - video channel number (1 to 4)
#
#################################################################

  def frameGrab camera_id
  
    unless (camera_id == CHAMBER_1)
      syslog "Video Fault: bad camera id: #{camera_id}"
      return false
    end
    
    getcmd = "wget -q http://#{@ip}/jpg/#{camera_id}/image.jpg"
    syslog getcmd
    
    # On error, log it and return false
    #
    unless (system(getcmd))
      syslog "Fault: failed to retrieve frame grab on camera #{camera_id}"
      return false
    end
    
    true
  end
 
#################################################################
# Move latest image file from local to the images directory. 
# The target filename is constructed using the given prefix
# supplmented with a suffix that virtually guarantees a unique
# filename.
#
#################################################################

  def moveImage prefix
    
    # Create a unique suffix from the current time down to 1/100 of a second
    #
    suffix = Time.now
    cpcmd = "cp image.jpg ../images/#{prefix}_#{\"%10.2f\" % suffix.to_f}.jpg"
    datalog cpcmd
    
    # On error, log it and return false
    #
    unless (system(cpcmd))
      syslog "Fault: failed to move image"
      return false
    end
    
    true
  end
 
end   # class Video

