Пример #1
0
  private void addPortMappingImpl(Service connectionService, int port) throws Exception {
    final Semaphore gotReply = new Semaphore(0);
    final AtomicReference<String> error = new AtomicReference<String>();
    upnpService
        .getControlPoint()
        .execute(
            new PortMappingAdd(connectionService, createPortMapping(port)) {

              @Override
              public void success(ActionInvocation invocation) {
                gotReply.release();
              }

              @Override
              public void failure(
                  ActionInvocation invocation, UpnpResponse response, String defaultMsg) {
                error.set(String.valueOf(response) + ": " + defaultMsg);
                gotReply.release();
              }
            });
    gotReply.acquire();
    if (error.get() != null) {
      throw new Exception(error.get());
    }
  }
  void executeAction(UpnpService upnpService, Service NodoTemp) {

    Action getStatusAction = NodoTemp.getAction("GetStatus");
    ActionInvocation getStatusInvocation = new ActionInvocation(getStatusAction);

    ActionCallback getStatusCallback =
        new ActionCallback(getStatusInvocation) {

          @Override
          public void success(ActionInvocation invocation) {
            ActionArgumentValue status = invocation.getOutput("ResultStatus");

            assert status != null;

            System.out.println(status.toString());
          }

          @Override
          public void failure(
              ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
            System.err.println(defaultMsg);
          }
        };

    upnpService.getControlPoint().execute(getStatusCallback);
  }
Пример #3
0
 protected void subscribeAll(Device d, String uuid) {
   String name = getFriendlyName(d);
   int ctrl = 0;
   for (Service s : d.getServices()) {
     String sid = s.getServiceId().getId();
     LOGGER.debug("Subscribing to " + sid + " service on " + name);
     if (sid.contains("AVTransport")) {
       ctrl |= AVT;
     } else if (sid.contains("RenderingControl")) {
       ctrl |= RC;
     }
     upnpService.getControlPoint().execute(new SubscriptionCB(s));
   }
   rendererMap.mark(uuid, RENEW, false);
   rendererMap.mark(uuid, CONTROLS, ctrl);
 }
Пример #4
0
  // Convenience functions for sending various upnp service requests
  public static ActionInvocation send(
      final Device dev, String instanceID, String service, String action, String... args) {
    Service svc = dev.findService(ServiceId.valueOf("urn:upnp-org:serviceId:" + service));
    final String uuid = getUUID(dev);
    if (svc != null) {
      Action x = svc.getAction(action);
      String name = getFriendlyName(dev);
      boolean log = !action.equals("GetPositionInfo");
      if (x != null) {
        ActionInvocation a = new ActionInvocation(x);
        a.setInput("InstanceID", instanceID);
        for (int i = 0; i < args.length; i += 2) {
          a.setInput(args[i], args[i + 1]);
        }
        if (log) {
          LOGGER.debug("Sending upnp {}.{} {} to {}[{}]", service, action, args, name, instanceID);
        }
        new ActionCallback(a, upnpService.getControlPoint()) {
          @Override
          public void success(ActionInvocation invocation) {
            rendererMap.mark(uuid, ACTIVE, true);
          }

          @Override
          public void failure(
              ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
            LOGGER.debug("Action failed: {}", defaultMsg);
            rendererMap.mark(uuid, ACTIVE, false);
          }
        }.run();

        if (log) {
          for (ActionArgumentValue arg : a.getOutput()) {
            LOGGER.debug(
                "Received from {}[{}]: {}={}",
                name,
                instanceID,
                arg.getArgument().getName(),
                arg.toString());
          }
        }
        return a;
      }
    }
    return null;
  }
  @Test
  public void sendMessageToTV() throws Exception {

    final boolean[] tests = new boolean[1];

    UpnpService upnpService = new MockUpnpService();

    LocalDevice device = MessageBoxSampleData.createDevice(MyTV.class);
    upnpService.getRegistry().addDevice(device);

    MessageSMS msg =
        new MessageSMS(
            new DateTime("2010-06-21", "16:34:12"),
            new NumberName("1234", "The Receiver"),
            new NumberName("5678", "The Sender"),
            "Hello World!");

    LocalService service =
        device.findService(new ServiceId("samsung.com", "MessageBoxService")); // DOC: S1

    upnpService
        .getControlPoint()
        .execute(
            new AddMessage(service, msg) {

              @Override
              public void success(ActionInvocation invocation) {
                // All OK
                tests[0] = true; // DOC: EXC1
              }

              @Override
              public void failure(
                  ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                // Something is wrong
              }
            }); // DOC: S1

    for (boolean test : tests) {
      assert test;
    }
    for (boolean test : ((LocalService<MyTV>) service).getManager().getImplementation().tests) {
      assert test;
    }
  }
Пример #6
0
  private void deletePortMappingImpl(Service connectionService, int port) throws Exception {
    final Semaphore gotReply = new Semaphore(0);
    upnpService
        .getControlPoint()
        .execute(
            new PortMappingDelete(connectionService, createPortMapping(port)) {

              @Override
              public void success(ActionInvocation invocation) {
                gotReply.release();
              }

              @Override
              public void failure(
                  ActionInvocation invocation, UpnpResponse response, String defaultMsg) {
                gotReply.release();
              }
            });
    gotReply.acquire();
  }
  @Override
  public void run() {
    try {

      UpnpService upnpService = new UpnpServiceImpl();

      // Adiciona um verificador de novos registros de dispositivos UPNP / Add a listener for device
      // registration events
      upnpService.getRegistry().addListener(createRegistryListener(upnpService));

      // Envia a mensagem de busca de novos dispositivos UPNP para todos os dispositivos da rede /
      // Broadcast a search message for all devices
      // Acontece só uma vez
      upnpService.getControlPoint().search(new STAllHeader());

      Scanner scanner = new Scanner(System.in);
      String command = "";

      while (!"quit".equals(command)) {
        command = scanner.next();

        // leitor de comandos do servidor de borda

        if ("getDevices".equals(command)) {
          Collection<Device> devices = upnpService.getRegistry().getDevices();
          int devicessize = devices.size();

          System.out.printf("Esses são os dispositivos locais ( %d )\n", devicessize);

          System.out.println(Arrays.toString(upnpService.getRegistry().getDevices().toArray()));

          RemoteDevice newdevice;

          for (int i = 0; i < devices.size(); i++) {
            newdevice = (RemoteDevice) devices.toArray()[i];
            System.out.println(newdevice.getDetails().getFriendlyName());
          }

        } else if ("exec".equals(command)) {
          /*Collection<Device> devices = upnpService.getRegistry().getDevices();
          ServiceId serviceId = new UDAServiceId("NodoTemp");
          RemoteDevice newdevice;

          for(int i = 0 ; i < devices.size() ; i++){
              newdevice = (RemoteDevice) devices.toArray()[i];

              Service edgeServer;
              if ((edgeServer = newdevice.findService(serviceId)) != null) {

                  //AÇÃO A SER EXECUTADA QUANDO ENCONTRADO DISPOSITIVO

                  //ADICIONAR O DISPOSITIVO EM ALGUM LUGAR PRA MONITORAMENTO
                  executeAction(upnpService, edgeServer);

              }
          }*/
        } else if ("countCadGateways".equals(command)) {
          synchronized (gatewaysCadastrados) {
            System.out.println(gatewaysCadastrados.size());
          }
        }
      }

      System.exit(0);

    } catch (Exception ex) {
      System.err.println("Exception occured: " + ex);
      System.exit(1);
    }
  }
Пример #8
0
  public void init() {

    try {
      db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      UMSHeaders = new UpnpHeaders();
      UMSHeaders.add(
          UpnpHeader.Type.USER_AGENT.getHttpName(),
          "UMS/" + PMS.getVersion() + " " + new ServerClientTokens());

      DefaultUpnpServiceConfiguration sc =
          new DefaultUpnpServiceConfiguration() {
            @Override
            public UpnpHeaders getDescriptorRetrievalHeaders(RemoteDeviceIdentity identity) {
              return UMSHeaders;
            }
          };

      RegistryListener rl =
          new DefaultRegistryListener() {
            @Override
            public void remoteDeviceAdded(Registry registry, RemoteDevice d) {
              super.remoteDeviceAdded(registry, d);
              if (isBlocked(getUUID(d)) || !addRenderer(d)) {
                LOGGER.debug("Ignoring device: {} {}", d.getType().getType(), d.toString());
              }
              // This may be unnecessary, but we might as well be thorough
              if (d.hasEmbeddedDevices()) {
                for (Device e : d.getEmbeddedDevices()) {
                  if (isBlocked(getUUID(e)) || !addRenderer(e)) {
                    LOGGER.debug("Ignoring embedded device: {} {}", e.getType(), e.toString());
                  }
                }
              }
            }

            @Override
            public void remoteDeviceRemoved(Registry registry, RemoteDevice d) {
              super.remoteDeviceRemoved(registry, d);
              String uuid = getUUID(d);
              if (rendererMap.containsKey(uuid)) {
                rendererMap.mark(uuid, ACTIVE, false);
                rendererRemoved(d);
              }
            }

            @Override
            public void remoteDeviceUpdated(Registry registry, RemoteDevice d) {
              super.remoteDeviceUpdated(registry, d);
              rendererUpdated(d);
            }
          };

      upnpService = new UpnpServiceImpl(sc, rl);

      // find all media renderers on the network
      for (DeviceType t : mediaRendererTypes) {
        upnpService.getControlPoint().search(new DeviceTypeHeader(t));
      }

      LOGGER.debug("UPNP Services are online, listening for media renderers");
    } catch (Exception ex) {
      LOGGER.debug("UPNP startup Error", ex);
    }
  }