Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.loloof64.j2se.cling_chess_exp;
- import java.awt.GridLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.util.Arrays;
- import java.util.Map;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JSpinner;
- import javax.swing.SpinnerNumberModel;
- import org.teleal.cling.UpnpService;
- import org.teleal.cling.UpnpServiceImpl;
- import org.teleal.cling.binding.annotations.AnnotationLocalServiceBinder;
- import org.teleal.cling.controlpoint.ActionCallback;
- import org.teleal.cling.controlpoint.SubscriptionCallback;
- import org.teleal.cling.model.DefaultServiceManager;
- import org.teleal.cling.model.ValidationException;
- import org.teleal.cling.model.action.ActionInvocation;
- import org.teleal.cling.model.gena.CancelReason;
- import org.teleal.cling.model.gena.GENASubscription;
- import org.teleal.cling.model.message.UpnpResponse;
- import org.teleal.cling.model.message.header.STAllHeader;
- import org.teleal.cling.model.meta.Device;
- import org.teleal.cling.model.meta.DeviceDetails;
- import org.teleal.cling.model.meta.DeviceIdentity;
- import org.teleal.cling.model.meta.Icon;
- import org.teleal.cling.model.meta.LocalDevice;
- import org.teleal.cling.model.meta.LocalService;
- import org.teleal.cling.model.meta.ManufacturerDetails;
- import org.teleal.cling.model.meta.ModelDetails;
- import org.teleal.cling.model.meta.RemoteDevice;
- import org.teleal.cling.model.meta.Service;
- import org.teleal.cling.model.state.StateVariableValue;
- import org.teleal.cling.model.types.DeviceType;
- import org.teleal.cling.model.types.InvalidValueException;
- import org.teleal.cling.model.types.ServiceId;
- import org.teleal.cling.model.types.UDADeviceType;
- import org.teleal.cling.model.types.UDAServiceId;
- import org.teleal.cling.model.types.UDN;
- import org.teleal.cling.registry.DefaultRegistryListener;
- import org.teleal.cling.registry.Registry;
- import org.teleal.cling.registry.RegistryListener;
- public class ChessBoard extends JFrame {
- public ChessBoard(String id){
- setTitle("Chess board " + id);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- buildGraphicPart();
- Thread chessBoardThread = new Thread(new InitializeUpnP());
- chessBoardThread.setDaemon(false);
- chessBoardThread.start();
- }
- private void buildGraphicPart() {
- setLayout(new GridLayout(0,2));
- startFileSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
- startRankSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
- endFileSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
- endRankSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
- receivedCoordsLabel = new JLabel(" ");
- sendCoords = new JButton("send");
- add(new JLabel("Start file : "));
- add(startFileSpinner);
- add(new JLabel("Start rank : "));
- add(startRankSpinner);
- add(new JLabel("End file : "));
- add(endFileSpinner);
- add(new JLabel("End rank : "));
- add(endRankSpinner);
- add(sendCoords);
- add(new JLabel(" "));
- add(new JLabel("received coords"));
- add(receivedCoordsLabel);
- sendCoords.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- trySendingCoords();
- }
- });
- pack();
- }
- protected void trySendingCoords() {
- if (otherBoard != null && sendCoordsInvocation != null){
- sendCoordsInvocation.setCoords(new ChessMove(
- (int) startFileSpinner.getValue(),
- (int) startRankSpinner.getValue(),
- (int) endFileSpinner.getValue(),
- (int) endRankSpinner.getValue()
- ));
- new ActionCallback.Default(sendCoordsInvocation, upnpService.getControlPoint()).run();
- }
- }
- public static void main(String[] args) {
- new ChessBoard(args[0]).setVisible(true);
- }
- private class InitializeUpnP implements Runnable {
- @Override
- public void run() {
- upnpService = new UpnpServiceImpl();
- Runtime.getRuntime().addShutdownHook(new Thread(){
- @Override
- public void run() {
- upnpService.shutdown();
- }
- });
- try {
- upnpService.getRegistry().addDevice(createDevice());
- upnpService.getRegistry().addListener(createRegistryListener());
- upnpService.getControlPoint().search(new STAllHeader());
- } catch (Exception e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(
- null,
- "Failed to create the local device !",
- "Error",
- JOptionPane.ERROR_MESSAGE
- );
- }
- }
- }
- private LocalDevice createDevice() throws ValidationException {
- DeviceIdentity deviceIdentity = new DeviceIdentity(
- UDN.uniqueSystemIdentifier("Chess Board")
- );
- DeviceType deviceType = new UDADeviceType("ChessMove",1);
- DeviceDetails deviceDetails = new DeviceDetails(
- "Chess move service",
- new ManufacturerDetails("Laurent Bernabe"),
- new ModelDetails("ChessMove", "A chess move service", "v1")
- );
- Icon icon = null;
- @SuppressWarnings("unchecked")
- LocalService<ChessMoveService> chessMoveService =
- new AnnotationLocalServiceBinder().read(ChessMoveService.class);
- chessMoveService.setManager(
- new DefaultServiceManager<>(chessMoveService, ChessMoveService.class)
- );
- LocalDevice device = new LocalDevice(deviceIdentity, deviceType, deviceDetails, icon, chessMoveService);
- return device;
- }
- private RegistryListener createRegistryListener() {
- return new DefaultRegistryListener(){
- private ServiceId serviceId = new UDAServiceId("ChessMove");
- @Override
- public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
- tryMatchingDevice(device);
- }
- @Override
- public void remoteDeviceRemoved(Registry registry,
- RemoteDevice device) {
- tryRemovingDevice(device);
- }
- @Override
- public void localDeviceAdded(Registry registry, LocalDevice device) {
- tryMatchingDevice(device);
- }
- @Override
- public void localDeviceRemoved(Registry registry, LocalDevice device) {
- tryRemovingDevice(device);
- }
- private void tryMatchingDevice(@SuppressWarnings("rawtypes") Device device) {
- if (otherBoard == null){
- ///////////////////
- System.out.println("Found a device !");
- System.out.println(Arrays.toString(device.getServices()));
- ///////////////////
- @SuppressWarnings("rawtypes")
- Service soughtService = device.findService(serviceId);
- if (soughtService != null){
- ////////////
- System.out.println("Matched a device !");
- ////////////
- otherBoard = device;
- sendCoordsInvocation = new SendCoordsInvocation(soughtService);
- receiveCoordsSubscription = new ReceiveCoordsSubscriptionCallback(soughtService);
- upnpService.getControlPoint().execute(receiveCoordsSubscription);
- }
- ///////////////////
- else
- System.out.println("But could not be matched !");
- ////////////////
- }
- }
- private void tryRemovingDevice(@SuppressWarnings("rawtypes") Device device) {
- if (device == otherBoard){
- receiveCoordsSubscription.end();
- receiveCoordsSubscription = null;
- sendCoordsInvocation = null;
- otherBoard = null;
- }
- }
- };
- }
- @SuppressWarnings({ "rawtypes" })
- protected class SendCoordsInvocation extends ActionInvocation{
- @SuppressWarnings("unchecked")
- public SendCoordsInvocation(Service service){
- super(service.getAction("ChangeTo"));
- }
- public void setCoords(ChessMove moveCoords) throws InvalidValueException {
- setInput("CompactedValue", moveCoords.packValue());
- }
- }
- protected class ReceiveCoordsSubscriptionCallback extends SubscriptionCallback {
- public ReceiveCoordsSubscriptionCallback(@SuppressWarnings("rawtypes") Service service){
- super(service);
- }
- @Override
- protected void ended(@SuppressWarnings("rawtypes") GENASubscription sub, CancelReason reason,
- UpnpResponse resp) {
- }
- @Override
- protected void established(@SuppressWarnings("rawtypes") GENASubscription sub) {
- }
- @SuppressWarnings("rawtypes")
- @Override
- protected void eventReceived(GENASubscription sub) {
- @SuppressWarnings("unchecked")
- Map<String, StateVariableValue> values = sub.getCurrentValues();
- StateVariableValue status = values.get("LastMove");
- int compactedCoords = (Integer) status.getValue();
- ChessMove moveCoords = ChessMove.unpack(compactedCoords);
- receivedCoordsLabel.setText(String.format(
- "%d %d %d %d",
- moveCoords.startFile,
- moveCoords.startRank,
- moveCoords.endFile,
- moveCoords.endRank
- ));
- }
- @Override
- protected void eventsMissed(@SuppressWarnings("rawtypes") GENASubscription sub, int id) {
- }
- @Override
- protected void failed(@SuppressWarnings("rawtypes") GENASubscription sub, UpnpResponse resp,
- Exception ex, String message) {
- }
- }
- @SuppressWarnings("rawtypes")
- private Device otherBoard = null;
- private JSpinner startFileSpinner, startRankSpinner;
- private JSpinner endFileSpinner, endRankSpinner;
- private JLabel receivedCoordsLabel;
- private JButton sendCoords;
- protected UpnpService upnpService;
- private SendCoordsInvocation sendCoordsInvocation;
- private SubscriptionCallback receiveCoordsSubscription;
- private static final long serialVersionUID = 2166480665114176165L;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement