Exemple #1
0
def focus(x, s):

    # Connecting to Camera
    mycam = ONVIFCamera('192.168.15.43', 80, 'admin', 'Supervisor',
                        'C:\Users\komar\Documents\python-onvif-master\wsdl')

    # Creation of Media Service
    media = mycam.create_media_service()

    # Getting of Media Profile
    media_profile = media.GetProfiles()[0]

    # Creation of Imaging Service
    img = mycam.create_imaging_service()

    # Creation of Request for supported Focus Move modes with Video Source Token
    request = img.create_type('GetMoveOptions')
    request.VideoSourceToken = media_profile.VideoSourceConfiguration.SourceToken

    # Getting Focus Move options
    move_options = img.GetMoveOptions(request)
    print move_options

    # Getting Current Focus Status
    # status = img.GetStatus({'VideoSourceToken': media_profile.VideoSourceConfiguration.SourceToken})
    # print status

    # Creation of Request for Focus Move with Video Source Token
    request = img.create_type('Move')
    request.VideoSourceToken = media_profile.VideoSourceConfiguration.SourceToken

    # Setting Focus Move Params
    # Absolute Move
    # request.Focus.Absolute.Position = x
    # request.Focus.Absolute.Speed = s

    # Continuous Move
    request.Focus.Continuous.Speed = s

    # Relative Move
    # request.Focus.Relative.Distance = x
    # request.Focus.Relative.Speed = s

    # Calling Move Method of Imaging Service with request as a param
    img.Move(request)

    # Stopping any movement after 5 seconds delay
    sleep(5)
    img.Stop({
        'VideoSourceToken':
        media_profile.VideoSourceConfiguration.SourceToken
    })
Exemple #2
0
def prova_zeep():

    cam = ONVIFCamera('192.168.1.108', 80, 'project', 'ONVIFADMIN2020',
                      './wsdl')

    media = cam.create_media_service()

    print(media.GetProfiles())
    token_main = 'MediaProfile000'

    profile = media.GetProfile(token_main)

    #print(profile)

    token_video_encod_conf = profile.VideoEncoderConfiguration.token

    #print(media.GetVideoEncoderConfiguration(token_video_encod_conf))

    video_source = media.GetVideoSources()[0]
    #print(video_source)

    #print(media.GetVideoSourceConfiguration(video_source.token))

    image = cam.create_imaging_service()
Exemple #3
0
histog = cv2.calcHist([hsv], [0, 1], None, [180, 256],
                      [0, 180, 0, 256])  #hue 180 saturation 256
fig.add_subplot(4, 2, 3)
plt.imshow(histog, interpolation='nearest')

fig.add_subplot(4, 2, 4)
for i, col in enumerate(
        color
):  #each value corresponds to number of pixels in that imaging with its corresponding pixel value RGB
    histogr = cv2.calcHist([frame_43], [i], None, [256], [0, 256])
    plt.plot(histogr, color=col)
    plt.xlim([0, 256])

media42 = cam_42.create_media_service()
media_profile42 = media42.GetProfiles()[0]
imaging42 = cam_42.create_imaging_service()
token42 = media_profile42.VideoSourceConfiguration.SourceToken
SY42 = imaging42.create_type('GetImagingSettings')
SY42.VideoSourceToken = token42
request42 = imaging42.GetImagingSettings(SY42)
print(request42)

media43 = mycam43.create_media_service()
media_profile43 = media43.GetProfiles()[0]
imaging43 = mycam43.create_imaging_service()
token43 = media_profile43.VideoSourceConfiguration.SourceToken
SY43 = imaging43.create_type('GetImagingSettings')
SY43.VideoSourceToken = token43
request43 = imaging43.GetImagingSettings(SY43)
print(request43)
Exemple #4
0
class Onvif_Manager:

    # Istanza della classe Camera
    instance = None

    __mycam__ = None

    # Parametri necessari per la connesione
    IP = None
    Port = None
    Username = None
    Password = None
    Setting_Par = False

    # Token Camera
    __main_token__ = None
    __token_encoder__ = None

    # Servizi offerti dal Framework ONVIF
    __media__ = None
    __image__ = None
    __video_sources__ = None

    # Configurazione Servizio Device Managment
    __device_mgmt__ = None

    __main_profile__ = None
    __config_media__ = None
    __config_videosources__ = None
    __option_camera__ = None

    __config_image__ = None
    __config_move__ = None

    def __init__(self):
        if self.__mycam__ is None:

            # Connessione al dispositivo Onvif
            self.__mycam__ = ONVIFCamera(Onvif_Manager.IP, Onvif_Manager.Port,
                                         Onvif_Manager.Username,
                                         Onvif_Manager.Password, '../wsdl')

            self.__media__ = self.__mycam__.create_media_service()

            try:
                self.__video_sources__ = self.__media__.GetVideoSources()

                self.__image__ = self.__mycam__.create_imaging_service()

                # Token del Profilo Principale
                self.__main_token__ = self.__media__.GetProfiles()[0].token

                # Token del Video Encoder utilizzato
                self.__token_encoder__ = self.__media__.GetVideoEncoderConfigurations(
                )[0].token

                self.get_device_management()
                self.get_config_image()
                self.get_config_media()

                self.update_system_Date_Time()

                Onvif_Manager.instance = self

            except (exceptions.ONVIFError):
                self.__mycam__ = None
                self.__media__ = None

                Onvif_Manager.reset_parameters()

                print("ONVIF Invalid Username e Password!")

        else:
            raise ("You cannot create another Camera class")

    @staticmethod
    def set_parameters(_IP, _Port, _Username, _Password):
        if Onvif_Manager.Setting_Par is False:
            Onvif_Manager.IP = _IP
            Onvif_Manager.Port = _Port
            Onvif_Manager.Username = _Username
            Onvif_Manager.Password = _Password
            Onvif_Manager.Setting_Par = True

    @staticmethod
    def reset_parameters():
        Onvif_Manager.instance = None
        Onvif_Manager.IP = None
        Onvif_Manager.Port = None
        Onvif_Manager.Username = None
        Onvif_Manager.Password = None
        Onvif_Manager.Setting_Par = False

    @staticmethod
    def get_camera():
        if Onvif_Manager.Setting_Par and Onvif_Manager.instance is None:
            Onvif_Manager()
        return Onvif_Manager.instance

    def get_config_media(self):

        self.__main_profile__ = self.__media__.GetProfiles()[0]
        self.__config_media__ = self.__media__.GetVideoEncoderConfiguration(
            self.__token_encoder__)
        self.__config_videosources__ = self.__main_profile__.VideoSourceConfiguration
        self.__option_camera__ = self.__media__.GetVideoEncoderConfigurationOptions(
            self.__token_encoder__)

    def get_config_image(self):

        self.__config_image__ = self.__image__.GetImagingSettings(
            self.__token_encoder__)
        self.__config_move__ = self.__image__.GetStatus(self.__token_encoder__)

    # ------------------ Setting Core ---------------------------
    def get_device_management(self):
        self.__device_mgmt__ = self.__mycam__.devicemgmt

    def get_system_Date_Time(self):
        return self.__device_mgmt__.GetSystemDateAndTime()

    def update_system_Date_Time(self):
        request_device = self.__device_mgmt__.create_type(
            "SetSystemDateAndTime")

        actual_time = time.localtime()

        request_device.DateTimeType = 'Manual'
        request_device.DaylightSavings = True
        request_device.TimeZone = {'TZ': 'CST-0:00:00'}
        request_device.UTCDateTime = {
                                        'Date':{'Year':actual_time.tm_year,'Month':actual_time.tm_mon,'Day':actual_time.tm_mday},\
                                        'Time':{'Hour':actual_time.tm_hour,'Minute':actual_time.tm_min,'Second':actual_time.tm_sec}
                                    }

        self.__device_mgmt__.SetSystemDateAndTime(request_device)

    def reboot(self):
        self.__device_mgmt__.SystemReboot()

    def soft_factory_reset(self):
        request_device = self.__device_mgmt__.create_type(
            "SetSystemFactoryDefault")

        request_device.FactoryDefault = 'Soft'

        self.__device_mgmt__.SetSystemFactoryDefault(request_device)

    def hard_factory_reset(self):
        request_device = self.__device_mgmt__.create_type(
            "SetSystemFactoryDefault")

        request_device.FactoryDefault = 'Hard'

        self.__device_mgmt__.SetSystemFactoryDefault(request_device)

    # ------------------ Setting Imaging -------------------------
    # Creazione della richiesta da inviare alla camera relativa alla modifica dei parametri dell'immagine
    def create_request_image(self):
        request_img = self.__image__.create_type('SetImagingSettings')
        request_img.VideoSourceToken = self.__token_encoder__
        request_img.ForcePersistence = True

        return request_img

    def create_request_focus(self):
        request_focus = self.__image__.create_type('Move')
        request_focus.VideoSourceToken = self.__token_encoder__

        return request_focus

    def set_Brightness(self, Value_Brightness):

        try:
            if (Value_Brightness >= 0.0 and Value_Brightness <= 100.0):
                request_img = self.create_request_image()

                self.__config_image__.Brightness = Value_Brightness
                request_img.ImagingSettings = self.__config_image__

                self.__image__.SetImagingSettings(request_img)
        except (exceptions.ONVIFError):
            self.__mycam__ = None
            self.__media__ = None

            Onvif_Manager.reset_parameters()

            print("Onvif Errore Connessione")

    def set_Saturation(self, Value_Saturation):

        try:
            if (Value_Saturation >= 0.0 and Value_Saturation <= 100.0):
                request_img = self.create_request_image()

                self.__config_image__.ColorSaturation = Value_Saturation
                request_img.ImagingSettings = self.__config_image__

                self.__image__.SetImagingSettings(request_img)
        except (exceptions.ONVIFError):
            self.__mycam__ = None
            self.__media__ = None

            Onvif_Manager.reset_parameters()

            print("Onvif Errore Connessione")

    def set_Sharpness(self, Value_Sharpness):

        try:
            if (Value_Sharpness >= 0.0 and Value_Sharpness <= 100.0):
                request_img = self.create_request_image()

                self.__config_image__.Sharpness = Value_Sharpness
                request_img.ImagingSettings = self.__config_image__

                self.__image__.SetImagingSettings(request_img)
        except (exceptions.ONVIFError):
            self.__mycam__ = None
            self.__media__ = None

            Onvif_Manager.reset_parameters()

            print("Onvif Errore Connessione")

    def set_Contrast(self, Value_Contrast):

        try:
            if (Value_Contrast >= 0.0 and Value_Contrast <= 100.0):
                request_img = self.create_request_image()

                self.__config_image__.Contrast = Value_Contrast
                request_img.ImagingSettings = self.__config_image__

                self.__image__.SetImagingSettings(request_img)
        except (exceptions.ONVIFError):
            self.__mycam__ = None
            self.__media__ = None

            Onvif_Manager.reset_parameters()

            print("Onvif Errore Connessione")

    def set_Focus_Move(self, Value_Position):

        try:
            if (Value_Position >= 0.0 and Value_Position <= 1.0):
                request_focus = self.create_request_focus()

                request_focus.Focus = {'Absolute': {'Position': Value_Position, 'Speed': None}, \
                                       'Relative': {'Distance': Value_Position, 'Speed': None}, \
                                       'Continuous': {'Speed': 0.0}}

                self.__image__.Move(request_focus)

                return True

            return False
        except (exceptions.ONVIFError):
            self.__mycam__ = None
            self.__media__ = None

            Onvif_Manager.reset_parameters()

            print("Onvif Errore Connessione")

            return False

    # ------------------ Setting Media -------------------------
    # Creazione della richiesta da inviare alla camera relativa alla modifica dei parametri dell'encoder
    def create_request_media(self):
        request_media = self.__media__.create_type(
            'SetVideoEncoderConfiguration')
        request_media.ForcePersistence = True

        return request_media

    def get_ResolutionAvailable(self):
        return self.__option_camera__.H264.ResolutionsAvailable

    def set_Resolution(self, Index_Resolution):

        try:
            if (Index_Resolution >= 0 and
                    Index_Resolution < len(self.get_ResolutionAvailable())):
                request_media = self.create_request_media()
                self.__config_media__.Resolution = self.__option_camera__.H264.ResolutionsAvailable[
                    Index_Resolution]

                request_media.Configuration = self.__config_media__

                self.__media__.SetVideoEncoderConfiguration(request_media)
        except (exceptions.ONVIFError):
            self.__mycam__ = None
            self.__media__ = None

            Onvif_Manager.reset_parameters()

            print("Onvif Errore Connessione")
Exemple #5
0
class OnvifCamCtl:
    def __init__(self, ip, port, user, password):
        self.ip = ip
        self.port = port
        self.user = user
        self.password = password
        self.cam = None
        self.media = None
        self.media_profile = None
        self.ptz = None
        self.ptz_configuration_options = None
        self.requestA = None
        self.XMAX = 0
        self.XMIN = 0
        self.YMAX = 0
        self.YMIN = 0
        self.ZOOMMIN = 0
        self.ZOOMMAX = 0
        self.xRangeOneDegreePOS = 0.0
        self.yRangeOneDegreePOS = 0.0
        self.xRangeOneDegreeNEG = 0.0
        self.yRangeOneDegreeNEG = 0.0
        self.surveyRangeOneDegree = 0.0
        self.status = None
        self.image = None
        self.image_config = None
        self.image_video_token = None
        self.requestI = None

    def connect(self):
        # Connect to remote camera
        self.cam = ONVIFCamera(self.ip, self.port, self.user, self.password)
        # Create media service object
        self.media = self.cam.create_media_service()



    def initPTZ(self):
        # Create ptz service object
        self.ptz = self.cam.create_ptz_service()
        # Get target profile
        self.media_profile = self.media.GetProfiles()[0]

    def initImageService(self):
        self.image = self.cam.create_imaging_service()
        request = self.image.create_type('GetOptions')
        video_sources = self.cam.media.GetVideoSources()
        self.image_video_token = video_sources[0].token
        request.VideoSourceToken = self.image_video_token
        self.image_config = self.image.GetOptions(request)
        print(self.image_config)

    def initImageSettingRequest(self):
        self.initImageService()
        self.requestI = self.image.create_type('GetImagingSettings')
        self.requestI.VideoSourceToken = self.image_video_token
        self.requestI = self.image.GetImagingSettings(self.requestI)
        self.image.Stop({'VideoSourceToken': self.image_video_token})

    def __interpolateXRangeToDegree(self):
        if self.XMAX == 0 or self.XMIN == 0:
            return False
        middle_bound = global_var.g_pan_range_max / 2
        self.xRangeOneDegreePOS = self.XMAX / middle_bound
        self.xRangeOneDegreeNEG = (self.XMIN * -1) / middle_bound
        return True

    def __interpolateYRangeToDegree(self):
        if self.YMAX == 0 or self.YMIN == 0:
            return False
        middle_bound = global_var.g_tilt_range_max / 2
        self.yRangeOneDegreePOS = self.YMAX / middle_bound
        self.yRangeOneDegreeNEG = (self.YMIN * -1) / middle_bound
        return True

    def __getPanTiltRange(self):
        # Get range of pan and tilt
        self.XMAX = self.ptz_configuration_options.Spaces.AbsolutePanTiltPositionSpace[0].XRange.Max
        self.XMIN = self.ptz_configuration_options.Spaces.AbsolutePanTiltPositionSpace[0].XRange.Min
        self.YMAX = self.ptz_configuration_options.Spaces.AbsolutePanTiltPositionSpace[0].YRange.Max
        self.YMIN = self.ptz_configuration_options.Spaces.AbsolutePanTiltPositionSpace[0].YRange.Min
        self.ZOOMMIN = self.ptz_configuration_options.Spaces.AbsoluteZoomPositionSpace[0].XRange.Min
        self.ZOOMMAX = self.ptz_configuration_options.Spaces.AbsoluteZoomPositionSpace[0].XRange.Max
        self.surveyRangeOneDegree = self.ZOOMMAX / (global_var.g_zoom_range_min - global_var.g_zoom_range_max)

    def __getPTZConfig(self):
        # Get PTZ configuration options for getting absolute move range
        self.requestA = self.ptz.create_type('GetConfigurationOptions')
        self.requestA.ConfigurationToken = self.media_profile.PTZConfiguration.token
        self.ptz_configuration_options = self.ptz.GetConfigurationOptions(self.requestA)
        print(self.ptz)
        self.__getPanTiltRange()
        if not self.__interpolateXRangeToDegree():
            return False
        if not self.__interpolateYRangeToDegree():
            return False
        return True

    def initAbsoluteMoveRequest(self):
        self.__getPTZConfig()
        self.requestA = self.ptz.create_type('AbsoluteMove')
        self.requestA.ProfileToken = self.media_profile.token
        self.ptz.Stop({'ProfileToken': self.media_profile.token})

    #def initImagingSettings(self):

    # Move camera by x - axis
    # g_north - global variable that define
    def __move_x(self, x):
        lower_bound = global_var.g_pan_range_min    # begin of pan range
        middle_bound = global_var.g_pan_range_max / 2   # middle of pan range
        upper_bound = global_var.g_pan_range_max    # end of pan range
        x_mod = (x + global_var.g_north) % upper_bound      # calculate user defined zero position
        if lower_bound <= x_mod <= middle_bound - 1:
            self.requestA.Position.PanTilt.x = x_mod * self.xRangeOneDegreePOS
        elif middle_bound <= x_mod < upper_bound:
            self.requestA.Position.PanTilt.x = ((x_mod - upper_bound) * -1) * self.xRangeOneDegreeNEG * -1

    def __move_y(self, y):
        lower_bound = global_var.g_tilt_range_min   # begin of tilt range
        middle_bound = global_var.g_tilt_range_max / 2  # middle of tilt range
        upper_bound = global_var.g_tilt_range_max   # end of tilt range
        if lower_bound <= y <= middle_bound - 1:
            self.requestA.Position.PanTilt.y = ((y - (middle_bound - 1)) * -1) * self.yRangeOneDegreePOS
        elif middle_bound <= y <= upper_bound:
            self.requestA.Position.PanTilt.y = (y - middle_bound) * self.yRangeOneDegreeNEG * -1

    def __move_zoom(self, zoom):
        z_range = global_var.g_zoom_range_min - global_var.g_zoom_range_max
        if global_var.g_zoom_range_max <= zoom <= global_var.g_zoom_range_min:
            zoom_mod = (((zoom - global_var.g_zoom_range_max) - z_range) * -1) * self.surveyRangeOneDegree
            if zoom_mod > 1:
                zoom_mod = 1
            if zoom_mod < 0:
                zoom_mod = 0
            self.requestA.Position.Zoom.x = zoom_mod

    def move(self, x=0, y=0):
        self.status = self.ptz.GetStatus({'ProfileToken': self.media_profile.token})
        self.requestA.Position = self.status.Position
        self.__move_x(x)
        self.__move_y(y)
        self.ptz.AbsoluteMove(self.requestA)

    def zoom(self, val):
        self.status = self.ptz.GetStatus({'ProfileToken': self.media_profile.token})
        self.requestA.Position = self.status.Position
        self.__move_zoom(val)
        self.ptz.AbsoluteMove(self.requestA)

    def take_position(self, x, y, z):
        self.status = self.ptz.GetStatus({'ProfileToken': self.media_profile.token})
        self.requestA.Position = self.status.Position
        self.__move_x(x)
        self.__move_y(y)
        self.__move_zoom(z)
        self.ptz.AbsoluteMove(self.requestA)

    def setBrightness(self, val):
        request = self.image.create_type('SetImagingSettings')
        request.VideoSourceToken = self.image_video_token
        request.ImagingSettings = {'Brightness': val}
        self.image.SetImagingSettings(request)

    def setContrast(self, val):
        request = self.image.create_type('SetImagingSettings')
        request.VideoSourceToken = self.image_video_token
        request.ImagingSettings = {'Contrast': val}
        self.image.SetImagingSettings(request)

    def setIRFilter(self, val):
        request = self.image.create_type('SetImagingSettings')
        request.VideoSourceToken = self.image_video_token
        request.ImagingSettings = {'IrCutFilter': str(val)}
        self.image.SetImagingSettings(request)
Exemple #6
0
class Camera:
    def __init__(self, ip, port, login, password):
        # Connecting to the camera
        self.my_cam = ONVIFCamera(ip, port, login, password)

        # Creating media service
        self.media_service = self.my_cam.create_media_service()

        # Getting profiles
        self.profiles = self.media_service.GetProfiles()
        self.media_profile = self.profiles[0]

        # Creating PTZ service
        self.ptz = self.my_cam.create_ptz_service()

        # Getting ptz move options
        self.request_absolute_move = self.ptz.create_type("AbsoluteMove")
        self.request_absolute_move.ProfileToken = self.media_profile._token

        self.request_continuous_move = self.ptz.create_type("ContinuousMove")
        self.request_continuous_move.ProfileToken = self.media_profile._token

        self.request_relative_move = self.ptz.create_type("RelativeMove")
        self.request_relative_move.ProfileToken = self.media_profile._token

        self.request_stop = self.ptz.create_type("Stop")
        self.request_stop.ProfileToken = self.media_profile._token

        # Creating imaging service
        self.imaging = self.my_cam.create_imaging_service()

        # Getting imaging move options
        self.request_focus_change = self.imaging.create_type("Move")
        self.request_focus_change.VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken

        self.stop()

    # Print debug information
    def get_debug_info(self):

        # Getting device information
        print("Device information: " +
              str(self.my_cam.devicemgmt.GetDeviceInformation()))
        print(long_line)

        # Getting hostname
        print("Device hostname: " +
              str(self.my_cam.devicemgmt.GetHostname().Name))
        print(long_line)

        # Getting system date and time
        dt = self.my_cam.devicemgmt.GetSystemDateAndTime()
        tz = dt.TimeZone
        year = dt.UTCDateTime.Date.Year
        hour = dt.UTCDateTime.Time.Hour

        print("Timezone: " + str(tz))
        print("Year: " + str(year))
        print("Hour: " + str(hour))
        print(long_line)

        print("Profiles: " + str(self.profiles))
        print(long_line)

        print("Token: " + str(self.media_profile._token))
        print(long_line)

        # Getting available PTZ services
        request = self.ptz.create_type("GetServiceCapabilities")
        ptz_service_capabilities = self.ptz.GetServiceCapabilities(request)

        print("Service capabilities: " + str(ptz_service_capabilities))
        print(long_line)

        # Getting PTZ status
        ptz_status = self.ptz.GetStatus(
            {"ProfileToken": self.media_profile._token})

        print("PTZ status: " + str(ptz_status))
        print(long_line)
        print("Pan position:" + str(ptz_status.Position.PanTilt._x))
        print("Tilt position:" + str(ptz_status.Position.PanTilt._y))
        print("Zoom position:" + str(ptz_status.Position.Zoom._x))
        try:
            print("Pan/Tilt Moving?:" + str(ptz_status.MoveStatus.PanTilt))
        except:
            pass
        print(long_line)

        # Getting PTZ configuration options for getting option ranges
        request = self.ptz.create_type("GetConfigurationOptions")
        request.ConfigurationToken = self.media_profile.PTZConfiguration._token
        ptz_configuration_options = self.ptz.GetConfigurationOptions(request)

        print("PTZ configuration options: " + str(ptz_configuration_options))
        print(long_line)

        print("Continuous move options: " + str(self.request_continuous_move))
        print(long_line)

        print("Absolute move options: " + str(self.request_absolute_move))
        print(long_line)

        print("Relative move options: " + str(self.request_relative_move))
        print(long_line)

        print("Stop options: " + str(self.request_stop))
        print(long_line)

        # Getting available imaging services
        request = self.imaging.create_type("GetServiceCapabilities")
        imaging_service_capabilities = self.ptz.GetServiceCapabilities(request)

        print("Service capabilities: " + str(imaging_service_capabilities))
        print(long_line)

        # Getting imaging status
        imaging_status = self.imaging.GetStatus({
            "VideoSourceToken":
            self.media_profile.VideoSourceConfiguration.SourceToken
        })

        print("Imaging status: " + str(imaging_status))
        print(long_line)

        print("Focus move options: " + str(self.request_focus_change))
        print(long_line)

    # "--------------------------------------------------------------------------------"

    # Get position of the camera
    def get_ptz_position(self):
        # Getting PTZ status
        status = self.ptz.GetStatus(
            {"ProfileToken": self.media_profile._token})

        print(long_line)
        print("PTZ position: " + str(status.Position))
        print(long_line)

    def get_focus_options(self):
        # Getting imaging status
        imaging_status = self.imaging.GetStatus({
            "VideoSourceToken":
            self.media_profile.VideoSourceConfiguration.SourceToken
        })

        print(long_line)
        # Getting available imaging services
        request = self.imaging.create_type("GetServiceCapabilities")
        imaging_service_capabilities = self.ptz.GetServiceCapabilities(request)

        print("Service capabilities: " + str(imaging_service_capabilities))
        print(long_line)
        print("Imaging status: " + str(imaging_status))
        print(long_line)

    # "--------------------------------------------------------------------------------"

    # Stop any movement
    def stop(self):
        self.request_stop.PanTilt = True
        self.request_stop.Zoom = True

        self.ptz.Stop(self.request_stop)

    # "--------------------------------------------------------------------------------"

    # Continuous move functions
    def perform_continuous_move(self, timeout):
        # Start continuous move
        self.ptz.ContinuousMove(self.request_continuous_move)

        sleep(timeout)

        self.stop()

        sleep(2)

    def move_continuous_tilt(self, velocity, timeout):
        print("Tilting with velocity: \"" + str(velocity) +
              "\" and timeout: \"" + str(timeout) + "\"")

        status = self.ptz.GetStatus(
            {"ProfileToken": self.media_profile._token})
        status.Position.PanTilt._x = 0.0
        status.Position.PanTilt._y = velocity

        self.request_continuous_move.Velocity = status.Position

        self.perform_continuous_move(timeout)

    def move_continuous_pan(self, velocity, timeout):
        print("Panning with velocity: \"" + str(velocity) +
              "\" and timeout: \"" + str(timeout) + "\"")

        status = self.ptz.GetStatus(
            {"ProfileToken": self.media_profile._token})
        status.Position.PanTilt._x = velocity
        status.Position.PanTilt._y = 0.0

        self.request_continuous_move.Velocity = status.Position

        self.perform_continuous_move(timeout)

    def move_continuous_diagonal(self, velocity_x, velocity_y, timeout):
        print("Moving diagonally with velocities: \"" + str(velocity_x) + ":" +
              str(velocity_y) + "\" and timeout: \"" + str(timeout) + "\"")

        status = self.ptz.GetStatus(
            {"ProfileToken": self.media_profile._token})
        status.Position.PanTilt._x = velocity_x
        status.Position.PanTilt._y = velocity_y

        self.request_continuous_move.Velocity = status.Position

        self.perform_continuous_move(timeout)

    def move_continuous_zoom(self, velocity, timeout):
        print("Zooming with velocity: \"" + str(velocity) +
              "\" and timeout: \"" + str(timeout) + "\"")

        status = self.ptz.GetStatus(
            {"ProfileToken": self.media_profile._token})
        status.Position.Zoom._x = velocity

        self.request_continuous_move.Velocity = status.Position

        self.perform_continuous_move(timeout)

    def move_continuous_custom(self, velocity_one, timeout_one, velocity_two,
                               timeout_two, velocity_three, timeout_three):

        self.move_continuous_pan(velocity_one, timeout_one)
        self.move_continuous_tilt(velocity_two, timeout_two)
        self.move_continuous_zoom(velocity_three, timeout_three)

    # "--------------------------------------------------------------------------------"

    # Absolute move functions
    def perform_absolute_move(self):
        # Start absolute move
        self.ptz.AbsoluteMove(self.request_absolute_move)

        sleep(4)

    def move_absolute(self, x, y, zoom):
        print("Moving to: \"" + str(x) + ":" + str(y) + ":" + str(zoom) + "\"")

        status = self.ptz.GetStatus(
            {"ProfileToken": self.media_profile._token})
        status.Position.PanTilt._x = x
        status.Position.PanTilt._y = y
        status.Position.Zoom._x = zoom

        self.request_absolute_move.Position = status.Position

        self.perform_absolute_move()

    # "--------------------------------------------------------------------------------"

    # Focus change functions
    def change_focus_continuous(self, speed, timeout):
        print("Changing focus with speed: \"" + str(speed) +
              "\" and timeout: \"" + str(timeout) + "\"")

        self.request_focus_change.Focus = {"Continuous": {"Speed": speed}}

        self.imaging.Move(self.request_focus_change)

        sleep(timeout)

        self.stop()

        sleep(2)

    def change_focus_absolute(self, position, speed):
        print("Changing focus to: \"" + str(position) + "\" with speed: \"" +
              str(speed) + "\"")

        self.request_focus_change.Focus = {
            "Absolute": {
                "Position": position,
                "Speed": speed
            }
        }

        self.imaging.Move(self.request_focus_change)

        sleep(4)
Exemple #7
0
hsv = cv2.cvtColor(frame43,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv], [0,1], None, [180, 256], [0, 180, 0, 256]) #hue 180 saturation 256
fig.add_subplot(2, 4, 3)
plt.imshow(hist,interpolation = 'nearest')
    
fig.add_subplot(2, 4, 4)
for i,col in enumerate(color): #each value corresponds to number of pixels in that image with its corresponding pixel value RGB
    histr = cv2.calcHist([frame43],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])    
    
    
#Создаём сервис для 42 и 43 камер, т.к другие без доступа
media42 = mycam42.create_media_service()
media_profile42 = media42.GetProfiles()[0]
image42 = mycam42.create_imaging_service()
token42 = media_profile42.VideoSourceConfiguration.SourceToken
SY42 = image42.create_type('GetImagingSettings')
SY42.VideoSourceToken = token42
request42 = image42.GetImagingSettings(SY42)
print(request42)

media43 = mycam43.create_media_service()
media_profile43 = media43.GetProfiles()[0]
image43 = mycam43.create_imaging_service()
token43 = media_profile43.VideoSourceConfiguration.SourceToken
SY43 = image43.create_type('GetImagingSettings')
SY43.VideoSourceToken = token43
request43 = image43.GetImagingSettings(SY43)
print(request43)
Exemple #8
0
class camera_onvif(object):
    def __init__(self, ip, port, username, password):

        try:
            self.my_camera = ONVIFCamera(ip, port, username, password)
        except Exception as e:
            print e
            raise Exception("Error in ONVIFCamera function")

        # Device management service is available by default if camera is created
        # Create media service object
        self.media_service_object = self.my_camera.create_media_service()
        # Create ptz service object
        self.ptz_service_object = self.my_camera.create_ptz_service()
        # Create ptz service object
        self.imaging_service_object = self.my_camera.create_imaging_service()
        # Get target profile
        self.media_profile = self.media_service_object.GetProfiles()[0]
        # Get video sources
        video_sources = self.my_camera.media.GetVideoSources()
        # Save the range values
        nodes = self.my_camera.ptz.GetNodes()
        self.absolute_pan_value_min = nodes[
            0].SupportedPTZSpaces.AbsolutePanTiltPositionSpace[0].XRange.Min
        # print 'Absolute pan range Min:', self.absolute_pan_value_min
        self.absolute_pan_value_max = nodes[
            0].SupportedPTZSpaces.AbsolutePanTiltPositionSpace[0].XRange.Max
        # print 'Absolute pan range Max:',self.absolute_pan_value_max
        self.absolute_tilt_value_min = nodes[
            0].SupportedPTZSpaces.AbsolutePanTiltPositionSpace[0].YRange.Min
        # print 'Absolute tilt range Min:', self.absolute_tilt_value_min
        self.absolute_tilt_value_max = nodes[
            0].SupportedPTZSpaces.AbsolutePanTiltPositionSpace[0].YRange.Max
        # print 'Absolute tilt range Max:', self.absolute_tilt_value_max
        self.absolute_zoom_value_min = nodes[
            0].SupportedPTZSpaces.AbsoluteZoomPositionSpace[0].XRange.Min
        # print 'Absolute zoom range Min:', self.absolute_zoom_value_min
        self.absolute_zoom_value_max = nodes[
            0].SupportedPTZSpaces.AbsoluteZoomPositionSpace[0].XRange.Max
        # print 'Absolute zoom range Max:', self.absolute_zoom_value_max
        self.absolute_relative_pan_tilt_speed_min = nodes[
            0].SupportedPTZSpaces.PanTiltSpeedSpace[0].XRange.Min
        # print 'Absolute relative pan tilt speed range Min:', self.absolute_relative_pan_tilt_speed_min
        self.absolute_relative_pan_tilt_speed_max = nodes[
            0].SupportedPTZSpaces.PanTiltSpeedSpace[0].XRange.Max
        # print 'Absolute relative pan tilt speed range Max:', self.absolute_relative_pan_tilt_speed_max
        self.absolute_relative_zoom_speed_min = nodes[
            0].SupportedPTZSpaces.ZoomSpeedSpace[0].XRange.Min
        # print 'Absolute relative zoom speed range Min:', self.absolute_relative_zoom_speed_min
        self.absolute_relative_zoom_speed_max = nodes[
            0].SupportedPTZSpaces.ZoomSpeedSpace[0].XRange.Max
        # print 'Absolute relative zoom speed range Max:', self.absolute_relative_zoom_speed_max
        self.max_number_of_presets = nodes[0].MaximumNumberOfPresets
        # get presets
        self.presets = self.my_camera.ptz.create_type('GetPresets')
        self.presets.ProfileToken = self.media_profile._token
        self.presets = self.my_camera.ptz.GetPresets(self.presets)

        self.preset_count = 0
        self.preset_objects = []
        # print 'Max number of presets: ', self.max_number_of_presets

        self.slope_pan = (CAMERA_PAN_RANGE_MAX - CAMERA_PAN_RANGE_MIN) / (
            self.absolute_pan_value_max - self.absolute_pan_value_min)
        self.slope_tilt = (CAMERA_TILT_RANGE_MAX - CAMERA_TILT_RANGE_MIN) / (
            self.absolute_tilt_value_max - self.absolute_tilt_value_min)
        self.slope_zoom = (CAMERA_ZOOM_RANGE_MAX - CAMERA_ZOOM_RANGE_MIN) / (
            self.absolute_zoom_value_max - self.absolute_zoom_value_min)
        # self.set_home_position( CAMERA_DEFAULT_POSITION_PAN, CAMERA_DEFAULT_POSITION_TILT, CAMERA_DEFAULT_POSITION_ZOOM)
        # set date time format ( check if needed ), timezone?

        param = self.my_camera.devicemgmt.create_type('SetHostname')
        param.Name = DEFAULT_HOSTNAME_OF_CAMERA
        self.my_camera.devicemgmt.SetHostname(param)
        print('camera_onvif comamnds object created')
        print("pan min:", self.absolute_pan_value_min, " max:",
              self.absolute_pan_value_max)
        print("tilt min:", self.absolute_tilt_value_min, " max:",
              self.absolute_tilt_value_max)
        print("zoom min:", self.absolute_zoom_value_min, " max:",
              self.absolute_zoom_value_max)

    def __get_users(self):
        response = self.my_camera.devicemgmt.GetUsers()
        total_users = len(response)
        print('Total number of users: ', total_users)
        return STATUS_OK, response

    def __create_user(self, username, password, userlevel):
        try:
            param = self.my_camera.devicemgmt.create_type('CreateUsers')
            param.User = {
                'Username': username,
                'Password': password,
                'UserLevel': userlevel
            }
            response = self.my_camera.devicemgmt.CreateUsers(param)
            return STATUS_OK
        except Exception as e:
            print e
            print("Error in CreateUsers function")
            return STATUS_ERROR

    def __remove_user(self, username):
        try:
            param = self.my_camera.devicemgmt.create_type('DeleteUsers')
            param.Username = username
            response = self.my_camera.devicemgmt.DeleteUsers(param)
            print(response)
            print(username, "deleted")
            return STATUS_OK
        except Exception as e:
            print e
            print("Error in DeleteUsers function")
            return STATUS_ERROR

# This function return error when pan value is 1 and -1 and if tilt is -1
# "The home position is fixed and cannot be overwritten."

    def onvif_set_home_position(self, pan, tilt, zoom):
        status = self.move_camera(pan, tilt, zoom)
        if status != STATUS_OK:
            print('Error in move_camera')
            return STATUS_ERROR
        else:
            sleep(2)
            try:
                request = self.my_camera.ptz.create_type('SetHomePosition')
                request.ProfileToken = self.media_profile._token
                self.my_camera.ptz.SetHomePosition(request)
                print('Home position set')
                return STATUS_OK
            except Exception as e:
                print e
                print('Error in SetHomePosition function')
                return STATUS_ERROR

    def onvif_go_to_home_position(self):
        try:
            request = self.my_camera.ptz.create_type('GotoHomePosition')
            request.ProfileToken = self.media_profile._token
            request.Speed.PanTilt._x = absolute_relative_pan_tilt_speed_max
            request.Speed.PanTilt._y = absolute_relative_pan_tilt_speed_max
            request.Speed.Zoom._x = absolute_relative_zoom_speed
            self.my_camera.ptz.GotoHomePosition(request)
            return STATUS_OK
        except Exception as e:
            print e
            print('Error in GotoHomePosition function')
            return STATUS_ERROR

    def onvif_get_pan_range(self):
        return CAMERA_PAN_RANGE_MIN, CAMERA_PAN_RANGE_MAX

    def onvif_get_tilt_range(self):
        return CAMERA_TILT_RANGE_MIN, CAMERA_TILT_RANGE_MAX

    def onvif_get_zoom_range(self):
        return CAMERA_ZOOM_RANGE_MIN, CAMERA_ZOOM_RANGE_MAX

    def onvif_create_preset(self, pan, tilt, zoom):

        if self.preset_count < self.max_number_of_presets:
            status = self.onvif_move_camera(pan, tilt, zoom)
            if status != STATUS_OK:
                print('Error in move_camera')
                return STATUS_ERROR
            else:
                sleep(2)
                try:
                    request = self.my_camera.ptz.create_type('SetPreset')
                    request.ProfileToken = self.media_profile._token
                    request.PresetName = str(self.preset_count)
                    request.PresetToken = self.presets[
                        self.preset_count]._token
                    my_preset = self.my_camera.ptz.SetPreset(request)
                    self.preset_objects.append(my_preset)
                    self.preset_count += 1
                    print('Preset created')
                    return STATUS_OK, (self.preset_count - 1)
                except Exception as e:
                    print e
                    print('Error in create preset function')
                    return STATUS_ERROR, -1
        else:
            print('Max number of presets reached')
            return STATUS_ERROR, -1

    def onvif_go_to_preset(self, preset_id):
        if preset_id < self.max_number_of_presets:
            try:
                preset = self.my_camera.ptz.create_type('GotoPreset')
                preset.ProfileToken = self.media_profile._token
                preset.PresetToken = self.preset_objects[preset_id]
                self.my_camera.ptz.GotoPreset(preset)
                return STATUS_OK
            except Exception as e:
                print e
                print('Error in GotoPreset function')
                return STATUS_ERROR
        else:
            print('Invalid preset id')
            return STATUS_ERROR

    def onvif_get_position(self):
        request = self.my_camera.ptz.create_type('GetStatus')
        request.ProfileToken = self.media_profile._token
        response = self.my_camera.ptz.GetStatus(request)

        pan_value = response.Position.PanTilt._x
        # Tilt value returned by this function is multiplied by -1,
        tilt_value = response.Position.PanTilt._y
        zoom_value = response.Position.Zoom._x
        #print("onvif_get_position pan:",pan_value," tilt:",tilt_value," zoom:",zoom_value)
        #mapping physical values to camera values
        pan = (pan_value - self.absolute_pan_value_min
               ) * self.slope_pan + CAMERA_PAN_RANGE_MIN
        tilt = (tilt_value - self.absolute_tilt_value_min) * self.slope_tilt
        zoom = 0
        if (tilt > CAMERA_TILT_RANGE_MAX):
            tilt = 360 - (tilt - CAMERA_TILT_RANGE_MAX)
        else:
            tilt = CAMERA_TILT_RANGE_MAX - tilt
        if pan < 0:
            pan = pan + 360
        camera_focus_dis = [
            4.3, 8.6, 12.9, 17.2, 21.5, 25.8, 30.1, 34.4, 38.7, 43, 47.3, 51.6,
            55.9, 60.2, 64.5, 68.8, 73.1, 77.4, 81.7, 86, 90.3, 94.6, 98.9,
            103.2, 107.5, 111.8, 116.1, 120.4, 124.7, 129, 135, 140, 153
        ]
        camera_actual_zoom_values = [
            0, 0.062, 0.093, 0.121, 0.152, 0.184, 0.215, 0.243, 0.274, 0.305,
            0.333, 0.364, 0.395, 0.427, 0.454, 0.486, 0.517361111111, 0.548,
            0.576, 0.607, 0.638, 0.666, 0.697, 0.729, 0.760, 0.788, 0.819,
            0.850, 0.881, 0.909, 0.933, 0.972, 1
        ]
        index = 0
        for value in camera_actual_zoom_values:
            if zoom_value < value:
                break
            else:
                index = index + 1
        if index > len(camera_focus_dis) - 1:
            index = len(camera_focus_dis) - 1
        zoom = camera_focus_dis[index]
        #print("onvif_get_position pan:",pan," tilt:",tilt," zoom:",zoom)
        return STATUS_OK, pan, tilt, zoom, response.MoveStatus.PanTilt, response.MoveStatus.Zoom

    def onvif_move_camera(self, pan, tilt, zoom):
        # mapping physical values to camera values
        # zoom values are not mapping linearly with the input and output values
        # as conversion is not linear.
        # Maybe same thing is happenning for pan and tilt but we are not able to identify that,
        # as we don't exactly by what angle camera is rotating.
        # print pan, tilt, zoom

        if zoom > CAMERA_ZOOM_RANGE_MAX:
            zoom = CAMERA_ZOOM_RANGE_MAX

        pan_value = (
            (pan - CAMERA_PAN_RANGE_MIN) +
            (self.absolute_pan_value_min * self.slope_pan)) / self.slope_pan
        tilt_value = (
            (tilt - CAMERA_TILT_RANGE_MIN) +
            (self.absolute_tilt_value_min * self.slope_tilt)) / self.slope_tilt

        # Hardware actual input values
        camera_actual_zoom_values = [
            0, 0, 0.062, 0.093, 0.121, 0.152, 0.184, 0.215, 0.243, 0.274,
            0.305, 0.333, 0.364, 0.395, 0.427, 0.454, 0.486, 0.517361111111,
            0.548, 0.576, 0.607, 0.638, 0.666, 0.697, 0.729, 0.760, 0.788,
            0.819, 0.850, 0.881, 0.909, 0.933, 0.972, 1
        ]
        zoom_value = camera_actual_zoom_values[int(zoom)]

        try:
            request = self.my_camera.ptz.create_type('AbsoluteMove')
            request.ProfileToken = self.media_profile._token
            request.Position.PanTilt._x = pan_value
            request.Position.PanTilt._y = tilt_value
            request.Position.Zoom._x = zoom_value
            request.Speed.PanTilt._x = self.absolute_relative_pan_tilt_speed_max
            request.Speed.PanTilt._y = self.absolute_relative_pan_tilt_speed_max
            request.Speed.Zoom._x = self.absolute_relative_zoom_speed_max
            self.my_camera.ptz.AbsoluteMove(request)
            print('Camera moved')
            return STATUS_OK
        except Exception as e:
            print e
            print('Error in AbsoluteMove function')
            return STATUS_ERROR

    def onvif_set_ptz(self, p, t, z):
        # mapping physical values to camera values
        # zoom values are not mapping linearly with the input and output values
        # as conversion is not linear.
        # Maybe same thing is happenning for pan and tilt but we are not able to identify that,
        # as we don't exactly by what angle camera is rotating.
        # print pan, tilt, zoom
        if p > 180 and p < 360:
            p = p - 360
        pan = (p - CAMERA_PAN_RANGE_MIN
               ) / self.slope_pan + self.absolute_pan_value_min
        if t > CAMERA_TILT_RANGE_MAX:
            t = CAMERA_TILT_RANGE_MAX + (360 - t)
        else:
            t = CAMERA_TILT_RANGE_MAX - t
        tilt = t / self.slope_tilt + self.absolute_tilt_value_min
        #zoom = ( zoom_value - self.absolute_zoom_value_min )* self.slope_zoom + CAMERA_ZOOM_RANGE_MIN
        camera_focus_dis = [
            4.3, 8.6, 12.9, 17.2, 21.5, 25.8, 30.1, 34.4, 38.7, 43, 47.3, 51.6,
            55.9, 60.2, 64.5, 68.8, 73.1, 77.4, 81.7, 86, 90.3, 94.6, 98.9,
            103.2, 107.5, 111.8, 116.1, 120.4, 124.7, 129, 135, 140, 153
        ]
        camera_actual_zoom_values = [
            0, 0, 0.062, 0.093, 0.121, 0.152, 0.184, 0.215, 0.243, 0.274,
            0.305, 0.333, 0.364, 0.395, 0.427, 0.454, 0.486, 0.517361111111,
            0.548, 0.576, 0.607, 0.638, 0.666, 0.697, 0.729, 0.760, 0.788,
            0.819, 0.850, 0.881, 0.909, 0.933, 0.972, 1
        ]
        index = 0
        for dis in camera_focus_dis:
            if z < dis:
                break
            else:
                index = index + 1
        if index > len(camera_actual_zoom_values) - 1:
            index = len(camera_actual_zoom_values) - 1
        zoom = camera_actual_zoom_values[index]
        # print ( "onvif_set_ptz pan:" + str(pan) )
        # print ( "onvif_set_ptz tilt:" + str(tilt) )
        # print ( "onvif_set_ptz zoom:"  + str(zoom) )
        try:
            request = self.my_camera.ptz.create_type('AbsoluteMove')
            request.ProfileToken = self.media_profile._token
            request.Position.PanTilt._x = pan
            request.Position.PanTilt._y = tilt
            request.Position.Zoom._x = zoom
            request.Speed.PanTilt._x = self.absolute_relative_pan_tilt_speed_max
            request.Speed.PanTilt._y = self.absolute_relative_pan_tilt_speed_max
            request.Speed.Zoom._x = self.absolute_relative_zoom_speed_max
            self.my_camera.ptz.AbsoluteMove(request)
            print('Camera moved')
            return STATUS_OK
        except Exception as e:
            print e
            print('Error in AbsoluteMove function')
            return STATUS_ERROR

    def onvif_get_device_information(self):
        response = self.my_camera.devicemgmt.GetDeviceInformation()
        return STATUS_OK, response.Manufacturer, response.Model, response.FirmwareVersion, \
            response.SerialNumber, response.HardwareId

    def onvif_set_hostname(self, hostname):
        param = self.my_camera.devicemgmt.create_type('SetHostname')
        param.Name = hostname

        try:
            self.my_camera.devicemgmt.SetHostname(param)
            return STATUS_OK
        except Exception as e:
            print e
            print('Error in SetHostname function')
            return STATUS_ERROR

    def onvif_get_hostname(self):
        response = self.my_camera.devicemgmt.GetHostname()
        return STATUS_OK, response.Name

    def onvif_get_system_date_and_time(self):
        response = self.my_camera.devicemgmt.GetSystemDateAndTime()
        return STATUS_OK, response.TimeZone.TZ, response.UTCDateTime, response.LocalDateTime

    def onvif_reboot_camera(self):
        response = self.my_camera.devicemgmt.SystemReboot()
        return STATUS_OK, response

    def onvif_update(self, host, port):
        self.my_camera.update_url(host, port)
Exemple #9
0
    return xmlvalue


zeep.xsd.simple.AnySimpleType.pythonvalue = zeep_pythonvalue

if __name__ == '__main__':
    mycam = ONVIFCamera('172.18.212.17', 80, 'laba2102', 'TMPpassword',
                        'C:/wsdl/')
    media = mycam.create_media_service()
    media_profile = media.GetProfiles()[0]
    ptz = mycam.create_ptz_service()

    abs_move = ptz.create_type('AbsoluteMove')
    abs_move.ProfileToken = media_profile.token

    imaging = mycam.create_imaging_service()
    brightness = imaging.create_type('SetImagingSettings')
    brightness.VideoSourceToken = media_profile.VideoSourceConfiguration.SourceToken
    brightness.ImagingSettings = imaging.GetImagingSettings({
        'VideoSourceToken':
        media_profile.VideoSourceConfiguration.SourceToken
    })
    cur_bright = int(brightness.ImagingSettings.Brightness)

    coords = np.linspace(-1, 1, 10)
    coords = {str(i): coords[i] for i in range(0, 10)}

    while True:
        ch = msvcrt.getch()
        ch = ch.lower().decode('utf-8')
Exemple #10
0
	def run(self):
		mycam = ONVIFCamera(self.ip, self.port, self.login, self.passw, '/etc/onvif/wsdl')
		media_service = mycam.create_media_service()
		media_profile = media_service.GetProfiles()[0]
		imaging = mycam.create_imaging_service()
		token = media_profile.VideoSourceConfiguration.SourceToken

		request = createImagingRequest(imaging, token)
		try:
			request.ImagingSettings.Exposure.Mode = 'MANUAL'
		except Exception as e:
			print str(self.id) + ': Exposure error'
		try:
			request.ImagingSettings.WhiteBalance.Mode = 'MANUAL'
		except Exception as e:
			print str(self.id) + ': WhiteBalance error'
		try:
			imaging.SetImagingSettings(request)
		except Exception as e:
			print str(self.id) + ': Camera error'

		plusExposure = 0
		minusExposure = 0
		while True:
			previewUri = media_service.GetSnapshotUri({'ProfileToken': media_profile._token}).Uri
			login = '******'
			password = '******'

			manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
			manager.add_password(None, previewUri, login, password)

			auth = urllib2.HTTPBasicAuthHandler(manager)

			opener = urllib2.build_opener(auth)
			urllib2.install_opener(opener)
			image_on_web = urllib2.urlopen(previewUri)
			buf = image_on_web.read()
			filename = "img.jpg"
			downloaded_image = open(filename, "wb")
			downloaded_image.write(buf)
			downloaded_image.close()
			image_on_web.close()

			im = cv2.imread('img.jpg')

			ycbcr = cv2.cvtColor(im, cv2.COLOR_BGR2YCrCb)

			hist_y = cv2.calcHist([ycbcr],[0],None,[256],[0,256])
			hist_cb_2 = cv2.calcHist([ycbcr],[2],None,[2],[0,256])
			hist_cr_2 = cv2.calcHist([ycbcr],[1],None,[2],[0,256])

			hist_y_6 = cv2.calcHist([ycbcr], [0], None, [6], [0,256])

			if not isNeedToStop(hist_y, self.id):
				b = len(hist_y_6) - 2
				w = 1
				for i in range(2, len(hist_y_6)):
					if hist_y_6[i][0] > 250000:
						b = i
						break
				for i in range(len(hist_y_6) - 3, 0, -1):
					if hist_y_6[i][0] > 250000:
						w = i
						break
				black = hist_y_6[0][0] > 250000
				white = hist_y_6[-1][0] > 250000
				if black and white:
					val = max(hist_y_6[0][0], hist_y_6[-1][0])
					dif = val / 2000000.0 * 20.0
					dif = round(dif)
					print(str(self.id) + ': contrast -', dif)
					setContrast(imaging, token, -dif)
					plusExposure = 0
					minusExposure = 0
				elif black:
					dif = (len(hist_y_6) - w - 1) * 10.0 / len(hist_y_6)
					dif = round(dif) + plusExposure
					print(str(self.id) + ': exp +', dif)
					setExposure(imaging, token, dif)
					plusExposure += 1
					minusExposure = 0
				elif white:
					dif = b * 10.0 / len(hist_y_6)
					dif = round(dif) + minusExposure
					print(str(self.id) + ': exp -', dif)
					setExposure(imaging, token, -dif)
					minusExposure += 1
					plusExposure = 0
				else:
					plusExposure = 0
					minusExposure = 0
					val = min(b, len(hist_y_6) - w - 1)
					dif = val * 20.0 / (len(hist_y_6) / 2.0)
					dif = round(dif)
					print(str(self.id) + ': contrast +', dif)
					setContrast(imaging, token, dif)

			try:
				Cb = calc_move(hist_cb_2, 2.56, 0.9, 2)
				Cb = round(Cb)
				print(str(self.id) + ': Cb:', Cb)
				if Cb != 0:
					setCbGain(imaging, token, Cb)
				Cr = calc_move(hist_cr_2, 2.56, 0.9, 2)
				Cr = round(Cr)
				print(str(self.id) + ': Cr:', Cr)
				if Cr != 0:
					setCrGain(imaging, token, Cr)
			except Exception as e:
				print str(self.id) + ': WhiteBalance error'

			time.sleep(1)
class ipCamera:
    def __init__(self, ip, port, usr, pswd, wsdl_path):
        # Monkey coded to pass error
        self.cam = ONVIFCamera(ip, port, usr, pswd, wsdl_path)

        if debug_mode:
            self.print_trace("Camera information : " +
                             str(self.cam.devicemgmt.GetDeviceInformation()))
            self.print_trace("Camera hostname :" +
                             str(self.cam.devicemgmt.GetHostname().Name))

        self.media_service = self.cam.create_media_service()
        self.media_profile = self.media_service.GetProfiles()[0]

        if debug_mode:
            self.print_trace("Media service profiles : " +
                             str(self.media_service.GetProfiles()))

        self.ptz = self.cam.create_ptz_service()

        if debug_mode:
            req = self.ptz.create_type('GetServiceCapabilities')
            ser_cap = self.ptz.GetServiceCapabilities(req)
            self.print_trace("Service capabilities: " + str(ser_cap))

            req = self.ptz.create_type('GetConfigurationOptions')
            req.ConfigurationToken = self.media_profile.PTZConfiguration.token
            ptz_opt = self.ptz.GetConfigurationOptions(req)
            self.print_trace("Configuration options : " + str(ptz_opt))

        self.absolute_move = self.ptz.create_type('AbsoluteMove')
        self.absolute_move.ProfileToken = self.media_profile.token

        self.relative_move = self.ptz.create_type('RelativeMove')
        self.relative_move.ProfileToken = self.media_profile.token

        self.continous_move = self.ptz.create_type('ContinuousMove')
        self.continous_move.ProfileToken = self.media_profile.token

        self.req_stop = self.ptz.create_type('Stop')
        self.req_stop.ProfileToken = self.media_profile.token

        self.imaging = self.cam.create_imaging_service()

        if debug_mode:
            req = self.imaging.create_type('GetServiceCapabilities')
            ser_cap = self.ptz.GetServiceCapabilities(req)
            self.print_trace("Imaging service cap : " + str(ser_cap))

            status = self.imaging.GetStatus({
                'VideoSourceToken':
                self.media_profile.VideoSourceConfiguration.SourceToken
            })

            self.print_trace("Status" + str(status))

        self.focus = self.imaging.create_type("Move")
        self.focus.VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken

        self.action_timeout = 3

    def print_trace(self, string):
        print(string)
        print(80 * '=')

    def stop(self):
        self.req_stop.PanTilt = True
        self.req_stop.Zoom = True

        self.ptz.Stop(self.req_stop)

    def perform_continous(self, timeout):
        self.ptz.ContinuousMove(self.continous_move)

        sleep(timeout)

        self.stop()

        sleep(self.action_timeout)

    def move_continous(self, tiltX, tiltY, timeout):
        print("CMoving with tiltX: {0} tiliY: {1} timeout {2}".format(
            tiltX, tiltY, timeout))

        status = self.ptz.GetStatus({'ProfileToken': self.media_profile.token})
        status.Position.PanTilt.x = tiltX
        status.Position.PanTilt.y = tiltY

        self.continous_move.Velocity = status.Position

        self.perform_continous(timeout)

    def zoom(self, xVelocity, timeout):
        print("Zooming with xVelocity: {0} timeout: {1}".format(
            xVelocity, timeout))

        status = self.ptz.GetStatus({'ProfileToken': self.media_profile.token})
        status.Position.Zoom.x = velocity

        self.continous_move.Velocity = status.Position

        self.perform_continous(timeout)

    def move_absolute(self, x, y, zoom):
        print("AMoving with x: {0} y: {1} zoom: {2}".format(x, y, zoom))

        status = self.ptz.GetStatus({'ProfileToken': self.media_profile.token})
        status.Position.PanTilt.x = x
        status.Position.PanTilt.y = y
        status.Position.Zoom = zoom

        self.absolute_move.Position = status.Position
        self.ptz.AbsoluteMove(self.absolute_move)

        sleep(self.action_timeout)

    def cont_focus(self, speed, timeout):
        self.focus.Focus = {"Continuous": {"Speed": speed}}
        self.imaging.Move(self.focus)
        sleep(timeout)
        self.stop()

        sleep(self.action_timeout)

    def abs_focus(self, pos, speed):
        self.focus.Focus = {"Absolute": {"Position": pos, "Speed": speed}}
        self.imaging.Move(self.focus)

        sleep(self.action_timeout)

    def rel_focus(self, dist, speed):
        self.focus.Focus = {"Relative": {"Distance": dist, "Speed": speed}}
        self.imaging.Move(self.focus)

        sleep(self.action_timeout)
Exemple #12
0
#43
ret,frame43=str43.read()
hsv = cv2.cvtColor(frame43,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv], [0,1], None, [180, 256], [0, 180, 0, 256]) #hue 180 saturation 256
fig.add_subplot(2, 4, 3)
plt.imshow(hist,interpolation = 'nearest')
    
fig.add_subplot(2, 4, 4)
for i,col in enumerate(color): #each value corresponds to number of pixels in that image with its corresponding pixel value RGB
    histr = cv2.calcHist([frame43],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])    

media42 = mycam1.create_media_service()
media_profile42 = media42.GetProfiles()[0]
image42 = mycam1.create_imaging_service()
token42 = media_profile42.VideoSourceConfiguration.SourceToken
SY42 = image42.create_type('GetImagingSettings')
SY42.VideoSourceToken = token42
request42 = image42.GetImagingSettings(SY42)
print(request42)

media43 = mycam2.create_media_service()
media_profile43 = media43.GetProfiles()[0]
image43 = mycam2.create_imaging_service()
token43 = media_profile43.VideoSourceConfiguration.SourceToken
SY43 = image43.create_type('GetImagingSettings')
SY43.VideoSourceToken = token43
request43 = image43.GetImagingSettings(SY43)
print(request43)
Exemple #13
0
class EssentialTest:
    def __init__(self, ip, port, user, passw):
        self.ip = ip
        self.port = port
        self.user = user
        self.passw = passw
        self.cam = ONVIFCamera(self.ip, self.port, self.user, self.passw)
        self.event_service = self.cam.create_events_service()
        self.media = self.cam.create_media_service()

    def genpass(self, length=8, chars=string.ascii_letters + string.digits):
        return ''.join([choice(chars) for k in range(length)])

    def genchar(self, length=8, chars=string.ascii_letters):
        return ''.join([choice(chars) for k in range(length)])

    def gendigits(self, length=8, chars=string.digits):
        return ''.join([choice(chars) for k in range(length)])

    def genhardpass(self,
                    length=8,
                    chars=string.ascii_letters + string.digits +
                    string.punctuation):
        return ''.join([choice(chars) for k in range(length)])

    def test(self, a):
        i = 4
        k = 1000
        z = 0
        while i < 50:
            try:
                name = self.genpass(7)
                if a == 'chars':
                    self.cam.devicemgmt.CreateUsers({
                        'User': {
                            'Username': name,
                            'Password': self.genchar(i),
                            'UserLevel': 'User'
                        }
                    })
                elif a == 'digits':
                    self.cam.devicemgmt.CreateUsers({
                        'User': {
                            'Username': name,
                            'Password': self.gendigits(i),
                            'UserLevel': 'User'
                        }
                    })
                elif a == 'chars+digits':
                    self.cam.devicemgmt.CreateUsers({
                        'User': {
                            'Username': name,
                            'Password': self.genpass(i),
                            'UserLevel': 'User'
                        }
                    })
                elif a == 'chars+digits+symbols':
                    self.cam.devicemgmt.CreateUsers({
                        'User': {
                            'Username': name,
                            'Password': self.genhardpass(i),
                            'UserLevel': 'User'
                        }
                    })
                if self.cam.devicemgmt.GetUsers()[-1].Username == name:
                    if i < k:
                        k = i
                    if i > z:
                        z = i
                    self.cam.devicemgmt.DeleteUsers({'Username': name})
                    i += 1
                else:
                    break
            except exceptions.ONVIFError:
                i += 1
        if k != 1000 and z != 0:
            return 'The range for password length is from ' + str(
                k) + ' to ' + str(z) + ' for ' + a
        else:
            return 'No user has been created. Password with ' + str(
                a) + ' does not work'

    def maxminpass(self):
        result = []
        for m in ['chars', 'digits', 'chars+digits', 'chars+digits+symbols']:
            result.append(self.test(m))
        return result

    def getusers(self):
        users = self.cam.devicemgmt.GetUsers()
        if users is not None:
            return str(users)
        else:
            return 'Function does not work, sorry'

    def maxminuser(self):
        i = 1
        k = 100
        z = 0
        while i < 32:
            try:
                name = self.genpass(i)
                self.cam.devicemgmt.CreateUsers({
                    'User': {
                        'Username': name,
                        'Password': self.genpass(9),
                        'UserLevel': 'User'
                    }
                })
                if self.cam.devicemgmt.GetUsers()[-1].Username == name:
                    if i < k:
                        k = i
                    if i > z:
                        z = i
                # print self.cam.devicemgmt.GetUsers()[-1].Username, name
                self.cam.devicemgmt.DeleteUsers({'Username': name})
                i += 1
            except exceptions.ONVIFError:
                i += 1
        if k != 1000 and z != 0:
            return 'The range for username length is from ' + str(
                k) + ' to ' + str(z)
        else:
            return 'No user has been created. Can not obtain username length properties Something is wrong'

    def maxusers(self):
        k = []
        n, z, i, max1 = 1, 1, 1, 0
        for item in self.cam.devicemgmt.GetUsers():
            max1 += 1
        while i <= 100:
            k += [self.genpass(8)]
            i += 1
        while n < i - 1:
            try:
                self.cam.devicemgmt.CreateUsers({
                    'User': {
                        'Username': k[n],
                        'Password': self.genpass(),
                        'UserLevel': 'User'
                    }
                })
                if self.cam.devicemgmt.GetUsers()[-1].Username == k[n]:
                    n += 1
                    max1 += 1
                else:
                    break
            except exceptions.ONVIFError:
                break
        if n == i:
            return 'No user has been created. Something is wrong'
        # print self.cam.devicemgmt.GetUsers()
        while z < n:
            self.cam.devicemgmt.DeleteUsers({'Username': k[z]})
            z += 1
        if n != 1:
            return 'Camera supports ' + str(max1) + ' max users'
        else:
            return 'No user has been created. Something is wrong'

    def absolutemove(self):
        token = self.media.GetProfiles()[0]._token
        try:
            ptz = self.cam.create_ptz_service()
            ptz.create_type("AbsoluteMove")
            pos = ptz.GetStatus({"ProfileToken": token}).Position
        except (exceptions.ONVIFError, AttributeError):
            return 'Device does not support PTZ service'
        try:
            try:
                x = pos.PanTilt._x
                y = pos.PanTilt._y
                x_z = pos.Zoom._x
            except AttributeError:
                try:
                    x_z = pos.Zoom._x
                    if x_z + 0.1 < 1:
                        x_z1 = x_z + 0.1
                    else:
                        x_z1 = x_z - 0.1
                    ptz.AbsoluteMove({
                        "ProfileToken": token,
                        "Position": {
                            "Zoom": {
                                "_x": x_z1
                            }
                        }
                    })
                    sleep(3)
                    pos = ptz.GetStatus({"ProfileToken": token}).Position
                    x_z = pos.Zoom._x
                    dif3 = (round((x_z1 - x_z), 3))
                    print dif3
                    if dif3 == 0.0:
                        return 'AbsoluteMove supported partly, works only zoom. Current zoom coordinates: ' + str(
                            x_z)
                    else:
                        return 'AbsoluteMove is not supported'
                except AttributeError:
                    return 'AbsoluteMove is not supported'
            # x_z, x, y = pos.Zoom._x, pos.PanTilt._x, pos.PanTilt._y
            if x + 0.1 < 1:
                x1 = x + 0.1
            else:
                x1 = x - 0.1
            if y + 0.1 < 1:
                y1 = y + 0.1
            else:
                y1 = y - 0.1
            if x_z + 0.1 < 1:
                x_z1 = x_z + 0.1
            else:
                x_z1 = x_z - 0.1
            # print x_z
            ptz.AbsoluteMove({
                "ProfileToken": token,
                "Position": {
                    "PanTilt": {
                        "_x": x1,
                        "_y": y1
                    },
                    "Zoom": {
                        "_x": x_z1
                    }
                }
            })
            sleep(3)
            pos = ptz.GetStatus({"ProfileToken": token}).Position
            x_z = pos.Zoom._x
            x = pos.PanTilt._x
            y = pos.PanTilt._y
            dif1 = (round((x1 - x), 3))
            dif2 = (round((y1 - y), 3))
            dif3 = (round((x_z1 - x_z), 3))
            x_z, x, y = round(x_z, 2), round(x, 2), round(y, 2)
            if dif1 == 0.0 and dif2 == 0.0 and dif3 == 0.0:
                return 'AbsoluteMove is supported, current coordinates: ' + str(
                    x) + ' ' + str(y) + ' ' + str(x_z)
            elif dif1 == 0.0 and dif2 == 0.0 and dif3 != 0.0:
                return 'AbsoluteMove is partly supported, only PatTilt works. Current PanTilt coordinates: ' \
                           + str(x) + ' ' + str(y)
            elif dif1 != 0.0 and dif2 != 0.0 and dif3 == 0.0:
                return 'AbsoluteMove is partly supported, only Zoom works. Current Zoom coordinates: ' + str(
                    x_z)
            else:
                return 'AbsoluteMove may be supported, but it cannot be checked. ' \
                       'Potential error with coordinates from GetStatus()'
        except AttributeError:
            return 'AbsoluteMove is not supported, AttributeError '

    def gotohomeposition(self):
        try:
            ptz = self.cam.create_ptz_service()
        except exceptions.ONVIFError:
            return 'PTZ service is not supported'
        try:
            if ptz.GetNodes()[0].HomeSupported:
                return 'GoToHomePosition supported'
        except AttributeError:
            return 'GoToHomePosition is not supported'

    def returnpos(self, ptz, token):
        try:
            pos = ptz.GetStatus({"ProfileToken": token}).Position
        except AttributeError:
            return False
        try:
            pos.x_z = pos.Zoom._x
        except AttributeError:
            pos.x_z = False
        try:
            pos.x = pos.PanTilt._x
            pos.y = pos.PanTilt._y
        except AttributeError:
            pos.x = False
            pos.y = False
        return pos

    def continiousmove(self):
        try:
            ptz = self.cam.create_ptz_service()
        except exceptions.ONVIFError:
            return 'PTZ service is not supported'
        token = self.cam.create_media_service().GetProfiles()[0]._token

        req_move = ptz.create_type('ContinuousMove')
        req_move.ProfileToken = token

        req_stop = ptz.create_type('Stop')
        req_stop.ProfileToken = token

        def left(req_move, req_stop, ptz, token):
            sleep(0.3)
            ptz.Stop(req_stop)
            pos1 = self.returnpos(ptz, token).x
            req_move.Velocity.Zoom._x = 0.0
            req_move.Velocity.PanTilt._x = -0.5
            req_move.Velocity.PanTilt._y = 0.0
            ptz.ContinuousMove(req_move)
            sleep(1)
            ptz.Stop(req_stop)
            sleep(0.3)
            pos2 = self.returnpos(ptz, token).x
            # print pos1 - pos2
            return pos1 - pos2

        def right(req_move, req_stop, ptz, token):
            sleep(0.3)
            ptz.Stop(req_stop)
            pos1 = self.returnpos(ptz, token).x
            req_move.Velocity.Zoom._x = 0.0
            req_move.Velocity.PanTilt._x = 0.5
            req_move.Velocity.PanTilt._y = 0.0
            ptz.ContinuousMove(req_move)
            sleep(1)
            ptz.Stop(req_stop)
            sleep(0.3)
            pos2 = self.returnpos(ptz, token).x
            # print pos1 - pos2
            return pos1 - pos2

        def zoom_in(req_move, req_stop, ptz, token):
            sleep(0.3)
            ptz.Stop(req_stop)
            pos1 = self.returnpos(ptz, token).x_z
            req_move.Velocity.PanTilt._x = 0.0
            req_move.Velocity.PanTilt._y = 0.0
            req_move.Velocity.Zoom._x = 0.1
            ptz.ContinuousMove(req_move)
            sleep(1)
            ptz.Stop(req_stop)
            sleep(0.3)
            pos2 = self.returnpos(ptz, token).x_z
            return pos1 - pos2

        def zoom_out(req_move, req_stop, ptz, token):
            sleep(0.3)
            ptz.Stop(req_stop)
            pos1 = self.returnpos(ptz, token).x_z
            req_move.Velocity.PanTilt._x = 0.0
            req_move.Velocity.PanTilt._y = 0.0
            req_move.Velocity.Zoom._x = -0.1
            ptz.ContinuousMove(req_move)
            sleep(1)
            ptz.Stop(req_stop)
            sleep(0.3)
            pos2 = self.returnpos(ptz, token).x_z
            return pos1 - pos2

        pos = self.returnpos(ptz, token)
        # print 'x ', pos.x, ' y ', pos   .y, ' z ', pos.x_z
        if pos is False:
            return 'PTZ service is not supported'
        elif pos.x is not False and pos.y is not False:
            if round(left(req_move, req_stop, ptz, token), 1) + round(
                    right(req_move, req_stop, ptz, token), 1) == 0:
                if pos.x_z is False:
                    return 'ContinuousMove is partly supported, zoom does not work'
                elif round(zoom_in(req_move, req_stop, ptz, token), 1) + round(
                        zoom_out(req_move, req_stop, ptz, token), 1) == 0:
                    return 'ContinuousMove is supported'
                elif round(zoom_out(
                        req_move, req_stop, ptz, token), 1) + round(
                            zoom_in(req_move, req_stop, ptz, token), 1) == 0:
                    return 'ContinuousMove is supported'
                else:
                    return 'ContinuousMove is partly supported, zoom does not work'
            elif round(right(req_move, req_stop, ptz, token), 1) + round(
                    left(req_move, req_stop, ptz, token), 1) == 0:
                if pos.x_z is False:
                    return 'ContinuousMove is partly supported, zoom does not work'
                elif round(zoom_in(req_move, req_stop, ptz, token), 1) + round(
                        zoom_out(req_move, req_stop, ptz, token), 1) == 0:
                    return 'ContinuousMove is supported'
                elif round(zoom_out(
                        req_move, req_stop, ptz, token), 1) + round(
                            zoom_in(req_move, req_stop, ptz, token), 1) == 0:
                    return 'ContinuousMove is supported'
                else:
                    return 'ContinuousMove is not supported'
            else:
                return 'ContinuousMove is not supported. Camera does not move'
        elif pos.x is False and pos.y is False and pos.x_z >= 0:
            if round(zoom_in(req_move, req_stop, ptz, token), 1) + round(
                    zoom_out(req_move, req_stop, ptz, token), 1) == 0:
                return 'ContinuousMove is partly supported, only zoom works'
            elif round(zoom_out(req_move, req_stop, ptz, token), 1) + round(
                    zoom_in(req_move, req_stop, ptz, token), 1) == 0:
                return 'ContinuousMove is partly supported, only zoom works'
            else:
                return 'ContinuousMove is not supported'
        else:
            return 'ContinuousMove is not supported'

    def relativemove(self):
        try:
            ptz = self.cam.create_ptz_service()
        except exceptions.ONVIFError:
            return 'PTZ service is not supported'
        token = self.cam.create_media_service().GetProfiles()[0]._token
        rel_move = ptz.create_type('RelativeMove')
        rel_move.ProfileToken = token
        req_stop = ptz.create_type('Stop')
        req_stop.ProfileToken = token

        node = ptz.GetNodes()[0]

        # zoom_min = node.SupportedPTZSpaces.RelativeZoomTranslationSpace[0].XRange.Min
        # zoom_max = node.SupportedPTZSpaces.RelativeZoomTranslationSpace[0].XRange.Max
        # pan_min = node.SupportedPTZSpaces.RelativePanTiltTranslationSpace[0].XRange.Min
        # pan_max = node.SupportedPTZSpaces.RelativePanTiltTranslationSpace[0].XRange.Max
        # tilt_min = node.SupportedPTZSpaces.RelativePanTiltTranslationSpace[0].YRange.Min
        # tilt_max = node.SupportedPTZSpaces.RelativePanTiltTranslationSpace[0].YRange.Max

        def move_x(x, token, req_stop, rel_move, ptz):
            ptz.Stop(req_stop)
            pos1 = self.returnpos(ptz, token).x
            rel_move.Translation.PanTilt._x = x
            rel_move.Translation.PanTilt._y = 0
            rel_move.Translation.Zoom._x = 0
            ptz.RelativeMove(rel_move)
            sleep(1)
            ptz.Stop(req_stop)
            pos2 = self.returnpos(ptz, token).x
            # print 'Pan ' + str(pos1 - pos2)
            return pos1 - pos2

        def move_y(y, token, req_stop, rel_move, ptz):
            ptz.Stop(req_stop)
            pos1 = self.returnpos(ptz, token).y
            rel_move.Translation.PanTilt._x = 0
            rel_move.Translation.PanTilt._y = y
            rel_move.Translation.Zoom._x = 0
            ptz.RelativeMove(rel_move)
            sleep(1)
            ptz.Stop(req_stop)
            pos2 = self.returnpos(ptz, token).y
            # print 'Tilt ' + str(pos1 - pos2)
            return pos1 - pos2

        def move_z(z, token, req_stop, rel_move, ptz):
            ptz.Stop(req_stop)
            pos1 = self.returnpos(ptz, token).x_z
            rel_move.Translation.PanTilt._x = 0
            rel_move.Translation.PanTilt._y = 0
            rel_move.Translation.Zoom._x = z
            ptz.RelativeMove(rel_move)
            sleep(1)
            ptz.Stop(req_stop)
            pos2 = self.returnpos(ptz, token).x_z
            # print 'Zoom ' + str(pos1 - pos2)
            return pos1 - pos2

        d = 0.05
        pos = self.returnpos(ptz, token)
        movx = movy = movz = False
        if pos is False:
            return 'PTZ service is not supported'
        if pos.x is not False:
            try:
                mov1 = round(move_x(d, token, req_stop, rel_move, ptz), 2)
                mov2 = round(move_x(-d, token, req_stop, rel_move, ptz), 2)
                if mov1 + mov2 == 0 and not mov1 == mov2 == 0:
                    movx = True
                else:
                    mov3 = round(move_x(-d, token, req_stop, rel_move, ptz), 2)
                    mov4 = round(move_x(d, token, req_stop, rel_move, ptz), 2)
                    if mov3 + mov4 == 0 and not mov3 == mov4 == 0:
                        movx = True
            except exceptions.ONVIFError:
                movx = False
        if pos.y is not False:
            try:
                mov1 = round(move_y(d, token, req_stop, rel_move, ptz), 2)
                mov2 = round(move_y(-d, token, req_stop, rel_move, ptz), 2)
                if mov1 + mov2 == 0 and not mov1 == mov2 == 0:
                    movy = True
                else:
                    mov3 = round(move_y(-d, token, req_stop, rel_move, ptz), 2)
                    mov4 = round(move_y(d, token, req_stop, rel_move, ptz), 2)
                    if mov3 + mov4 == 0 and not mov3 == mov4 == 0:
                        movy = True
            except exceptions.ONVIFError:
                movy = False
        if pos.x_z is not False:
            try:
                mov1 = round(move_z(-0.2, token, req_stop, rel_move, ptz), 2)
                mov2 = round(move_z(0.2, token, req_stop, rel_move, ptz), 2)
                # print 'mov1 ' + str(mov1) + ' mov2 ' + str(mov2)
                if mov1 + mov2 == 0 and not mov1 == mov2 == 0:
                    movz = True
                else:
                    mov3 = round(move_z(0.2, token, req_stop, rel_move, ptz),
                                 2)
                    mov4 = round(move_z(-0.2, token, req_stop, rel_move, ptz),
                                 2)
                    if mov3 + mov4 == 0 and not mov3 == mov4 == 0:
                        movz = True
            except exceptions.ONVIFError:
                movz = False

        if movx and movz and movy:
            return 'RelativeMove is supported'
        elif movx and movy and not movz:
            return 'RelativeMove is supported partly, only PanTilt works'
        elif movx and movz and not movy:
            return 'RelativeMove is supported partly, only PanZoom works'
        elif movy and movz and not movx:
            return 'RelativeMove is supported partly, only TiltZoom works'
        elif movz and not movx and not movy:
            return 'RelativeMove is supported partly, only Zoom works'
        elif movy and not movx and not movz:
            return 'RelativeMove is supported partly, only Tilt works'
        elif movx and not movy and not movz:
            return 'RelativeMove is supported partly, only Pan works'
        else:
            return 'RelativeMove is not supported'

    def absoluteimaging(self):
        media = self.cam.create_media_service()  # Creating media service
        imaging = self.cam.create_imaging_service()  # Creating imaging service
        vstoken = media.GetVideoSources(
        )[0]._token  # Getting videosources token
        options = imaging.GetMoveOptions({'VideoSourceToken': vstoken})
        imaging.create_type('Move')  # Creating new type of imaging
        try:
            options.Absolute
        except AttributeError:
            return 'Absolute imaging is not supported, AttributeError'
        imaging.SetImagingSettings({
            'VideoSourceToken': vstoken,
            'ImagingSettings': {
                'Focus': {
                    'AutoFocusMode': 'MANUAL'
                }
            }
        })
        imaging.Stop({'VideoSourceToken': vstoken})
        try:
            imaging.GetStatus({'VideoSourceToken': vstoken})
        except exceptions.ONVIFError:
            return 'ONVIFError 400 while calling GetStatus(), try again later'
        x0 = round(
            imaging.GetStatus({
                'VideoSourceToken': vstoken
            }).FocusStatus20.Position, 2)
        max_x = options.Absolute.Position.Max
        if x0 + (max_x / 2) < max_x:
            x1 = x0 + max_x / 2
        else:
            x1 = x0 - max_x / 2
        try:
            imaging.Move({
                'VideoSourceToken': vstoken,
                'Focus': {
                    'Absolute': {
                        'Position': x1,
                        'Speed': 0.8
                    }
                }
            })
            sleep(2)  # waiting
            imaging.Stop({'VideoSourceToken': vstoken})  # stopping imaging
            x2 = round(
                imaging.GetStatus({
                    'VideoSourceToken': vstoken
                }).FocusStatus20.Position, 2)
            # print 'x0 ', x0, ' x1 ', x1, ' x2 ', x2
            if abs(x1 - x2) == 0 and not x0 == x2 == 0:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Focus': {
                            'AutoFocusMode': 'AUTO'
                        }
                    }
                })
                return 'Absolute imaging is supported'
            else:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Focus': {
                            'AutoFocusMode': 'AUTO'
                        }
                    }
                })
                return 'Absolute imaging may be supported, but it cannot be checked. ' \
                       'Potential error with coordinates from GetStatus()'
        except AttributeError:  # Catching error
            imaging.SetImagingSettings({
                'VideoSourceToken': vstoken,
                'ImagingSettings': {
                    'Focus': {
                        'AutoFocusMode': 'AUTO'
                    }
                }
            })
            return 'Absolute Imaging is not supported, AttributeError'

    def continuousimaging(self):
        media = self.cam.create_media_service()  # Creating media service
        imaging = self.cam.create_imaging_service()  # Creating imaging service
        vstoken = media.GetVideoSources(
        )[0]._token  # Getting videosources token
        options = imaging.GetMoveOptions({'VideoSourceToken': vstoken})
        imaging.create_type('Move')
        try:
            options.Continuous
        except AttributeError:
            return 'Continuous imaging is not supported'
        max_speed = options.Continuous.Speed.Max

        imaging.SetImagingSettings({
            'VideoSourceToken': vstoken,
            'ImagingSettings': {
                'Focus': {
                    'AutoFocusMode': 'MANUAL'
                }
            }
        })
        imaging.Stop({'VideoSourceToken': vstoken})
        try:
            imaging.GetStatus({'VideoSourceToken': vstoken})
        except exceptions.ONVIFError:
            return 'ONVIFError 400 while calling GetStatus(), try again later'
        x0 = round(
            imaging.GetStatus({
                'VideoSourceToken': vstoken
            }).FocusStatus20.Position, 2)
        if x0 + (max_speed / 2) < max_speed:
            x1 = x0 + max_speed / 2
        else:
            x1 = x0 - max_speed / 2
        try:
            imaging.Move({
                'VideoSourceToken': vstoken,
                'Focus': {
                    'Continuous': {
                        'Speed': x1
                    }
                }
            })
            sleep(1)
            imaging.Stop({'VideoSourceToken': vstoken})
            x2 = round(
                imaging.GetStatus({
                    'VideoSourceToken': vstoken
                }).FocusStatus20.Position, 2)
            # print 'x0 ', x0, ' x1 ', x1, ' x2 ', x2
            if abs(x1 - x2) == 0 and not x0 == x2 == 0:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Focus': {
                            'AutoFocusMode': 'AUTO'
                        }
                    }
                })
                return 'Continuous imaging is supported'
            else:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Focus': {
                            'AutoFocusMode': 'AUTO'
                        }
                    }
                })
                return 'Continuous imaging may be supported, but it cannot be checked. ' \
                       'Potential error with coordinates from GetStatus()'
        except AttributeError:  # Catching error
            imaging.SetImagingSettings({
                'VideoSourceToken': vstoken,
                'ImagingSettings': {
                    'Focus': {
                        'AutoFocusMode': 'AUTO'
                    }
                }
            })
            return 'Continuous Imaging is not supported, AttributeError'

    def relativeimaging(self):
        media = self.cam.create_media_service()  # Creating media service
        imaging = self.cam.create_imaging_service()  # Creating imaging service
        vstoken = media.GetVideoSources(
        )[0]._token  # Getting videosources token
        options = imaging.GetMoveOptions({'VideoSourceToken': vstoken})
        imaging.create_type('Move')
        try:
            options.Relative
        except AttributeError:
            return 'Relative imaging is not supported'
        imaging.SetImagingSettings({
            'VideoSourceToken': vstoken,
            'ImagingSettings': {
                'Focus': {
                    'AutoFocusMode': 'MANUAL'
                }
            }
        })
        imaging.Stop({'VideoSourceToken': vstoken})
        x0 = round(
            imaging.GetStatus({
                'VideoSourceToken': vstoken
            }).FocusStatus20.Position, 2)
        max_x = options.Relative.Distance.Max
        if x0 + (max_x / 2) < max_x:
            x1 = x0 + max_x / 2
        else:
            x1 = x0 - max_x / 2
        try:
            imaging.Move({
                'VideoSourceToken': vstoken,
                'Focus': {
                    'Relative': {
                        'Distance': x1,
                        'Speed': 0.8
                    }
                }
            })
            sleep(2)  # waiting
            imaging.Stop({'VideoSourceToken': vstoken})  # stopping imaging
            x2 = round(
                imaging.GetStatus({
                    'VideoSourceToken': vstoken
                }).FocusStatus20.Position, 2)
            # print 'x0 ', x0, ' x1 ', x1, ' x2 ', x2
            if abs(x1 - x2) == 0 and not x0 == x2 == 0:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Focus': {
                            'AutoFocusMode': 'AUTO'
                        }
                    }
                })
                return 'Relative imaging is supported'
            else:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Focus': {
                            'AutoFocusMode': 'AUTO'
                        }
                    }
                })
                return 'Relative imaging may be supported, but it cannot be checked. ' \
                       'Potential error with coordinates from GetStatus()'
        except AttributeError:  # Catching error
            imaging.SetImagingSettings({
                'VideoSourceToken': vstoken,
                'ImagingSettings': {
                    'Focus': {
                        'AutoFocusMode': 'AUTO'
                    }
                }
            })
            return 'Relative Imaging is not supported, AttributeError'

    def videoencoding(self):
        media = self.cam.create_media_service()
        encoders = []
        try:
            configs = media.GetVideoEncoderConfigurations()
            for i in configs:
                encoders.append(i.Encoding)
            return list(set(encoders))
        except AttributeError:
            return 'AttributeError, something is wrong'

    def videoresolutions(self):
        media = self.cam.create_media_service()
        res = []
        try:
            configs = media.GetVideoEncoderConfigurations()
            for i in configs:
                res.append(
                    str(i.Resolution.Width) + 'x' + str(i.Resolution.Height))
            return list(set(res))
        except AttributeError:
            return 'Attribute error, something is wrong'

    def audioencoding(self):
        media = self.cam.create_media_service()
        try:
            audio = []
            configs = media.GetAudioEncoderConfigurations()
            print configs
            for i in configs:
                audio.append(i.Encoding)
            return list(set(audio))
        except AttributeError:
            return 'Attribute error, something is wrong'

    def getbrightness(self):
        media = self.cam.create_media_service()
        imaging = self.cam.create_imaging_service()
        vstoken = media.GetVideoSources()[0]._token
        f1 = True
        f2 = True
        settings = imaging.GetImagingSettings({'VideoSourceToken': vstoken})
        options = imaging.GetOptions({'VideoSourceToken': vstoken})
        try:
            Min = options.Brightness.Min
            Max = options.Brightness.Max
        except AttributeError:
            f1 = False
        try:
            Curr = settings.Brightness
        except AttributeError:
            f2 = False
        if f1 and f2:
            return 'Min: ' + str(Min) + ' Curr: ' + str(Curr) + ' Max: ' + str(
                Max)
        elif f1 and not f2:
            return 'Min: ' + str(Min) + ' Curr: ' + 'NULL' + ' Max: ' + str(
                Max)
        elif not f1:
            return 'Brightness not supported'

    def setbrightness(self, value):
        media = self.cam.create_media_service()
        imaging = self.cam.create_imaging_service()
        vstoken = media.GetVideoSources()[0]._token
        options = imaging.GetOptions({'VideoSourceToken': vstoken})
        get0 = imaging.GetImagingSettings({'VideoSourceToken': vstoken})
        try:
            Min = options.Brightness.Min
            Max = options.Brightness.Max
            br0 = get0.Brightness
            if Min < value < Max:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Brightness': value
                    }
                })
            else:
                return 'Value given is out of range'
            get1 = imaging.GetImagingSettings({'VideoSourceToken': vstoken})
            br1 = get1.Brightness
            if br1 == value:
                imaging.SetImagingSettings({
                    'VideoSourceToken': vstoken,
                    'ImagingSettings': {
                        'Brightness': br0
                    }
                })
                return 'Setbrightness works. Current value: ', br1
            else:
                return 'Setbrightness does not work'
        except AttributeError:
            return 'Setbrightness does not work, AttributeError'

    def stepbrightness(self):
        media = self.cam.create_media_service()
        imaging = self.cam.create_imaging_service()
        vstoken = media.GetVideoSources()[0]._token
        set1 = imaging.GetImagingSettings({'VideoSourceToken': vstoken})
        options = imaging.GetOptions({'VideoSourceToken': vstoken})
        # print set1
        step = 100000
        percmin = 1000000

        try:
            br0 = set1.Brightness
            br1 = br0
            perc = 0.0000001
            for h in range(6):
                n = 7
                for i in range(6):
                    k = 1
                    while k < 7:
                        br1 += perc
                        imaging.SetImagingSettings({
                            'VideoSourceToken': vstoken,
                            'ImagingSettings': {
                                'Brightness': br1
                            }
                        })
                        br2 = imaging.GetImagingSettings({
                            'VideoSourceToken':
                            vstoken
                        }).Brightness
                        if round(br1, n) == round(br2, n):
                            # print 'br1 = ', br1, ' br2 = ', br2
                            # print 'Round Br1 = ', round(br1, n), 'Round Br2 = ', round(br2, n), 'N = ', n
                            percmin = k * (0.0000001 * pow(10, i))
                            # print 'K = ', k, ' I= ', i, 'N = ', n, 'Percmin = ', percmin
                            break
                        perc += 0.0000001 * pow(10, i)
                        #
                        k += 1
                    n -= 1
                    if percmin < step:
                        step = percmin
        except AttributeError:
            return 'AttributeError, try again'
        if step == 100000:
            return 'Step was not calculated, try again'
        else:
            return 'Step is ' + '{:.0e}'.format(float(step))

    def imagingsettings(self):
        media = self.cam.create_media_service()  # Creating media service
        imaging = self.cam.create_imaging_service()  # Creating imaging service
        vstoken = media.GetVideoSources(
        )[0]._token  # Getting videosources token
        settings = imaging.GetImagingSettings({'VideoSourceToken': vstoken})
        # print settings
        options = imaging.GetOptions({'VideoSourceToken': vstoken})
        print options
        try:
            Backlight = ''
            Backlight.Min = options.BacklightCompensation.Level.Min
            Backlight.Max = options.BacklightCompenSharpnessevel.Max
            Backlight.Curr = settings.Backlight
        except AttributeError:
            pass
        try:
            ColorSaturation = ''
            ColorSaturation.Min = options.ColorSaturation.Min
            ColorSaturation.Max = options.ColorSaturation.Max
            ColorSaturation.Curr = settings.ColorSaturation
        except AttributeError:
            pass
        try:
            Contrast = ''
            Contrast.Min = options.Contrast.Min
            Contrast.Max = options.Contrast.Max
            Contrast.Curr = settings.Contrast
        except AttributeError:
            pass
        try:
            Sharpness = ''
            Sharpness.Min = options.Sharpness.Min
            Sharpness.Max = options.Sharpness.Max
            Sharpness.Curr = settings.Sharpness
        except AttributeError:
            pass
        try:
            WhiteBalance, WhiteBalance.YrGain, WhiteBalance.YbGain = '', '', ''
            WhiteBalance.YrGain.Min = options.WhiteBalance.YrGain.Min
            WhiteBalance.YrGain.Max = options.WhiteBalance.YrGain.Max
            WhiteBalance.YbGain.Min = options.WhiteBalance.YbGain.Min
            WhiteBalance.YbGain.Max = options.WhiteBalance.YbGain.Max
            WhiteBalance.YrGain.Curr = settings.WhiteBalance.YrGain
            WhiteBalance.YbGain.Curr = settings.WhiteBalance.YbGain
        except AttributeError:
            pass
        try:
            WideDynamicRange = ''
            WideDynamicRange.Mode = options.WideDynamicRange.Mode
        except AttributeError:
            pass

        try:
            features = ''
            for feature in settings:
                features += str(feature[0]) + '\n'
            return str(features[:-1])
        except AttributeError:
            return 'Attribute error, something is wrong'

    def currentposition(self):
        media = self.cam.create_media_service()
        token = media.GetProfiles()[0]._token
        vstoken = media.GetVideoSources(
        )[0]._token  # Getting videosources token
        focus = ''
        try:
            imaging = self.cam.create_imaging_service(
            )  # Creating imaging service
        except exceptions.ONVIFError:
            return 'Imaging service is not supported'
        try:
            focus = str(
                round(
                    imaging.GetStatus({
                        'VideoSourceToken': vstoken
                    }).FocusStatus20.Position, 2))
        except (AttributeError, exceptions.ONVIFError):
            focus = 'None'
        try:
            ptz = self.cam.create_ptz_service()
        except exceptions.ONVIFError:
            return 'PTZ service is not supported'

        try:
            pos = ptz.GetStatus({"ProfileToken": token}).Position
        except AttributeError:
            return 'AttributeError, something is wrong'
        try:
            pos.z = str(round(pos.Zoom._x, 2))
        except AttributeError:
            pos.z = 'None'
        try:
            pos.x, pos.y = str(round(pos.PanTilt._x,
                                     2)), str(round(pos.PanTilt._y, 2))
        except AttributeError:
            pos.x, pos.y = 'None', 'None'
        return 'x: ' + pos.x + ' y: ' + pos.y + ' z: ' + pos.z + ' focus: ' + focus

    def relays(self):
        relays = self.cam.devicemgmt.GetRelayOutputs()
        if relays:
            token = relays[0]._token
            mode0 = relays[0].Properties.Mode
            if mode0 == 'Bistable':
                mode1 = 'Monostable'
            else:
                mode1 = 'Bistable'
            state = relays[0].Properties.IdleState
            if state == 'closed':
                state1 = ''
            self.cam.devicemgmt.SetRelayOutputSettings({
                'RelayOutput': {
                    'token': token,
                    'Properties': {
                        'Mode': mode1
                    }
                }
            })
        return relays

    def dynamicdns(self):
        dns = self.cam.devicemgmt.GetDynamicDNS()
        if dns:
            return 'works', dns
        else:
            return 'dynamicdns is not supported'
class Camera:

    # Istanza della classe Camera
    instance = None

    __mycam__ = None

    # Parametri necessari per la connesione
    IP = None
    Port = None
    Username = None
    Password = None
    Setting_Par = False

    # Token Camera
    __main_token__ = None
    __token_encoder__ = None

    # Servizi offerti dal Framework ONVIF
    __media__ = None
    __ptz_service__ = None
    __image__ = None
    __video_sources__ = None

    # Configurazione Servizio Device Managment
    __device_mgmt__ = None

    # Configurazione Servizio Media
    __all_profiles__ = None
    __main_profile__ = None

    __config_media__ = None
    __option_camera__ = None

    __config_metadata__ = None
    __option_metadata__ = None

    __config_videosources__ = None
    __option_videosources__ = None

    __config_video_source_modes__ = None
    __option_media_capabilities__ = None

    # Configurazione Servizio Imaging
    __config_image__ = None
    __option_image__ = None

    __option_image_capabilities__ = None

    __config_move__ = None
    __option_move__ = None

    # Configurazione Servizio PTZ_Service
    __config_ptz__ = None

    def __init__(self):
        if self.__mycam__ is None:

            # Connessione al dispositivo Onvif
            self.__mycam__ = ONVIFCamera(Camera.IP, Camera.Port,
                                         Camera.Username, Camera.Password,
                                         './wsdl')

            self.__media__ = self.__mycam__.create_media_service()

            try:
                self.__video_sources__ = self.__media__.GetVideoSources()

                self.__ptz_service__ = self.__mycam__.create_ptz_service()
                self.__image__ = self.__mycam__.create_imaging_service()

                # Token del Profilo Principale
                self.__main_token__ = self.__media__.GetProfiles()[0].token

                # Token del Video Encoder utilizzato
                self.__token_encoder__ = self.__media__.GetVideoEncoderConfigurations(
                )[0].token

                self.get_device_management()
                self.get_config_image()
                self.get_config_media()

                self.update_system_Date_Time()

            except (exceptions.ONVIFError):
                self.__mycam__ = None
                self.__media__ = None

                Camera.reset_parameters()

                print("ONVIF Invalid Username e Password!")

        else:
            raise ("You cannot create another Camera class")

    @staticmethod
    def set_parameters(_IP, _Port, _Username, _Password):
        if Camera.Setting_Par is False:
            Camera.IP = _IP
            Camera.Port = _Port
            Camera.Username = _Username
            Camera.Password = _Password
            Camera.Setting_Par = True

    @staticmethod
    def reset_parameters():
        Camera.IP = None
        Camera.Port = None
        Camera.Username = None
        Camera.Password = None
        Camera.Setting_Par = False

    @staticmethod
    def get_camera():
        if Camera.Setting_Par:
            Camera.instance = Camera()
        return Camera.instance

    def get_config_media(self):

        self.__all_profiles__ = self.__media__.GetProfiles()
        self.__main_profile__ = self.__all_profiles__[0]

        self.__config_media__ = self.__media__.GetVideoEncoderConfiguration(
            self.__token_encoder__)
        self.__option_camera__ = self.__media__.GetVideoEncoderConfigurationOptions(
            self.__token_encoder__)

        self.__config_metadata__ = self.__media__.GetMetadataConfiguration(
            self.__token_encoder__)
        self.__option_metadata__ = self.__media__.GetMetadataConfigurationOptions(
            self.__token_encoder__)

        self.__config_videosources__ = self.__main_profile__.VideoSourceConfiguration
        self.__option_videosources__ = self.__media__.GetVideoSourceConfigurationOptions(
            self.__token_encoder__)

        self.__option_media_capabilities__ = self.__media__.GetServiceCapabilities(
        )

        #self.__config_video_source_modes__ = self.__media__.GetVideoSourceModes(self.__token_encoder__)

    def get_config_image(self):
        self.__config_image__ = self.__image__.GetImagingSettings(
            self.__token_encoder__)
        self.__option_image__ = self.__image__.GetOptions(
            self.__token_encoder__)

        self.__option_image_capabilities__ = self.__image__.GetServiceCapabilities(
        )

        self.__config_move__ = self.__image__.GetStatus(self.__token_encoder__)
        self.__option_move__ = self.__image__.GetMoveOptions(
            self.__token_encoder__)

    '''
    -- Da controllare il metodo get utilizzato per il recupero dei settaggi del servizio PTZ --
    def get_config_ptz(self):
        self.__config_ptz__ = self.__ptz_service__.GetCompatibleConfigurations(Camera.__token__)
    '''

    # ------------------ Setting Core ---------------------------
    def get_device_management(self):
        self.__device_mgmt__ = self.__mycam__.devicemgmt

    def get_Hostname(self):
        return self.__device_mgmt__.GetHostname().Name

    def set_Hostname(self, name):
        request_device = self.__device_mgmt__.create_type("SetHostname")

        request_device.Name = name

        self.__device_mgmt__.SetHostname(request_device)

    def get_all_information_device(self):
        return self.__device_mgmt__.GetDeviceInformation()

    '''
        This operation is used to retrieve URIs from which system information may be downloaded using HTTP. 
        URIs may be returned for the following system information:
            -   System Logs:                Multiple system logs may be returned, of different types.  
                                            The exact format of the system logs is outside the scope of this specification.
            -   Support  Information:       This consists of arbitrary device diagnostics information from a device.  
                                            The exact format of the diagnostic information is outside the scope of this specification.
            -   System  Backup:             The received file is a backup file that can be used to restore the current device configuration  
                                            at a later date.  
                                            The exact format of the backup configuration file is outside the scope of this specification.
    
        Non sono stati implementati i seguenti metodi:
            -   GetSystemUris
            -   GetSystemBackup
            -   GetSystemLog
    '''

    def get_system_Date_Time(self):
        return self.__device_mgmt__.GetSystemDateAndTime()

    def update_system_Date_Time(self):
        request_device = self.__device_mgmt__.create_type(
            "SetSystemDateAndTime")

        actual_time = time.localtime()

        request_device.DateTimeType = 'Manual'
        request_device.DaylightSavings = True
        request_device.TimeZone = {'TZ': 'CST-0:00:00'}
        request_device.UTCDateTime = {
                                        'Date':{'Year':actual_time.tm_year,'Month':actual_time.tm_mon,'Day':actual_time.tm_mday},\
                                        'Time':{'Hour':actual_time.tm_hour,'Minute':actual_time.tm_min,'Second':actual_time.tm_sec}
                                    }

        self.__device_mgmt__.SetSystemDateAndTime(request_device)

    def reboot(self):
        self.__device_mgmt__.SystemReboot()

    def soft_factory_reset(self):
        request_device = self.__device_mgmt__.create_type(
            "SetSystemFactoryDefault")

        request_device.FactoryDefault = 'Soft'

        self.__device_mgmt__.SetSystemFactoryDefault(request_device)

    def hard_factory_reset(self):
        request_device = self.__device_mgmt__.create_type(
            "SetSystemFactoryDefault")

        request_device.FactoryDefault = 'Hard'

        self.__device_mgmt__.SetSystemFactoryDefault(request_device)

    #------------------ Setting Imaging -------------------------
    # Creazione della richiesta da inviare alla camera relativa alla modifica dei parametri dell'immagine
    def create_request_image(self):
        request_img = self.__image__.create_type('SetImagingSettings')
        request_img.VideoSourceToken = self.__token_encoder__
        request_img.ForcePersistence = True

        return request_img

    def create_request_focus(self):
        request_focus = self.__image__.create_type('Move')
        request_focus.VideoSourceToken = self.__token_encoder__

        return request_focus

    def print_config_image(self):
        self.get_config_image()
        print(self.__config_image__)

    def print_options_image__(self):
        self.get_config_image()
        print(self.__option_image__)

    def print_config_move(self):
        self.get_config_image()
        print(self.__config_move__)

    def print_options_move__(self):
        self.get_config_image()
        print(self.__option_move__)

    def print_option_image_capabilities(self):
        self.get_config_image()
        print(self.__option_image_capabilities__)

    def get_Brightness(self):
        return self.__config_image__.Brightness

    def set_Brightness(self, Value_Brightness):

        if (Value_Brightness >= 0.0 and Value_Brightness <= 100.0):
            request_img = self.create_request_image()

            self.__config_image__.Brightness = Value_Brightness
            request_img.ImagingSettings = self.__config_image__

            self.__image__.SetImagingSettings(request_img)

    def get_Saturation(self):
        return self.__config_image__.ColorSaturation

    def set_Saturation(self, Value_Saturation):

        if (Value_Saturation >= 0.0 and Value_Saturation <= 100.0):
            request_img = self.create_request_image()

            self.__config_image__.ColorSaturation = Value_Saturation
            request_img.ImagingSettings = self.__config_image__

            self.__image__.SetImagingSettings(request_img)

    def get_Sharpness(self):
        return self.__config_image__.Sharpness

    def set_Sharpness(self, Value_Sharpness):

        if (Value_Sharpness >= 0.0 and Value_Sharpness <= 100.0):
            request_img = self.create_request_image()

            self.__config_image__.Sharpness = Value_Sharpness
            request_img.ImagingSettings = self.__config_image__

            self.__image__.SetImagingSettings(request_img)

    def get_Contrast(self):
        return self.__config_image__.Contrast

    def set_Contrast(self, Value_Contrast):

        if (Value_Contrast >= 0.0 and Value_Contrast <= 100.0):
            request_img = self.create_request_image()

            self.__config_image__.Contrast = Value_Contrast
            request_img.ImagingSettings = self.__config_image__

            self.__image__.SetImagingSettings(request_img)

        #--------------- Exposure ------------------------
    def get_Iris(self):
        return self.__config_image__.Exposure.Iris

    def set_Iris(self, Value_Iris):

        if (Value_Iris >= 0.0 and Value_Iris <= 1.0):
            request_img = self.create_request_image()

            self.__config_image__.Exposure.Iris = Value_Iris
            request_img.ImagingSettings = self.__config_image__

            self.__image__.SetImagingSettings(request_img)

    def get_Focus_Position(self):
        return self.__config_move__.FocusStatus20.Position

    def set_Focus_Move(self, Value_Position):

        if (Value_Position >= 0.0 and Value_Position <= 1.0):
            request_focus = self.create_request_focus()

            request_focus.Focus = {'Absolute': {'Position': Value_Position, 'Speed': None}, \
                                   'Relative': {'Distance': Value_Position, 'Speed': None}, \
                                   'Continuous': {'Speed': 0.0}}

            self.__image__.Move(request_focus)

    '''
        #------------- FOCUS ---------------------------
    def set_AutoFocus(self):

        request_img = self.create_request_image()

        WideDynamicRange = {'Mode':'MANUAL','CrGain':90.0,'CbGain':20.0,'Extension':None}

        Camera.__config_image__.WideDynamicRange = WideDynamicRange
        #print(Camera.__config_image__)
        request_img.ImagingSettings = Camera.__config_image__

        Camera.__image__.SetImagingSettings(request_img)
    '''

    # ------------------ Setting Media -------------------------
    # Creazione della richiesta da inviare alla camera relativa alla modifica dei parametri dell'encoder
    def create_request_media(self):
        request_media = self.__media__.create_type(
            'SetVideoEncoderConfiguration')
        request_media.ForcePersistence = True

        return request_media

    def print_all_profiles(self):
        self.get_config_media()
        print(self.__all_profiles__)

    def print_main_profile(self):
        self.get_config_media()
        print(self.__main_profile__)

    def print_config_media(self):
        self.get_config_media()
        print(self.__config_media__)

    def print_options_config_media(self):
        self.get_config_media()
        print(self.__option_camera__)

    def print_config_metadata(self):
        self.get_config_media()
        print(self.__config_metadata__)

    def print_options_config_metadata(self):
        self.get_config_media()
        print(self.__option_metadata__)

    def print_config_videosources(self):
        self.get_config_media()
        print(self.__config_videosources__)

    def print_options_config_videosources(self):
        self.get_config_media()
        print(self.__option_videosources__)

    def print_config_videosources_modes(self):
        self.get_config_media()
        print(self.__config_video_source_modes__)

    def print_option_media_capabilities__(self):
        self.get_config_media()
        print(self.__option_media_capabilities__)

    def get_ResolutionAvailable(self):
        return self.__option_camera__.H264.ResolutionsAvailable

    def get_Resolution(self):
        return self.__config_media__.Resolution

    def set_Resolution(self, Index_Resolution):

        if (Index_Resolution >= 0
                and Index_Resolution < len(self.get_ResolutionAvailable())):
            request_media = self.create_request_media()
            self.__config_media__.Resolution = self.__option_camera__.H264.ResolutionsAvailable[
                Index_Resolution]

            request_media.Configuration = self.__config_media__

            self.__media__.SetVideoEncoderConfiguration(request_media)

    def get_Options_QualityRange(self):
        min = int(self.__option_camera__.QualityRange.Min)
        max = int(self.__option_camera__.QualityRange.Max)

        return min, max

    def get_QualityRange(self):
        return self.__config_media__.Quality

    def set_QualityRange(self, value_QualityRange):

        min, max = self.get_Options_QualityRange()

        if (value_QualityRange > min and value_QualityRange < max):
            request_media = self.create_request_media()
            self.__config_media__.Quality = value_QualityRange

            request_media.Configuration = self.__config_media__

            self.__media__.SetVideoEncoderConfiguration(request_media)

    '''
        The GOV length of an H.264 stream is the sum total of I-frames and P-frames in a GOV (Group
        of video images). An I-frame, or intra frame, is an image that is coded in its entirety. A P-frame,
        or predictive inter frame, refers to parts of earlier images (I-frames and/or P-frames) to code the
        frame and therefore uses less bits to transmit the image. Increasing the GOV length decreases
        the frequency of I-frames, and therefore reduces bandwidth consumption and image quality.
    '''

    def get_Options_GovLengthRange(self):
        min = int(self.__option_camera__.H264.GovLengthRange.Min)
        max = int(self.__option_camera__.H264.GovLengthRange.Max)

        return min, max

    def get_GovLengthRange(self):
        return self.__config_media__.H264.GovLength

    def set_GovLengthRange(self, value_GovLengthRange):

        min, max = self.get_Options_GovLengthRange()

        if (value_GovLengthRange > min and value_GovLengthRange < max):
            request_media = self.create_request_media()
            self.__config_media__.H264.GovLength = value_GovLengthRange

            request_media.Configuration = self.__config_media__

            self.__media__.SetVideoEncoderConfiguration(request_media)

    def get_Options_FrameRate(self):
        min = int(self.__option_camera__.H264.FrameRateRange.Min)
        max = int(self.__option_camera__.H264.FrameRateRange.Max)

        return min, max

    def get_FrameRate(self):
        return self.__config_media__.RateControl.FrameRateLimit

    # NON FUNZIONA
    def set_FrameRate(self, value_FrameRate):

        min, max = self.get_Options_FrameRate()

        if (value_FrameRate > min and value_FrameRate < max):
            request_media = self.create_request_media()
            self.__config_media__.RateControl.FrameRateLimit = value_FrameRate

            request_media.Configuration = self.__config_media__

            self.__media__.SetVideoEncoderConfiguration(request_media)

    # ------------------ Setting PTZ -------------------------
    def print_config_ptz(self):
        pass
Exemple #15
0
class Camera(object):
    def __init__(self, options):
        self.id = options['id']
        self.name = options['name']
        self.host = options['host']
        self.port = int(options['port'])
        self.__userid = options['userid']
        self.__password = options['password']
        self.__isconnected = False
        th = Thread(target=self.__initialize, name=f"CameraInit-{self.name}")
        th.start()

    def __initialize(self):
        logger.info(
            f'Initializing Camera {self.name} at {(self.host,self.port)}')
        try:
            self.__cam = ONVIFCamera(self.host, self.port, self.__userid,
                                     self.__password)
            self.__media_service = self.__cam.create_media_service()
            self.__ptz_service = self.__cam.create_ptz_service()
            self.__imaging_service = self.__cam.create_imaging_service()
            self.__profile = self.__media_service.GetProfiles()[0]
            self.__video_source = self.__get_video_sources()[0]
            self.__ptz_status = self.__ptz_service.GetStatus(
                {'ProfileToken': self.__profile.token})
            self.__isconnected = True
            self.capabilities = self.__get_service_capabilities()
            logger.info(
                f'Successfully Initialized Camera {self.name} at {(self.host, self.port)}'
            )
        except Exception as e:
            self.__isconnected = False
            logger.info(
                f'Initialization for Camera {self.name} at {(self.host, self.port)} failed. Not Connected'
            )

    @property
    def isconnected(self):
        return self.__isconnected

    @property
    def configuration(self):
        return self.__get_configurations()

    @property
    def configOptions(self):
        return self.__get_ptz_conf_opts()

    def get_stream_uri(self, protocol='UDP', stream='RTP-Unicast'):
        """
        :param protocol
            string 'UDP', 'TCP', 'RTSP', 'HTTP'
        :param stream
             string either 'RTP-Unicast' or 'RTP-Multicast'
        WARNING!!!
        Some cameras return invalid stream uri

        RTP unicast over UDP: StreamType = "RTP_Unicast", TransportProtocol = "UDP"
        RTP over RTSP over HTTP over TCP: StreamType = "RTP_Unicast", TransportProtocol = "HTTP"
        RTP over RTSP over TCP: StreamType = "RTP_Unicast", TransportProtocol = "RTSP"
        """
        logger.debug(
            f'Camera {self.name}: Getting stream uri {protocol} {stream}')
        req = self.__media_service.create_type('GetStreamUri')
        req.ProfileToken = self.__profile.token
        req.StreamSetup = {
            'Stream': stream,
            'Transport': {
                'Protocol': protocol
            }
        }
        return self.__media_service.GetStreamUri(req)

    def get_status(self):
        return self.__ptz_service.GetStatus(
            {'ProfileToken': self.__profile.token})

    def go_home(self):
        logger.debug(f'Camera {self.name}: Moving home')
        req = self.__ptz_service.create_type('GotoHomePosition')
        req.ProfileToken = self.__profile.token
        self.__ptz_service.GotoHomePosition(req)

    def get_presets(self):
        logger.debug(f'Camera {self.name}: Getting presets')
        return self.__ptz_service.GetPresets(self.__profile.token)

    def goto_preset(self, preset_token, ptz_velocity=(1.0, 1.0, 1.0)):
        """
        :param preset_token:
            unsigned int
        :param ptz_velocity:
            tuple (pan,tilt,zoom) where
            pan tilt and zoom in range [0,1]
        """
        logger.debug(
            f'Camera {self.name}: Moving to preset {preset_token}, speed={ptz_velocity}'
        )
        req = self.__ptz_service.create_type('GotoPreset')
        req.ProfileToken = self.__profile.token
        req.PresetToken = preset_token
        req.Speed = self.__ptz_status.Position
        vel = req.Speed
        vel.PanTilt.x, vel.PanTilt.y = ptz_velocity[0], ptz_velocity[1]
        vel.Zoom.x = ptz_velocity[2]
        return self.__ptz_service.GotoPreset(req)

    def set_preset(self, preset_token=None, preset_name=None):
        """
        :param preset_token:
            unsigned int, usually in range [1, 128] dependent on camera
        :param preset_name:
            string
            if None then duplicate preset_token
        """
        logger.debug(
            f'Camera {self.name}: Setting preset {preset_token} ({preset_name})'
        )
        req = self.__ptz_service.create_type('SetPreset')
        req.ProfileToken = self.__profile.token
        req.PresetToken = preset_token
        req.PresetName = preset_name
        return self.__ptz_service.SetPreset(req)

    def remove_preset(self, preset_token=None, preset_name=None):
        """
        :param preset_token:
            unsigned int, usually in range [1, 128] dependent on camera
        :param preset_name:
            string
            if None then duplicate preset_token
        """
        logger.debug(f'Camera {self.name}: Removing preset {preset_token}')
        req = self.__ptz_service.create_type('RemovePreset')
        req.ProfileToken = self.__profile.token
        req.PresetToken = preset_token
        return self.__ptz_service.RemovePreset(req)

    def stop(self):
        logger.debug(f'Camera {self.name}: Stopping movement')
        self.__ptz_service.Stop({'ProfileToken': self.__profile.token})

    def get_brightness(self):
        logger.debug(f'Camera {self.name}: Getting brightness')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.Brightness

    def set_brightness(self, brightness):
        """
        :param brightness:
            float in range [0, 100]
        """
        logger.debug(f'Camera {self.name}: Settings brightness')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Brightness = brightness
        self.__set_imaging_settings(imaging_settings)

    def get_color_saturation(self):
        logger.debug(f'Camera {self.name}: Getting color_saturation')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.ColorSaturation

    def set_color_saturation(self, color_saturation):
        """
        :param color_saturation:
            float in range [0, 100]
        """
        logger.debug(f'Camera {self.name}: Settings color_saturation')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.ColorSaturation = color_saturation
        self.__set_imaging_settings(imaging_settings)

    def get_contrast(self):
        logger.debug(f'Camera {self.name}: Getting contrast')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.Contrast

    def set_contrast(self, contrast):
        """
        :param contrast:
            float in range [0, 100]
        """
        logger.debug(f'Camera {self.name}: Settings contrast')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Contrast = contrast
        self.__set_imaging_settings(imaging_settings)

    def get_sharpness(self):
        logger.debug(f'Camera {self.name}: Getting sharpness')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.Sharpness

    def set_sharpness(self, sharpness):
        """
        :param sharpness:
            float in range [0, 100]
        """
        logger.debug(f'Camera {self.name}: Settings sharpness')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Sharpness = sharpness
        self.__set_imaging_settings(imaging_settings)

    def set_focus_mode(self, mode='AUTO'):
        """
        :param mode:
            string, can be either 'AUTO' or 'MANUAL'
        """
        logger.debug(f'Camera {self.name}: Settings focus mode')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Focus.AutoFocusMode = mode
        self.__set_imaging_settings(imaging_settings)

    def move_focus_continuous(self, speed):
        """
        :param speed:
            float in range [-1,1]
        """
        logger.debug(f'Camera {self.name}: Doing move focus continuous')
        req = self.__imaging_service.create_type('Move')
        req.VideoSourceToken = self.__video_source.token
        req.Focus = self.__get_move_options()
        req.Focus.Continuous.Speed = speed
        self.__imaging_service.Move(req)

    def move_focus_absolute(self, position, speed=1):
        """
        :param position:
            float in range [0,1]
        :param speed:
            float in range [0,1]
        """
        logger.debug(f'Camera {self.name}: Doing move focus absolute')
        req = self.__imaging_service.create_type('Move')
        req.VideoSourceToken = self.__video_source.token
        req.Focus = self.__get_move_options()
        req.Focus.Absolute.Position = position
        req.Focus.Absolute.Speed = speed
        self.__imaging_service.Move(req)

    def stop_focus(self):
        logger.debug(f'Camera {self.name}: Stopping focus')
        self.__imaging_service.Stop(self.__video_source.token)

    def move_continuous(self, ptz_velocity, timeout=None):
        """
        :param ptz_velocity:
            tuple (pan,tilt,zoom) where
            pan tilt and zoom in range [-1,1]
        """
        logger.debug(
            f'Camera {self.name}: Continuous move {ptz_velocity} {"" if timeout is None else " for " + str(timeout)}'
        )
        req = self.__ptz_service.create_type('ContinuousMove')
        req.Velocity = self.__ptz_status.Position
        req.ProfileToken = self.__profile.token
        vel = req.Velocity
        vel.PanTilt.x, vel.PanTilt.y = float(ptz_velocity[0]), float(
            ptz_velocity[1])
        vel.Zoom.x = float(ptz_velocity[2])
        # force default space
        vel.PanTilt.space, vel.Zoom.space = None, None
        if timeout is not None:
            if type(timeout) is timedelta:
                req.Timeout = timeout
            else:
                raise TypeError(
                    'Camera {self.name}: timeout parameter is of datetime.timedelta type'
                )
        self.__ptz_service.ContinuousMove(req)

    def move_absolute(self, ptz_position, ptz_velocity=(1.0, 1.0, 1.0)):
        logger.debug(f'Camera {self.name}: Absolute move {ptz_position}')
        req = self.__ptz_service.create_type['AbsoluteMove']
        req.ProfileToken = self.__profile.token
        pos = req.Position
        pos.PanTilt.x, pos.PanTilt.y = ptz_position[0], ptz_position[1]
        pos.Zoom.x = ptz_position[2]
        vel = req.Speed
        vel.PanTilt.x, vel.PanTilt.y = ptz_velocity[0], ptz_velocity[1]
        vel.Zoom.x = ptz_velocity[2]
        self.__ptz_service.AbsoluteMove(req)

    def move_relative(self, ptz_position, ptz_velocity=(1.0, 1.0, 1.0)):
        logger.debug(f'Camera {self.name}: Relative move {ptz_position}')
        req = self.__ptz_service.create_type['RelativeMove']
        req.ProfileToken = self.__profile.token
        pos = req.Translation
        pos.PanTilt.x, pos.PanTilt.y = ptz_position[0], ptz_position[1]
        pos.Zoom.x = ptz_position[2]
        vel = req.Speed
        vel.PanTilt.x, vel.PanTilt.y = ptz_velocity[0], ptz_velocity[1]
        vel.Zoom.x = ptz_velocity[2]
        self.__ptz_service.RelativeMove(req)

    def __get_move_options(self):
        logger.debug(f'Camera {self.name}: Getting Move Options')
        req = self.__imaging_service.create_type('GetMoveOptions')
        req.VideoSourceToken = self.__video_source.token
        return self.__imaging_service.GetMoveOptions(req)

    def __get_options(self):
        logger.debug(f'Camera {self.name}: Getting options')
        req = self.__imaging_service.create_type('GetOptions')
        req.VideoSourceToken = self.__video_source.token
        return self.__imaging_service.GetOptions(req)

    def __get_video_sources(self):
        logger.debug(
            f'Camera {self.name}: Getting video source configurations')
        req = self.__media_service.create_type('GetVideoSources')
        return self.__media_service.GetVideoSources(req)

    def __get_ptz_conf_opts(self):
        logger.debug(f'Camera {self.name}: Getting configuration options')
        req = self.__ptz_service.create_type('GetConfigurationOptions')
        req.ConfigurationToken = self.__profile.PTZConfiguration.token
        return self.__ptz_service.GetConfigurationOptions(req)

    def __get_configurations(self):
        logger.debug(f'Camera {self.name}: Getting configurations')
        req = self.__ptz_service.create_type('GetConfigurations')
        return self.__ptz_service.GetConfigurations(req)[0]

    def __get_node(self, node_token):
        logger.debug(f'Camera {self.name}: Getting node {node_token}')
        req = self.__ptz_service.create_type('GetNode')
        req.NodeToken = node_token
        return self.__ptz_service.GetNode(req)

    def __set_imaging_settings(self, imaging_settings):
        logger.debug(f'Camera {self.name}: Setting imaging settings')
        req = self.__imaging_service.create_type('SetImagingSettings')
        req.VideoSourceToken = self.__video_source.token
        req.ImagingSettings = imaging_settings
        return self.__imaging_service.SetImagingSettings(req)

    def __get_imaging_settings(self):
        logger.debug(f'Camera {self.name}: Getting imaging settings')
        req = self.__imaging_service.create_type('GetImagingSettings')
        req.VideoSourceToken = self.__video_source.token
        return self.__imaging_service.GetImagingSettings(req)

    def __get_service_capabilities(self):
        logger.debug(f'Camera {self.name}: Getting capabilities')
        return self.__ptz_service.GetServiceCapabilities()
Exemple #16
0
class Test:
    def __init__(self, ip, port, user, passw):
        self.ip = ip
        self.port = port
        self.user = user
        self.passw = passw
        self.cam = ONVIFCamera(self.ip, self.port, self.user, self.passw)

    def AbsoluteMoveSupport(self):
        media = self.cam.create_media_service()  #Creating media service
        profiles = media.GetProfiles()  #Getting the list with profiles' info
        token = profiles[
            0]._token  #Getting token from the first protile, we'll need it soon
        ptz = self.cam.create_ptz_service()  #Creating ptz service
        ptz_token = profiles[
            0].PTZConfiguration._token  #Saving ptz config token
        ptz.create_type("AbsoluteMove")  #creating new type of ptz

        try:
            pos = ptz.GetStatus({
                "ProfileToken": token
            }).Position  # getting current position
            x_z = pos.Zoom._x
            x = pos.PanTilt._x
            y = pos.PanTilt._y
            if (
                (x + 0.1) < 1
            ):  #checking if x max or min, so we decrease or increase the number
                x1 = x + 0.1
            else:
                x1 = x - 0.1
            if (
                (y + 0.1) < 1
            ):  #checking if y max or min, so we decrease or increase the number
                y1 = y + 0.1
            else:
                y1 = y - 0.1
            if (
                (x_z + 0.1) < 1
            ):  #checking if x_z max or min, so we decrease or increase the number
                x_z1 = x_z + 0.1
            else:
                x_z1 = x_z - 0.1
            ptz.AbsoluteMove({
                "ProfileToken": token,
                "Position": {
                    "PanTilt": {
                        "_x": x1,
                        "_y": y1
                    },
                    "Zoom": {
                        "_x": x_z1
                    }
                }
            })  #AbsoluteMove to new parameter x1
            sleep(3)  #Wait for camera to move
            pos = ptz.GetStatus({
                "ProfileToken": token
            }).Position  #Getting new position
            x_z = pos.Zoom._x  #
            x = pos.PanTilt._x  #Updating current coordinates
            y = pos.PanTilt._y  #
            dif1 = (round((x1 - x), 6))
            dif2 = (round((y1 - y), 6))
            dif3 = (round((x_z1 - x_z), 6))
            # print dif1, ' ', dif2, ' ',dif2
            if ((dif1 == 0) & (dif2 == 0) &
                (dif3 == 0)):  #Checking, if camera moved
                return 'AbsoluteMove is supported, current coordinates: ' + str(
                    x) + ' ' + str(y) + ' ' + str(x_z)
            else:
                return 'AbsoluteMove is not supported, it does not follow instructions'
        except AttributeError:
            return 'AbsoluteMove is not supported, AttributeError'

    def Focus(self):
        media = self.cam.create_media_service()  #Creating media service
        profiles = media.GetProfiles()  #Getting the list with profiles' info
        imaging = self.cam.create_imaging_service()  #Creating imaging service
        token = profiles[
            0]._token  #Getting token from the first protile, we'll need it soon
        vstoken = media.GetVideoSources(
        )[0]._token  #Getting videosources token

        print 'imaging status(position):'  #printing Imaging Status
        print imaging.GetStatus({
            'VideoSourceToken': vstoken
        }).FocusStatus20.Position
        options = imaging.GetMoveOptions({'VideoSourceToken': vstoken})
        imaging.create_type('Move')  #Creating new type of imaging
        #Stopping imaging before start to disturb (if it was) previous moving and setting focus to manual
        imaging.Stop({'VideoSourceToken': vstoken})
        focus = imaging.SetImagingSettings({
            'VideoSourceToken': vstoken,
            'ImagingSettings': {
                'Focus': {
                    'AutoFocusMode': 'MANUAL'
                }
            }
        })
        try:
            options.Absolute  #Checking if absolutemove options are supported and trying absolutemove
            abs_mov = imaging.Move({
                'VideoSourceToken': vstoken,
                'Focus': {
                    'Absolute': {
                        'Position': 0.5,
                        'Speed': 0.5
                    }
                }
            })
            sleep(5)  #waiting
            imaging.Stop({'VideoSourceToken': vstoken})  #stopping imaging
            print 'imaging status(position):'  #Getiing current position of imaging
            print imaging.GetStatus({
                'VideoSourceToken': vstoken
            }).FocusStatus20.Position
            print 'Absolute imaging is supported, check if it is working. Now trying Continuous imaging'
        except AttributeError:  #Catching error
            print 'Absolute Imaging is not supported, trying Continuous imaging...'
        print 'sleep 4s'
        sleep(4)
        try:
            options.Continuous
            cont_mov = imaging.Move({
                'VideoSourceToken':
                vstoken,  #trying continious move if it's supported
                'Focus': {
                    'Continuous': {
                        'Speed': +0.5
                    }
                }
            })
            sleep(2)
            imaging.Stop({'VideoSourceToken': vstoken})
            print 'imaging status(position):'  #Getting current position
            print imaging.GetStatus({
                'VideoSourceToken': vstoken
            }).FocusStatus20.Position
            print 'Continuous imaging works'
        except AttributeError:  #Catching error
            print 'Continious Imaging is not supported'  #setting autofocus mode back
        imaging.SetImagingSettings({
            'VideoSourceToken': vstoken,
            'ImagingSettings': {
                'Focus': {
                    'AutoFocusMode': 'AUTO'
                }
            }
        })
        return 'Test done'
class ONVIFCameraControl:
    def __init__(self, addr, login, password):
        self.__check_addr(addr)
        logger.info(f'Initializing camera {addr}')

        self.__cam = ONVIFCamera(addr[0], addr[1], login, password)

        self.__media_service = self.__cam.create_media_service()
        self.__ptz_service = self.__cam.create_ptz_service()
        self.__imaging_service = self.__cam.create_imaging_service()

        self.__profile = self.__media_service.GetProfiles()[0]
        self.__video_source = self.__get_video_sources()[0]
        self.__status = self.__ptz_service.GetStatus(
            {'ProfileToken': self.__profile.token})

        logging.info(f'Initialized camera at {addr} successfully')

    def get_stream_uri(self, protocol='UDP', stream='RTP-Unicast'):
        """
        :param protocol
            string 'UDP', 'TCP', 'RTSP', 'HTTP'
        :param stream
             string either 'RTP-Unicast' or 'RTP-Multicast'
        WARNING!!!
        Some cameras return invalid stream uri
        RTP unicast over UDP: StreamType = "RTP_Unicast", TransportProtocol = "UDP"
        RTP over RTSP over HTTP over TCP: StreamType = "RTP_Unicast", TransportProtocol = "HTTP"
        RTP over RTSP over TCP: StreamType = "RTP_Unicast", TransportProtocol = "RTSP"
        """
        logger.info(f'Getting stream uri {protocol} {stream}')
        request = self.__media_service.create_type('GetStreamUri')
        request.ProfileToken = self.__profile.token
        request.StreamSetup = {
            'Stream': stream,
            'Transport': {
                'Protocol': protocol
            }
        }
        return self.__media_service.GetStreamUri(request)

    def set_brightness(self, brightness):
        """
        :param brightness:
            float in range [0, 100]
        """
        logger.info(f'Settings brightness')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Brightness = brightness
        self.__set_imaging_settings(imaging_settings)

    def set_color_saturation(self, color_saturation):
        """
        :param color_saturation:
            float in range [0, 100]
        """
        logger.info(f'Settings color_saturation')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.ColorSaturation = color_saturation
        self.__set_imaging_settings(imaging_settings)

    def set_contrast(self, contrast):
        """
        :param contrast:
            float in range [0, 100]
        """
        logger.info(f'Settings contrast')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Contrast = contrast
        self.__set_imaging_settings(imaging_settings)

    def set_sharpness(self, sharpness):
        """
        :param sharpness:
            float in range [0, 100]
        """
        logger.info(f'Settings sharpness')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Sharpness = sharpness
        self.__set_imaging_settings(imaging_settings)

    def set_focus_mode(self, mode='AUTO'):
        """
        :param mode:
            string, can be either 'AUTO' or 'MANUAL'
        """
        logger.info(f'Settings focus mode')
        imaging_settings = self.__get_imaging_settings()
        imaging_settings.Focus.AutoFocusMode = mode
        self.__set_imaging_settings(imaging_settings)

    def move_focus_continuous(self, speed):
        """
        :param speed:
            float in range [-1,1]
        """
        logger.info(f'Doing move focus continuous')
        request = self.__imaging_service.create_type('Move')
        request.VideoSourceToken = self.__video_source.token
        request.Focus = self.__get_move_options()
        request.Focus.Continuous.Speed = speed
        self.__imaging_service.Move(request)

    def move_focus_absolute(self, position, speed=1):
        """
        :param position:
            float in range [0,1]
        :param speed:
            float in range [0,1]
        """
        logger.info(f'Doing move focus absolute')
        request = self.__imaging_service.create_type('Move')
        request.VideoSourceToken = self.__video_source.token
        request.Focus = self.__get_move_options()
        request.Focus.Absolute.Position = position
        request.Focus.Absolute.Speed = speed
        self.__imaging_service.Move(request)

    def stop_focus(self):
        logger.info(f'Stoping focus')
        self.__imaging_service.Stop(self.__video_source.token)

    def set_preset(self, preset_token=None, preset_name=None):
        """
        :param preset_token:
            unsigned int, usually in range [1, 128] dependent on camera
        :param preset_name:
            string
            if None then duplicate preset_token
        """
        logger.info(f'Setting preset {preset_token} ({preset_name})')
        request = self.__ptz_service.create_type('SetPreset')
        request.ProfileToken = self.__profile.token
        request.PresetToken = preset_token
        request.PresetName = preset_name
        return self.__ptz_service.SetPreset(request)

    def goto_preset(self, preset_token, ptz_velocity=(1.0, 1.0, 1.0)):
        """
        :param preset_token:
            unsigned int
        :param ptz_velocity:
            tuple (pan,tilt,zoom) where
            pan tilt and zoom in range [0,1]
        """
        logger.info(f'Moving to preset {preset_token}, speed={ptz_velocity}')
        request = self.__ptz_service.create_type('GotoPreset')
        request.ProfileToken = self.__profile.token
        request.PresetToken = preset_token
        request.Speed = self.__status.Position
        vel = request.Speed
        vel.PanTilt.x, vel.PanTilt.y = ptz_velocity[0], ptz_velocity[1]
        vel.Zoom.x = ptz_velocity[2]
        return self.__ptz_service.GotoPreset(request)

    def get_presets(self):
        logger.debug(f'Getting presets')
        return self.__ptz_service.GetPresets(self.__profile.token)

    def get_brightness(self):
        logger.info(f'Getting brightness')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.Brightness

    def get_color_saturation(self):
        logger.info(f'Getting color_saturation')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.ColorSaturation

    def get_contrast(self):
        logger.info(f'Getting contrast')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.Contrast

    def get_sharpness(self):
        logger.info(f'Getting sharpness')
        imaging_settings = self.__get_imaging_settings()
        return imaging_settings.Sharpness

    def move_continuous(self, ptz_velocity, timeout=None):
        """
        :param ptz_velocity:
            tuple (pan,tilt,zoom) where
            pan tilt and zoom in range [-1,1]
        """
        logger.info(
            f'Continuous move {ptz_velocity} {"" if timeout is None else " for " + str(timeout)}'
        )
        req = self.__ptz_service.create_type('ContinuousMove')
        req.Velocity = self.__status.Position
        req.ProfileToken = self.__profile.token
        vel = req.Velocity
        vel.PanTilt.x, vel.PanTilt.y = ptz_velocity[0], ptz_velocity[1]
        vel.Zoom.x = ptz_velocity[2]
        # force default space
        vel.PanTilt.space, vel.Zoom.space = None, None
        if timeout is not None:
            if type(timeout) is timedelta:
                req.Timeout = timeout
            else:
                raise TypeError(
                    'timeout parameter is of datetime.timedelta type')
        self.__ptz_service.ContinuousMove(req)

    def move_absolute(self, ptz_position, ptz_velocity=(1.0, 1.0, 1.0)):
        logger.info(f'Absolute move {ptz_position}')
        req = self.__ptz_service.create_type('AbsoluteMove')
        req.ProfileToken = self.__profile.token
        pos = req.Position
        pos.PanTilt.x, pos.PanTilt.y = ptz_position[0], ptz_position[1]
        pos.Zoom.x = ptz_position[2]
        vel = req.Speed
        vel.PanTilt.x, vel.PanTilt.y = ptz_velocity[0], ptz_velocity[1]
        vel.Zoom.x = ptz_velocity[2]
        self.__ptz_service.AbsoluteMove(req)

    def move_relative(self, ptz_position, ptz_velocity=(1.0, 1.0, 1.0)):
        logger.info(f'Relative move {ptz_position}')
        req = self.__ptz_service.create_type('RelativeMove')
        req.ProfileToken = self.__profile.token
        pos = req.Translation
        pos.PanTilt.x, pos.PanTilt.y = ptz_position[0], ptz_position[1]
        pos.Zoom.x = ptz_position[2]
        vel = req.Speed
        vel.PanTilt.x, vel.PanTilt.y = ptz_velocity[0], ptz_velocity[1]
        vel.Zoom.x = ptz_velocity[2]
        self.__ptz_service.RelativeMove(req)

    def go_home(self):
        logger.info(f'Moving home')
        req = self.__ptz_service.create_type('GotoHomePosition')
        req.ProfileToken = self.__profile.token
        self.__ptz_service.GotoHomePosition(req)

    def stop(self):
        logger.info(f'Stopping movement')
        self.__ptz_service.Stop({'ProfileToken': self.__profile.token})

    def get_snapshot_uri(self):
        return self.__media_service.GetSnapshotUri(
            {'ProfileToken': self.__profile.token})["Uri"]

    def __get_move_options(self):
        request = self.__imaging_service.create_type('GetMoveOptions')
        request.VideoSourceToken = self.__video_source.token
        return self.__imaging_service.GetMoveOptions(request)

    def __get_options(self):
        logger.debug(f'Getting options')
        request = self.__imaging_service.create_type('GetOptions')
        request.VideoSourceToken = self.__video_source.token
        return self.__imaging_service.GetOptions(request)

    def __get_video_sources(self):
        logger.debug(f'Getting video source configurations')
        request = self.__media_service.create_type('GetVideoSources')
        return self.__media_service.GetVideoSources(request)

    def __get_ptz_conf_opts(self):
        logger.debug(f'Getting configuration options')
        request = self.__ptz_service.create_type('GetConfigurationOptions')
        request.ConfigurationToken = self.__profile.PTZConfiguration.token
        return self.__ptz_service.GetConfigurationOptions(request)

    def __get_configurations(self):
        logger.debug(f'Getting configurations')
        request = self.__ptz_service.create_type('GetConfigurations')
        return self.__ptz_service.GetConfigurations(request)[0]

    def __get_node(self, node_token):
        logger.debug(f'Getting node {node_token}')
        request = self.__ptz_service.create_type('GetNode')
        request.NodeToken = node_token
        return self.__ptz_service.GetNode(request)

    def __set_imaging_settings(self, imaging_settings):
        logger.debug(f'Setting imaging settings')
        request = self.__imaging_service.create_type('SetImagingSettings')
        request.VideoSourceToken = self.__video_source.token
        request.ImagingSettings = imaging_settings
        return self.__imaging_service.SetImagingSettings(request)

    def __get_imaging_settings(self):
        request = self.__imaging_service.create_type('GetImagingSettings')
        request.VideoSourceToken = self.__video_source.token
        return self.__imaging_service.GetImagingSettings(request)

    def __check_addr(self, addr):
        if not isinstance(addr, tuple) or not isinstance(
                addr[0], str) or not isinstance(addr[1], int):
            raise TypeError(f'addr must be of type tuple(str, int)')
Exemple #18
0
cv2.imshow('qwerty',frame)
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv], [0,1], None, [180, 256], [0, 180, 0, 256]) #hue 180 saturation 256
fig.add_subplot(2, 2, 1)
plt.imshow(hist,interpolation = 'nearest')

fig.add_subplot(2, 2, 2)
for i,col in enumerate(color): #each value corresponds to number of pixels in that image with its corresponding pixel value RGB
      histr = cv2.calcHist([frame],[i],None,[256],[0,256])
      plt.plot(histr,color = col)
      plt.xlim([0,256])

media = mycam1.create_media_service()
ptz = mycam1.create_ptz_service()
media_profile = media.GetProfiles()[0]
image = mycam1.create_imaging_service()
token = media_profile.VideoSourceConfiguration.SourceToken
SY = image.create_type('GetImagingSettings')
SY.VideoSourceToken = token
request = image.GetImagingSettings(SY)
print(request)


#regulating
brightness=request42.Brightness
if brightness <48.0:
    while brightness < 48.0:
        image42.SetImagingSettings({'VideoSourceToken' : token42, 'ImagingSettings' : request42})
        request42.Brightness = request42.Brightness + 1.0
        brightness = brightness+1.0
if brightness > 50.0:
Exemple #19
0
    def connect(self, a=True, b=None):
        if not a:
            self.add_log("Connecting...")
            ip, port, login, password, length = open_config()
            num = self.comboBox.currentIndex()
            self.add_log("IP: " + ip[num])
            self.add_log("Port: " + str(port[num]))
            self.add_log("Login: "******"Password: "******"Connecting...")
            ip, port, login, password, length = open_config()
            self.add_log("IP: " + ip[num])
            self.add_log("Port: " + str(port[num]))
            self.add_log("Login: "******"Password: "******"Joystick is connected")
            self.add_log("Number of connected joysticks: " +
                         str(pygame.joystick.get_count()))
        else:
            self.add_log("Joystick is uninitialized or not connected")
            return

        try:
            joystick = pygame.joystick.Joystick(
                0)  # создаем новый объект joystick с id = 0
        except pygame.error:
            self.add_log("Joystick is uninitialized or not connected")
            pygame.close()
            return

        joystick.init()  # инициализация джойстика
        self.add_log("Joystick system name: " +
                     joystick.get_name())  # вывод имени джойстика
        # есть три попытки для подключения к камере
        mycam = None
        attempts = 3
        while mycam is None:
            self.add_log("Connecting to the camera...")
            try:
                mycam = ONVIFCamera(ip[num], port[num], login[num],
                                    password[num])  # инициализация камеры
            except ONVIFError:
                self.add_log("Connection failed")
            attempts -= 1
            if attempts == 0:
                del mycam
                pygame.quit()
                return

        self.add_log("Camera is connected")
        self.connectBtn.setDisabled(True)
        self.disconnectBtn.setEnabled(True)

        media = mycam.create_media_service()  # создание media service
        ptz = mycam.create_ptz_service()  # создание ptz service
        image = mycam.create_imaging_service()  # создание imaging service

        media_profile = media.GetProfiles()[0]  # достаем медиа-профиль камеры

        # достаем ptz configuration options
        request = ptz.create_type('GetConfigurationOptions')
        request.ConfigurationToken = media_profile.PTZConfiguration.token
        ptz_configuration_options = ptz.GetConfigurationOptions(request)
        ptz_configurations_list = ptz.GetConfigurations()
        ptz_configuration = ptz_configurations_list[0]

        # создание запроса continuous move для настройки движения камеры
        request = ptz.create_type('ContinuousMove')
        request.ProfileToken = media_profile.token
        request.Velocity = media_profile.PTZConfiguration.DefaultPTZSpeed  # поиск структуры Velocity
        # преобразование структуры Velocity
        request.Velocity.Zoom.x = 0.0
        request.Velocity.PanTilt.space = ''
        request.Velocity.Zoom.space = ''
        ptz.Stop({'ProfileToken': media_profile.token
                  })  # остановка камеры на случай, если она двигалась

        # создание запроса set preset для сохранения пресетов камеры
        prequest = ptz.create_type('SetPreset')
        prequest.ProfileToken = media_profile.token

        # создание запроса go to preset для перехода между пресетами камеры
        grequest = ptz.create_type('GotoPreset')
        grequest.ProfileToken = media_profile.token

        # создание запроса set configuration для настройки скорости движения камеры
        srequest = ptz.create_type('SetConfiguration')

        # создание запроса set imaging settings для настройки изображения с камеры
        irequest = image.create_type('SetImagingSettings')
        video_token = media.GetVideoSourceConfigurationOptions(
        ).VideoSourceTokensAvailable[0]
        img_settings = image.GetImagingSettings(video_token)

        global XMAX, XMIN, YMAX, YMIN, ZMAX, ZMIN

        # получение числового диапазона осей X, Y, Z
        XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[
            0].XRange.Max
        XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[
            0].XRange.Min
        YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[
            0].YRange.Max
        YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[
            0].YRange.Min
        ZMAX = ptz_configuration_options.Spaces.ContinuousZoomVelocitySpace[
            0].XRange.Max
        ZMIN = ptz_configuration_options.Spaces.ContinuousZoomVelocitySpace[
            0].XRange.Min

        s = -1
        while s < 1:
            print("%2g maps to %g" % (s, maprange((-1, 1), (XMIN, XMAX), s)))
            s += 0.1

        global throttle

        isMoving = False
        OX = False
        OY = False
        OZ = False

        self.done = False

        while not self.done:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True

            throttle = (-(joystick.get_axis(THR_AXIS))) / 2 + 0.5
            thread = threading.Thread(target=midi.run, args=())
            thread.daemon = True
            thread.start()

            ptz_configuration.DefaultPTZSpeed.PanTilt.x = throttle * XMAX
            ptz_configuration.DefaultPTZSpeed.PanTilt.y = throttle * YMAX
            ptz_configuration.DefaultPTZSpeed.Zoom.x = throttle * ZMAX

            srequest.PTZConfiguration = ptz_configuration
            srequest.ForcePersistence = False

            ptz.SetConfiguration(srequest)

            grequest.Speed = ptz_configuration.DefaultPTZSpeed
            grequest.Speed.PanTilt.x = throttle
            grequest.Speed.PanTilt.y = throttle
            grequest.Speed.Zoom.x = throttle

            irequest.VideoSourceToken = video_token
            irequest.ImagingSettings = img_settings
            irequest.ForcePersistence = False

            if joystick.get_axis(X_AXIS) > 0.1 or joystick.get_axis(
                    X_AXIS) < -0.1:
                move_horizontal(ptz, request, joystick)
                print(
                    str(
                        maprange((-1, 1), (XMIN, XMAX),
                                 joystick.get_axis(X_AXIS))))
                isMoving = True
                OX = True

            if joystick.get_axis(Y_AXIS) > 0.2 or joystick.get_axis(
                    Y_AXIS) < -0.2:
                move_vertical(ptz, request, joystick)
                print(
                    str(
                        maprange((-1, 1), (YMIN, YMAX),
                                 joystick.get_axis(Y_AXIS))))
                isMoving = True
                OY = True

            if joystick.get_axis(Z_AXIS) > 0.3 or joystick.get_axis(
                    Z_AXIS) < -0.3:
                zoom(ptz, request, joystick)
                print(
                    str(
                        maprange((-1, 1), (ZMIN, ZMAX),
                                 joystick.get_axis(Z_AXIS))))
                isMoving = True
                OZ = True

            if isMoving:

                if -0.1 <= joystick.get_axis(X_AXIS) <= 0.1 and OX:
                    ptz.Stop({'ProfileToken': request.ProfileToken})
                    isMoving = False
                    OX = False

                if -0.2 <= joystick.get_axis(Y_AXIS) <= 0.2 and OY:
                    ptz.Stop({'ProfileToken': request.ProfileToken})
                    isMoving = False
                    OY = False

                if -0.3 <= joystick.get_axis(Z_AXIS) <= 0.3 and OZ:
                    ptz.Stop({'ProfileToken': request.ProfileToken})
                    isMoving = False
                    OZ = False

            ptz = mycam.create_ptz_service()
            if joystick.get_button(6):
                self.disconnect1(2)
            if joystick.get_button(7):
                self.disconnect1(4)
            if joystick.get_button(0) == 1:
                if self.focusMode:
                    self.focusMode = False
                    self.add_log("Entering Brightness / Contrast mode...")
                else:
                    self.focusMode = True
                    self.add_log("Entering Focus mode...")

            if joystick.get_button(2) == 1:

                if self.preset1 == 1:
                    prequest.PresetName = "1"
                    prequest.PresetToken = '1'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #1...")
                    self.preset1 = 0

                if self.preset2 == 1:
                    prequest.PresetName = "2"
                    prequest.PresetToken = '2'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #2...")
                    self.preset2 = 0

                if self.preset3 == 1:
                    prequest.PresetName = "3"
                    prequest.PresetToken = '3'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #3...")
                    self.preset3 = 0
                if self.preset4 == 1:
                    prequest.PresetName = "4"
                    prequest.PresetToken = '4'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #4...")
                    self.preset4 = 0
                if self.preset5 == 1:
                    prequest.PresetName = "5"
                    prequest.PresetToken = '5'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #5...")
                    self.preset5 = 0
                if self.preset6 == 1:
                    prequest.PresetName = "6"
                    prequest.PresetToken = '6'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #6...")
                    self.preset6 = 0
                if self.preset7 == 1:
                    prequest.PresetName = "7"
                    prequest.PresetToken = '7'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #7...")
                    self.preset7 = 0
                if self.preset8 == 1:
                    prequest.PresetName = "8"
                    prequest.PresetToken = '8'
                    preset = ptz.SetPreset(prequest)
                    self.add_log("Setting preset #8...")
                    self.preset8 = 0

            if self.preset1 == 1:
                grequest.PresetToken = '1'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #1...")
                self.preset1 = 0
            if self.preset2 == 1:
                grequest.PresetToken = '2'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #2...")
                self.preset2 = 0
            if self.preset3 == 1:
                grequest.PresetToken = '3'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #3...")
                self.preset3 = 0

            if self.preset4 == 1:
                grequest.PresetToken = '4'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #4...")
                self.preset4 = 0

            if self.preset5 == 1:
                grequest.PresetToken = '5'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #5...")
                self.preset5 = 0

            if self.preset6 == 1:
                grequest.PresetToken = '6'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #6...")
                self.preset6 = 0

            if self.preset7 == 1:
                grequest.PresetToken = '7'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #7...")
                self.preset7 = 0

            if self.preset8 == 1:
                grequest.PresetToken = '8'
                ptz.GotoPreset(grequest)
                self.add_log("Going to preset #8...")
                self.preset8 = 0

            # настройка изображения

            if not self.focusMode:
                # увеличение яркости (6 кнопка)
                if self.brightnessWasPressed == 1:
                    if img_settings.Brightness < 100:
                        img_settings.Brightness += 10
                        if img_settings.Brightness > 100:
                            img_settings.Brightness = 100
                    image.SetImagingSettings(irequest)
                    self.add_log("Increasing brightness to " +
                                 str(img_settings.Brightness) + "...")
                    print("Increasing brightness to {}".format(
                        img_settings.Brightness))
                    self.brightnessWasPressed = 0

                # уменьшение яркости (4 кнопка)
                if self.brightnessWasPressed == -1:
                    if img_settings.Brightness > 0:
                        img_settings.Brightness -= 10
                        if img_settings.Brightness < 0:
                            img_settings.Brightness = 0
                    image.SetImagingSettings(irequest)
                    self.add_log("Reducing brightness to " +
                                 str(img_settings.Brightness) + "...")
                    print("reducing brightness to {}".format(
                        img_settings.Brightness))
                    self.brightnessWasPressed = 0
                #увеличение резкости
                if self.sharpnessWasPressed == 1:
                    if img_settings.Sharpness < 100:
                        img_settings.Sharpness += 10
                        if img_settings.Sharpness > 100:
                            img_settings.Sharpness = 100
                    image.SetImagingSettings(irequest)
                    self.add_log("Increasing sharpness to " +
                                 str(img_settings.Sharpness) + "...")
                    print("Increasing sharpness to {}".format(
                        img_settings.Sharpness))
                    self.sharpnessWasPressed = 0
                #уменьшение резкости
                if self.sharpnessWasPressed == -1:
                    if img_settings.Sharpness > 0:
                        img_settings.Sharpness -= 10
                        if img_settings.Sharpness < 0:
                            img_settings.Sharpness = 0
                    image.SetImagingSettings(irequest)
                    self.add_log("Reducing sharpness to " +
                                 str(img_settings.Sharpness) + "...")
                    print("Reducing sharpness to {}".format(
                        img_settings.Sharpness))
                    self.sharpnessWasPressed = 0
                #увеличение насыщености
                if self.saturWasPressed == 1:
                    if img_settings.ColorSaturation < 100:
                        img_settings.ColorSaturation += 10
                        if img_settings.ColorSaturation > 100:
                            img_settings.ColorSaturation = 100
                    image.SetImagingSettings(irequest)
                    self.add_log("Increasing Color Saturation to " +
                                 str(img_settings.ColorSaturation) + "...")
                    print("Increasing Color Saturation to {}".format(
                        img_settings.ColorSaturation))
                    self.saturWasPressed = 0
                #уменьшение насыщености
                if self.saturWasPressed == -1:
                    if img_settings.ColorSaturation > 0:
                        img_settings.ColorSaturation -= 10
                        if img_settings.ColorSaturation < 0:
                            img_settings.ColorSaturation = 0
                    image.SetImagingSettings(irequest)
                    self.add_log("Reducing Color Saturation to " +
                                 str(img_settings.ColorSaturation) + "...")
                    print("Reducing Color Saturation to {}".format(
                        img_settings.ColorSaturation))
                    self.saturWasPressed = 0
                # увеличение контрастности (5 кнопка)
                if self.contrastWasPressed == 1:
                    if img_settings.Contrast < 100:
                        img_settings.Contrast += 10
                        if img_settings.Contrast > 100:
                            img_settings.Contrast = 100
                    image.SetImagingSettings(irequest)
                    self.add_log("Increasing contrast to " +
                                 str(img_settings.Contrast) + "...")
                    self.contrastWasPressed = 0

                # уменьшение контрастности (3 кнопка)
                if self.contrastWasPressed == -1:
                    if img_settings.Contrast > 0:
                        img_settings.Contrast -= 10
                        if img_settings.Contrast < 0:
                            img_settings.Contrast = 0
                    image.SetImagingSettings(irequest)
                    self.add_log("Reducing contrast to " +
                                 str(img_settings.Contrast) + "...")
                    self.contrastWasPressed = 0
            else:
                # включение автофокуса (6 кнопка)
                if joystick.get_button(5) == 1:
                    img_settings.Focus.AutoFocusMode = 'AUTO'
                    self.add_log("Turning on AUTO focus...")

                # включение ручного фокуса (5 кнопка)
                if joystick.get_button(4) == 1:
                    img_settings.Focus.AutoFocusMode = 'MANUAL'
                    self.add_log("Turning on MANUAL focus...")
                irequest.ImagingSettings = img_settings
                image.SetImagingSettings(irequest)

            # переключение режима цветового баланса
            if joystick.get_button(1) == 1:
                img_settings = image.GetImagingSettings(video_token)
                if img_settings.WhiteBalance.Mode == 'AUTO':
                    img_settings.WhiteBalance.Mode = 'MANUAL'
                    self.add_log("Switching to MANUAL white balance mode...")
                    img_settings.WhiteBalance.CbGain = 80  # оптимальные настройки CbGain
                    img_settings.WhiteBalance.CrGain = 30  # оптимальные настройки CrGain
                else:
                    img_settings.WhiteBalance.Mode = 'AUTO'
                    self.add_log("Switching to AUTO white balance mode...")
                irequest.ImagingSettings = img_settings
                image.SetImagingSettings(irequest)
                img_settings = image.GetImagingSettings(video_token)

            if img_settings.WhiteBalance.Mode == 'MANUAL':

                # увеличение CbGain
                if joystick.get_hat(0) == (1, 0):
                    if img_settings.WhiteBalance.CbGain < 100:
                        img_settings.WhiteBalance.CbGain += 5
                        if img_settings.WhiteBalance.CbGain > 100:
                            img_settings.WhiteBalance.CbGain = 100
                    image.SetImagingSettings(irequest)
                    self.add_log("Increasing CbGain to " +
                                 str(img_settings.WhiteBalance.CbGain) + "...")

                # уменьшение CbGain
                if joystick.get_hat(0) == (-1, 0):
                    if img_settings.WhiteBalance.CbGain > 0:
                        img_settings.WhiteBalance.CbGain -= 5
                        if img_settings.WhiteBalance.CbGain < 0:
                            img_settings.WhiteBalance.CbGain = 0
                    image.SetImagingSettings(irequest)
                    self.add_log("Reducing CbGain to " +
                                 str(img_settings.WhiteBalance.CbGain) + "...")

                # увеличение CrGain
                if joystick.get_hat(0) == (0, 1):
                    if img_settings.WhiteBalance.CrGain < 100:
                        img_settings.WhiteBalance.CrGain += 5
                        if img_settings.WhiteBalance.CrGain > 100:
                            img_settings.WhiteBalance.CrGain = 100
                    image.SetImagingSettings(irequest)
                    self.add_log("Increasing CrGain to " +
                                 str(img_settings.WhiteBalance.CrGain) + "...")

                # уменьшение CrGain
                if joystick.get_hat(0) == (0, -1):
                    if img_settings.WhiteBalance.CrGain > 0:
                        img_settings.WhiteBalance.CrGain -= 5
                        if img_settings.WhiteBalance.CrGain < 0:
                            img_settings.WhiteBalance.CrGain = 0
                    image.SetImagingSettings(irequest)
                    self.add_log("Reducing CrGain to " +
                                 str(img_settings.WhiteBalance.CrGain) + "...")

            self.listWidget.scrollToBottom()

        del mycam
        self.connectBtn.setEnabled(True)
        self.disconnectBtn.setDisabled(True)
        pygame.quit()
Exemple #20
0
class Camera():
    def __init__(self, ip, port, user, passwd):
        # Connecting to the camera
        self.cam = ONVIFCamera(ip, port, user, passwd)

        self.request_continuous_move = None
        self.ptz = None
        # Create media service object
        self.media = self.cam.create_media_service()
        # Get target profile
        self.media_profile = self.media.GetProfiles()[0]
        self.ptz = self.cam.create_ptz_service()
        # Get PTZ configuration options for getting move ranges
        request = self.ptz.create_type('GetConfigurationOptions')
        request.ConfigurationToken = self.media_profile.PTZConfiguration._token
        self.ptz_configuration_options = self.ptz.GetConfigurationOptions(request)
        print('PTZ configuration options: ' + str(self.ptz_configuration_options))


        self.request_stop = self.ptz.create_type('Stop')
        self.request_stop.ProfileToken = self.media_profile._token

        self.request_continuous_move = self.ptz.create_type('ContinuousMove')
        self.request_continuous_move.ProfileToken = self.media_profile._token
        if self.request_continuous_move.Velocity is None:
            self.request_continuous_move.Velocity = self.ptz.GetStatus({'ProfileToken': self.media_profile._token}).Position

        self.request_absolute_move = self.ptz.create_type('AbsoluteMove')
        self.request_absolute_move.ProfileToken = self.media_profile._token

        # Create imaging service
        self.imaging = self.cam.create_imaging_service()
        # Getting available imaging services
        request = self.imaging.create_type('GetServiceCapabilities')
        service_capabilities = self.ptz.GetServiceCapabilities(request)
        print("Service capabilities: " + str(service_capabilities))
        self.request_absolute_focus = self.imaging.create_type('Move')
        self.request_absolute_focus.VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken
        print('Focus move options: ' + str(self.request_absolute_focus))

        request = self.imaging.create_type('GetMoveOptions')
        request.VideoSourceToken = VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken
        move_options = self.imaging.GetMoveOptions(request)
        print('Imaging options: ' + str(move_options))
        

    # Function to get camera's information
    def get_info(self):
        # Get Hostname
        print('Hostname is: ' + str(self.cam.devicemgmt.GetHostname().Name))
        # Get info
        print('Device information: ' + str(self.cam.devicemgmt.GetDeviceInformation()))
        # Get system date and time
        dt = self.cam.devicemgmt.GetSystemDateAndTime()
        tz = dt.TimeZone
        year = dt.UTCDateTime.Date.Year
        hour = dt.UTCDateTime.Time.Hour

        print('Timezone: ' + str(tz))

        print('Year: ' + str(year))
        print('Hour: ' + str(hour))

    def get_pos(self):
        # Getting PTZ status
        status = self.ptz.GetStatus({'ProfileToken': self.media_profile._token})

        print("PTZ position: " + str(status.Position))

    def stop(self):
        self.request_stop = self.ptz.create_type('Stop')
        self.request_stop.ProfileToken = self.media_profile._token
        self.request_stop.PanTilt = True
        self.request_stop.Zoom = True
        self.ptz.Stop(self.request_stop)
        
    def perform_continuous_move(self,timeout):
        # Start continuous move
        self.ptz.ContinuousMove(self.request_continuous_move)

        # Wait a certain time
        sleep(timeout)

        # Stop continuous move
        self.stop()

        sleep(2)
        print(str(self.request_continuous_move))

    def move_continuous(self, velocity1, velocity2, velocity3, timeout=1):
        print ('move continuous...')
        self.request_continuous_move.Velocity.PanTilt._x = velocity1
        self.request_continuous_move.Velocity.PanTilt._y = velocity2
        self.request_continuous_move.Velocity.Zoom._x = velocity3
        self.request_continuous_move.Timeout = timeout

        self.perform_continuous_move(timeout)

    def perform_absolute_move(self, x, y, z):
        print ('move absolute...')
        self.request_absolute_move.Position.PanTilt._x = x
        self.request_absolute_move.Position.PanTilt._y = y
        self.request_absolute_move.Position.Zoom._x = z

        self.stop()

        self.ptz.AbsoluteMove(self.request_absolute_move)

        print(str(self.request_absolute_move))

    def change_absolute_focus(self, x):
        print('changing focus: ' + str(x))

        self.request_absolute_focus.Focus = x
        
        self.imaging.Move(self.request_absolute_focus)

        print(str(self.request_absolute_focus))
Exemple #21
0
def adjustCamera(ip, port, login, password):
    mycam = ONVIFCamera(ip, port, login, password, 'C:\Python27\wsdl')
    media_service = mycam.create_media_service()
    media_profile = media_service.GetProfiles()[0]
    imaging = mycam.create_imaging_service()
    token = media_profile.VideoSourceConfiguration.SourceToken

    request = createImagingRequest(imaging, token)
    try:
        request.ImagingSettings.Exposure.Mode = 'MANUAL'
    except Exception as e:
        print 'exposureMode can not bo MANUAL'
    try:
        request.ImagingSettings.WhiteBalance.Mode = 'MANUAL'
    except Exception as e:
        print 'whiteBalanceMode can not be MANUAL'
    try:
        imaging.SetImagingSettings(request)
    except Exception as e:
        print 'error'

    y_ax = plt.subplot(121)
    cb_ax = plt.subplot(222)
    cr_ax = plt.subplot(224)
    plt.ion()
    plt.show()
    while True:
        downloadImage(media_service, media_profile, login, password)

        im = cv2.imread('img.jpg')

        ycbcr = cv2.cvtColor(im, cv2.COLOR_BGR2YCrCb)

        hist_y = cv2.calcHist([ycbcr], [0], None, [256], [0, 256])
        hist_cr = cv2.calcHist([ycbcr], [1], None, [256], [0, 256])
        hist_cb = cv2.calcHist([ycbcr], [2], None, [256], [0, 256])

        drawAxis(y_ax, hist_y, 'b')
        drawAxis(cb_ax, hist_cb, 'b')
        drawAxis(cr_ax, hist_cr, 'r')
        plt.pause(0.01)

        hist_cb_2 = cv2.calcHist([ycbcr], [2], None, [2], [0, 256])
        hist_cr_2 = cv2.calcHist([ycbcr], [1], None, [2], [0, 256])

        hist_y_6 = cv2.calcHist([ycbcr], [0], None, [6], [0, 256])

        if not isNeedToStop(hist_y):
            leftIndex = findFirstExtraFromLeftIndex(hist_y_6)
            rightIndex = findFirstExtraFromRightIndex(hist_y_6)

            black = hist_y_6[0][0] > 300000
            white = hist_y_6[-1][0] > 300000
            if black and white:
                decreaseContrast(imaging, token, hist_y_6)
            elif black:
                increaseExp(imaging, token, hist_y_6, rightIndex)
            elif white:
                decreaseExp(imaging, token, hist_y_6, leftIndex)
            else:
                increaseContrast(imaging, token, hist_y_6, rightIndex,
                                 leftIndex)

        try:
            Cb = calculateMove(hist_cb_2, 2.56, 0.9, 2)
            print('Cb:', Cb)
            setCbGain(imaging, token, Cb)
            Cr = calculateMove(hist_cr_2, 2.56, 0.9, 2)
            print('Cr:', Cr)
            setCrGain(imaging, token, Cr)
        except Exception as e:
            print 'WhiteBalance error'

        time.sleep(1)
Exemple #22
0
class Camera:
    def __init__(self, ip, port, login, password):
        #соединение с камерой
        self.my_cam = ONVIFCamera(ip, port, login, password)

        # Создание медиа сервиса
        self.media_service = self.my_cam.create_media_service()

        self.profiles = self.media_service.GetProfiles()
        self.media_profile = self.profiles[0]

        # создание ptz сервиса
        self.ptz = self.my_cam.create_ptz_service()

        self.request_absolute_move = self.ptz.create_type("AbsoluteMove")
        self.request_absolute_move.ProfileToken = self.media_profile.token

        self.request_stop = self.ptz.create_type("Stop")
        self.request_stop.ProfileToken = self.media_profile.token

        # создание imaging сервиса
        self.imaging = self.my_cam.create_imaging_service()

        self.request_focus_change = self.imaging.create_type("Move")
        self.request_focus_change.VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken

        self.stop()

    # получение позиции камеры
    def get_ptz_position(self):
        status = self.ptz.GetStatus({"ProfileToken": self.media_profile.token})

        print(long_line)
        print("PTZ position: " + str(status.Position))
        print(long_line)

    def get_focus_options(self):
        imaging_status = self.imaging.GetStatus({
            "VideoSourceToken":
            self.media_profile.VideoSourceConfiguration.SourceToken
        })

        print(long_line)
        request = self.imaging.create_type("GetServiceCapabilities")
        imaging_service_capabilities = self.ptz.GetServiceCapabilities(request)

        print("Service capabilities: " + str(imaging_service_capabilities))
        print(long_line)
        print("Imaging status: " + str(imaging_status))
        print(long_line)

    # остановить движение камеры
    def stop(self):
        self.request_stop.PanTilt = True
        self.request_stop.Zoom = True

        self.ptz.Stop(self.request_stop)

    # Absolute move
    def perform_absolute_move(self):
        self.ptz.AbsoluteMove(self.request_absolute_move)

        sleep(4)

    def move_absolute(self, x, y, zoom):
        print("Moving to: \"" + str(x) + ":" + str(y) + ":" + str(zoom) + "\"")

        status = self.ptz.GetStatus({"ProfileToken": self.media_profile.token})
        status.Position.PanTilt.x = x
        status.Position.PanTilt.y = y
        status.Position.Zoom.x = zoom

        self.request_absolute_move.Position = status.Position

        self.perform_absolute_move()

    # изменение значений фокуса
    def change_focus(self, speed, timeout):
        print("Changing focus with speed: \"" + str(speed) +
              "\" and timeout: \"" + str(timeout) + "\"")

        self.request_focus_change.Focus = {"Continuous": {"Speed": speed}}

        self.imaging.Move(self.request_focus_change)

        sleep(timeout)

        self.stop()

        sleep(2)