Beispiel #1
0
    def RunTests(self, request, response):
        """Handle a /RunTests request."""
        universe = self._CheckValidUniverse(request)

        uid_param = self.RaiseExceptionIfMissing(request, 'uid')
        uid = UID.FromString(uid_param)
        if uid is None:
            raise ServerException('Invalid uid: %s' % uid_param)

        # The tests to run, None means all
        test_filter = request.GetParam('t')
        if test_filter is not None:
            if test_filter == 'all':
                test_filter = None
            else:
                test_filter = set(test_filter.split(','))

        broadcast_write_delay = request.GetParam('broadcast_write_delay')
        if broadcast_write_delay is None:
            broadcast_write_delay = 0
        try:
            broadcast_write_delay = int(broadcast_write_delay)
        except ValueError:
            raise ServerException('Invalid broadcast write delay')

        inter_test_delay = request.GetParam('inter_test_delay')
        if inter_test_delay is None:
            inter_test_delay = 0
        try:
            inter_test_delay = int(inter_test_delay)
        except ValueError:
            raise ServerException('Invalid inter-test delay')

        slot_count = request.GetParam('slot_count')
        if slot_count is None:
            slot_count = 0
        try:
            slot_count = int(slot_count)
        except ValueError:
            raise ServerException('Invalid slot count')
        if slot_count not in range(0, 513):
            raise ServerException('Slot count not in range 0..512')

        dmx_frame_rate = request.GetParam('dmx_frame_rate')
        if dmx_frame_rate is None:
            dmx_frame_rate = 0
        try:
            dmx_frame_rate = int(dmx_frame_rate)
        except ValueError:
            raise ServerException('Invalid DMX frame rate')

        ret = self._test_thread.ScheduleTests(universe, uid, test_filter,
                                              broadcast_write_delay,
                                              inter_test_delay, dmx_frame_rate,
                                              slot_count)
        if ret is not None:
            raise ServerException(ret)

        response.SetStatus(HTTPResponse.OK)
        return {'status': True}
Beispiel #2
0
    def HandleRequest(self, request, response):
        uid_param = request.GetParam('uid') or ''
        uid = UID.FromString(uid_param)
        if uid is None:
            raise ServerException('Missing uid parameter: uid')

        timestamp = request.GetParam('timestamp')
        if timestamp is None:
            raise ServerException('Missing timestamp parameter: timestamp')

        include_debug = request.GetParam('debug')
        include_description = request.GetParam('description')
        category = request.GetParam('category')
        test_state = request.GetParam('state')

        reader = TestLogger.TestLogger(settings['log_directory'])
        try:
            output = reader.ReadAndFormat(uid, timestamp, category, test_state,
                                          include_debug, include_description)
        except TestLogger.TestLoggerException as e:
            raise ServerException(e)

        filename = ('%04x-%08x.%s.txt' %
                    (uid.manufacturer_id, uid.device_id, timestamp))
        response.SetStatus(HTTPResponse.OK)
        response.SetHeader('Content-disposition',
                           'attachment; filename="%s"' % filename)
        response.SetHeader('Content-type', 'text/plain')
        response.SetHeader('Content-length', '%d' % len(output))
        response.AppendData(output)
Beispiel #3
0
def ParseOptions():
  usage = 'Usage: %prog [options] <uid>'
  description = textwrap.dedent("""\
    Run a series of tests on a RDM responder to check the behaviour.
    This requires the OLA server to be running, and the RDM device to have been
    detected. You can confirm this by running ola_rdm_discover -u
    UNIVERSE.  This will send SET commands to the broadcast UIDs which means
    the start address, device label etc. will be changed for all devices
    connected to the responder. Think twice about running this on your
    production lighting rig.
  """)
  parser = OptionParser(usage, description=description)
  parser.add_option('-c', '--slot-count', default=10,
                    help='Number of slots to send when sending DMX.')
  parser.add_option('-d', '--debug', action='store_true',
                    help='Print debug information to assist in diagnosing '
                         'failures.')
  parser.add_option('-f', '--dmx-frame-rate', default=0,
                    type='int',
                    help='Send DMX frames at this rate in the background.')
  parser.add_option('-l', '--log', metavar='FILE',
                    help='Also log to the file named FILE.uid.timestamp.')
  parser.add_option('--list-tests', action='store_true',
                    help='Display a list of all tests')
  parser.add_option('-p', '--pid-store', metavar='FILE',
                    help='The location of the PID definitions.')
  parser.add_option('-s', '--skip-check', action='store_true',
                    help='Skip the check for multiple devices.')
  parser.add_option('-t', '--tests', metavar='TEST1,TEST2',
                    help='A comma separated list of tests to run.')
  parser.add_option('--timestamp', action='store_true',
                    help='Add timestamps to each test.')
  parser.add_option('--no-factory-defaults', action='store_true',
                    help="Don't run the SET factory defaults tests")
  parser.add_option('-w', '--broadcast-write-delay', default=0,
                    type='int',
                    help='The time in ms to wait after sending broadcast set'
                         'commands.')
  parser.add_option('-u', '--universe', default=0,
                    type='int',
                    help='The universe number to use, default is universe 0.')

  options, args = parser.parse_args()

  if options.list_tests:
    return options

  if not args:
    parser.print_help()
    sys.exit(2)

  uid = UID.FromString(args[0])
  if uid is None:
    parser.print_usage()
    print 'Invalid UID: %s' % args[0]
    sys.exit(2)

  options.uid = uid
  return options
Beispiel #4
0
def ReadFile(filename):
    try:
        f = open(filename, 'rb')
    except IOError as e:
        raise LoadException(e)

    raw_data = pickle.load(f)
    f.close()
    data = {}
    for uid, settings in raw_data.items():
        data[UID.FromString(uid)] = settings
    return data
Beispiel #5
0
  def Pack(self, args):
    uid = None
    if isinstance(args[0], UID):
      uid = args[0]
    else:
      uid = UID.FromString(args[0])

    if uid is None:
      raise ArgsValidationError("Invalid UID: %s" % e)

    format_string = self._FormatString()
    try:
      data = struct.pack(format_string, uid.manufacturer_id, uid.device_id)
    except struct.error, e:
      raise ArgsValidationError("Can't pack data: %s" % e)
Beispiel #6
0
    def testFromString(self):
        self.assertEqual(None, UID.FromString(''))
        self.assertEqual(None, UID.FromString('abc'))
        self.assertEqual(None, UID.FromString(':'))
        self.assertEqual(None, UID.FromString('0:1:2'))
        self.assertEqual(None, UID.FromString('12345:1234'))

        uid = UID.FromString('00a0:12345678')
        self.assertTrue(uid)
        self.assertEqual(0x00a0, uid.manufacturer_id)
        self.assertEqual(0x12345678, uid.device_id)
        self.assertEqual('00a0:12345678', str(uid))
Beispiel #7
0
  def do_uid(self, line):
    """Sets the active UID."""
    args = line.split()
    if len(args) != 1:
      print('*** Requires a single UID argument')
      return

    uid = UID.FromString(args[0])
    if uid is None:
      print('*** Invalid UID')
      return

    if uid not in self._uids:
      print('*** UID not found')
      return

    self._uid = uid
    print('Fetching queued messages...')
    self._FetchQueuedMessages()
    self.wrapper.Run()
Beispiel #8
0
def main():
  readline.set_completer_delims(' \t')
  try:
    opts, args = getopt.getopt(sys.argv[1:], 'd:hilp:u:',
                               ['sub-device=', 'help', 'interactive',
                                'list-pids', 'pid-location=', 'uid=',
                                'universe='])
  except getopt.GetoptError as err:
    print(str(err))
    Usage()
    sys.exit(2)

  universe = None
  uid = None
  sub_device = 0
  list_pids = False
  pid_location = None
  interactive_mode = False
  for o, a in opts:
    if o in ('-d', '--sub-device'):
      sub_device = int(a)
    elif o in ('-h', '--help'):
      Usage()
      sys.exit()
    elif o in ('-i', '--interactive'):
      interactive_mode = True
    elif o in ('-l', '--list-pids'):
      list_pids = True
    elif o in ('--uid',):
      uid = UID.FromString(a)
    elif o in ('-p', '--pid-location',):
      pid_location = a
    elif o in ('-u', '--universe'):
      universe = int(a)

  if universe is None and not list_pids:
    Usage()
    sys.exit()

  if not uid and not list_pids and not interactive_mode:
    Usage()
    sys.exit()

  # try to load the PID store so we fail early if we're missing PIDs
  try:
    PidStore.GetStore(pid_location)
  except PidStore.MissingPLASAPIDs as e:
    print(e)
    sys.exit()

  controller = InteractiveModeController(universe,
                                         uid,
                                         sub_device,
                                         pid_location)
  if interactive_mode:
    sys.stdout.write('Available Uids:\n')
    controller.onecmd('uids')
    controller.cmdloop()
    sys.exit()

  if list_pids:
    controller.onecmd('list')
    sys.exit()

  if len(args) == 0:
    Usage()
    sys.exit()

  request_type = 'get'
  if os.path.basename(sys.argv[0]) == 'ola_rdm_set.py':
    request_type = 'set'
  controller.onecmd('%s %s' % (request_type, ' '.join(args)))
    sub_device = 0
    list_pids = False
    pid_file = None
    interactive_mode = False
    for o, a in opts:
        if o in ('-d', '--sub-device'):
            sub_device = int(a)
        elif o in ('-h', '--help'):
            Usage()
            sys.exit()
        elif o in ('-i', '--interactive'):
            interactive_mode = True
        elif o in ('-l', '--list-pids'):
            list_pids = True
        elif o in ('--uid', ):
            uid = UID.FromString(a)
        elif o in ('--pid_file', ):
            pid_file = a
        elif o in ('-u', '--universe'):
            universe = int(a)

    if universe is None and not list_pids:
        Usage()
        sys.exit()

    if not uid and not list_pids and not interactive_mode:
        Usage()
        sys.exit()

    controller = InteractiveModeController(universe, uid, sub_device, pid_file)
    if interactive_mode:
Beispiel #10
0
    def testGetWithResponse(self):
        """uses client to send an RDM get with mocked olad.
    Regression test that confirms sent message is correct and
    sends fixed response message."""
        sockets = socket.socketpair()
        wrapper = ClientWrapper(sockets[0])
        pid_store = PidStore.GetStore(pid_store_path)
        client = wrapper.Client()
        rdm_api = RDMAPI(client, pid_store)

        class results:
            got_request = False
            got_response = False

        def DataCallback(self):
            # request and response for
            # ola_rdm_get.py -u 1 --uid 7a70:ffffff00 device_info
            # against olad dummy plugin
            # enable logging in rpc/StreamRpcChannel.py
            data = sockets[1].recv(4096)
            expected = binascii.unhexlify(
                "29000010080110001a0a52444d436f6d6d616e6422170801120908f0f4011500"
                "ffffff180020602a0030003800")
            self.assertEqual(data,
                             expected,
                             msg="Regression check failed. If protocol change "
                             "was intended set expected to: " +
                             str(binascii.hexlify(data)))
            results.got_request = True
            response = binascii.unhexlify(
                "3f0000100802100022390800100018002213010000017fff0000000300050204"
                "00010000032860300038004a0908f0f4011500ffffff520908f0f40115ac1100"
                "02580a")
            sent_bytes = sockets[1].send(response)
            self.assertEqual(sent_bytes, len(response))

        def ResponseCallback(self, response, data, unpack_exception):
            results.got_response = True
            self.assertEqual(response.response_type, client.RDM_ACK)
            self.assertEqual(response.pid, 0x60)
            self.assertEqual(data["dmx_footprint"], 5)
            self.assertEqual(data["software_version"], 3)
            self.assertEqual(data["personality_count"], 4)
            self.assertEqual(data["device_model"], 1)
            self.assertEqual(data["current_personality"], 2)
            self.assertEqual(data["protocol_major"], 1)
            self.assertEqual(data["protocol_minor"], 0)
            self.assertEqual(data["product_category"], 32767)
            self.assertEqual(data["dmx_start_address"], 1)
            self.assertEqual(data["sub_device_count"], 0)
            self.assertEqual(data["sensor_count"], 3)
            wrapper.AddEvent(0, wrapper.Stop)

        wrapper._ss.AddReadDescriptor(sockets[1], lambda: DataCallback(self))

        uid = UID.FromString("7a70:ffffff00")
        pid = pid_store.GetName("DEVICE_INFO")
        rdm_api.Get(1, uid, 0, pid,
                    lambda x, y, z: ResponseCallback(self, x, y, z))

        wrapper.Run()

        sockets[0].close()
        sockets[1].close()

        self.assertTrue(results.got_request)
        self.assertTrue(results.got_response)
Beispiel #11
0
    def testSetParamsWithNack(self):
        """uses client to send an RDM set with mocked olad.
    Regression test that confirms sent message is correct and
    sends fixed response message."""
        sockets = socket.socketpair()
        wrapper = ClientWrapper(sockets[0])
        pid_store = PidStore.GetStore(pid_store_path)
        client = wrapper.Client()
        rdm_api = RDMAPI(client, pid_store)

        class results:
            got_request = False
            got_response = False

        def DataCallback(self):
            # request and response for
            # ola_rdm_set.py -u 1 --uid 7a70:ffffff00 DMX_PERSONALITY 10
            # against olad dummy plugin
            # enable logging in rpc/StreamRpcChannel.py
            data = sockets[1].recv(4096)
            expected = binascii.unhexlify(
                "2b000010080110001a0a52444d436f6d6d616e6422190801120908f0f401150"
                "0ffffff180020e0012a010a30013800")
            self.assertEqual(data,
                             expected,
                             msg="Regression check failed. If protocol change "
                             "was intended set expected to: " +
                             str(binascii.hexlify(data)))
            results.got_request = True
            response = binascii.unhexlify(
                "2f0000100802100022290800100218002202000628e001300138004a0908f0f"
                "4011500ffffff520908f0f40115ac107de05831")
            sent_bytes = sockets[1].send(response)
            self.assertEqual(sent_bytes, len(response))

        def ResponseCallback(self, response, data, unpack_exception):
            results.got_response = True
            self.assertEqual(response.response_type, client.RDM_NACK_REASON)
            self.assertEqual(response.pid, 0xe0)
            self.assertEqual(response.nack_reason,
                             RDMNack.NR_DATA_OUT_OF_RANGE)
            wrapper.AddEvent(0, wrapper.Stop)

        wrapper._ss.AddReadDescriptor(sockets[1], lambda: DataCallback(self))

        uid = UID.FromString("7a70:ffffff00")
        pid = pid_store.GetName("DMX_PERSONALITY")
        rdm_api.Set(1,
                    uid,
                    0,
                    pid,
                    lambda x, y, z: ResponseCallback(self, x, y, z),
                    args=["10"])

        wrapper.Run()

        sockets[0].close()
        sockets[1].close()

        self.assertTrue(results.got_request)
        self.assertTrue(results.got_response)
Beispiel #12
0
    def testGetParamsWithResponse(self):
        """uses client to send an RDM get with mocked olad.
    Regression test that confirms sent message is correct and
    sends fixed response message."""
        sockets = socket.socketpair()
        wrapper = ClientWrapper(sockets[0])
        pid_store = PidStore.GetStore(pid_store_path)
        client = wrapper.Client()
        rdm_api = RDMAPI(client, pid_store)

        class results:
            got_request = False
            got_response = False

        def DataCallback(self):
            # request and response for
            # ola_rdm_get.py -u 1 --uid 7a70:ffffff00 DMX_PERSONALITY_DESCRIPTION 2
            # against olad dummy plugin
            # enable logging in rpc/StreamRpcChannel.py
            data = sockets[1].recv(4096)
            expected = binascii.unhexlify(
                "2b000010080110001a0a52444d436f6d6d616e6422190801120908f0f4011500"
                "ffffff180020e1012a010230003800")
            self.assertEqual(data,
                             expected,
                             msg="Regression check failed. If protocol change "
                             "was intended set expected to: " +
                             str(binascii.hexlify(data)))
            results.got_request = True
            response = binascii.unhexlify(
                "3d0000100802100022370800100018002210020005506572736f6e616c697479"
                "203228e101300038004a0908f0f4011500ffffff520908f0f40115ac107de058"
                "29")
            sent_bytes = sockets[1].send(response)
            self.assertEqual(sent_bytes, len(response))

        def ResponseCallback(self, response, data, unpack_exception):
            results.got_response = True
            self.assertEqual(response.response_type, client.RDM_ACK)
            self.assertEqual(response.pid, 0xe1)
            self.assertEqual(data['personality'], 2)
            self.assertEqual(data['slots_required'], 5)
            self.assertEqual(data['name'], "Personality 2")
            wrapper.AddEvent(0, wrapper.Stop)

        wrapper._ss.AddReadDescriptor(sockets[1], lambda: DataCallback(self))

        uid = UID.FromString("7a70:ffffff00")
        pid = pid_store.GetName("DMX_PERSONALITY_DESCRIPTION")
        rdm_api.Get(1,
                    uid,
                    0,
                    pid,
                    lambda x, y, z: ResponseCallback(self, x, y, z),
                    args=["2"])

        wrapper.Run()

        sockets[0].close()
        sockets[1].close()

        self.assertTrue(results.got_request)
        self.assertTrue(results.got_response)