Exemple #1
0
    def WaitForPrinterState(self,
                            state,
                            timeout=Constants.TIMEOUT['PRINTER_STATUS']):
        """Wait until the printer state becomes the specified status

        Args:
          state: string, printer state to wait for
          timeout: integer, number of seconds to wait.
        Returns:
          boolean, True if state is observed within timeout; otherwise, False.
        """
        print '[Configurable timeout] PRINTER_STATUS:'
        print('Waiting up to %s seconds for the printer to have status: %s' %
              (timeout, state))

        end = time.time() + timeout

        while time.time() < end:
            info = self.Info()
            if info is not None:
                if info['device_state'] == state:
                    print 'Device state observed to be: %s' % state
                    return True
            Sleep('POLL')

        return False
Exemple #2
0
  def WaitJobStateIn(self, job_id, job_state, timeout=60):
    """Wait until the job state becomes the specified state(s)

    Args:
      job_id: string, id of the print job.
      job_state: string or list, job state(s) to wait for.
      timeout: integer, number of seconds to wait.
    Returns:
      dict, current job.

    """
    print ('Waiting up to %s seconds for the job to have one of the following '
           'job state(s): %s\n' % (timeout, job_state))

    end = time.time() + timeout

    while time.time() < end:
      job = self.JobState(job_id)

      if job is not None:
        if job['semantic_state']['state']['type'] in job_state:
          return job

      Sleep('POLL')

    raise AssertionError
  def WaitForUpdate(self, dev_id, key, expected_value,
                    timeout=Constants.TIMEOUT['GCP_UPDATE']):
    '''Wait for the printer's local_settings attribute matches an expected value

      Args:
        dev_id: string, id of the printer.
        key: string, the local_settings attribute to poll for.
        expected_value: int or boolean, the expected value of the attribute.
        timeout: integer, number of seconds to wait.
      Returns:
        boolean, True if expected value is observed, otherwise False
    '''
    print '[Configurable timeout] GCP_UPDATE:'
    print ('Waiting up to %s seconds for printer to accept pending settings' %
           timeout)

    end = time.time() + timeout

    while time.time() < end:
      # Continue to use the /Update to access the current local settings
      try:
        res = self.Update(dev_id,{})
      except AssertionError:
        print 'GCP Update call failed'
        return False
      else:
        if key not in res['printer']['local_settings']['current']:
          print 'ERROR: "%s" does not exist in local_settings' % key
          return False
        cur_val = res['printer']['local_settings']['current'][key]
        if expected_value == cur_val:
          return True
      Sleep('POLL')
    return False
  def WaitJobStateNotIn(self, job_id, printer_id, job_state, timeout=60):
    """Wait until the job state is not the specified state.

    Args:
      job_id: string, id of the print job.
      printer_id: string, id of the printer
      job_state: string or list, job state(s) that should not be observed.
      timeout: integer, number of seconds to wait.
    Returns:
      string, current job.

    """
    print ('Waiting up to %s seconds for the job to not have any of the '
           'following job state(s): %s\n' % (timeout, job_state))

    end = time.time() + timeout

    while time.time() < end:
      job = self.GetJobInfo(job_id, printer_id)

      if job is not None:
        if job['semanticState']['state']['type'] not in job_state:
          return job

      Sleep('POLL')

    return None
Exemple #5
0
    def CancelRegistration(self):
        """Cancel Privet Registration that is in progress.

    Returns:
      return code from HTTP request.
    """
        self.logger.debug('Sending request to cancel Privet Registration.')
        url = self.privet_url['register']['cancel']
        params = {'user': Constants.USER['EMAIL']}
        r = self.transport.HTTPPost(url, headers=self.headers, params=params)

        if r is None:
            raise

        Sleep('REG_CANCEL')

        return r.status_code
Exemple #6
0
    def CreateJob(self, cjt=None):
        """First step required to submit a local print job.
       Keep trying to obtain the job id for 60 seconds if the printer returns
       busy status

        Args:
          cjt: CloudJobTicket, object that defines the options of the print job
        Returns:
          string, the newly created job_id if successful, else None
        """

        if cjt is None:
            cjt = {}
        else:
            cjt = cjt.val

        url = self.privet_url['createjob']

        print 'Attempt to get a local job id for up to 30 seconds'
        t_end = time.time() + 30

        while time.time() < t_end:
            r = self.transport.HTTPPost(url,
                                        data=dumps(cjt),
                                        headers=self.headers)

            if r is None or requests.codes.ok != r.status_code:
                return None

            res = r.json()

            if 'job_id' not in res:
                if 'error' in res and 'printer_busy' in res['error'].lower():
                    print(
                        'Printer is still busy, will try again in %s second(s)'
                        % Constants.SLEEP['POLL'])
                    Sleep('POLL')
                else:
                    print 'Error: ', res['error']
                    return None
            else:
                print 'Got a job id\n'
                return res['job_id']
        return None
  def WaitLocalJobExist(self, printer_id, job_title, timeout=60):
    """Wait until the local print job is present in /job api.

    Args:
      printer_id: string, id of the printer
      job_title: string, title of the print job.
      timeout: integer, number of seconds to wait.
    Returns:
      boolean, True if job exists.

    """
    print ('Waiting up to %s seconds for the local print job to be reported to '
           'GCP servers\n' % timeout)

    end = time.time() + timeout

    while time.time() < end:
      res = self.Jobs(printer_id=printer_id, job_title=job_title)
      if res['jobsCount'] > 0:
        return True

      Sleep('POLL')

    return False
  def Submit(self, printer_id, content, title, cjt=None, is_url=False):
    """Submit a print job to the printer

        Args:
          printer_id: string, target printer to print from.
          content: string, url or absolute filepath of the item to print.
          title: string, title of the print job.
          cjt: CloudJobTicket, object that defines the options of the print job
          is_url: boolean, flag to identify between url's and files
        Returns:
          dictionary, response msg from the printer if successful;
                      otherwise, None
        """

    if cjt is None:
      cjt = {}
    else:
      cjt = cjt.val

    name = content

    if not is_url:
      name = basename(content)
      with open(content, 'rb') as f:
        content = f.read()

    if title is None:
      title = "LogoCert Testing: " + name

    content_type = 'url' if is_url else mimetypes.guess_type(name)[0]
    files = {"content": (name,content)}
    url = '%s/submit' % (Constants.GCP['MGT'])
    headers = {'Authorization': 'Bearer %s' % self.auth_token}

    data = {'printerid': printer_id,
            'title': title,
            'contentType': content_type,
            'ticket': dumps(cjt)}

    # Depending on network speed, large files may take a while to submit
    print 'Attempting to submit a job through GCP for up to 60 seconds'
    t_end = time.time()+60
    while time.time() < t_end:
      r = self.transport.HTTPPost(url, data=data, files=files, headers=headers)
      if r is None:
        print 'ERROR! HTTP POST to /submit returned None type'
        return None
      elif r.status_code == requests.codes.ok:
        # Success
        res = r.json()
        # TODO may have to fuzzy match here, print job added may not be standard
        res['success'] = (res['success'] and
                          'print job added' in res['message'].lower())

        if res['success']:
          print 'Job submitted successfully'
        else:
          print 'success: %s, msg: %s' % (res['success'], res['message'])
        return res
      else:
        # Try again if we get HTTP error code
        print 'Bad status code from Submit(): %s' % r.status_code
        if r.status_code == requests.codes.forbidden:
          # This should not happen, calling code should manage token refresh
          self.logger.info('Access token expired, need to refresh it.')
        print 'Trying again in %s sec(s)' % Constants.SLEEP['POLL']
        Sleep('POLL')
    # Continuously gotten HTTP error codes to fall out of the while loop
    return None