求问:在Ionic 3/Ionic 4应用中集成xdrip-js的完整流程经验
Hey there! I’ve walked through the full process of integrating xdrip-js into both Ionic 3 and Ionic 4 applications, so I can break down the key steps, configuration tweaks, and common pitfalls to help you get up and running smoothly.
Before diving in, make sure you have:
- A working Ionic 3 or 4 project (we’ll cover creating one if you don’t have it)
- Node.js 12+ installed (LTS versions work best for compatibility)
- Basic familiarity with Bluetooth Low Energy (BLE) concepts, since xdrip-js relies on BLE to connect to glucose monitors
- The
cordova-plugin-ble-centralplugin (we’ll add this later, but it’s non-negotiable for BLE functionality)
For Ionic 3:
Create a new project with the Ionic Angular template:
ionic start my-glucose-app blank --type=ionic-angular cd my-glucose-app
For Ionic 4:
Use the Angular template (Ionic 4 shifted to Angular as the default framework):
ionic start my-glucose-app blank --type=angular cd my-glucose-app
First, install xdrip-js via npm:
npm install xdrip-js --save
Next, install the required BLE plugin for Cordova:
cordova plugin add cordova-plugin-ble-central
Note for Ionic 3 users: You may need to add polyfills for ES6+ features that xdrip-js uses. Open src/polyfills.ts and add these lines at the bottom:
import 'core-js/es7/array'; import 'core-js/es7/object';
To keep your code organized, wrap xdrip-js functionality in an Angular service. Generate a service with:
ionic generate service services/xdrip
Ionic 4 Service Code:
Replace the contents of src/services/xdrip.service.ts with this:
import { Injectable } from '@angular/core'; import * as xdrip from 'xdrip-js'; @Injectable({ providedIn: 'root' }) export class XdripService { private bluetoothManager: any; public glucoseUpdates: any[] = []; constructor() { this.initializeXdrip(); } private initializeXdrip() { this.bluetoothManager = new xdrip.BluetoothManager(); // Listen for device connection events this.bluetoothManager.on('deviceConnected', (device) => { console.log('Connected to:', device.name); }); // Listen for new glucose readings this.bluetoothManager.on('glucoseData', (data) => { console.log('New glucose reading:', data); this.glucoseUpdates.push(data); }); // Handle disconnections this.bluetoothManager.on('deviceDisconnected', () => { console.log('Device disconnected'); }); } // Scan for nearby BLE glucose monitors async scanForDevices(): Promise<any[]> { try { const devices = await this.bluetoothManager.scan(); return devices.filter(device => device.name?.includes('Dexcom') || device.name?.includes('Medtronic')); // Filter common devices } catch (error) { console.error('Scan failed:', error); throw error; } } // Connect to a specific device by ID async connectToDevice(deviceId: string): Promise<void> { try { await this.bluetoothManager.connect(deviceId); } catch (error) { console.error('Connection failed:', error); throw error; } } // Disconnect from the current device disconnectDevice(): void { this.bluetoothManager.disconnect(); } }
Ionic 3 Adjustment:
Change the @Injectable() decorator to @Injectable() (no providedIn), then add the service to your app.module.ts providers array.
BLE requires specific permissions on both Android and iOS. Update your config.xml (root project folder) with these entries:
<!-- Android Permissions --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Required for scanning on Android 6+ --> <!-- iOS Permissions --> <edit-config file="*-Info.plist" mode="merge" target="NSBluetoothAlwaysUsageDescription"> <string>Need Bluetooth access to connect to your glucose monitoring device</string> </edit-config> <edit-config file="*-Info.plist" mode="merge" target="NSBluetoothPeripheralUsageDescription"> <string>Need Bluetooth access to connect to your glucose monitoring device</string> </edit-config>
Update src/app/home/home.page.ts (Ionic 4) or src/pages/home/home.ts (Ionic 3):
import { Component } from '@angular/core'; import { XdripService } from '../services/xdrip.service'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { public availableDevices: any[] = []; public currentReading: number | null = null; public isConnected = false; constructor(private xdripService: XdripService) { // Check for new glucose readings every second setInterval(() => { if (this.xdripService.glucoseUpdates.length > 0) { const latest = this.xdripService.glucoseUpdates.at(-1); this.currentReading = latest.glucose; } }, 1000); } async scanDevices() { this.availableDevices = await this.xdripService.scanForDevices(); } async connectToDevice(device: any) { await this.xdripService.connectToDevice(device.id); this.isConnected = true; } disconnect() { this.xdripService.disconnectDevice(); this.isConnected = false; this.currentReading = null; } }
Then update the corresponding HTML file (home.page.html):
<ion-header> <ion-toolbar> <ion-title>Glucose Monitor</ion-title> </ion-toolbar> </ion-header> <ion-content class="ion-padding"> <ion-button (click)="scanDevices()" expand="block" [disabled]="isConnected"> Scan for Devices </ion-button> <ion-list *ngIf="availableDevices.length > 0 && !isConnected"> <ion-item *ngFor="let device of availableDevices" (click)="connectToDevice(device)"> <ion-label> <h2>{{ device.name || 'Unknown Device' }}</h2> <p>{{ device.id }}</p> </ion-label> </ion-item> </ion-list> <div *ngIf="isConnected" class="connected-state"> <h3>Connected to Device</h3> <ion-button (click)="disconnect()" color="danger" expand="block">Disconnect</ion-button> </div> <div *ngIf="currentReading !== null" class="glucose-display"> <h1>{{ currentReading }} mg/dL</h1> <p>Latest reading</p> </div> </ion-content>
- Bluetooth Permission Errors: On Android 12+, add
BLUETOOTH_SCANandBLUETOOTH_CONNECTpermissions toconfig.xmlif you see access denied errors. - Ionic 3 Polyfill Issues: If you get "property 'includes' does not exist" errors, double-check your
polyfills.tsentries. - Device Connection Drops: Some glucose monitors have short connection timeouts. Add reconnection logic in the
deviceDisconnectedevent listener if needed. - xdrip-js Compatibility: Stick to the latest stable version of xdrip-js to avoid bugs with newer Ionic/Cordova versions.
内容的提问来源于stack exchange,提问作者Esem

