Search in sources :

Example 11 with DBHandler

use of nodomain.freeyourgadget.gadgetbridge.database.DBHandler in project Gadgetbridge by Freeyourgadget.

the class FetchActivityOperation method flushActivityDataHolder.

/**
     * empty the local buffer for activity data, arrange the values received in groups of three and
     * store them in the DB
     */
private void flushActivityDataHolder() {
    if (activityStruct == null) {
        LOG.debug("nothing to flush, struct is already null");
        return;
    }
    int bpm = getBytesPerMinuteOfActivityData();
    LOG.debug("flushing activity data samples: " + activityStruct.activityDataHolderProgress / bpm);
    byte category, intensity, steps, heartrate = 0;
    try (DBHandler dbHandler = GBApplication.acquireDB()) {
        MiBandSampleProvider provider = new MiBandSampleProvider(getDevice(), dbHandler.getDaoSession());
        User user = DBHelper.getUser(dbHandler.getDaoSession());
        Device device = DBHelper.getDevice(getDevice(), dbHandler.getDaoSession());
        int minutes = 0;
        try {
            int timestampInSeconds = (int) (activityStruct.activityDataTimestampProgress.getTimeInMillis() / 1000);
            if ((activityStruct.activityDataHolderProgress % bpm) != 0) {
                throw new IllegalStateException("Unexpected data, progress should be multiple of " + bpm + ": " + activityStruct.activityDataHolderProgress);
            }
            int numSamples = activityStruct.activityDataHolderProgress / bpm;
            MiBandActivitySample[] samples = new MiBandActivitySample[numSamples];
            for (int i = 0; i < activityStruct.activityDataHolderProgress; i += bpm) {
                category = activityStruct.activityDataHolder[i];
                intensity = activityStruct.activityDataHolder[i + 1];
                steps = activityStruct.activityDataHolder[i + 2];
                if (hasExtendedActivityData) {
                    heartrate = activityStruct.activityDataHolder[i + 3];
                //                        LOG.debug("heartrate received: " + (heartrate & 0xff));
                }
                MiBandActivitySample sample = getSupport().createActivitySample(device, user, timestampInSeconds, provider);
                sample.setRawIntensity(intensity & 0xff);
                sample.setSteps(steps & 0xff);
                sample.setRawKind(category & 0xff);
                sample.setHeartRate(heartrate & 0xff);
                samples[minutes] = sample;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("sample: " + samples[minutes]);
                }
                // next minute
                minutes++;
                timestampInSeconds += 60;
            }
            provider.addGBActivitySamples(samples);
        } finally {
            activityStruct.bufferFlushed(minutes);
        }
    } catch (Exception ex) {
        GB.toast(getContext(), ex.getMessage(), Toast.LENGTH_LONG, GB.ERROR, ex);
    }
}
Also used : DBHandler(nodomain.freeyourgadget.gadgetbridge.database.DBHandler) User(nodomain.freeyourgadget.gadgetbridge.entities.User) Device(nodomain.freeyourgadget.gadgetbridge.entities.Device) MiBandSampleProvider(nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandSampleProvider) MiBandActivitySample(nodomain.freeyourgadget.gadgetbridge.entities.MiBandActivitySample) IOException(java.io.IOException)

Example 12 with DBHandler

use of nodomain.freeyourgadget.gadgetbridge.database.DBHandler in project Gadgetbridge by Freeyourgadget.

the class HPlusHandlerThread method processRealtimeStats.

/**
     * Process a message containing real time information
     *
     * @param data the message from the device
     * @return boolean indicating success or fail
     */
public boolean processRealtimeStats(byte[] data) {
    HPlusDataRecordRealtime record;
    try {
        record = new HPlusDataRecordRealtime(data);
    } catch (IllegalArgumentException e) {
        LOG.debug((e.getMessage()));
        return false;
    }
    //This can be used to detect the user is moving (not sleeping)
    if (prevRealTimeRecord != null && record.same(prevRealTimeRecord))
        return true;
    prevRealTimeRecord = record;
    getDevice().setBatteryLevel(record.battery);
    //Because a message with a valid Heart Rate will be provided, this loss very limited
    if (record.heartRate == ActivityKind.TYPE_NOT_MEASURED) {
        getDevice().setFirmwareVersion2("---");
        getDevice().sendDeviceUpdateIntent(getContext());
    } else {
        getDevice().setFirmwareVersion2("" + record.heartRate);
        getDevice().sendDeviceUpdateIntent(getContext());
    }
    try (DBHandler dbHandler = GBApplication.acquireDB()) {
        HPlusHealthSampleProvider provider = new HPlusHealthSampleProvider(getDevice(), dbHandler.getDaoSession());
        HPlusHealthActivitySample sample = createSample(dbHandler, record.timestamp);
        sample.setRawKind(record.type);
        sample.setRawIntensity(record.intensity);
        sample.setHeartRate(record.heartRate);
        sample.setDistance(record.distance);
        sample.setCalories(record.calories);
        sample.setSteps(record.steps);
        sample.setRawHPlusHealthData(record.getRawData());
        sample.setProvider(provider);
        provider.addGBActivitySample(sample);
        sample.setSteps(sample.getSteps() - prevRealTimeRecord.steps);
        Intent intent = new Intent(DeviceService.ACTION_REALTIME_SAMPLES).putExtra(DeviceService.EXTRA_REALTIME_SAMPLE, sample).putExtra(DeviceService.EXTRA_TIMESTAMP, System.currentTimeMillis());
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
    //TODO: Handle Active Time. With Overlay?
    } catch (GBException ex) {
        LOG.debug((ex.getMessage()));
    } catch (Exception ex) {
        LOG.debug(ex.getMessage());
    }
    return true;
}
Also used : HPlusHealthActivitySample(nodomain.freeyourgadget.gadgetbridge.entities.HPlusHealthActivitySample) DBHandler(nodomain.freeyourgadget.gadgetbridge.database.DBHandler) Intent(android.content.Intent) GBException(nodomain.freeyourgadget.gadgetbridge.GBException) HPlusHealthSampleProvider(nodomain.freeyourgadget.gadgetbridge.devices.hplus.HPlusHealthSampleProvider) GBException(nodomain.freeyourgadget.gadgetbridge.GBException)

Example 13 with DBHandler

use of nodomain.freeyourgadget.gadgetbridge.database.DBHandler in project Gadgetbridge by Freeyourgadget.

the class HPlusHandlerThread method processIncomingDaySlotData.

/**
     * Process a message containing information regarding a day slot
     * A slot summarizes 10 minutes of data
     *
     * @param data the message from the device
     * @return boolean indicating success or fail
     */
public boolean processIncomingDaySlotData(byte[] data) {
    HPlusDataRecordDaySlot record;
    try {
        record = new HPlusDataRecordDaySlot(data);
    } catch (IllegalArgumentException e) {
        LOG.debug((e.getMessage()));
        return false;
    }
    Calendar now = GregorianCalendar.getInstance();
    int nowSlot = now.get(Calendar.HOUR_OF_DAY) * 6 + (now.get(Calendar.MINUTE) / 10);
    if (record.slot == nowSlot) {
        if (mCurrentDaySlot != null && mCurrentDaySlot != record) {
            mCurrentDaySlot.accumulate(record);
            mDaySlotRecords.add(mCurrentDaySlot);
            mCurrentDaySlot = null;
        } else {
            //Store it to a temp variable as this is an intermediate value
            mCurrentDaySlot = record;
            if (!mSlotsInitialSync)
                return true;
        }
    }
    if (mSlotsInitialSync) {
        //Subtract a day of seconds
        if (record.slot > nowSlot) {
            record.timestamp -= 3600 * 24;
        }
        if (record.slot == mLastSlotReceived + 1) {
            mLastSlotReceived = record.slot;
        }
        //Ignore the current slot as it is incomplete
        if (record.slot != nowSlot)
            mDaySlotRecords.add(record);
        //Still fetching ring buffer. Request the next slots
        if (record.slot == mLastSlotRequested) {
            mGetDaySlotsTime.clear();
            synchronized (waitObject) {
                waitObject.notify();
            }
        }
        //Keep buffering
        if (record.slot != 143)
            return true;
    } else {
        mGetDaySlotsTime = GregorianCalendar.getInstance();
        mGetDaySlotsTime.add(Calendar.DAY_OF_MONTH, 1);
    }
    if (mDaySlotRecords.size() > 0) {
        //Sort the samples
        Collections.sort(mDaySlotRecords, new Comparator<HPlusDataRecordDaySlot>() {

            public int compare(HPlusDataRecordDaySlot one, HPlusDataRecordDaySlot other) {
                return one.timestamp - other.timestamp;
            }
        });
        try (DBHandler dbHandler = GBApplication.acquireDB()) {
            HPlusHealthSampleProvider provider = new HPlusHealthSampleProvider(getDevice(), dbHandler.getDaoSession());
            List<HPlusHealthActivitySample> samples = new ArrayList<>();
            for (HPlusDataRecordDaySlot storedRecord : mDaySlotRecords) {
                HPlusHealthActivitySample sample = createSample(dbHandler, storedRecord.timestamp);
                sample.setRawHPlusHealthData(storedRecord.getRawData());
                sample.setSteps(storedRecord.steps);
                sample.setHeartRate(storedRecord.heartRate);
                sample.setRawKind(storedRecord.type);
                sample.setProvider(provider);
                samples.add(sample);
            }
            provider.getSampleDao().insertOrReplaceInTx(samples);
            mDaySlotRecords.clear();
        } catch (GBException ex) {
            LOG.debug((ex.getMessage()));
        } catch (Exception ex) {
            LOG.debug(ex.getMessage());
        }
    }
    return true;
}
Also used : HPlusHealthActivitySample(nodomain.freeyourgadget.gadgetbridge.entities.HPlusHealthActivitySample) DBHandler(nodomain.freeyourgadget.gadgetbridge.database.DBHandler) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ArrayList(java.util.ArrayList) GBException(nodomain.freeyourgadget.gadgetbridge.GBException) HPlusHealthSampleProvider(nodomain.freeyourgadget.gadgetbridge.devices.hplus.HPlusHealthSampleProvider) GBException(nodomain.freeyourgadget.gadgetbridge.GBException)

Example 14 with DBHandler

use of nodomain.freeyourgadget.gadgetbridge.database.DBHandler in project Gadgetbridge by Freeyourgadget.

the class PebblePairingActivity method getMatchingParentDeviceFromDB.

private GBDevice getMatchingParentDeviceFromDB(BluetoothDevice btDevice) {
    String expectedSuffix = btDevice.getName();
    expectedSuffix = expectedSuffix.replace("Pebble-LE ", "");
    expectedSuffix = expectedSuffix.replace("Pebble Time LE ", "");
    expectedSuffix = expectedSuffix.substring(0, 2) + ":" + expectedSuffix.substring(2);
    LOG.info("will try to find a Pebble with BT address suffix " + expectedSuffix);
    GBDevice gbDevice = null;
    try (DBHandler dbHandler = GBApplication.acquireDB()) {
        DaoSession session = dbHandler.getDaoSession();
        DeviceDao deviceDao = session.getDeviceDao();
        Query<Device> query = deviceDao.queryBuilder().where(DeviceDao.Properties.Type.eq(1), DeviceDao.Properties.Identifier.like("%" + expectedSuffix)).build();
        List<Device> devices = query.list();
        if (devices.size() == 0) {
            GB.toast("Please pair your non-LE Pebble before pairing the LE one", Toast.LENGTH_SHORT, GB.INFO);
            returnToPairingActivity();
            return null;
        } else if (devices.size() > 1) {
            GB.toast("Can not match this Pebble LE to a unique device", Toast.LENGTH_SHORT, GB.INFO);
            returnToPairingActivity();
            return null;
        }
        DeviceHelper deviceHelper = DeviceHelper.getInstance();
        gbDevice = deviceHelper.toGBDevice(devices.get(0));
        gbDevice.setVolatileAddress(btDevice.getAddress());
    } catch (Exception e) {
        GB.toast("Error retrieving devices from database", Toast.LENGTH_SHORT, GB.ERROR);
        returnToPairingActivity();
        return null;
    }
    return gbDevice;
}
Also used : DBHandler(nodomain.freeyourgadget.gadgetbridge.database.DBHandler) BluetoothDevice(android.bluetooth.BluetoothDevice) Device(nodomain.freeyourgadget.gadgetbridge.entities.Device) GBDevice(nodomain.freeyourgadget.gadgetbridge.impl.GBDevice) DeviceHelper(nodomain.freeyourgadget.gadgetbridge.util.DeviceHelper) DeviceDao(nodomain.freeyourgadget.gadgetbridge.entities.DeviceDao) GBDevice(nodomain.freeyourgadget.gadgetbridge.impl.GBDevice) DaoSession(nodomain.freeyourgadget.gadgetbridge.entities.DaoSession)

Aggregations

DBHandler (nodomain.freeyourgadget.gadgetbridge.database.DBHandler)14 DaoSession (nodomain.freeyourgadget.gadgetbridge.entities.DaoSession)6 GBException (nodomain.freeyourgadget.gadgetbridge.GBException)5 ArrayList (java.util.ArrayList)4 HPlusHealthSampleProvider (nodomain.freeyourgadget.gadgetbridge.devices.hplus.HPlusHealthSampleProvider)4 Device (nodomain.freeyourgadget.gadgetbridge.entities.Device)4 HPlusHealthActivitySample (nodomain.freeyourgadget.gadgetbridge.entities.HPlusHealthActivitySample)4 IOException (java.io.IOException)3 GBDevice (nodomain.freeyourgadget.gadgetbridge.impl.GBDevice)3 BluetoothDevice (android.bluetooth.BluetoothDevice)2 GregorianCalendar (java.util.GregorianCalendar)2 GBDeviceEvent (nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEvent)2 GBDeviceEventSendBytes (nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventSendBytes)2 MiBandSampleProvider (nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandSampleProvider)2 MiBandActivitySample (nodomain.freeyourgadget.gadgetbridge.entities.MiBandActivitySample)2 PebbleHealthActivityOverlay (nodomain.freeyourgadget.gadgetbridge.entities.PebbleHealthActivityOverlay)2 PebbleHealthActivityOverlayDao (nodomain.freeyourgadget.gadgetbridge.entities.PebbleHealthActivityOverlayDao)2 User (nodomain.freeyourgadget.gadgetbridge.entities.User)2 Intent (android.content.Intent)1 File (java.io.File)1