public void commandAction(Command c, Displayable d) {
    if (c == startCmd) {
      form.deleteAll();
      form.removeCommand(startCmd);
      form.addCommand(byeCmd);

      Thread t =
          new Thread() {

            public void run() {
              startSession();
            }
          };
      t.start();

      //	    startSession();
      return;
    } else if (c == exitCmd) {
      destroyApp(true);
      return;
    } else if (c == byeCmd) {
      form.removeCommand(byeCmd);
      form.addCommand(restartCmd);
      sendBYE();
      return;
    } else if (c == restartCmd) {
      stopListener();
      form.removeCommand(restartCmd);
      form.addCommand(startCmd);
      form.deleteAll();
      form.append(address);
      return;
    }
  }
  public HTTPConnManager(
      final int type,
      final String http,
      BigVector _postData,
      final int handler,
      final HTTPAnswerListener _listener) {
    listener = _listener;
    postData = _postData;
    // Create a preference-ordered list of transports.
    int[] _intTransports = {
      TransportInfo.TRANSPORT_TCP_WIFI,
      TransportInfo.TRANSPORT_BIS_B,
      TransportInfo.TRANSPORT_MDS,
      TransportInfo.TRANSPORT_WAP2,
      TransportInfo.TRANSPORT_TCP_CELLULAR
    };

    // Remove any transports that are not currently available.
    for (int i = 0; i < _intTransports.length; i++) {
      int transport = _intTransports[i];
      if (!TransportInfo.isTransportTypeAvailable(transport)
          || !TransportInfo.hasSufficientCoverage(transport)) {
        Arrays.removeAt(_intTransports, i);
      }
    }

    // Set ConnectionFactory options.
    if (_intTransports.length > 0) {
      _factory.setPreferredTransportTypes(_intTransports);
    }

    _factory.setAttemptsLimit(5);

    // Open a connection on a new thread.
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                DebugStorage.getInstance().Log(0, "HTTPConnManager: open connection to " + http);
                ConnectionDescriptor cd = _factory.getConnection(http);
                if (cd != null) {
                  DebugStorage.getInstance().Log(0, "HTTPConnManager: connection created.");
                  Connection c = cd.getConnection();
                  new HTTPOut(type, postData, c, handler, listener);
                } else {
                  DebugStorage.getInstance()
                      .Log(0, "HTTPConnManager: UNABLE TO CREATE CONNECTION!");
                }
              }
            });
    t.start();
  }
Beispiel #3
0
 public void get() {
   try {
     new Thread(this).start();
     Thread.sleep(10);
   } catch (Exception e) {
   }
 }
  public Location getLocation(int timeout) throws LocationException, InterruptedException {
    /* TODO The timeout might play to the fact that it is still acquiring satellites?
     * I was wondering about that before. Maybe it makes sense to have timeout in SimpleGPS?
     * TODO: Solution! Keep asking for altitude until is positive? (longitude can be negative)
     * Or perhaps just until speed positive? (set those after)
     * TODO: -1 in timeout is supposed to represent the default timeout (GPSListener?)
     * TODO: I don't know if this is supposed to wait for the GPS to provide a new
     * coordinate data or if it is okay to pass the latest cached GPS coordinates.
     * Is the purpose of the timeout that it gets a new updated location that
     * is not the previously returned or cached one?
     */

    if (timeout == 0) throw new IllegalArgumentException("timeout cannot equal 0");

    // Timeout results in LocationException:
    long startTime = System.currentTimeMillis();

    // TODO: Perhaps initialize and test for NaN instead.
    while (gps.getLatitude() == 0 & gps.getLongitude() == 0) {
      if (timeout != -1 & System.currentTimeMillis() - startTime > (timeout * 1000))
        throw new LocationException("GPS timed out");
      Thread.sleep(100); /* NOTE: This might very occasionally cause an error because
			* Thread.yield() seems to cause sentence parsing to start too soon.
			* (try changing sleep() to yield() to see what happens)
			* Perhaps something needs to be synchronized? */
    }

    QualifiedCoordinates qc =
        new QualifiedCoordinates(
            gps.getLatitude(),
            gps.getLongitude(),
            gps.getAltitude(),
            (gps.getHDOP() * 6),
            (gps.getVDOP() * 6));
    Location loc =
        new Location(
            qc,
            gps.getSpeed(),
            gps.getCourse(),
            gps.getTimeStamp(),
            0,
            null); // TODO: Implement location method and extraInfo (0 and null for now)

    return loc;
  }
  protected BTGPSLocationProvider() throws LocationException {

    // TODO: Move this to searchConnect method?
    // TODO: The problem here is that it searches every time. Slow. Need to try Properties?
    // TODO: BIG ONE: Should only connect to GPS that isPaired() (from menu). Will
    // allow some degree of control over which GPS is connects to in classroom.
    try {
      da = LocalDevice.getLocalDevice().getDiscoveryAgent();
      da.startInquiry(DiscoveryAgent.GIAC, this);
    } catch (BluetoothStateException e) {
      throw new LocationException(e.getMessage());
    }

    while (!doneInq) {
      Thread.yield();
    }

    if (btDevice == null) throw new LocationException("No device found");

    String address = btDevice.getBluetoothAddress();
    String btaddy = "btspp://" + address;

    try {
      StreamConnectionNotifier scn = (StreamConnectionNotifier) Connector.open(btaddy);

      if (scn == null) throw new LocationException("Bad BT address");
      StreamConnection c = scn.acceptAndOpen();

      /* This problem below occurred one time for my Holux GPS. The solution was to
       * remove the device from the Bluetooth menu, then find and pair again.
       */
      if (c == null) throw new LocationException("Failed. Try pairing at menu again");
      InputStream in = c.openInputStream();

      if (in != null) {
        gps = new SimpleGPS(in);
        // c.close(); // TODO: Clean up when done. HOW TO HANDLE IN LOCATION?
      }
    } catch (IOException e) {
      throw new LocationException(e.getMessage());
    }
    // Add itself to SimpleGPS as listener
    SimpleGPS.addListener(this);
  }
Beispiel #6
0
  /**
   * Install a suite.
   *
   * @param selectedSuite index into the installList
   */
  private void installSuite(int selectedSuite) {
    MIDletStateHandler midletStateHandler = MIDletStateHandler.getMidletStateHandler();
    MIDletSuite midletSuite = midletStateHandler.getMIDletSuite();
    SuiteDownloadInfo suite;
    String displayName;

    suite = (SuiteDownloadInfo) installList.elementAt(selectedSuite);

    midletSuite.setTempProperty(null, "arg-0", "I");
    midletSuite.setTempProperty(null, "arg-1", suite.url);
    midletSuite.setTempProperty(null, "arg-2", suite.label);

    displayName = Resource.getString(ResourceConstants.INSTALL_APPLICATION);
    try {
      midletStateHandler.startMIDlet("com.sun.midp.installer.GraphicalInstaller", displayName);
      /*
       * Give the create MIDlet notification 1 second to get to
       * AMS.
       */
      Thread.sleep(1000);
      notifyDestroyed();
    } catch (Exception ex) {
      StringBuffer sb = new StringBuffer();

      sb.append(displayName);
      sb.append("\n");
      sb.append(Resource.getString(ResourceConstants.ERROR));
      sb.append(": ");
      sb.append(ex.toString());

      Alert a =
          new Alert(
              Resource.getString(ResourceConstants.AMS_CANNOT_START),
              sb.toString(),
              null,
              AlertType.ERROR);
      a.setTimeout(Alert.FOREVER);
      display.setCurrent(a, urlTextBox);
    }
  }
Beispiel #7
0
    public void run() {
      while (connection != null) {
        synchronized (lock) {
          FileItem fileItem = Scheduler.peekQueue();
          try {
            Thread.sleep(500);
          } catch (InterruptedException e2) {
            e2.printStackTrace();
          }
          FileInputStream fis = null;
          BufferedInputStream bis = null;
          if (fileItem != null) {
            try {
              try {
                Thread.sleep(100);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              sendString(fileItem.toString());
              if (fileItem.getCmd() == Command.cp) {
                File file = new File(fileItem.getName());
                long length = file.length();
                if (length > Integer.MAX_VALUE) {
                  System.out.println("File is too large.");
                }
                byte[] bytes = new byte[buffersize];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                System.out.println("Length: " + length);
                int count;
                int counter = 0;
                while (length > 0 && ((count = bis.read(bytes)) > 0)) {
                  try {
                    Thread.sleep(100);
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                  }
                  outStream.write(bytes, 0, count);
                  outStream.flush();
                  length -= count;
                  counter++;
                  System.out.println("Length: " + length);
                }

                System.out.println("Outside file sending loop");
                System.out.println("Counter: " + counter);
                outStream.flush();
                fis.close();
                bis.close();
              }
              outStream.flush();
              Scheduler.pollFromQueue();
            } catch (IOException e) {
              e.printStackTrace();
              try {
                fis.close();
                bis.close();
              } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
              }
            }
          }
        }
      }
    }
  public void setLocationListener(
      LocationListener listener, int interval, int timeout, int maxAge) {

    // * Stop all previous listener threads *
    listenerRunning = false;
    if (listyThread != null) {
      while (listyThread.isAlive()) {
        Thread.yield();
      } // End old thread
      listyThread = null; // Discard the listener thread instance
    }

    // * Remove any listeners from GPSListener *
    if (listener == null) {
      // Remove current listener from SimpleGPS
      SimpleGPS.removeListener(gpsl);
      gpsl = null;
      return; // No listener provided, so return now so it dosn't make a new one
    }

    // * Inner classes need final variables *
    final int to = timeout;
    final LocationListener l = listener;
    final LocationProvider lp = this;
    final int delay = interval * 1000; // Oddly interval is in seconds, and not float

    // Make new thread here and start it if interval > 0, else if -1
    // then use the GPSListener interface.
    if (interval > 0) { // Notify according to interval by user
      listyThread =
          new Thread() {
            public void run() {
              while (listenerRunning) {
                try {
                  // TODO: Probably only notify if location changed? Need to compare to old.
                  // TODO: Make helper method since this is used below too.
                  l.locationUpdated(lp, lp.getLocation(to));
                  Thread.sleep(delay);
                } catch (LocationException e) {
                  // TODO Auto-generated catch block
                } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                }
              }
            }
          };
      listyThread.setDaemon(true); // so JVM exits if thread is still running
      listenerRunning = true;
      listyThread.start();
    } else if (interval < 0) { // If interval is -1, use default update interval
      // In our case, update as soon as new coordinates are available from GPS (via GPSListener)
      // TODO: Alternate method: Use GPSListener for ProximityListener and this.
      gpsl =
          new GPSListener() {
            public void sentenceReceived(NMEASentence sen) {
              // Check if GGASentence. Means that new location info is ready
              if (sen.getHeader().equals(GGASentence.HEADER)) {
                try {
                  // TODO: Probably only notify if location changed? Need to compare to old.
                  l.locationUpdated(lp, lp.getLocation(to));
                } catch (LocationException e) {
                  // TODO Auto-generated catch block
                } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                }
              }
            }
          };
      SimpleGPS.addListener(gpsl);
    }

    // TODO: Need to implement LocationListener.providerStateChanged()
  }
  /**
   * Task execution code: <br>
   * ---------- <br>
   * Performed operations: <br>
   *
   * <ul type="disc">
   *   <li>Add alarm to position strings, if necessary;
   *   <li>Send string;
   *   <li>Check the number of sent strings.
   * </ul>
   */
  public void run() {

    list = new BCListenerCustom();
    list.addInfoStato(infoS);
    BearerControl.addListener(list);

    while (!infoS.isCloseUDPSocketTask()) {

      // if(false){
      if ((infoS.getInfoFileString(TrkState).equals("ON")
              || (infoS.getInfoFileString(TrkState)).equalsIgnoreCase("ON,FMS"))
          && infoS.getInfoFileString(GPRSProtocol).equals("UDP")
          && ((infoS.getInfoFileInt(TrkIN) != infoS.getInfoFileInt(TrkOUT))
              || !infoS.getDataRAM().equals(""))) {

        exitTRKON = false;

        try {

          // Indicates if GPRS SOCKET is ACTIVE
          // System.out.println("TT*UDPSocketTask: START");
          infoS.setIfsocketAttivo(true);
          destAddressUDP =
              "datagram://"
                  + infoS.getInfoFileString(DestHost)
                  + ":"
                  + infoS.getInfoFileString(DestPort);

          /*
           * Once this task has been started, it is completely
           * finished before proceeding to a re-use, even if the
           * timeout expires (so there may be a FIX GPRS timeout
           * expired!)
           */
          try {
            try {
              while (!InfoStato.getCoda()) Thread.sleep(1L);
            } catch (InterruptedException e) {
            }

            if (infoS.getInfoFileInt(TrkIN) == infoS.getInfoFileInt(TrkOUT)) {
              outText = infoS.getDataRAM();
              ram = true;
            } else {
              ram = false;
              temp = infoS.getInfoFileInt("TrkOUT");
              System.out.println("TT*UDPSocketTask: pointer out - " + temp);
              if ((temp >= codaSize) || (temp < 0)) temp = 0;
              outText = infoS.getRecord(temp);
              new LogError("TT*UDPSocketTask: pointer out - " + temp + " " + outText);
              System.out.println("TT*UDPSocketTask: data in queue: " + outText);
            }

            System.out.println("TT*UDPSocketTask: string to send through GPRS:\r\n" + this.outText);

            ctrlSpeed = infoS.getSpeedForTrk();
            if (debug_speed) {
              ctrlSpeed = infoS.getSpeedGree();
              System.out.println("SPEED " + ctrlSpeed);
            }
            try {
              val_insensibgps = Integer.parseInt(infoS.getInfoFileString(InsensibilitaGPS));
            } catch (NumberFormatException e) {
              val_insensibgps = 0;
            }
            // new LogError("Actual speed: " + ctrlSpeed + ". Val insens: " + val_insensibgps);

            if (ram) {

              // System.out.println("ACTUAL SPEED: " + this.ctrlSpeed);
              // System.out.println("outText.indexOf(ALARM) " + (this.outText.indexOf("ALARM") >
              // 0));
              // System.out.println("outText.indexOf(ALIVE) " + (this.outText.indexOf("ALIVE") >
              // 0));
              // System.out.println("SPEED LIMIT: " + this.val_insensibgps);
              // System.out.println("PREVIOUS MESSAGE IS ALIVE: " + this.infoS.getPreAlive());
              // System.out.println("SPEED LIMIT: " + this.val_insensibgps);
              // System.out.println("PREVIOUS SPEED: " + this.infoS.getPreSpeedDFS());

              if (this.ctrlSpeed > this.val_insensibgps) {
                System.out.println("Speed check ok.");
                infoS.settrasmetti(true);
                if (this.infoS.getInvioStop()) {
                  infoS.setApriGPRS(true);
                }
                infoS.setInvioStop(false);
              } else {
                if ((outText.indexOf("ALARM") > 0) || (outText.indexOf("ALIVE") > 0)) {
                  System.out.println("Alarm");
                  infoS.settrasmetti(true);
                  infoS.setApriGPRS(true);
                } else {

                  if ((!infoS.getPreAlive())
                      && (ctrlSpeed <= val_insensibgps)
                      && (infoS.getPreSpeedDFS() > val_insensibgps)) {

                    System.out.println(
                        "Speed check less then insensitivity, previous speed is greater");
                    infoS.settrasmetti(true);
                    if (infoS.getInvioStop() == true) {
                      infoS.setApriGPRS(true);
                    }
                    infoS.setInvioStop(false);

                  } else {

                    System.out.println("Speed check failed.");
                    if (infoS.getInvioStop() == false) {
                      System.out.println("Send stop coordinate.");
                      infoS.settrasmetti(true);
                      infoS.setInvioStop(true);
                      infoS.setChiudiGPRS(true);

                      // new LogError("Send stop.");
                    }
                  }
                }
              }
              if (this.outText.indexOf("ALIVE") > 0) {
                System.out.println("ALIVE MESSAGE");
                infoS.setPreAlive(true);
              } else {
                infoS.setPreAlive(false);
                System.out.println("NO ALIVE MESSAGE");
              }
            } else {
              // new LogError("From store.");

              infoS.settrasmetti(true);

              infoS.setChiudiGPRS(false);
            }

            // new LogError("Transmission status: " + infoS.gettrasmetti());

            if (infoS.gettrasmetti() == true) {

              infoS.settrasmetti(false);

              if (infoS.getApriGPRS() == true) {

                close = false;
                infoS.setTRKstate(true);
                try {
                  semAT.getCoin(5);
                  infoS.setATexec(true);
                  mbox2.write("at^smong\r");
                  while (infoS.getATexec()) {
                    Thread.sleep(whileSleep);
                  }
                  infoS.setATexec(true);
                  mbox2.write("at+cgatt=1\r");
                  while (infoS.getATexec()) {
                    Thread.sleep(whileSleep);
                  }
                  semAT.putCoin();
                } catch (Exception e) {
                }

                // Open GPRS Channel
                try {
                  udpConn = (UDPDatagramConnection) Connector.open(destAddressUDP);
                } catch (Exception e) {
                  System.out.println("TT*UDPSocketTask: Connector.open");
                }
                infoS.setApriGPRS(false);
              }

              try {
                // mem2 = r.freeMemory();
                // System.out.println("Free memory after allocation: " + mem2);
                if ((outText == null) || (outText.indexOf("null") >= 0)) {
                  outText =
                      infoS.getInfoFileString(Header)
                          + ","
                          + infoS.getInfoFileString(IDtraker)
                          + defaultGPS
                          + ",<ERROR>*00";
                  buff = outText.getBytes();
                }
                System.out.println("OPEN DATAGRAM");
                System.out.println(outText);
                dgram = udpConn.newDatagram(outText.length());
                buff = new byte[outText.length()];
                System.out.println("SEND DATAGRAM");
                buff = outText.getBytes();
                new LogError("outText = " + outText);
                dgram.setData(buff, 0, buff.length);
                udpConn.send(dgram);
                int gprsCount = 0;
                answer = "";
                String ack = infoS.getInfoFileString(Ackn);
                if (!infoS.getInfoFileString(Ackn).equals("")) {
                  while (true) {
                    dgram.reset();
                    dgram.setLength(infoS.getInfoFileString(Ackn).length() + 1);
                    udpConn.receive(dgram);
                    byte[] data = dgram.getData();
                    answer = new String(data);
                    answer = answer.substring(0, ack.length());
                    if (debug) {
                      System.out.println("ACK: " + answer);
                    }
                    if (answer.equals(ack)) {
                      new LogError("ACK");
                      if (debug) System.out.println("ACK RECEIVED");
                      break;
                    } else {
                      if (debug) System.out.println("WAITING ACK");
                      try {
                        Thread.sleep(1000);
                      } catch (InterruptedException e) {
                      }
                      gprsCount++;
                    }
                    if (gprsCount > 15) {
                      new LogError("NACK");
                      infoS.setReboot();
                      errorSent = true;
                      break;
                    }
                  }
                }

              } catch (Exception err) {
                System.out.println("TT*UDPSocketTask: Exception err");
                new LogError("TT*UDPSocketTask: Exception during out text" + err.getMessage());
                infoS.setReboot();
                errorSent = true;
                break;
              }
              // new LogError(outText);
              if (debug) System.out.println(outText);

              if (infoS.getChiudiGPRS() == true) {

                infoS.setTRKstate(false);
                try {
                  System.out.println("TT*UDPSocketTask: close UDP");
                  udpConn.close();
                } catch (NullPointerException e) {
                  infoS.setChiudiGPRS(false);
                }
                infoS.setChiudiGPRS(false);
              }
            }

            System.out.println("BEARER: " + infoS.getGprsState());
            if (!infoS.getGprsState()) {
              errorSent = true;
              System.out.println("BEARER ERROR");
              new LogError("BEARER ERROR");
            }

            if (ram) {
              if (!errorSent) {
                infoS.setDataRAM("");
              }
            } else {
              if (!errorSent) {
                temp++;
                if (temp >= codaSize || temp < 0) temp = 0;
                infoS.setInfoFileInt(TrkOUT, "" + temp);
                file.setImpostazione(TrkOUT, "" + temp);
                InfoStato.getFile();
                file.writeSettings();
                InfoStato.freeFile();
              }
              errorSent = false;
            }
            InfoStato.freeCoda();

            infoS.setIfsocketAttivo(false);
            Thread.sleep(100);
            if (errorSent) {
              close = true;
              semAT.putCoin(); // release AT interface
              infoS.setIfsocketAttivo(false);
              infoS.setApriGPRS(false);
              infoS.setChiudiGPRS(false);
            }
            // r.gc(); // request garbage collection

            // mem2 = r.freeMemory();
            // System.out.println("Free memory after collecting" + " discarded Integers: " + mem2);

          } catch (IOException e) {
            close = true;
            String msgExcept = e.getMessage();
            System.out.println("TT*UDPSocketTask: exception: " + msgExcept);

            // new LogError("SocketGPRStask IOException: " + e);
            infoS.setIfsocketAttivo(false);

            infoS.setApriGPRS(false);
            infoS.setChiudiGPRS(false);

          } catch (EmptyStackException e) {
            close = true;
            // System.out.println("exception: " + e.getMessage());
            e.printStackTrace();

            // new LogError("SocketGPRStask EmptyStackException");
            infoS.setIfsocketAttivo(false);

            infoS.setApriGPRS(false);
            infoS.setChiudiGPRS(false);
          } // catch

        } catch (Exception e) {
          close = true;
          // new LogError("SocketGPRSTask generic Exception");
          infoS.setIfsocketAttivo(false);

          infoS.setApriGPRS(false);
          infoS.setChiudiGPRS(false);
        }

        if (close) {

          try {
            semAT.getCoin(5);
            infoS.setATexec(true);
            mbox2.write("at^smong\r");
            while (infoS.getATexec()) {
              Thread.sleep(whileSleep);
            }
            semAT.putCoin();
          } catch (Exception e) {
          }

          try {
            // System.out.println("***************CLOSE******************");
            try {
              udpConn.close();
            } catch (NullPointerException e) {

            }
            // System.out.println("***************CLOSED******************");

            infoS.setTRKstate(false);
            infoS.setEnableCSD(true);

            semAT.getCoin(5);
            // Close GPRS channel
            // System.out.println("SocketGPRSTask: KILL GPRS");
            infoS.setATexec(true);
            mbox2.write("at+cgatt=0\r");
            while (infoS.getATexec()) {
              Thread.sleep(whileSleep);
            }

            semAT.putCoin();

            Thread.sleep(5000);
          } catch (InterruptedException e) {

          } catch (IOException e) {

          } catch (Exception e) {

          }
          System.out.println("WAIT - DISCONNECT GPRS");
          for (countDownException = 0; countDownException < 100; countDownException++) {
            if (infoS.isCloseUDPSocketTask()) break;
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
          }
          infoS.setApriGPRS(true);
        }
      } else {

        try {
          if (infoS.getInfoFileString(TrkState).equals("OFF")) {

            infoS.setTRKstate(false);
            infoS.setEnableCSD(true);
            semAT.putCoin(); // release AT interface
            try {
              semAT.getCoin(5);
              // Close GPRS channel
              // System.out.println("SocketGPRSTask: TRK OFF KILL GPRS");
              infoS.setATexec(true);
              mbox2.write("at+cgatt=0\r");
              while (infoS.getATexec()) {
                Thread.sleep(whileSleep);
              }
              semAT.putCoin();
            } catch (InterruptedException e) {
            }
          }
          Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
      }
    } // while
  } // run