fleeta-lib
Version:
A comprehensive library for fleet management applications - API, Auth, Device management
612 lines (460 loc) β’ 13.3 kB
Markdown
# π FleetA Library
[](https://badge.fury.io/js/fleeta-lib)
[](http://www.typescriptlang.org/)
[](https://reactjs.org/)
[](#tree-shaking)
A comprehensive library for fleet management applications. Features authentication, API client, device management, and data storage for BlackVue Fleeta ecosystem.
## π Quick Start
### Installation
```bash
npm install fleeta-lib
```
### Peer Dependencies
Install required peer dependencies:
```bash
npm install react react-dom
```
### Basic Usage
```tsx
import React from 'react';
import {
login,
logout,
getDeviceList,
useAuthStore,
useApiEndpointStore
} from 'fleeta-lib';
function MyFleetApp() {
const { isAuthenticated, userToken } = useAuthStore();
const handleLogin = async () => {
await login({
email: 'user@example.com',
password: 'password'
});
};
const handleGetDevices = async () => {
const deviceList = await getDeviceList();
console.log('Devices:', deviceList);
};
return (
<div>
{!isAuthenticated ? (
<button onClick={handleLogin}>Login</button>
) : (
<button onClick={handleGetDevices}>Get Devices</button>
)}
</div>
);
}
```
## β¨ Features
### π Authentication Module
Complete authentication solution for BlackVue Fleeta:
- **Login/Logout** - Email/password authentication
- **Password Reset** - Reset password functionality
- **Auth Store** - Zustand-based state management
- **Auth Utils** - Helper functions and type checking
- π **Authentication** - Complete login/logout system for BlackVue Fleeta
- π± **Device Management** - Device listing, grouping, and statistics
- π **API Client** - HTTP client with authentication headers
- πͺ **State Management** - Zustand stores for auth and API endpoints
- π¨ **TypeScript** - Full type safety and excellent DX
- π³ **Tree Shaking** - Import only what you need
### π± Device Management Module
Advanced device management for BlackVue fleet:
- **Device List API** - Get devices with grouping and statistics
- **Mock Data** - Testing with combined mock + real data
- **Device Filtering** - Search, filter by status, mode, etc.
- **Group Management** - Organize devices into groups
### π API Management Module
Centralized API endpoint management:
- **Endpoint Configuration** - Manage API URLs
- **Environment Variables** - Load from .env files
- **Validation** - Ensure endpoints are configured properly
## π§ Environment Setup
Set up your environment variables:
```bash
# .env file
VITE_API_GATEWAY=https://your-api-gateway.com
VITE_IOT_API_GATEWAY=https://your-iot-api-gateway.com
```
## π API Documentation
### Authentication
```tsx
import { login, logout, resetPassword, useAuthStore } from 'fleeta-lib';
// Login
await login({
email: 'user@example.com',
password: 'password'
});
// Logout
await logout();
// Password Reset
const result = await resetPassword('user@example.com');
// Use Auth Store
const { isAuthenticated, userToken, subscribeInfo } = useAuthStore();
```
### Device Management
```tsx
import { getDeviceList, getMockDeviceList, useAuthStore } from 'fleeta-lib';
// Get real device list (requires authentication)
const deviceList = await getDeviceList();
// Get mock + real device list
const mockDeviceList = await getMockDeviceList();
// Use with authentication
const { isAuthenticated } = useAuthStore();
if (isAuthenticated) {
const devices = await getDeviceList();
}
```
### API Endpoint Management
```tsx
import {
getApiGateway,
getIotApiGateway,
useApiEndpointStore
} from 'fleeta-lib';
// Get configured endpoints
const apiUrl = getApiGateway();
const iotUrl = getIotApiGateway();
// Configure endpoints (usually in main.tsx)
useApiEndpointStore.getState().setConfig({
apiGateway: 'https://api.example.com',
iotApiGateway: 'https://iot.example.com'
});
```
## π‘ GPS Data Provider
Advanced GPS data management system for real-time device tracking:
```tsx
import {
createBasicGpsProvider,
useGpsDataStream,
RealTimeGpsMap
} from 'fleeta-components';
const provider = createBasicGpsProvider(userEmail, gpsSDK);
const { optimizedDevices, selectedDevice, selectDevice } = useGpsDataStream({
provider,
subscriberId: 'my-map',
enableOptimization: true
});
<RealTimeGpsMap
devices={optimizedDevices}
selectedDevice={selectedDevice}
onDeviceSelect={selectDevice}
/>
```
**Key Features:**
- π **Smart Data Processing**: Filters unnecessary updates
- β‘ **Performance Optimized**: Map-rendering optimizations
- π **Multi-Subscriber Support**: Share data across components
- πΎ **Built-in Caching**: LRU cache with memory management
- π― **Flexible Filtering**: PSN lists, bounding boxes, status filters
## π Documentation
- [Installation Guide](./docs/INSTALLATION.md)
- [API Documentation](./docs/API.md)
- [Usage Examples](./docs/EXAMPLES.md)
- [GPS Data Provider Guide](./docs/GPS_DATA_PROVIDER.md)
- [Troubleshooting](./docs/TROUBLESHOOTING.md)
## π³ Tree Shaking
Import only what you need to reduce bundle size:
```tsx
// Import authentication only
import { login, logout } from 'fleeta-lib';
// Import device management only
import { getDeviceList } from 'fleeta-lib';
// Import stores only
import { useAuthStore, useApiEndpointStore } from 'fleeta-lib';
// Import only types (zero runtime cost)
import type { AuthConfig, DeviceListItem } from 'fleeta-lib';
```
**Bundle size savings:**
- Authentication only: ~60% smaller
- Device API only: ~70% smaller
- Stores only: ~80% smaller
- Types only: 100% smaller (no runtime cost)
### Import VideoPlayer and WebRTC components
```tsx
// Import VideoPlayer for recorded videos
import { VideoPlayer } from 'fleeta-components';
// Import WebRTC components for live streaming
import { WebRTCPlayer, createWebRTCProvider } from 'fleeta-components';
// Import utilities
import { parseGpsData } from 'fleeta-components';
```
## π Documentation
- [Installation Guide](./docs/INSTALLATION.md)
- [API Documentation](./docs/API.md)
- [Usage Examples](./docs/EXAMPLES.md)
- [Troubleshooting](./docs/TROUBLESHOOTING.md)
## π§ Configuration
### Environment Variables
Set up required environment variables:
```bash
VITE_API_GATEWAY=https://your-api-gateway.com
VITE_IOT_API_GATEWAY=https://your-iot-api-gateway.com
```
### Initialize in your app
```tsx
// main.tsx or App.tsx
import { useApiEndpointStore } from 'fleeta-lib';
// Initialize API endpoints
useApiEndpointStore.getState().setConfig({
apiGateway: import.meta.env.VITE_API_GATEWAY,
iotApiGateway: import.meta.env.VITE_IOT_API_GATEWAY
});
```
### Components
#### VideoPlayer
The main video player component with integrated GPS mapping and sensor data visualization.
```tsx
interface VideoPlayerProps {
// Video source and configuration
videoUrl: string | null;
enableMetadataParsing?: boolean;
showMap?: boolean;
// GPS and sensor data (external)
gpsPoints?: GpsPoint[] | null;
sensorData?: IAccel[] | null;
// Player configuration
autoPlay?: boolean;
showControls?: boolean;
showMap?: boolean;
speedUnit?: 'km/h' | 'mph';
// Event callbacks
onTimeUpdate?: (currentTime: number) => void;
onDurationChange?: (duration: number) => void;
onPlay?: () => void;
onPause?: () => void;
onError?: (error: string) => void;
// Styling
className?: string;
}
```
**Example:**
```tsx
<VideoPlayer
videoUrl="https://example.com/video.mp4"
enableMetadataParsing={true}
autoPlay={true}
showMap={true}
speedUnit="km/h"
onTimeUpdate={(time) => console.log('Current time:', time)}
onError={(error) => console.error('Video error:', error)}
/>
```
**Key Features:**
- π¬ Advanced video controls with frame stepping
- πΊοΈ Integrated GPS map with route visualization
- π Real-time G-sensor data display
- π¨ Dark/light mode support
#### MapComponent
Displays GPS tracking data on an interactive map.
```tsx
interface MapComponentProps {
gpsPoints?: GpsPoint[];
currentTime?: number;
sensorData?: IAccel[];
speedUnit?: 'km/h' | 'mph';
mapStyle?: 'streets' | 'satellite' | 'outdoors' | 'light' | 'dark';
height?: string;
className?: string;
}
```
**Example:**
```tsx
<MapComponent
gpsPoints={gpsData}
currentTime={30}
speedUnit="mph"
mapStyle="satellite"
height="300px"
/>
```
#### EventComponent
Visualizes G-sensor acceleration data.
```tsx
interface EventComponentProps {
sensorData?: IAccel[];
currentTime?: number;
videoDuration?: number;
height?: string;
className?: string;
}
```
**Example:**
```tsx
<EventComponent
sensorData={accelerationData}
currentTime={30}
videoDuration={120}
height="100px"
/>
```
### Utilities
#### GPS Data Parsing
```tsx
import { parseGpsData, GpsParsingStatus } from 'fleeta-video-player';
const result = parseGpsData(base64Data);
if (result.status === GpsParsingStatus.SUCCESS) {
console.log('GPS points:', result.points);
}
```
#### Sensor Data Parsing
```tsx
import { parseSensorData, SensorParsingStatus } from 'fleeta-video-player';
const result = parseSensorData(base64Data);
if (result.status === SensorParsingStatus.SUCCESS) {
console.log('Sensor data:', result.points);
}
```
#### MP4 Metadata Extraction
```tsx
import { fetchAndParseMP4 } from 'fleeta-video-player';
const metadata = await fetchAndParseMP4('https://example.com/video.mp4');
console.log('GPS data:', metadata.gps);
console.log('Sensor data:', metadata.sensor);
console.log('Thumbnail:', metadata.thumbnail);
```
## π¨ Styling
FleetA VideoPlayer uses Tailwind CSS classes. You can:
1. **Use default styles** - Include the CSS bundle
2. **Custom styling** - Override with your own CSS
3. **Tailwind integration** - Use Tailwind classes directly
```tsx
// Include component styles
import 'fleeta-components/dist/style.css';
// Custom styling
<VideoPlayer
className="my-custom-player border-2 border-blue-500"
videoUrl={url}
/>
```
## π³ Tree Shaking
Import only what you need to reduce bundle size:
```tsx
// Import VideoPlayer (includes all sub-components)
import { VideoPlayer } from 'fleeta-components';
// Import only utilities
import { parseGpsData } from 'fleeta-components';
// Import only types (zero runtime cost)
import type { VideoPlayerProps } from 'fleeta-components';
```
**Bundle size savings:**
- VideoPlayer only: ~40% smaller
- GPS parsing only: ~80% smaller
- Utilities only: ~90% smaller
- Types only: 100% smaller (no runtime cost)
## π§ Configuration
### Environment Variables
Set up Mapbox for map functionality:
```bash
VITE_MAPBOX_ACCESS_TOKEN=your_token_here
```
### TypeScript
FleetA Video Player includes complete TypeScript definitions:
```tsx
import type {
VideoPlayerProps,
GpsPoint,
IAccel,
ExtractedMetadata
} from 'fleeta-components';
```
## π± Responsive Design
The components are fully responsive and work on all screen sizes:
```tsx
<div className="w-full h-screen md:h-96">
<VideoPlayer
videoUrl={url}
showMap={true}
className="w-full h-full"
/>
</div>
```
## π Key Features
### GPS Tracking
- Real-time vehicle position
- Route visualization
- Speed display (km/h or mph)
- Heading direction
### G-Sensor Visualization
- Acceleration visualization
- Event detection
- Synchronized with video playback
### MP4 Metadata
- Automatic data extraction
- GPS and sensor parsing
- Thumbnail generation
## π Advanced Examples
### Custom GPS Data
```tsx
const customGpsPoints: GpsPoint[] = [
{
timestamp: 0,
lat: 37.7749,
lng: -122.4194,
relativeTime: 0,
speedKmh: 50,
speedKnots: 27,
course: 90
}
];
<VideoPlayer
videoUrl={url}
gpsPoints={customGpsPoints}
showMap={true}
/>
```
### Event Handling
```tsx
<VideoPlayer
videoUrl={url}
onTimeUpdate={(time) => {
console.log(`Video time: ${time}s`);
}}
onPlay={() => {
console.log('Video started playing');
}}
onError={(error) => {
console.error('Playback error:', error);
}}
/>
```
### Dark Mode
```tsx
// Manual dark mode
<div className="dark">
<VideoPlayer
videoUrl={url}
mapStyle="dark"
/>
</div>
```
## π οΈ Development
### Building from Source
```bash
git clone https://github.com/fleeta-team/fleeta-components.git
cd fleeta-components
npm install
npm run build:lib
```
### Running Tests
```bash
npm run quality:full
npm run validate:full
```
## π Browser Support
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
## π€ Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
## π License
MIT License - see [LICENSE](LICENSE) file for details.
## π Support
- π [API Documentation](./docs/API.md)
- π [Issue Tracker](https://github.com/fleeta-team/fleeta-components/issues)
- π¬ [Discussions](https://github.com/fleeta-team/fleeta-components/discussions)
---
**π¬ FleetA VideoPlayer - Complete Video Playback Solution for Fleet Management**