package charly.demo;

import charly.client.*;
import charly.server.devices.ChGpibTimeOutException;

/** SRQ-test-application. 
  * You can find the  <a href="doc-files/ChSimpleSrq.java.html">source here</a>.
  * 
  * <ul>The Steps:
  *   <li>create Charly-task- and Charly-gpib-objects.</li>
  *   <li>add the SRQ sending device to the task as a resource</li>
  *   <li>add a gpibListener</li>
  *   <li>connect task- and gpib-object and start task.</li>
  *   <li>call checkSrq() for the SRQ sending device</li>
  *   <li>ask device to send SRQ</li>
  *   <li>result: the GpibListener.srq()-method has to handle the SRQ-Event</li>
  * </ul>
  */
public class ChSimpleSrq implements ChGpibListener
{
  ChTask task;
  ChGpibClient gpib;
  ChConnect server;
  
  public static void main(String args[])
    throws Exception
  {
    System.out.println("usage: ChSimpleSrq [TCP/IP-address]");
    ChConnect server=new ChConnect(args.length==0?"localhost":args[0]);
    
    new ChSimpleSrq(server).start();
  }
  
  // Konstruktor
  public ChSimpleSrq(ChConnect server)
    throws Exception  // throws all exceptions
  {
    this.server=server;
    task=new ChTask("Simple Srq");
    gpib=new ChGpibClient(server);
    
    // reserve device nr 7 (Oszilloskop)
    task.addResource(server, gpib.getResourceName(7));
        // resource: Gpib-device nr: 7 (Oszilloskop) on server: conn
        
    gpib.addGpibListener(this); // adds this as a listener for srq
    
  }      
  
  public void start()
    throws Exception // throws all the exceptions except for timeout 
  {       
    task.start(true);  // starts task and waits for reservation of device 
    
    gpib.setTask(task); // gpib works on my task
    
    try
    {      
      gpib.checkSrq(7); // expects to get an SRQ
      gpib.send(7,":AUT;*OPC"); // sending ":AUT;*OPC" to the device nr 7 (Oszilloskop)
        // causing this device to produce an SRQ after performing :AUT
        
    } catch(ChGpibTimeOutException e)
    {
      System.out.println("Device timed out!");
      gpib.uncheckSrq(7); // do not expect SRQ any more
      task.stop(); // task is not needed any more
    }
    
    System.out.println("bye");
    System.exit(0); // This is not really necessary, but because it 
      // takes some time until that the system detects that there is 
      // no activity any more on the RMI-system, this method call
      // shortens the waiting time immensely
  }
  
  public void srq(ChGpibEvent ev)
  {
    System.out.println("Received SRQ from device Nr:"+ ev.getDvcAddr());
    try
    {
      task.stop(); // end of task
    } catch(Exception e)
    {}
  }
}