示例#1
0
def importconfig(configpath='StationConfig.ini'):

    Log.printandlog("Reading configuration file: {0}".format(configpath))

    #Read the configuration file
    config = configparser.ConfigParser()
    config.read(configpath)  #assumed to be in the same folder as script

    Log.printandlog("Configuration file successfully read")

    return (config)
示例#2
0
def WarmupPOE(config):
    '''
    Function to wait for the POE to power up, doing so will allow the cameras to
    set their internal clocks. The ActiA31 cameras queries the NRC online clock
    every 5 minutes
    '''

    WarmUp = int(config['DefaultVideoConfig']['warmup'])

    Log.printandlog(
        "Waiting {x} seconds for camera system to turn on and set clock".
        format(x=WarmUp))

    time.sleep(WarmUp)
示例#3
0
def TurnPOEoff(config):
    '''
    Function to turn the POE router off, this will power down all of the IP cameras
    '''

    PowerPin = int(config['GPIO']['POE'])

    Log.printandlog("Turning POE off (via Pin {0})".format(PowerPin))
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BOARD)  # set GPI mode
    GPIO.setup(PowerPin, GPIO.OUT)  #configure pin 11 to output
    GPIO.output(PowerPin, GPIO.HIGH)
    GPIO.cleanup()

    Log.printandlog("PIN {0} is turned off".format(PowerPin))
示例#4
0
def TurnPOEon(config):
    '''
    Function to turn the POE router on, this will power up all of the IP cameras
    '''
    #get pin number from config file
    PowerPin = int(config['GPIO']['POE'])
    Log.printandlog("Turning POE on (via Pin {0})".format(PowerPin))

    GPIO.setmode(GPIO.BOARD)  # set GPI mode
    GPIO.setup(PowerPin, GPIO.OUT)  #configure pin to output
    GPIO.output(
        PowerPin, GPIO.LOW
    )  #turn pin voltage to low, this will turn POE on (as per relay design)

    Log.printandlog("PIN {0} is turned on".format(PowerPin))
示例#5
0
def videotoimage(inVideoPath, outImagePath, ffmpegpath='ffmpeg '):
    '''
    base function to extract image (2 seconds in) from a video using ffmpeg
    '''

    if not os.path.exists(outImagePath):
        #todo add ffmpegconverttoimagefunction in the FFMPEG module
        cmd = '{ff} -i {iv} -ss 2 -vframes 1 {oi}'.format(ff=ffmpegpath,
                                                          iv=inVideoPath,
                                                          oi=outImagePath)

        result = subprocess.run(cmd.split(),
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT,
                                universal_newlines=True)

        Log.printandlog("Extracting Image from video")
        Log.printandlog(cmd)
        Log.printandlog(result.stdout)
示例#6
0
def FtpNewmedias(ftp_limit=10, Cam=1, Media='video'):
    """
    This function takes the images stored in the base storage directory (as
    defined in the configuration file), and then tries to ftp them to
    an offsite location. If the transfer is successfull, the original
    file also gets moved to a longterm storage directory for redundancy
    
    User can define the maximum number of images they want transferred,
    the default is 10
    """
    #****************************************************************************
    #get the option arguments from commandline
    parser = argparse.ArgumentParser()
    parser.add_argument("--camera",
                        help="integer to decide what camera to use (1-4)",
                        type=int)
    parser.add_argument("--media",
                        help="video or image, default is video",
                        type=str)
    parser.add_argument("--trans_limit",
                        help="transfer limit, integer",
                        type=int)
    args = parser.parse_args()

    #If a commandline argument is given, use it to overwrite the default camera
    if args.camera:
        Cam = args.camera

    #If a commandline argument is given, use it to overwrite the default media type
    if args.media:
        Media = args.media

    #If a commandline argument is given, use it to overwrite the default transfer limit
    if args.trans_limit:
        ftp_limit = args.trans_limit

    #Read the configuration file
    config = configparser.ConfigParser()
    config.read(
        'StationConfig.ini')  #assumed to be in the same folder as script

    #Parse the relevant configuration details
    StationNumber = config['DEFAULT']['Station_Number']
    CamNum = 'Camera' + str(Cam)

    #set video path defaults if that is what is selected
    if Media == 'video':
        #First try the camera specific path
        if config[CamNum]['stor_path_video']:
            storage_path = config[CamNum]['stor_path_video']
        else:
            storage_path = config['DefaultStorage']['stor_path_video']

        #define folder where files go after they are ftp'd
        longterm_stor_path = config['DefaultStorage'][
            'longterm_stor_path_video']
        ftp_directory = config['FTP']['Directory_Video']

    #set image path defaults if that is what is selected
    if Media == 'image':
        #First try the camera specific path
        if config[CamNum]['stor_path_image']:
            storage_path = config[CamNum]['stor_path_image']
        else:
            storage_path = config['DefaultStorage']['stor_path_image']

        #define folder where files go after they are ftp'd
        longterm_stor_path = config['DefaultStorage'][
            'longterm_stor_path_image']
        ftp_directory = config['FTP']['Directory_Image']

    if not os.path.exists(longterm_stor_path):
        os.makedirs(longterm_stor_path)

    #set ftp defaults
    ftp_address = config['FTP']['Address']
    ftp_user = config['FTP']['User']
    ftp_pwd = config['FTP']['Pwd']
    ftp_maxtime = int(config['FTP']['Timeout_Video'])

    #search the directory and get a list of just the videos
    list_of_files = os.listdir(storage_path)
    list_of_media = [
        os.path.join(storage_path, i) for i in list_of_files
        if (i.endswith(('.mp4', '.mkv', 'jpg', 'jpeg')))
    ]
    list_of_media = sorted(
        list_of_media)[::-1]  #reorder so the newest video is first

    ftp_limit = min(
        ftp_limit, len(list_of_media)
    )  #ensure the user defined number isn't bigger than the number of video files

    #print message if no videos will be uploaded
    if ftp_limit == 0:
        Log.printandlog("No media to upload")

    #subset to a maximum of the limit set by the user at the beginning of the script
    ftp_list = list_of_media[0:ftp_limit]

    #loop through the videos
    for media in ftp_list:
        media_name = os.path.basename(media)

        #first check if file exists in the ftp'd folder, if it does then skip the transfer and delete the orginal
        if os.path.exists(os.path.join(longterm_stor_path, media_name)):
            os.remove(media)
            Log.printandlog("File {0} has already been ftpd".format(media))

        else:
            try:
                Log.printandlog("Opening ftp session\n")
                session = ftplib.FTP(ftp_address,
                                     ftp_user,
                                     ftp_pwd,
                                     timeout=ftp_maxtime)
                session.cwd(ftp_directory)
                file = open(media, 'rb')
                Log.printandlog("Sending File: " + media_name)
                session.storbinary('STOR ' + media_name, file)
                file.close()
                Log.printandlog("file sent to ftp")

                #move the file
                os.rename(media, os.path.join(longterm_stor_path, media_name))

                Log.printandlog(
                    "Successful: File sent, local file has been moved to folder 'ftpd_vidoes'"
                )
                session.quit()
            except Exception as e:
                Log.printandlog(str(e))
                Log.printandlog("an error occured for file: " +
                                os.path.basename(media))
示例#7
0
                                     ftp_pwd,
                                     timeout=ftp_maxtime)
                session.cwd(ftp_directory)
                file = open(media, 'rb')
                Log.printandlog("Sending File: " + media_name)
                session.storbinary('STOR ' + media_name, file)
                file.close()
                Log.printandlog("file sent to ftp")

                #move the file
                os.rename(media, os.path.join(longterm_stor_path, media_name))

                Log.printandlog(
                    "Successful: File sent, local file has been moved to folder 'ftpd_vidoes'"
                )
                session.quit()
            except Exception as e:
                Log.printandlog(str(e))
                Log.printandlog("an error occured for file: " +
                                os.path.basename(media))


#execute the function if the script is being explicitly called (and not imported as a module into other code)
if __name__ == "__main__":

    #****************************************************************************
    #set logging file
    Log.initiatelog("FTPMedialog")

    FtpNewmedias()
示例#8
0
import logging
import time
import argparse
import RPi.GPIO as GPIO

#import local libraries
import CBlib.POEcommands as POEcommands
import CBlib.AXIS as AXIS
import CBlib.Log as Log
import CBlib.FFMPEG as FFMPEG

#execute the function if the script is being explicitly called (and not imported as a module into other code)
if __name__ == "__main__":

    #****************************************************************************
    Log.initiatelog("GrabMedia")

    #get the option arguments from commandline
    parser = argparse.ArgumentParser()
    parser.add_argument("--camera",
                        help="integer to decide what camera to use (1-4)",
                        type=int)
    args = parser.parse_args()

    #If camera is specified, use that. otherwise default to camera 1
    if args.camera:
        Cam = args.camera
    else:
        Cam = 1

    CamString = 'Camera' + str(Cam)
示例#9
0
def captureIPstream(config, Cam=1):

    CamNum = 'Camera{0}'.format(Cam)
    #camera address
    CameraIP = config[CamNum]['IP']
    CameraUser = config[CamNum]['User']
    CameraPwd = config[CamNum]['Pwd']
    CameraPort = config[CamNum]['RTSP_Port']

    #Media details specific to camera
    CameraPort = config[CamNum]['RTSP_Port']
    VideoFolder = config[CamNum]['stor_path_video']
    ImageFolder = config[CamNum]['stor_path_image']
    VideoLength = config[CamNum]['length_video_sec']
    VideoFormat = config[CamNum]['format_video']

    #station details
    StationNumber = config['DEFAULT']['Station_Number']
    ffmpegpath = config['DefaultVideoConfig']['ffmpeg_local']

    #fill in default values if not specific to camera
    if not VideoFolder:
        VideoFolder = config['DefaultStorage']['stor_path_video']
    if not ImageFolder:
        ImageFolder = config['DefaultStorage']['stor_path_image']
    if not VideoFormat:
        VideoFormat = config['DefaultVideoConfig']['format_video']
    if not VideoLength:
        VideoLength = config['DefaultVideoConfig']['length_video_sec']

    #create storage folders if they don't already exist
    if not os.path.exists(VideoFolder):
        os.makedirs(VideoFolder)
    if not os.path.exists(ImageFolder):
        os.makedirs(ImageFolder)

    TimeStamp = datetime.today().strftime(
        '%Y%m%d_%H%M%S')  #formated for re.match exact string

    #****************************************************************************
    #Record

    Log.printandlog("Capturing Video from {x}".format(x=CamNum))
    #define some commands and variables
    #TimeStamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    VideoName = StationNumber + "_" + TimeStamp + "_" + CamNum + "." + VideoFormat
    VideoPath = os.path.join(VideoFolder, VideoName)

    #camera source
    if (CameraPort.isdigit()):
        cam_source = (
            '-i rtsp://{CamUser}:{CamPwd}@{CamIP}:{CamPort} '  #camera source
        ).format(  #output filename
            CamUser=CameraUser,
            CamPwd=CameraPwd,
            CamIP=CameraIP,
            CamPort=CameraPort)
    else:
        cam_source = (
            '-i rtsp://{CamUser}:{CamPwd}@{CamIP}/{CamPort} '  #camera source
        ).format(  #output filename
            CamUser=CameraUser,
            CamPwd=CameraPwd,
            CamIP=CameraIP,
            CamPort=CameraPort)

    #capture the video stream to specified format
    cmd = (
        '{ff} '  #cmd for ffmpeg
        '{cm} '  #camera source
        '-t {vtime} '  #length of video (seconds)
        '-vcodec copy -acodec copy '  #copy codecs
        '-ss 10 '  #this turns on the feed, but delays it by X seconds and reduces and initial errors from ffmpeg
        '{Ipath}').format(  #output filename
            ff=ffmpegpath,
            cm=cam_source,
            vtime=VideoLength,
            Ipath=VideoPath)

    result = subprocess.run(cmd.split(),
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT,
                            universal_newlines=True)

    Log.printandlog("Capturing IP Stream")
    Log.printandlog(cmd)
    Log.printandlog(result.stdout)

    return (VideoPath)