реагировать на службу текущего времени родного приложения bluetooth

Мне нужно разработать приложение ReactNative, которое подключает устройство Bluetooth BLE. Я использую библиотеку react-native-ble-plx.

Одна из ключевых вещей, которые нужно сделать, — это синхронизировать текущее время между приложением ReactNative и устройством Bluetooth.

Я понял, что приложение должно иметь CTS, который является службой текущего времени. Как я могу внедрить службу CTS? Есть ли какая-нибудь библиотека, предоставляющая сервис CTS?


person Steve    schedule 01.11.2018    source источник


Ответы (1)


Я не уверен, касается ли ваш вопрос создания CTS на устройстве или взаимодействия с устройством, имеющим CTS. Я предполагаю, что это последнее, и ваш вопрос звучит примерно так: «Как записать текущее время в службу текущего времени на периферийном устройстве BLE?»

Вот как мне удалось записать время в CTS на периферийном устройстве с помощью библиотеки react-native-ble-plx.

constructCT = (): string => {
    // Order:
    // Year_LSO (byte), Year_MSO (byte),  Month (byte), DayOfMonth (byte), Hours (byte), Minutes (byte), Seconds (byte), DayOfWeek (byte), Fractions (byte), AdjReason (byte)

    const fullDateTime = new Date();
    const year = fullDateTime.getFullYear();
    const month = fullDateTime.getMonth() + 1;
    const dayOfMonth = fullDateTime.getDate();
    const hours = fullDateTime.getHours();
    const minutes = fullDateTime.getMinutes();
    const seconds = fullDateTime.getSeconds();
    let dayOfWeek = fullDateTime.getDay();
    if (dayOfWeek === 0) {
        dayOfWeek = 7;
    }
    const fraction1000 = fullDateTime.getMilliseconds();
    const adjustFractionDenom = 256 / 1000;
    const fraction256 = Math.round(fraction1000 * adjustFractionDenom);
    // TODO: Set your adjust reasons accordingly, in my case they were unnecessary
    // Adjust Reasons: Manual Update, External Update, Time Zone Change, Daylight Savings Change
    const adjustReasons = [true, false, false, true];
    let adjustValue = 0;
    for (let i = 0; i < 4; i++) {
        if (adjustReasons[i]) {
            adjustValue = adjustValue | (1 << i);
        }
    }

    // console.log("Year:", year, " Month:", month, " Date:", dayOfMonth, " Hours:", hours, " Minutes:", minutes, " Seconds:", seconds, " DOW:", dayOfWeek, " MS:", fraction256, " Adjust Reason: ", adjustValue);

    const yearHex = this.correctLength(year.toString(16), 4);
    const yearHexMSO = yearHex.substr(0, 2);
    const yearHexLSO = yearHex.substr(2, 2);
    const monthHex = this.correctLength(month.toString(16), 2);
    const dayOfMonthHex = this.correctLength(dayOfMonth.toString(16), 2);
    const hoursHex = this.correctLength(hours.toString(16), 2);
    const minutesHex = this.correctLength(minutes.toString(16), 2);
    const secondsHex = this.correctLength(seconds.toString(16), 2);
    const dayOfWeekHex = this.correctLength(dayOfWeek.toString(16), 2);
    const fractionHex = this.correctLength(fraction256.toString(16), 2);
    const adjustValueHex = this.correctLength(adjustValue.toString(16), 2);

    const currentTime = yearHexLSO + yearHexMSO + monthHex + dayOfMonthHex + hoursHex + minutesHex + secondsHex + dayOfWeekHex + fractionHex + adjustValueHex;
    const currentTime64 = Buffer.from(currentTime, 'hex').toString('base64');
    return currentTime64;
}

correctLength = (str, dig): numFilled => {
    let result = str;
    while (result.length !== dig) {
        result = "0" + result;
    }
    return result;
}

pushTimeData = () => {
    const CTSValue = this.constructCT();
    this.state.manager.writeCharacteristicWithResponseForDevice(this.state.deviceName, time_service, time_charac, CTSValue)
        .then((charac) => {
            // console.log("CHARAC VALUE: ", charac.value);
        })
        .catch((error) => {
            console.log(JSON.stringify(error));
        })
}
person Nathan Dullea    schedule 24.06.2019