@Override public void start() { super.start(); setRunning(true); Log.d(TAG, "Starting Location sensor"); // Use any provider (LOCATION, Network or Passive) addLocationListenerWithAllProviders(); IntentFilter intentFilter = new IntentFilter(LOCATION_UPDATE_ACTION); getContext().registerReceiver(locationReceiver, intentFilter); Log.d(TAG, "Starting Location sensor [done]"); Sensor.setSensorStatus(Sensor.SENSOR_LOCATION, Sensor.SENSOR_ON); refreshStatus(); if (stpe == null) { stpe = new ScheduledThreadPoolExecutor(1); stpe.scheduleAtFixedRate(controller, 0, Utilities.LOCATION_CHECK_TIME, TimeUnit.MILLISECONDS); /*stpe.scheduleAtFixedRate(controller, MAX_TIME_WITHOUT_NEW_LOCATION, MAX_TIME_WITHOUT_NEW_LOCATION, TimeUnit.MILLISECONDS);*/ } }
@Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Object hint = new Object(); if (isAntialiased()) { hint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } translation = getTranslation(); Color oldColor = g2.getColor(); g2.setColor(new Color(230, 230, 250)); g2.fill(translation.createTransformedShape(getShape())); g2.setColor(Color.BLACK); g2.draw(translation.createTransformedShape(getShape())); if (isShowingSensors) { for (Iterator<Sensor> sIter = sensors.iterator(); sIter.hasNext(); ) { Sensor s = (Sensor) sIter.next(); s.paintComponent(g2); } } if (isShowingStatusFrame) { paintStatusFrame(g2); } g2.setColor(oldColor); if (isAntialiased()) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, hint); } }
public void moveForwardToWall(double pow, int timeout) throws InterruptedException { double angle = Math.abs(sensor.getGyroYaw()); double startAngle = angle; double power = pow; ElapsedTime time = new ElapsedTime(); time.startTime(); while (Math.abs(angle - startAngle) < 10 && time.milliseconds() < timeout) { angle = Math.abs(sensor.getGyroYaw()); opMode.telemetry.addData("LeftPower", motorBL.getPower()); opMode.telemetry.addData("RightPower", motorBR.getPower()); opMode.telemetry.update(); if (angle < startAngle - 1) { startMotors((power * .75), power); } else if (angle > startAngle + 1) { startMotors(power, (power * .75)); } else { startMotors(power, power); } opMode.idle(); } stopMotors(); angleError = sensor.getGyroYaw(); opMode.telemetry.update(); }
/** {@hide} */ public SystemSensorManager(Looper mainLooper) { mMainLooper = mainLooper; synchronized (sListeners) { if (!sSensorModuleInitialized) { sSensorModuleInitialized = true; nativeClassInit(); // initialize the sensor list sensors_module_init(); final ArrayList<Sensor> fullList = sFullSensorsList; int i = 0; do { Sensor sensor = new Sensor(); i = sensors_module_get_next_sensor(sensor, i); if (i >= 0) { // Log.d(TAG, "found sensor: " + sensor.getName() + // ", handle=" + sensor.getHandle()); fullList.add(sensor); sHandleToSensor.append(sensor.getHandle(), sensor); } } while (i > 0); sPool = new SensorEventPool(sFullSensorsList.size() * 2); sSensorThread = new SensorThread(); } } }
/** * reads an AOT Kx LUT (BBDR breadboard procedure GA_read_LUT_AOD) * * <p>A LUT value can be accessed with lut.getValue(new double[]{wvlValue, aotValue, hsfValue, * aziValue, szaValue, vzaValue, parameterValue}); * * @param sensor The sensor * @return LookupTable * @throws java.io.IOException when failing to real LUT data */ public static LookupTable getAotKxLookupTable(Sensor sensor) throws IOException { ImageInputStream iis = Luts.getAotKxLutData(sensor.getInstrument()); try { // read LUT dimensions and values float[] vza = Luts.readDimension(iis); int nVza = vza.length; float[] sza = Luts.readDimension(iis); int nSza = sza.length; float[] azi = Luts.readDimension(iis); int nAzi = azi.length; float[] hsf = Luts.readDimension(iis); int nHsf = hsf.length; float[] aot = Luts.readDimension(iis); int nAot = aot.length; float[] kx = new float[] {1.0f, 2.0f}; int nKx = kx.length; float[] wvl = sensor.getWavelength(); final int nWvl = wvl.length; float[] lut = new float[nKx * nVza * nSza * nAzi * nHsf * nAot * nWvl]; iis.readFully(lut, 0, lut.length); return new LookupTable(lut, wvl, aot, hsf, azi, sza, vza, kx); } finally { iis.close(); } }
/** The sensor manager determines what all of the sensors are able to confirm. */ @Override public Environment apply(Environment t) { /* * If we have any omniscient sensors, they will be the first sensor on * the list. */ Sensor firstSensor = sensors.peek(); if (firstSensor instanceof OmniscientSensor) { return firstSensor.apply(t); } /* * Otherwise, extract the different types of sensor */ LinkedList<ProximitySensor> proximitySensors = new LinkedList<>(); for (Sensor sensor : sensors) { if (sensor instanceof ProximitySensor) { proximitySensors.add((ProximitySensor) sensor); } } /* * If we have no other sensors, throw a problem */ if (proximitySensors.size() == 0) { throw new RuntimeException("Sensor was not omniscient!"); } return proximitySensors.getFirst().apply(t); }
public void publish(SensorObservation observation, SensorMetaData sensorMetaData) { logger.warn("asked to publish"); logger.warn(observation); logger.warn(sensorMetaData); if (true) return; // create an Observation object Observation obs = new Observation(); logger.warn(sensorMetaData.getSensorID()); // set SensorURL of observation Sensor sensor2 = lsmStore.getSensorById(sensorMetaData.getSensorID()); obs.setSensor(sensor2.getId()); // set time when the observation was observed. In this example, the time is current local time. obs.setTimes(observation.getTime()); ObservedProperty obvTem = new ObservedProperty(); obvTem.setObservationId(obs.getId()); obvTem.setPropertyName(observation.getPropertyName()); obvTem.setValue(observation.getValue()); obvTem.setUnit(observation.getUnit()); obs.addReading(obvTem); lsmStore.sensorDataUpdate(obs); }
public void moveFowardToLine(double ri, double le, int timeout) throws InterruptedException { double angle; double startAngle = Math.abs(sensor.getGyroYaw()); opMode.telemetry.update(); setNullValue(); ElapsedTime time = new ElapsedTime(); time.startTime(); while (!sensor.isLeftLine() && time.milliseconds() < timeout) { angle = Math.abs(sensor.getGyroYaw()); opMode.telemetry.addData("LeftPower", motorBL.getPower()); opMode.telemetry.addData("RightPower", motorBR.getPower()); opMode.telemetry.update(); // if(angle < startAngle - 2) { // startMotors((power * .75), power); // } else if(angle > startAngle + 2) { // startMotors(power, (power * .75)); // } else { // startMotors(power, power); // } startMotors(ri, le); opMode.idle(); } stopMotors(); opMode.telemetry.update(); angleError = sensor.getGyroYaw(); }
@Override public void moveComponent() { inMotion = true; direction = body.getRotation(); net.phys2d.math.ROVector2f p = body.getPosition(); x = p.getX(); y = p.getY(); for (Iterator<Sensor> sIter = sensors.iterator(); sIter.hasNext(); ) { Sensor s = (Sensor) sIter.next(); s.moveComponent(); } final double distance = Util.euclideanDistance(lastX, lastY, x, y); final double velDist = lastVelocity - getSpeed() > 0 ? lastVelocity - getSpeed() : 0; if (velDist > 10) { crashmeter += velDist; } if (velDist > maxDeceleration) { maxDeceleration = velDist; } overallDeceleration += velDist; lastVelocity = getSpeed(); odometer += distance; lastX = x; lastY = y; }
/** * sets segment current orientation using TRIAD algorithm * * @param sensor sensor of corresponding sensor */ public void setSegmentOrientationTRIAD(Sensor sensor) { float[][] rotMat = SensorDataProcessing.getRotationTRIAD(sensor.getAccNorm(), sensor.getMagNorm()); // rotate each segment for (int i = 0; i < 4; i++) { SensorDataProcessing.multiplyMatrix(rotMat, initialCross[i], cross[i]); } }
@Override public void stop() { pause(); stpe.shutdown(); super.stop(); Sensor.setSensorStatus(Sensor.SENSOR_LOCATION, Sensor.SENSOR_OFF); refreshStatus(); }
/** * Decorator pattern to construct a new HTMSensor wrapping the specified {@link Sensor}. * * @param sensor */ public HTMSensor(Sensor<T> sensor) { this.delegate = sensor; this.sensorParams = sensor.getSensorParams(); header = new Header(sensor.getInputStream().getMeta()); if (header == null || header.size() < 3) { throw new IllegalStateException("Header must always be present; and have 3 lines."); } createEncoder(); }
@Override protected ArrayList<Sensor> doInBackground(String... params) { // TODO Auto-generated method stub Log.d("ask", "running"); ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("_id", userId)); String result = null; // String url = "http://10.189.93.95:3000/auth/login"; String url = "http://smartwaterwatch.mybluemix.net/sensor/availableSensors"; BufferedReader in = null; StringBuffer sb = new StringBuffer(""); try { Log.d("Email in Home", "" + userId); HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(url); Log.d("2", ""); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); Log.d("3", ""); request.setEntity(formEntity); Log.d("4", ""); HttpResponse response = client.execute(request); Log.d("5", ""); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); Log.d("6", ""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); } catch (Exception e) { } result = sb.toString(); Log.d("response of smartwatch", "" + result); ArrayList<Sensor> sensorArrayList = new ArrayList<>(); try { JSONArray sensorArray = new JSONArray(result); Log.d("SensorArray", "" + sensorArray); for (int i = 0; i < sensorArray.length(); i++) { JSONObject sensorObject = sensorArray.getJSONObject(i); Sensor sensor = new Sensor(); sensor.setSensorName(sensorObject.getString("sensorName")); sensor.setSensorType(sensorObject.getString("sensorType")); sensor.setSensorStatus(sensorObject.getString("activated")); sensorArrayList.add(sensor); } } catch (Exception e) { Log.d("Exception", "" + e); } return sensorArrayList; }
public static void genDummieData() { Session ses = HibernateUtil.getSessionFactory().openSession(); ses.beginTransaction(); // du data Location l1 = new Location(); l1.setLocationName("Ubicacion principal"); Location l2 = new Location(); l2.setLocationName("Cochera"); Location l3 = new Location(); l3.setLocationName("Patio"); ses.save(l1); ses.save(l2); ses.save(l3); User u1 = new User(); u1.setUserName("_Leafhouse"); u1.setUserLeafHouse(true); u1.setUserPassword("weaadasdad"); u1.setUserEmail("*****@*****.**"); u1.setUserAdmin(true); ses.save(u1); Sensor s1 = new Sensor(); s1.setSensorLocation(l3); s1.setSensorName("Sensor puerta"); s1.setSensorGpioPin(1); s1.setSensorType(SensorType.EVENT_FIRED); ses.save(s1); for (int i = 0; i < 20; i++) { SensorState ss = new SensorState(); ss.setFireDate(Calendar.getInstance()); ss.setSecurityBreach(false); ss.setSensor(s1); ss.setUser(u1); ses.save(ss); } SecurityState sss1 = new SecurityState(); sss1.setSecurityEnabled(true); sss1.setUser(u1); sss1.setModifiedDate(Calendar.getInstance()); ses.save(sss1); SecurityState sss2 = new SecurityState(); sss2.setSecurityEnabled(false); sss2.setUser(u1); sss2.setModifiedDate(Calendar.getInstance()); ses.save(sss2); // end ses.getTransaction().commit(); ses.close(); }
public Segment getSegmentForSensor(Sensor s) throws Exception { int ind = s.get_SegmentIndex() * 2; if (s.get_SensorType() == SensorType.Outgoing) ind += 1; if (ind >= _segments.size()) throw new Exception("Segment does not exist on this route. Sensor: " + s); return _segments.get(ind); }
private boolean disableSensorLocked(Sensor sensor) { for (ListenerDelegate i : sListeners) { if (i.hasSensor(sensor)) { // not an error, it's just that this sensor is still in use return true; } } String name = sensor.getName(); int handle = sensor.getHandle(); return sensors_enable_sensor(sQueue, name, handle, SENSOR_DISABLE); }
@Test public void shouldStoreLastMeasurementForEachSensor() { triggerMeasurement("LHC", 150); triggerMeasurement("LHC2", 123); Sensor sensor2 = mock(Sensor.class); when(sensor2.getSensorName()).thenReturn("LHC2"); assertThat(sessionManager.getNow(sensor), equalTo(150.0)); assertThat(sessionManager.getNow(sensor2), equalTo(123.0)); }
@Test public void should_sensor_msg_start_with_motion_detected_in_when_sensor_tripped_and_type_motion() throws Exception { // given sensor = new MotionSensor("1", "here", MOTION); // when sensor.trip(); final String sensorMessage = sensor.getSensorMessage(); // then assertThat(sensorMessage.startsWith("Motion detected in "), is(true)); }
@Test public void should_sensor_msg_end_with_is_on_fire_when_sensor_tripped_and_type_fire() throws Exception { // given sensor = new FireSensor("1", "here", FIRE); // when sensor.trip(); final String sensorMessage = sensor.getSensorMessage(); // then assertThat(sensorMessage.endsWith(" is on FIRE!"), is(true)); }
@Test public void should_sensor_msg_end_with_is_ajar_when_sensor_tripped_and_type_window() throws Exception { // given sensor = new WindowSensor("1", "here", WINDOW); // when sensor.trip(); final String sensorMessage = sensor.getSensorMessage(); // then assertThat(sensorMessage.endsWith(" is ajar"), is(true)); }
@Test public void should_sensor_msg_end_with_is_open_when_sensor_tripped_and_type_door() throws Exception { // given sensor = new DoorSensor("1", "here", DOOR); // when sensor.trip(); final String sensorMessage = sensor.getSensorMessage(); // then assertThat(sensorMessage.endsWith(" is open"), is(true)); }
private boolean enableSensorLocked(Sensor sensor, int delay) { boolean result = false; for (ListenerDelegate i : sListeners) { if (i.hasSensor(sensor)) { String name = sensor.getName(); int handle = sensor.getHandle(); result = sensors_enable_sensor(sQueue, name, handle, delay); break; } } return result; }
private static Sensor createSensor(Element element) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Sensor value = (Sensor) element; value.setType(Element.Type.sensor.name()); em.persist(value); em.getTransaction().commit(); em.close(); return value; }
private void publicaSensor(Gateway gateway, Sensor sensor) throws Exception { // make sure cookies is turn on CookieHandler.setDefault(new CookieManager()); HTTPClient http = new HTTPClient(); List<NameValuePair> postp = new ArrayList<>(); postp.add(new BasicNameValuePair("login", "huberto")); postp.add(new BasicNameValuePair("password", "99766330")); http.sendPost(this.urlLogin, postp); List<NameValuePair> SensorParams = new ArrayList<>(); SensorParams.add(new BasicNameValuePair("sensor_nome", sensor.getNome())); SensorParams.add(new BasicNameValuePair("sensor_desc", sensor.getDescricao())); SensorParams.add(new BasicNameValuePair("sensor_modelo", sensor.getModelo())); SensorParams.add(new BasicNameValuePair("sensor_precisao", sensor.getPrecisao())); SensorParams.add(new BasicNameValuePair("sensor_tipo", sensor.getTipo())); SensorParams.add( new BasicNameValuePair("sensor_servidorborda", Integer.toString(this.ServidorBordaID))); SensorParams.add(new BasicNameValuePair("sensor_gateway", Integer.toString(gateway.getId()))); String result = http.GetPageContent(this.insertSensorURI, SensorParams); // System.out.println(result); String publicType = result.split(":")[0]; String sensorID = result.split(":")[1]; sensor.setId(Integer.parseInt(sensorID)); if (null != publicType) switch (publicType) { case "insert": System.out.println( "-> Sensor " + sensor.getNome() + "(" + sensor.getId() + ") cadastrado no Servidor de Contexto com sucesso."); break; case "update": System.out.println( "-> Sensor " + sensor.getNome() + "(" + sensor.getId() + ") atualizado no Servidor de Contexto com sucesso."); break; } }
@Test public void check_should_set_alarm_off_when_pressure_is_in_range() { when(sensorMock.popNextPressurePsiValue()).thenReturn(17.00); alarm.check(); assertThat(alarm.isAlarmOn(), is(false)); when(sensorMock.popNextPressurePsiValue()).thenReturn(21.00); alarm.check(); assertThat(alarm.isAlarmOn(), is(false)); }
public void rotatePB(double pow, int deg) throws InterruptedException { double power = pow; double angleTo = deg; double error; double inte = 0; double inteNoE = 0; double der; double currentAngle = sensor.getGyroYaw(); double previousError = angleTo - currentAngle; opMode.telemetry.addData("Current Angle", currentAngle + ""); opMode.telemetry.addData("Angle To", angleTo + ""); opMode.telemetry.update(); opMode.resetStartTime(); currentAngle = 0; while (Math.abs(currentAngle) < Math.abs(angleTo) - 2) { currentAngle = sensor.getGyroYaw(); error = Math.abs(angleTo) - Math.abs(currentAngle); opMode.telemetry.addData("error", error); power = (pow * (error) * .005) + .1; // update p values inte = ((opMode.getRuntime()) * error * .0025); // update inte value inteNoE = ((opMode.getRuntime()) * .05); der = (error - previousError) / opMode.getRuntime() * 0; // update der value power = power + inteNoE + der; if (angleTo > 0) power *= -1; Range.clip(power, -1, 1); startMotors(-power, power); opMode.telemetry.addData("PID", power); // opMode.telemetry.addData("integral", inte); opMode.telemetry.addData("integral without error", inteNoE); opMode.telemetry.addData("angle", currentAngle); opMode.telemetry.update(); previousError = error; opMode.idle(); } stopMotors(); opMode.telemetry.addData("finished", "done"); opMode.telemetry.update(); }
private void mockSensors() { sessionManager.locationHelper = mock(LocationHelper.class); sessionManager.audioReader = mock(SimpleAudioReader.class); sessionManager.externalSensors = mock(ExternalSensors.class); sessionManager.eventBus = mock(EventBus.class); sessionManager.sensorManager = mock(SensorManager.class); sensor = mock(Sensor.class); when(sensor.isEnabled()).thenReturn(true); when(sensor.getSensorName()).thenReturn("LHC"); when(sessionManager.locationHelper.getLastLocation()).thenReturn(location); when(sessionManager.sensorManager.getSensorByName(Mockito.any(String.class))) .thenReturn(sensor); }
public void ajustaTemperatura() { int interno = 0, externo = 0; double resultado; for (Sensor i : mediador.getSensoresInternos()) { interno += i.getQtdPessoas(); } for (Sensor j : mediador.getSensoresExternos()) { externo += j.getTemperaturaExterna(); } resultado = TEMP_MEDIA - ((interno / mediador.getSensoresInternos().size()) + (externo / mediador.getSensoresExternos().size())); System.out.println(resultado); }
private void jButton1ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed // Inicializando valores sensor.setUbicacion(JUbicacion.getText()); sensor.setServidor(JServidor.getText()); sensor.setVelocidadMaxima(Integer.parseInt(JVelocidad.getText())); sensor.setPuerto(Integer.parseInt(JPuerto.getText())); // Cerrando ventana this.dispose(); // Iniciando trabajo del sensor sensor.trabajar(); } // GEN-LAST:event_jButton1ActionPerformed
private void updateCurrentBgInfoForBtShare(TextView notificationText) { if ((android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)) { notificationText.setText( "Unfortunately your android version does not support Bluetooth Low Energy"); return; } String receiverSn = prefs.getString("share_key", "SM00000000").toUpperCase(); if (receiverSn.compareTo("SM00000000") == 0 || receiverSn.length() == 0) { notificationText.setText("Please set your Dex Receiver Serial Number in App Settings"); return; } if (receiverSn.length() < 10) { notificationText.setText( "Double Check Dex Receiver Serial Number, should be 10 characters, don't forget the letters"); return; } if (ActiveBluetoothDevice.first() == null) { notificationText.setText("Now pair with your Dexcom Share"); return; } if (!Sensor.isActive()) { notificationText.setText("Now choose start your sensor in your settings"); return; } displayCurrentInfo(); }