API-Referenz

Endpunkte, Datenmodelle und Fehlercodes der LiSA REST API, erzeugt aus dem offiziellen API-Wiki.
Wiki-Stand 158c1a5 · 28.7.2026

Data Models

Complete documentation of all data models used in the LISA REST API.

Core Data Types#

User#

Represents a user in the LISA system.

interface User {
  Email: string;                    // User's email address
  Flagged: boolean;                // Whether user is flagged
  Inactive: boolean;               // Whether user is inactive
  Language: string;                // User's preferred language
  Name: string;                    // User's display name
  Phone: string;                   // User's phone number
  Uid: string;                     // Unique user identifier
  FCMTokens?: UserPhone[];         // FCM tokens for push notifications
  RequestDeletion?: boolean;       // Whether user requested account deletion
  betaUser?: boolean;              // Beta user flag
  WedaIntegration?: boolean;       // Weda integration flag
  integrators?: string[];          // Array of integratorUIDs that can access this user's data
}

UserPhone (FCM Token)#

Represents a user's FCM token for push notifications.

interface UserPhone {
  CustomName: string;              // Custom name for the device
  Name: string;                    // Device name
  t: number;                       // Timestamp when token was added
  Token: string;                   // FCM token string
  Rank?: number;                   // 1=Admin, 2=Manager, 3=Worker
  Email: string;                   // Associated email address
}

UserIntegrator#

Represents an integrator with access permissions.

interface UserIntegrator {
  uid: string;                     // Integrator UID
  email: string;                   // Integrator email
  name: string;                    // Integrator name
  integrators: string[];           // Array of integratorUIDs this user has access to
  createdAt: string;               // Creation timestamp
  updatedAt: string;               // Last update timestamp
  isActive: boolean;               // Whether integrator is active
  permissions?: {                  // Optional permission object
    canRead: boolean;
    canWrite: boolean;
    canDelete: boolean;
  };
}

Animal Data#

Animal#

Represents a livestock animal in the system.

interface Animal {
  Active: boolean;                 // Whether animal is active
  Battery: number;                 // Battery level (0-100)
  CurrentActivity: number;         // Current activity level
  CurrentTemperature: number;      // Latest ear-pinna temperature reading (°C). NOT core body temp.
  ReferenceTemperature?: number | null; // Rolling 7-day per-animal median of CurrentTemperature.
                                        // null while tag is calibrating (<7d of data or <100 valid samples).
                                        // Updated daily. Use (CurrentTemperature - ReferenceTemperature)
                                        // as the meaningful delta for heat/fever signals.
  ReferenceTemperatureUpdatedAt?: number; // ms since epoch of last baseline refresh.
  ReferenceTemperatureWindowDays?: number; // Window length in days (currently 7).
  EartagStart: number;             // Eartag start number
  Father: string;                  // Father's identifier
  Group: string;                   // Group assignment
  ID: string;                      // Unique animal identifier
  MAC: string;                     // MAC address of tracking device
  Mother: string;                  // Mother's identifier
  Node: string;                    // Node assignment
  NodeWeight: number;              // Weight at node
  Sex: 'male' | 'female';         // Animal sex
  SignalStrength: number;          // Signal strength of tracking device
  Uid: string;                     // Owner's user ID
  WatchdogWeight: number;          // Watchdog weight
  t: number;                       // Timestamp
  Suspicious: boolean;             // Whether animal shows suspicious behavior
  HealthScore?: number;            // Health score (0-100)
  Diagnosed?: {                    // Optional diagnosis information
    Description: string;
    Diagnose: string;
    t: number;
  };
}

Temperature: CurrentTemperature vs ReferenceTemperature#

The CurrentTemperature field on Animal is the latest ear-pinna temperature read from the BioTag sensor, NOT a core body temperature. Absolute pinna values shift with ambient conditions (ventilation, sun, tag fit), so the meaningful clinical signal is the deviation from the animal's own baseline:

delta = CurrentTemperature - ReferenceTemperature

ReferenceTemperature is a rolling 7-day median of that animal's pinna readings (column c in BigQuery), refreshed once per day. It is computed in biocv-production.animals.<mac> and written back to the Firestore animal document, so the same value powers every endpoint that exposes Animal.

Calibration window. ReferenceTemperature is null (or absent) while a tag has fewer than 7 days of data or fewer than 100 valid samples in the window. Render an honest "calibrating" fallback in the UI rather than substituting a default value.

Suggested deviation bands (starting point, tune per herd):

Banddelta (°C)Interpretation
Green< 0.3Within normal variation
Yellow0.3 – 0.6Watch
Red> 0.6Investigate (heat / fever)

Samples outside [25.0, 42.0] °C are dropped from the baseline as sensor noise (tag detached, floor reading, etc.).

AnimalEvent#

Represents an event related to an animal.

interface AnimalEvent {
  EventType: string;               // Type of event
  Group: string;                   // Group assignment
  MAC: string;                     // Animal's MAC address
  Scale: string;                   // Scale identifier
  Value: number;                   // Event value
  t: number;                       // Timestamp
}

AnimalLocationReading#

Represents a location sample for an animal from BigQuery.

interface AnimalLocationReading {
  t: number;                       // Timestamp (milliseconds since epoch)
  rssi: number;                    // Signal strength in dBm
  nodeuid: string;                 // Node UID that detected the animal
}

AnimalSensorReading#

Represents a raw BioTag sensor sample for an animal from BigQuery.

interface AnimalSensorReading {
  t: number;                       // Timestamp (milliseconds since epoch)
  c: number;                       // Temperature in Celsius
  x: number;                       // Acceleration X-axis (g-force)
  y: number;                       // Acceleration Y-axis (g-force)
  z: number;                       // Acceleration Z-axis (g-force)
}

AnimalSensorAnalytics#

Represents raw BioTag sensor analytics over a given time window.

interface AnimalSensorAnalytics {
  averageTemperature: number;      // Average temperature over time window
  averageAccelerationMagnitude: number; // Average acceleration magnitude
  temperatureRange: {              // Temperature range
    min: number;
    max: number;
  };
  accelerationMagnitudeRange: {    // Acceleration magnitude range
    min: number;
    max: number;
  };
  dataPointsCount: number;         // Number of samples analyzed
  timeRange: {                     // Time window
    start: number;                 // Start timestamp (ms since epoch)
    end: number;                   // End timestamp (ms since epoch)
  };
}

Treatment Data#

Treatment#

Represents a medical treatment record.

interface Treatment {
  Archived: boolean;               // Whether treatment is archived
  Comment: string;                 // Treatment comments
  CustomName: string;              // Custom treatment name
  Diagnose: string;                // Diagnosis
  ID: string;                      // Unique treatment identifier (auto-generated)
  Mac: string;                     // Animal's MAC address
  Medicine: string;                // Medicine used
  PhoneHistory: UserPhone[];       // Phone history for notifications
  StartDate: string;               // Start date (string format)
  StartDateSeconds: number;        // Start date (Unix timestamp)
  TreatmentAmount: number;         // Amount of treatment
  TreatmentCount: number;          // Number of treatments
  TreatmentInterval: number;       // Treatment interval in hours
  Dosis?: number;                  // Optional dosage
  Group?: string;                  // Optional group assignment
  t: number;                       // Timestamp (auto-generated)
  Validated?: boolean;             // Whether treatment is validated
}

Validation Rules for POST /users/:userId/treatments:

  • Required Fields: Mac, Medicine, Diagnose, CustomName, Comment, TreatmentAmount, TreatmentCount, TreatmentInterval, StartDate, StartDateSeconds, Archived, PhoneHistory
  • Auto-generated Fields: ID (timestamp-based), t (current timestamp)
  • Optional Fields: Dosis, Group, Validated
  • MAC Validation: Must exist in user's Animals collection
  • Data Types:
    • TreatmentAmount, TreatmentCount, TreatmentInterval, StartDateSeconds must be non-negative numbers
    • Archived must be boolean
    • PhoneHistory must be an array
    • All string fields are required and cannot be empty

Insemination Data#

Insemination#

Represents an artificial insemination record.

interface Insemination {
  Archived: boolean;               // Whether insemination record is archived
  Boar: string;                    // Boar identification
  GeneticLine: string;             // Genetic line information
  ID: string;                      // Unique insemination identifier (auto-generated)
  MAC: string;                     // Animal's MAC address
  Occupied: boolean;               // Whether animal is occupied
  StartDate: string;               // Insemination date (string format)
  StartTime: string;               // Insemination time (string format)
  Tubes: number;                   // Number of tubes used
  Uid: string;                     // Owner's user ID
  t: number;                       // Timestamp (auto-generated)
}

Validation Rules for POST /users/:userId/inseminations:

  • Required Fields: MAC, Boar, GeneticLine, Tubes, StartDate, StartTime, Archived, Occupied, Uid
  • Auto-generated Fields: ID (timestamp-based), t (current timestamp)
  • MAC Validation: Must exist in user's Animals collection
  • Data Types:
    • Tubes must be a non-negative number
    • Archived and Occupied must be booleans
    • All string fields are required and cannot be empty

Birth Data#

Birth#

Represents a birth event record.

interface Birth {
  Archived: boolean;               // Whether birth record is archived
  Comment?: string;                // Birth comments (optional)
  Dead: number;                    // Number of dead piglets
  ID: string;                      // Unique birth identifier (auto-generated)
  Living: number;                  // Number of living piglets
  MAC: string;                     // Mother's MAC address
  StartDate: string;               // Birth date (string format)
  StartTime?: string;              // Birth time (string format, optional)
  Uid: string;                     // Owner's user ID
  t: number;                       // Timestamp (auto-generated)
  // Extended fields (optional)
  Mummified?: number;              // Number of mummified piglets
  Weaned?: number;                 // Number of weaned piglets
  Parity?: number;                 // Parity number
  Assisted?: boolean;              // Whether birth was assisted
  FarrowingDuration?: number;      // Farrowing duration in minutes
  Complications?: string;          // Complications description
  AverageLitterWeight?: number;    // Average weight of piglets (kg)
}

Validation Rules for POST /users/:userId/births:

  • Required Fields: MAC, Living, Dead, StartDate, StartTime, Comment, Archived, Uid
  • Auto-generated Fields: ID (timestamp-based), t (current timestamp)
  • MAC Validation: Must exist in user's Animals collection
  • Data Types:
    • Living and Dead must be non-negative numbers
    • Archived must be boolean
    • All string fields are required and cannot be empty

Birth Statistics#

Represents aggregated birth statistics.

interface BirthStatistics {
  totalBirths: number;             // Total number of births
  totalLiving: number;             // Total living piglets
  totalDead: number;               // Total dead piglets
  averageLitterSize: number;       // Average litter size
  survivalRate: number;            // Survival rate percentage
}

Insemination Data#

Insemination#

Represents an insemination event record.

interface Insemination {
  Archived: boolean;               // Whether insemination record is archived
  Boar: string;                    // Boar identifier (required)
  GeneticLine?: string;           // Genetic line identifier (optional)
  ID: string;                      // Unique insemination identifier
  MAC: string;                     // Animal's MAC address
  Occupied: boolean;               // Whether animal is occupied
  StartDate: string;               // Insemination date (string format)
  StartTime?: string;              // Insemination time (string format, optional)
  Tubes?: number;                  // Number of tubes used (optional)
  Uid?: string;                    // Owner's user ID (optional)
  t: number;                       // Timestamp
  // Extended fields (optional)
  serviceOrder?: number;           // Service order number (1, 2, 3, etc.)
  serviceType?: 'AI' | 'natural';  // Type of service
  semenSource?: string;            // Source of semen
  HeatDetectionDate?: string;     // Date heat was detected
  ServiceNumber?: number;          // Service number in cycle
  Parity?: number;                  // Parity number
  Technician?: string;             // Technician who performed insemination
  SemenBatch?: string;             // Semen batch identifier
  ExpectedFarrowingDate?: string; // Expected farrowing date
  PregnancyCheckDate?: string;     // Date of pregnancy check
  ReturnToEstrusDate?: string;     // Date of return to estrus (if applicable)
  BreedingGroup?: string;          // Breeding group identifier
  ScanningResult?: {              // Scanning result (optional)
    Confirmed: boolean;
    ScanningDate: string;
    Notes?: string;
  };
}

General Event Data#

GeneralEvent#

Represents a general event record for an animal.

interface GeneralEvent {
  Archived?: boolean;              // Whether event is archived (optional)
  MAC: string;                     // Animal's MAC address
  Uid: string;                     // Owner's user ID
  t: number;                       // Timestamp
  ID: string;                      // Unique event identifier
  Diagnose: string;                // Diagnosis or event type
  Description: string;             // Event description
  Token?: string;                  // Associated token (optional)
  Comment?: string;                // Additional comments (optional, alternative to Description)
}

Pregnancy Check Data#

PregnancyCheck#

Represents a pregnancy check record.

interface PregnancyCheck {
  t: number | string;              // Timestamp (can be number or string)
  ID: string;                      // Unique check identifier
  MAC: string;                     // Animal's MAC address
  checkDate: string;               // Date of pregnancy check (required)
  checkNumber?: number;            // Check number in sequence (default: 1)
  result: 'pregnant' | 'open' | 'recheck';  // Check result (required)
  method?: string;                 // Method used (default: 'ultrasound')
  ServiceTimestamp?: number;       // Timestamp of related service
  notes?: string;                  // Additional notes
  technician?: string;             // Technician who performed check
  Archived?: boolean;              // Whether check is archived (default: false)
}

Return to Estrus Data#

ReturnToEstrus#

Represents a return to estrus event record.

interface ReturnToEstrus {
  t: number | string;              // Timestamp (can be number or string)
  ID: string;                      // Unique event identifier
  MAC: string;                      // Animal's MAC address
  returnDate: string;               // Date of return to estrus (required)
  returnType: 'regular' | 'irregular';  // Type of return (required)
  daysSinceService: number;        // Days since last service (required, min: 0)
  PreviousServiceTimestamp?: number; // Timestamp of previous service
  reasonCode?: string;             // Reason code for return
  Archived?: boolean;              // Whether event is archived (default: false)
}

Weaning Data#

Weaning#

Represents a weaning record.

interface Weaning {
  t: number | string;              // Timestamp (can be number or string)
  ID: string;                      // Unique weaning identifier
  MAC: string;                     // Animal's MAC address
  weaningDate: string;             // Date of weaning (required)
  countWeaned: number;             // Number of piglets weaned (required, min: 0)
  BirthTimestamp?: number;        // Timestamp of related birth
  weaningAge?: number;             // Age at weaning in days (min: 0)
  fosterIn?: number;               // Number fostered in (min: 0)
  fosterOut?: number;              // Number fostered out (min: 0)
  weaningWeight?: number;          // Average weaning weight (min: 0)
  Archived?: boolean;             // Whether weaning is archived (default: false)
}

Animal Movement Data#

AnimalMovement#

Represents an animal movement record between stages or locations.

interface AnimalMovement {
  t: number | string;              // Timestamp (can be number or string)
  ID: string;                      // Unique movement identifier
  MAC: string;                     // Animal's MAC address
  movementDate: string;             // Date of movement (required)
  fromStage: 'gilt-pool' | 'bred' | 'gestation' | 'farrowing' | 'lactation' | 'weaned' | 'cull';  // Source stage (required)
  toStage: 'gilt-pool' | 'bred' | 'gestation' | 'farrowing' | 'lactation' | 'weaned' | 'cull';    // Destination stage (required)
  fromLocation?: string;           // Source location (optional)
  toLocation?: string;             // Destination location (optional)
  Archived?: boolean;             // Whether movement is archived (default: false)
}

LitterGuard IoT Data#

LitterGuardData#

Represents a LitterGuard IoT device.

interface LitterGuardData {
  MAC: string;                     // Device MAC address (e.g., "AA:BB:CC:DD:EE:FF")
  Name: string;                    // User-defined device name
  LastSeen: any;                   // FirestoreTimestamp of last data received
  Active: boolean;                 // Device connectivity status
  CurrentTemperature: number;      // Latest temperature reading (°C)
}

SensorReading#

Represents a single sensor reading from a LitterGuard device.

interface SensorReading {
  t: number;                       // Unix timestamp (seconds)
  c: number;                       // Temperature in Celsius
  x: number;                       // Acceleration X-axis (g-force)
  y: number;                       // Acceleration Y-axis (g-force)
  z: number;                       // Acceleration Z-axis (g-force)
}

LitterGuardAnalytics#

Represents analytics data for a LitterGuard device.

interface LitterGuardAnalytics {
  averageTemperature: number;      // Average temperature over time range
  averageAccelerationMagnitude: number; // Average acceleration magnitude
  temperatureRange: {              // Temperature range
    min: number;
    max: number;
  };
  activityLevel: 'low' | 'normal' | 'high'; // Activity level classification
  unusualActivityDetected: boolean; // Whether unusual activity was detected
  dataPointsCount: number;         // Number of data points analyzed
  timeRange: {                     // Time range of analysis
    start: number;                 // Start timestamp
    end: number;                   // End timestamp
  };
}

LitterGuardSummary#

Represents summary statistics for all LitterGuard devices.

interface LitterGuardSummary {
  totalDevices: number;            // Total number of devices
  activeDevices: number;           // Number of active devices
  inactiveDevices: number;         // Number of inactive devices
  averageTemperature: number;      // Average temperature across all devices
  devicesWithUnusualActivity: number; // Number of devices with unusual activity
  lastDataReceived: number;        // Timestamp of last data received
}

AI Prediction Data#

AIPrediction#

Represents an AI prediction result.

interface AIPrediction {
  timestamp: string;                // When the prediction was made
  classificationType: string;       // Type of prediction (heat, birth, lameness)
  userId: string;                   // User ID
  animal: {                        // Animal information at time of prediction
    id: string;                    // Animal ID
    mac: string;                   // Animal MAC address
    name: string;                  // Animal name
    group: string;                 // Animal group
    weight: number;                // Animal weight
    userId: string;                // Owner user ID
  };
  results: PredictionResult[];     // Array of prediction results
}

PredictionResult#

Represents a single prediction result within an AI prediction.

interface PredictionResult {
  timestamp: string;                // Timestamp of the prediction window
  probability: number;              // Confidence score (0.0-1.0)
}

PredictionQueryParams#

Query parameters for AI prediction endpoints.

interface PredictionQueryParams extends QueryParams {
  classificationType?: 'heat' | 'birth' | 'lameness'; // Filter by prediction type
  startDate?: string;              // Start date filter (ISO 8601 format)
  endDate?: string;                // End date filter (ISO 8601 format)
  minProbability?: number;         // Minimum probability threshold (0.0-1.0)
  maxProbability?: number;         // Maximum probability threshold (0.0-1.0)
}

API Response Types#

ApiResponse#

Base response format for all API endpoints.

interface ApiResponse<T = any> {
  success: boolean;                // Whether the request was successful
  data?: T;                       // Response data (type varies by endpoint)
  error?: string;                 // Error message (if success is false)
  message?: string;               // Success message (if success is true)
  timestamp: string;              // Response timestamp (ISO 8601 format)
}

PaginatedResponse#

Response format for paginated endpoints.

interface PaginatedResponse<T = any> extends ApiResponse<T[]> {
  pagination: {                   // Pagination information
    page: number;                 // Current page number
    limit: number;                // Items per page
    total: number;                // Total number of items
    totalPages: number;           // Total number of pages
  };
}

Query Parameters#

QueryParams#

Base query parameters for most endpoints.

interface QueryParams {
  page?: number;                  // Page number (default: 1)
  limit?: number;                 // Items per page (default: 10, max: 100)
  sortBy?: string;                // Field to sort by (default: 't')
  sortOrder?: 'asc' | 'desc';     // Sort order (default: 'desc')
  filter?: Record<string, any>;   // Filter object with field-value pairs
}

AnimalLocationQueryParams#

Query parameters for the raw animal time-series endpoints (/locations and /sensordata).

interface AnimalLocationQueryParams {
  startTime?: number;             // Start time filter (milliseconds since epoch)
  endTime?: number;               // End time filter (milliseconds since epoch)
  limit?: number;                 // Maximum number of rows (default: 100, max: 10000)
  sortOrder?: 'asc' | 'desc';     // Sort order (default: 'desc')
}

LitterGuardQueryParams#

Specialized query parameters for LitterGuard endpoints.

interface LitterGuardQueryParams extends QueryParams {
  active?: boolean;               // Filter by device status
  mac?: string;                   // Filter by MAC address
  name?: string;                  // Filter by device name
  startTime?: number;             // Start time filter (Unix timestamp)
  endTime?: number;               // End time filter (Unix timestamp)
  timeRange?: '1h' | '6h' | '24h' | '7d' | '30d'; // Predefined time ranges
  limit?: number;                 // Maximum number of readings
}

JWT Token Types#

TokenPayload#

JWT token payload structure.

interface TokenPayload {
  integratorUID: string;          // Integrator UID
  type: 'access' | 'refresh';     // Token type
  iat: number;                    // Issued at timestamp
  exp: number;                    // Expiration timestamp
  jti?: string;                   // JWT ID for token tracking
}

TokenRequest#

Request format for token generation.

interface TokenRequest {
  integratorUID: string;          // Integrator UID
  expiresIn?: number;             // Token expiration in seconds (300-86400, default: 3600)
  refreshToken?: boolean;         // Whether to include refresh token (default: false)
}

TokenResponse#

Response format for token generation and refresh.

interface TokenResponse {
  accessToken: string;            // JWT access token
  refreshToken?: string;          // JWT refresh token (optional)
  expiresAt: number;              // Token expiration timestamp
  tokenType: 'Bearer';            // Token type
  integratorUID: string;          // Integrator UID
}

Usage Tracking#

UsageRecord#

Represents an API usage record for tracking.

interface UsageRecord {
  timestamp: string;               // Request timestamp
  endpoint: string;                // API endpoint called
  method: string;                  // HTTP method
  integratorUID: string;           // Integrator UID
  responseCode: number;            // HTTP response code
  responseTime: number;            // Response time in milliseconds
  dataSize?: number;               // Response data size in bytes
  userAgent?: string;              // User agent string
  ipAddress?: string;              // Client IP address
}

Data Validation#

Field Validation Rules#

  • Email: Must be a valid email format
  • MAC Address: Must be in format "AA:BB:CC:DD:EE:FF"
  • Phone: Must be a valid phone number format
  • Timestamps: Must be Unix timestamps (seconds) or ISO 8601 strings
  • Probabilities: Must be between 0.0 and 1.0
  • Ranks: Must be 1 (Admin), 2 (Manager), or 3 (Worker)
  • Sex: Must be 'male' or 'female'
  • Sort Order: Must be 'asc' or 'desc'

Required Fields#

Most data models have required fields that must be present:

  • User: Email, Name, Uid
  • Animal: ID, MAC, Uid, Sex
  • Treatment: ID, Mac, Medicine, StartDate
  • Birth: ID, MAC, Uid, StartDate
  • LitterGuard: MAC, Name

Next: Error Handling - Complete error codes and handling guide

Diese Seite wird aus dem offiziellen LiSA-API-Wiki erzeugt. Sollte etwas falsch sein oder fehlen, kontaktieren Sie uns — wir korrigieren es an der Quelle.

Wiki-Stand 158c1a5 · 28.7.2026

Hallo! Brauchen Sie Hilfe? Chatten Sie mit mir!