Advertisement
loloof64

ChessBoard (Upnp application)

Apr 20th, 2013
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 9.28 KB | None | 0 0
  1. package com.loloof64.j2se.cling_chess_exp;
  2.  
  3. import java.awt.GridLayout;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import java.util.Arrays;
  7. import java.util.Map;
  8.  
  9. import javax.swing.JButton;
  10. import javax.swing.JFrame;
  11. import javax.swing.JLabel;
  12. import javax.swing.JOptionPane;
  13. import javax.swing.JSpinner;
  14. import javax.swing.SpinnerNumberModel;
  15.  
  16. import org.teleal.cling.UpnpService;
  17. import org.teleal.cling.UpnpServiceImpl;
  18. import org.teleal.cling.binding.annotations.AnnotationLocalServiceBinder;
  19. import org.teleal.cling.controlpoint.ActionCallback;
  20. import org.teleal.cling.controlpoint.SubscriptionCallback;
  21. import org.teleal.cling.model.DefaultServiceManager;
  22. import org.teleal.cling.model.ValidationException;
  23. import org.teleal.cling.model.action.ActionInvocation;
  24. import org.teleal.cling.model.gena.CancelReason;
  25. import org.teleal.cling.model.gena.GENASubscription;
  26. import org.teleal.cling.model.message.UpnpResponse;
  27. import org.teleal.cling.model.message.header.STAllHeader;
  28. import org.teleal.cling.model.meta.Device;
  29. import org.teleal.cling.model.meta.DeviceDetails;
  30. import org.teleal.cling.model.meta.DeviceIdentity;
  31. import org.teleal.cling.model.meta.Icon;
  32. import org.teleal.cling.model.meta.LocalDevice;
  33. import org.teleal.cling.model.meta.LocalService;
  34. import org.teleal.cling.model.meta.ManufacturerDetails;
  35. import org.teleal.cling.model.meta.ModelDetails;
  36. import org.teleal.cling.model.meta.RemoteDevice;
  37. import org.teleal.cling.model.meta.Service;
  38. import org.teleal.cling.model.state.StateVariableValue;
  39. import org.teleal.cling.model.types.DeviceType;
  40. import org.teleal.cling.model.types.InvalidValueException;
  41. import org.teleal.cling.model.types.ServiceId;
  42. import org.teleal.cling.model.types.UDADeviceType;
  43. import org.teleal.cling.model.types.UDAServiceId;
  44. import org.teleal.cling.model.types.UDN;
  45. import org.teleal.cling.registry.DefaultRegistryListener;
  46. import org.teleal.cling.registry.Registry;
  47. import org.teleal.cling.registry.RegistryListener;
  48.  
  49. public class ChessBoard extends JFrame {
  50.  
  51.     public ChessBoard(String id){
  52.         setTitle("Chess board " + id);
  53.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  54.         buildGraphicPart();
  55.        
  56.         Thread chessBoardThread = new Thread(new InitializeUpnP());
  57.         chessBoardThread.setDaemon(false);
  58.         chessBoardThread.start();
  59.     }
  60.  
  61.     private void buildGraphicPart() {
  62.         setLayout(new GridLayout(0,2));
  63.        
  64.         startFileSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
  65.         startRankSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
  66.         endFileSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
  67.         endRankSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 7, 1));
  68.        
  69.         receivedCoordsLabel = new JLabel("        ");
  70.        
  71.         sendCoords = new JButton("send");
  72.        
  73.         add(new JLabel("Start file : "));
  74.         add(startFileSpinner);
  75.         add(new JLabel("Start rank : "));
  76.         add(startRankSpinner);
  77.         add(new JLabel("End file : "));
  78.         add(endFileSpinner);
  79.         add(new JLabel("End rank : "));
  80.         add(endRankSpinner);
  81.        
  82.         add(sendCoords);
  83.         add(new JLabel("    "));
  84.        
  85.         add(new JLabel("received coords"));
  86.         add(receivedCoordsLabel);
  87.        
  88.         sendCoords.addActionListener(new ActionListener() {
  89.            
  90.             @Override
  91.             public void actionPerformed(ActionEvent e) {
  92.                 trySendingCoords();
  93.             }
  94.            
  95.         });
  96.        
  97.         pack();
  98.     }
  99.  
  100.     protected void trySendingCoords() {
  101.         if (otherBoard != null && sendCoordsInvocation != null){
  102.             sendCoordsInvocation.setCoords(new ChessMove(
  103.                     (int) startFileSpinner.getValue(),
  104.                     (int) startRankSpinner.getValue(),
  105.                     (int) endFileSpinner.getValue(),
  106.                     (int) endRankSpinner.getValue()
  107.             ));
  108.             new ActionCallback.Default(sendCoordsInvocation, upnpService.getControlPoint()).run();
  109.         }
  110.     }
  111.  
  112.     public static void main(String[] args) {
  113.         new ChessBoard(args[0]).setVisible(true);
  114.     }
  115.  
  116.     private class InitializeUpnP implements Runnable {
  117.  
  118.         @Override
  119.         public void run() {
  120.             upnpService = new UpnpServiceImpl();
  121.  
  122.             Runtime.getRuntime().addShutdownHook(new Thread(){
  123.  
  124.                 @Override
  125.                 public void run() {
  126.                     upnpService.shutdown();
  127.                 }
  128.  
  129.             });
  130.  
  131.             try {
  132.                 upnpService.getRegistry().addDevice(createDevice());
  133.                 upnpService.getRegistry().addListener(createRegistryListener());
  134.                 upnpService.getControlPoint().search(new STAllHeader());
  135.             } catch (Exception e) {
  136.                 e.printStackTrace();
  137.                 JOptionPane.showMessageDialog(
  138.                         null,
  139.                         "Failed to create the local device !",
  140.                         "Error",
  141.                         JOptionPane.ERROR_MESSAGE
  142.                         );
  143.             }
  144.  
  145.         }
  146.     }
  147.  
  148.     private LocalDevice createDevice() throws ValidationException {
  149.         DeviceIdentity deviceIdentity = new DeviceIdentity(
  150.                 UDN.uniqueSystemIdentifier("Chess Board")
  151.                 );
  152.         DeviceType deviceType = new UDADeviceType("ChessMove",1);
  153.         DeviceDetails deviceDetails = new DeviceDetails(
  154.                 "Chess move service",
  155.                 new ManufacturerDetails("Laurent Bernabe"),
  156.                 new ModelDetails("ChessMove", "A chess move service", "v1")
  157.                 );
  158.         Icon icon = null;
  159.         @SuppressWarnings("unchecked")
  160.         LocalService<ChessMoveService> chessMoveService =
  161.         new AnnotationLocalServiceBinder().read(ChessMoveService.class);
  162.         chessMoveService.setManager(
  163.                 new DefaultServiceManager<>(chessMoveService, ChessMoveService.class)  
  164.                 );
  165.         LocalDevice device = new LocalDevice(deviceIdentity, deviceType, deviceDetails, icon, chessMoveService);
  166.         return device;
  167.     }
  168.  
  169.     private RegistryListener createRegistryListener() {
  170.         return new DefaultRegistryListener(){
  171.             private ServiceId serviceId = new UDAServiceId("ChessMove");
  172.  
  173.             @Override
  174.             public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
  175.                 tryMatchingDevice(device);
  176.             }
  177.  
  178.             @Override
  179.             public void remoteDeviceRemoved(Registry registry,
  180.                     RemoteDevice device) {
  181.                 tryRemovingDevice(device);
  182.             }
  183.            
  184.             @Override
  185.             public void localDeviceAdded(Registry registry, LocalDevice device) {
  186.                 tryMatchingDevice(device);
  187.             }
  188.  
  189.             @Override
  190.             public void localDeviceRemoved(Registry registry, LocalDevice device) {
  191.                 tryRemovingDevice(device);
  192.             }
  193.  
  194.             private void tryMatchingDevice(@SuppressWarnings("rawtypes") Device device) {
  195.                 if (otherBoard == null){
  196.                     ///////////////////
  197.                     System.out.println("Found a device !");
  198.                     System.out.println(Arrays.toString(device.getServices()));
  199.                     ///////////////////
  200.                     @SuppressWarnings("rawtypes")
  201.                     Service soughtService = device.findService(serviceId);
  202.                     if (soughtService != null){
  203.                         ////////////
  204.                         System.out.println("Matched a device !");
  205.                         ////////////
  206.                         otherBoard = device;
  207.                         sendCoordsInvocation = new SendCoordsInvocation(soughtService);
  208.                         receiveCoordsSubscription = new ReceiveCoordsSubscriptionCallback(soughtService);
  209.                         upnpService.getControlPoint().execute(receiveCoordsSubscription);
  210.                     }
  211.                     ///////////////////
  212.                     else
  213.                         System.out.println("But could not be matched !");
  214.                     ////////////////
  215.                        
  216.                 }
  217.             }
  218.  
  219.             private void tryRemovingDevice(@SuppressWarnings("rawtypes") Device device) {
  220.                 if (device == otherBoard){
  221.                     receiveCoordsSubscription.end();
  222.                     receiveCoordsSubscription = null;
  223.                     sendCoordsInvocation = null;
  224.                     otherBoard = null;
  225.                 }
  226.             }
  227.  
  228.         };
  229.     }
  230.    
  231.     @SuppressWarnings({ "rawtypes" })
  232.     protected class SendCoordsInvocation extends ActionInvocation{
  233.         @SuppressWarnings("unchecked")
  234.         public SendCoordsInvocation(Service service){
  235.             super(service.getAction("ChangeTo"));
  236.         }
  237.        
  238.         public void setCoords(ChessMove moveCoords) throws InvalidValueException {
  239.             setInput("CompactedValue", moveCoords.packValue());
  240.         }
  241.     }
  242.    
  243.     protected class ReceiveCoordsSubscriptionCallback extends SubscriptionCallback {
  244.         public ReceiveCoordsSubscriptionCallback(@SuppressWarnings("rawtypes") Service service){
  245.             super(service);
  246.         }
  247.  
  248.         @Override
  249.         protected void ended(@SuppressWarnings("rawtypes") GENASubscription sub, CancelReason reason,
  250.                 UpnpResponse resp) {
  251.            
  252.         }
  253.  
  254.         @Override
  255.         protected void established(@SuppressWarnings("rawtypes") GENASubscription sub) {
  256.         }
  257.  
  258.         @SuppressWarnings("rawtypes")
  259.         @Override
  260.         protected void eventReceived(GENASubscription sub) {
  261.             @SuppressWarnings("unchecked")
  262.             Map<String, StateVariableValue> values = sub.getCurrentValues();
  263.             StateVariableValue status = values.get("LastMove");
  264.             int compactedCoords = (Integer) status.getValue();
  265.             ChessMove moveCoords = ChessMove.unpack(compactedCoords);
  266.            
  267.             receivedCoordsLabel.setText(String.format(
  268.                     "%d %d %d %d",
  269.                     moveCoords.startFile,
  270.                     moveCoords.startRank,
  271.                     moveCoords.endFile,
  272.                     moveCoords.endRank
  273.             ));
  274.         }
  275.  
  276.         @Override
  277.         protected void eventsMissed(@SuppressWarnings("rawtypes") GENASubscription sub, int id) {
  278.            
  279.         }
  280.  
  281.         @Override
  282.         protected void failed(@SuppressWarnings("rawtypes") GENASubscription sub, UpnpResponse resp,
  283.                 Exception ex, String message) {
  284.            
  285.         }
  286.     }
  287.  
  288.     @SuppressWarnings("rawtypes")
  289.     private Device otherBoard = null;
  290.  
  291.     private JSpinner startFileSpinner, startRankSpinner;
  292.     private JSpinner endFileSpinner, endRankSpinner;
  293.  
  294.     private JLabel receivedCoordsLabel;
  295.     private JButton sendCoords;
  296.    
  297.     protected UpnpService upnpService;
  298.  
  299.     private SendCoordsInvocation sendCoordsInvocation;
  300.     private SubscriptionCallback receiveCoordsSubscription;
  301.    
  302.     private static final long serialVersionUID = 2166480665114176165L;
  303.  
  304. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement