Complete implementation examples for the LISA REST API in various programming languages.
class LISAPIClient {
constructor(integratorUID, baseURL = 'https://api.biocv.info/api/v1') {
this.integratorUID = integratorUID;
this.baseURL = baseURL;
this.accessToken = null;
this.refreshToken = null;
}
async generateTokens(expiresIn = 3600) {
const response = await fetch(`${this.baseURL}/tokens`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
integratorUID: this.integratorUID,
expiresIn,
refreshToken: true
})
});
const data = await response.json();
if (data.success) {
this.accessToken = data.data.accessToken;
this.refreshToken = data.data.refreshToken;
return data.data;
}
throw new Error(data.error);
}
async makeRequest(endpoint, options = {}) {
if (!this.accessToken) {
await this.generateTokens();
}
const url = `${this.baseURL}${endpoint}`;
const headers = {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
...options.headers
};
const response = await fetch(url, { ...options, headers });
const data = await response.json();
if (!data.success) {
throw new Error(`API Error: ${data.error}`);
}
return data;
}
// Animal methods
async getAnimals(userId, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals?page=${page}&limit=${limit}`);
}
async getAnimal(userId, animalId) {
return this.makeRequest(`/users/${userId}/animals/${animalId}`);
}
// Treatment methods
async getTreatments(userId, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/treatments?page=${page}&limit=${limit}`);
}
// Birth methods
async getBirths(userId, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/births?page=${page}&limit=${limit}`);
}
async getBirthStatistics(userId) {
return this.makeRequest(`/users/${userId}/births/statistics`);
}
async createBirth(userId, birthData) {
return this.makeRequest(`/users/${userId}/births`, {
method: 'POST',
body: JSON.stringify(birthData)
});
}
// Insemination methods
async getInseminations(userId, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/inseminations?page=${page}&limit=${limit}`);
}
async createInsemination(userId, inseminationData) {
return this.makeRequest(`/users/${userId}/inseminations`, {
method: 'POST',
body: JSON.stringify(inseminationData)
});
}
// Treatment methods
async createTreatment(userId, treatmentData) {
return this.makeRequest(`/users/${userId}/treatments`, {
method: 'POST',
body: JSON.stringify(treatmentData)
});
}
// LitterGuard methods
async getLitterGuards(userId, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/litterguards?page=${page}&limit=${limit}`);
}
async getLitterGuardSummary(userId) {
return this.makeRequest(`/users/${userId}/litterguards/summary`);
}
async getLitterGuardDevice(userId, macAddress) {
return this.makeRequest(`/users/${userId}/litterguards/${macAddress}`);
}
async getLitterGuardSensorData(userId, macAddress, timeRange = '24h', limit = 100) {
return this.makeRequest(`/users/${userId}/litterguards/${macAddress}/sensordata?timeRange=${timeRange}&limit=${limit}`);
}
async getLitterGuardAnalytics(userId, macAddress, timeRange = '24h') {
return this.makeRequest(`/users/${userId}/litterguards/${macAddress}/analytics?timeRange=${timeRange}`);
}
// AI Predictions methods
async getAnimalPredictions(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/predictions?page=${page}&limit=${limit}`);
}
async getHeatPredictions(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/predictions/heat?page=${page}&limit=${limit}`);
}
async getBirthPredictions(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/predictions/birth?page=${page}&limit=${limit}`);
}
async getLamenessPredictions(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/predictions/lameness?page=${page}&limit=${limit}`);
}
async getRecentPredictions(userId, animalMac, limit = 10, classificationType = null) {
const params = new URLSearchParams({ limit: limit.toString() });
if (classificationType) params.append('classificationType', classificationType);
return this.makeRequest(`/users/${userId}/animals/${animalMac}/predictions/recent?${params}`);
}
async getPredictionsInRange(userId, animalMac, startDate, endDate, classificationType = null) {
const params = new URLSearchParams({
startDate: startDate.toISOString(),
endDate: endDate.toISOString()
});
if (classificationType) params.append('classificationType', classificationType);
return this.makeRequest(`/users/${userId}/animals/${animalMac}/predictions/range?${params}`);
}
// Animal Production Data methods
async getAnimalBirths(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/births?page=${page}&limit=${limit}`);
}
async getAnimalBirthById(userId, animalMac, birthId) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/births/${birthId}`);
}
async getRecentAnimalBirths(userId, animalMac, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/births/recent?limit=${limit}`);
}
async getAnimalBirthsInRange(userId, animalMac, startDate, endDate) {
const params = new URLSearchParams({
startDate: startDate.toISOString(),
endDate: endDate.toISOString()
});
return this.makeRequest(`/users/${userId}/animals/${animalMac}/births/range?${params}`);
}
async createAnimalBirth(userId, animalMac, birthData) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/births`, 'POST', birthData);
}
async getAnimalInseminations(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/inseminations?page=${page}&limit=${limit}`);
}
async getAnimalInseminationById(userId, animalMac, inseminationId) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/inseminations/${inseminationId}`);
}
async getRecentAnimalInseminations(userId, animalMac, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/inseminations/recent?limit=${limit}`);
}
async getAnimalInseminationsInRange(userId, animalMac, startDate, endDate) {
const params = new URLSearchParams({
startDate: startDate.toISOString(),
endDate: endDate.toISOString()
});
return this.makeRequest(`/users/${userId}/animals/${animalMac}/inseminations/range?${params}`);
}
async createAnimalInsemination(userId, animalMac, inseminationData) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/inseminations`, 'POST', inseminationData);
}
async getAnimalGeneralEvents(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/general-events?page=${page}&limit=${limit}`);
}
async getAnimalGeneralEventById(userId, animalMac, eventId) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/general-events/${eventId}`);
}
async getRecentAnimalGeneralEvents(userId, animalMac, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/general-events/recent?limit=${limit}`);
}
async getAnimalPregnancyChecks(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/pregnancy-checks?page=${page}&limit=${limit}`);
}
async getAnimalPregnancyCheckById(userId, animalMac, checkId) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/pregnancy-checks/${checkId}`);
}
async getRecentAnimalPregnancyChecks(userId, animalMac, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/pregnancy-checks/recent?limit=${limit}`);
}
async createAnimalPregnancyCheck(userId, animalMac, checkData) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/pregnancy-checks`, 'POST', checkData);
}
async getAnimalReturnToEstrus(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/return-to-estrus?page=${page}&limit=${limit}`);
}
async getAnimalReturnToEstrusById(userId, animalMac, eventId) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/return-to-estrus/${eventId}`);
}
async getRecentAnimalReturnToEstrus(userId, animalMac, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/return-to-estrus/recent?limit=${limit}`);
}
async createAnimalReturnToEstrus(userId, animalMac, eventData) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/return-to-estrus`, 'POST', eventData);
}
async getAnimalWeanings(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/weanings?page=${page}&limit=${limit}`);
}
async getAnimalWeaningById(userId, animalMac, weaningId) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/weanings/${weaningId}`);
}
async getRecentAnimalWeanings(userId, animalMac, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/weanings/recent?limit=${limit}`);
}
async createAnimalWeaning(userId, animalMac, weaningData) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/weanings`, 'POST', weaningData);
}
async getAnimalMovements(userId, animalMac, page = 1, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/movements?page=${page}&limit=${limit}`);
}
async getAnimalMovementById(userId, animalMac, movementId) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/movements/${movementId}`);
}
async getRecentAnimalMovements(userId, animalMac, limit = 10) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/movements/recent?limit=${limit}`);
}
async createAnimalMovement(userId, animalMac, movementData) {
return this.makeRequest(`/users/${userId}/animals/${animalMac}/movements`, 'POST', movementData);
}
}
// Usage
const client = new LISAPIClient('your-integrator-uid');
try {
// Get animals
const animals = await client.getAnimals('user123', 1, 20);
console.log('Animals:', animals.data);
// Get treatments
const treatments = await client.getTreatments('user123', 1, 10);
console.log('Treatments:', treatments.data);
// Get births and statistics
const births = await client.getBirths('user123', 1, 10);
console.log('Births:', births.data);
const stats = await client.getBirthStatistics('user123');
console.log('Birth statistics:', stats.data);
// Create new birth record
const newBirth = await client.createBirth('user123', {
MAC: 'AA:BB:CC:DD:EE:FF',
Living: 8,
Dead: 1,
StartDate: '2024-01-15',
StartTime: '14:30',
Comment: 'Normal birth, one stillborn',
Archived: false,
Uid: 'user123'
});
console.log('Created birth:', newBirth.data);
// Create new insemination record
const newInsemination = await client.createInsemination('user123', {
MAC: 'AA:BB:CC:DD:EE:FF',
Boar: 'Boar_001',
GeneticLine: 'Yorkshire',
Tubes: 2,
StartDate: '2024-01-15',
StartTime: '09:00',
Archived: false,
Occupied: true,
Uid: 'user123'
});
console.log('Created insemination:', newInsemination.data);
// Create new treatment record
const newTreatment = await client.createTreatment('user123', {
Mac: 'AA:BB:CC:DD:EE:FF',
Medicine: 'Penicillin',
Diagnose: 'Mastitis',
CustomName: 'Dr. Smith',
Comment: 'Left front quarter infection',
TreatmentAmount: 5,
TreatmentCount: 0,
TreatmentInterval: 12,
StartDate: '2024-01-15',
StartDateSeconds: 1705329000,
Archived: false,
PhoneHistory: []
});
console.log('Created treatment:', newTreatment.data);
// Get LitterGuard devices and data
const litterguards = await client.getLitterGuards('user123', 1, 10);
console.log('LitterGuards:', litterguards.data);
const lgSummary = await client.getLitterGuardSummary('user123');
console.log('LitterGuard Summary:', lgSummary.data);
// Get specific device data
const device = await client.getLitterGuardDevice('user123', 'AA:BB:CC:DD:EE:FF');
console.log('Device:', device.data);
const sensorData = await client.getLitterGuardSensorData('user123', 'AA:BB:CC:DD:EE:FF', '24h', 50);
console.log('Sensor Data:', sensorData.data);
const analytics = await client.getLitterGuardAnalytics('user123', 'AA:BB:CC:DD:EE:FF', '7d');
console.log('Analytics:', analytics.data);
// Get AI predictions
const predictions = await client.getAnimalPredictions('user123', 'AA:BB:CC:DD:EE:FF', 1, 10);
console.log('All Predictions:', predictions.data);
const heatPredictions = await client.getHeatPredictions('user123', 'AA:BB:CC:DD:EE:FF', 1, 5);
console.log('Heat Predictions:', heatPredictions.data);
const recentPredictions = await client.getRecentPredictions('user123', 'AA:BB:CC:DD:EE:FF', 5, 'heat');
console.log('Recent Heat Predictions:', recentPredictions.data);
// Get predictions in date range
const startDate = new Date('2024-01-01');
const endDate = new Date('2024-01-31');
const rangePredictions = await client.getPredictionsInRange('user123', 'AA:BB:CC:DD:EE:FF', startDate, endDate, 'birth');
console.log('Birth Predictions in Range:', rangePredictions.data);
// Get animal production data
const animalMac = 'AA:BB:CC:DD:EE:FF';
// Births
const animalBirths = await client.getAnimalBirths('user123', animalMac, 1, 10);
console.log('Animal Births:', animalBirths.data);
const recentBirths = await client.getRecentAnimalBirths('user123', animalMac, 5);
console.log('Recent Births:', recentBirths.data);
const birth = await client.createAnimalBirth('user123', animalMac, {
MAC: animalMac,
Living: 10,
Dead: 0,
StartDate: '2024-01-15',
StartTime: '14:30:00',
Comment: 'Normal birth'
});
console.log('Created Birth:', birth.data);
// Inseminations
const inseminations = await client.getAnimalInseminations('user123', animalMac);
console.log('Inseminations:', inseminations.data);
const newInsemination = await client.createAnimalInsemination('user123', animalMac, {
MAC: animalMac,
Boar: 'Boar-001',
StartDate: '2024-01-15',
StartTime: '10:00:00'
});
console.log('Created Insemination:', newInsemination.data);
// Pregnancy Checks
const checks = await client.getAnimalPregnancyChecks('user123', animalMac);
console.log('Pregnancy Checks:', checks.data);
const newCheck = await client.createAnimalPregnancyCheck('user123', animalMac, {
MAC: animalMac,
checkDate: '2024-01-15',
result: 'pregnant',
method: 'ultrasound'
});
console.log('Created Pregnancy Check:', newCheck.data);
} catch (error) {
console.error('API Error:', error.message);
}
class LitterGuardMonitor {
constructor(apiClient, userId) {
this.apiClient = apiClient;
this.userId = userId;
}
async getDeviceOverview() {
const [devices, summary] = await Promise.all([
this.apiClient.getLitterGuards(this.userId),
this.apiClient.getLitterGuardSummary(this.userId)
]);
console.log('=== LitterGuard Overview ===');
console.log(`Total devices: ${summary.data.totalDevices}`);
console.log(`Active devices: ${summary.data.activeDevices}`);
console.log(`Average temperature: ${summary.data.averageTemperature}°C`);
return { devices: devices.data, summary: summary.data };
}
async monitorDevice(macAddress, timeRange = '24h') {
const [device, analytics, latestReadings] = await Promise.all([
this.apiClient.getLitterGuard(this.userId, macAddress),
this.apiClient.getLitterGuardAnalytics(this.userId, macAddress, timeRange),
this.apiClient.getLatestSensorReadings(this.userId, macAddress, 10)
]);
console.log(`=== Device: ${device.data.Name} (${macAddress}) ===`);
console.log(`Status: ${device.data.Active ? 'Active' : 'Inactive'}`);
console.log(`Current Temperature: ${device.data.CurrentTemperature}°C`);
console.log(`\n--- Analytics (${timeRange}) ---`);
console.log(`Average Temperature: ${analytics.data.averageTemperature}°C`);
console.log(`Activity Level: ${analytics.data.activityLevel}`);
return { device: device.data, analytics: analytics.data, readings: latestReadings.data };
}
}
// Usage
const monitor = new LitterGuardMonitor(client, 'user123');
const overview = await monitor.getDeviceOverview();
const deviceData = await monitor.monitorDevice('AA:BB:CC:DD:EE:FF', '7d');
import requests
from typing import Dict, Any, Optional
class LISAPIClient:
def __init__(self, integrator_uid: str, base_url: str = "https://api.biocv.info/api/v1"):
self.integrator_uid = integrator_uid
self.base_url = base_url
self.access_token = None
self.refresh_token = None
self.session = requests.Session()
self.session.headers.update({"Content-Type": "application/json"})
def generate_tokens(self, expires_in: int = 3600) -> Dict[str, Any]:
response = self.session.post(f"{self.base_url}/tokens",
json={
"integratorUID": self.integrator_uid,
"expiresIn": expires_in,
"refreshToken": True
}
)
data = response.json()
if data["success"]:
self.access_token = data["data"]["accessToken"]
self.refresh_token = data["data"]["refreshToken"]
return data["data"]
raise Exception(f"Failed to generate tokens: {data.get('error', 'Unknown error')}")
def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
if not self.access_token:
self.generate_tokens()
self.session.headers.update({"Authorization": f"Bearer {self.access_token}"})
url = f"{self.base_url}{endpoint}"
response = self.session.request(method, url, **kwargs)
data = response.json()
if not data.get("success", False):
raise Exception(f"API Error: {data.get('error', 'Unknown error')}")
return data
def get_animals(self, user_id: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals?page={page}&limit={limit}")
def get_treatments(self, user_id: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/treatments?page={page}&limit={limit}")
def get_births(self, user_id: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/births?page={page}&limit={limit}")
def get_birth_statistics(self, user_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/births/statistics")
def get_litterguards(self, user_id: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/litterguards?page={page}&limit={limit}")
def get_litterguard_summary(self, user_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/litterguards/summary")
def get_inseminations(self, user_id: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/inseminations?page={page}&limit={limit}")
def create_birth(self, user_id: str, birth_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/births", json=birth_data)
def create_insemination(self, user_id: str, insemination_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/inseminations", json=insemination_data)
def create_treatment(self, user_id: str, treatment_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/treatments", json=treatment_data)
# Animal Production Data methods
def get_animal_births(self, user_id: str, animal_mac: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/births?page={page}&limit={limit}")
def get_animal_birth_by_id(self, user_id: str, animal_mac: str, birth_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/births/{birth_id}")
def get_recent_animal_births(self, user_id: str, animal_mac: str, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/births/recent?limit={limit}")
def get_animal_births_in_range(self, user_id: str, animal_mac: str, start_date: str, end_date: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/births/range?startDate={start_date}&endDate={end_date}")
def create_animal_birth(self, user_id: str, animal_mac: str, birth_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/animals/{animal_mac}/births", birth_data)
def get_animal_inseminations(self, user_id: str, animal_mac: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/inseminations?page={page}&limit={limit}")
def get_animal_insemination_by_id(self, user_id: str, animal_mac: str, insemination_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/inseminations/{insemination_id}")
def get_recent_animal_inseminations(self, user_id: str, animal_mac: str, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/inseminations/recent?limit={limit}")
def get_animal_inseminations_in_range(self, user_id: str, animal_mac: str, start_date: str, end_date: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/inseminations/range?startDate={start_date}&endDate={end_date}")
def create_animal_insemination(self, user_id: str, animal_mac: str, insemination_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/animals/{animal_mac}/inseminations", insemination_data)
def get_animal_general_events(self, user_id: str, animal_mac: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/general-events?page={page}&limit={limit}")
def get_animal_general_event_by_id(self, user_id: str, animal_mac: str, event_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/general-events/{event_id}")
def get_recent_animal_general_events(self, user_id: str, animal_mac: str, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/general-events/recent?limit={limit}")
def get_animal_pregnancy_checks(self, user_id: str, animal_mac: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/pregnancy-checks?page={page}&limit={limit}")
def get_animal_pregnancy_check_by_id(self, user_id: str, animal_mac: str, check_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/pregnancy-checks/{check_id}")
def get_recent_animal_pregnancy_checks(self, user_id: str, animal_mac: str, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/pregnancy-checks/recent?limit={limit}")
def create_animal_pregnancy_check(self, user_id: str, animal_mac: str, check_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/animals/{animal_mac}/pregnancy-checks", check_data)
def get_animal_return_to_estrus(self, user_id: str, animal_mac: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/return-to-estrus?page={page}&limit={limit}")
def get_animal_return_to_estrus_by_id(self, user_id: str, animal_mac: str, event_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/return-to-estrus/{event_id}")
def get_recent_animal_return_to_estrus(self, user_id: str, animal_mac: str, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/return-to-estrus/recent?limit={limit}")
def create_animal_return_to_estrus(self, user_id: str, animal_mac: str, event_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/animals/{animal_mac}/return-to-estrus", event_data)
def get_animal_weanings(self, user_id: str, animal_mac: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/weanings?page={page}&limit={limit}")
def get_animal_weaning_by_id(self, user_id: str, animal_mac: str, weaning_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/weanings/{weaning_id}")
def get_recent_animal_weanings(self, user_id: str, animal_mac: str, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/weanings/recent?limit={limit}")
def create_animal_weaning(self, user_id: str, animal_mac: str, weaning_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/animals/{animal_mac}/weanings", weaning_data)
def get_animal_movements(self, user_id: str, animal_mac: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/movements?page={page}&limit={limit}")
def get_animal_movement_by_id(self, user_id: str, animal_mac: str, movement_id: str) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/movements/{movement_id}")
def get_recent_animal_movements(self, user_id: str, animal_mac: str, limit: int = 10) -> Dict[str, Any]:
return self._make_request("GET", f"/users/{user_id}/animals/{animal_mac}/movements/recent?limit={limit}")
def create_animal_movement(self, user_id: str, animal_mac: str, movement_data: Dict[str, Any]) -> Dict[str, Any]:
return self._make_request("POST", f"/users/{user_id}/animals/{animal_mac}/movements", movement_data)
# Usage
client = LISAPIClient("your-integrator-uid")
try:
animals = client.get_animals("user123", page=1, limit=20)
print(f"Found {len(animals['data'])} animals")
stats = client.get_birth_statistics("user123")
print(f"Total births: {stats['data']['totalBirths']}")
# Create new birth record
new_birth = client.create_birth("user123", {
"MAC": "AA:BB:CC:DD:EE:FF",
"Living": 8,
"Dead": 1,
"StartDate": "2024-01-15",
"StartTime": "14:30",
"Comment": "Normal birth, one stillborn",
"Archived": False,
"Uid": "user123"
})
print(f"Created birth with ID: {new_birth['data']['ID']}")
# Create new treatment record
new_treatment = client.create_treatment("user123", {
"Mac": "AA:BB:CC:DD:EE:FF",
"Medicine": "Penicillin",
"Diagnose": "Mastitis",
"CustomName": "Dr. Smith",
"Comment": "Left front quarter infection",
"TreatmentAmount": 5,
"TreatmentCount": 0,
"TreatmentInterval": 12,
"StartDate": "2024-01-15",
"StartDateSeconds": 1705329000,
"Archived": False,
"PhoneHistory": []
})
print(f"Created treatment with ID: {new_treatment['data']['ID']}")
except Exception as e:
print(f"Error: {e}")
import pandas as pd
from datetime import datetime, timedelta
class LISADataAnalyzer:
def __init__(self, api_client):
self.api_client = api_client
def analyze_animal_health(self, user_id: str) -> Dict[str, Any]:
"""Analyze animal health data and identify issues."""
animals = self.api_client.get_animals(user_id, limit=1000)
df = pd.DataFrame(animals['data'])
# Identify suspicious animals
suspicious = df[df['Suspicious'] == True]
# Analyze temperature patterns
temp_stats = {
'average_temp': df['CurrentTemperature'].mean(),
'min_temp': df['CurrentTemperature'].min(),
'max_temp': df['CurrentTemperature'].max(),
'suspicious_count': len(suspicious)
}
return {
'total_animals': len(df),
'suspicious_animals': len(suspicious),
'temperature_stats': temp_stats,
'health_score_avg': df['HealthScore'].mean() if 'HealthScore' in df.columns else None
}
def generate_birth_report(self, user_id: str) -> Dict[str, Any]:
"""Generate comprehensive birth report."""
births = self.api_client.get_births(user_id, limit=1000)
stats = self.api_client.get_birth_statistics(user_id)
df = pd.DataFrame(births['data'])
# Monthly analysis
df['birth_date'] = pd.to_datetime(df['StartDate'])
monthly_births = df.groupby(df['birth_date'].dt.to_period('M')).agg({
'Living': 'sum',
'Dead': 'sum',
'ID': 'count'
}).rename(columns={'ID': 'total_births'})
return {
'summary': stats['data'],
'monthly_breakdown': monthly_births.to_dict('index'),
'recent_births': df.nlargest(10, 't')[['StartDate', 'Living', 'Dead']].to_dict('records')
}
# Usage
analyzer = LISADataAnalyzer(client)
health_analysis = analyzer.analyze_animal_health('user123')
birth_report = analyzer.generate_birth_report('user123')
# 1. Health check
curl -X GET "https://api.biocv.info/api/v1/health"
# 2. Generate token
curl -X POST "https://api.biocv.info/api/v1/tokens" \
-H "Content-Type: application/json" \
-d '{"integratorUID": "your-integrator-uid", "expiresIn": 3600, "refreshToken": true}'
# 3. Get animals
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals?page=1&limit=10"
# 4. Search animals
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/search?sex=female&active=true"
# 5. Get birth statistics
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/births/statistics"
# 6. Create birth record
curl -X POST "https://api.biocv.info/api/v1/users/user123/births" \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"Living": 8,
"Dead": 1,
"StartDate": "2024-01-15",
"StartTime": "14:30",
"Comment": "Normal birth, one stillborn",
"Archived": false,
"Uid": "user123"
}'
# 7. Create treatment record
curl -X POST "https://api.biocv.info/api/v1/users/user123/treatments" \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"Mac": "AA:BB:CC:DD:EE:FF",
"Medicine": "Penicillin",
"Diagnose": "Mastitis",
"CustomName": "Dr. Smith",
"Comment": "Left front quarter infection",
"TreatmentAmount": 5,
"TreatmentCount": 0,
"TreatmentInterval": 12,
"StartDate": "2024-01-15",
"StartDateSeconds": 1705329000,
"Archived": false,
"PhoneHistory": []
}'
# 8. Create insemination record
curl -X POST "https://api.biocv.info/api/v1/users/user123/inseminations" \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"Boar": "Boar_001",
"GeneticLine": "Yorkshire",
"Tubes": 2,
"StartDate": "2024-01-15",
"StartTime": "09:00",
"Archived": false,
"Occupied": true,
"Uid": "user123"
}'
# Get all LitterGuard devices
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/litterguards"
# Get device summary
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/litterguards/summary"
# Get sensor data for last 24 hours
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/litterguards/AA:BB:CC:DD:EE:FF/sensordata?timeRange=24h&limit=100"
# Get device analytics
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/litterguards/AA:BB:CC:DD:EE:FF/analytics?timeRange=7d"
# Get all births for an animal
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/births?page=1&limit=10"
# Get recent births for an animal
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/births/recent?limit=5"
# Get births in date range
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/births/range?startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z"
# Create birth record
curl -X POST \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"Living": 10,
"Dead": 0,
"StartDate": "2024-01-15",
"StartTime": "14:30:00",
"Comment": "Normal birth"
}' \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/births"
# Get inseminations for an animal
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/inseminations"
# Create insemination
curl -X POST \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"Boar": "Boar-001",
"StartDate": "2024-01-15",
"StartTime": "10:00:00"
}' \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/inseminations"
# Get pregnancy checks for an animal
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/pregnancy-checks"
# Create pregnancy check
curl -X POST \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"checkDate": "2024-01-15",
"result": "pregnant",
"method": "ultrasound"
}' \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/pregnancy-checks"
# Get return to estrus events
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/return-to-estrus"
# Create return to estrus event
curl -X POST \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"returnDate": "2024-01-15",
"returnType": "regular",
"daysSinceService": 21
}' \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/return-to-estrus"
# Get weanings for an animal
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/weanings"
# Create weaning
curl -X POST \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"weaningDate": "2024-01-15",
"countWeaned": 9
}' \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/weanings"
# Get animal movements
curl -H "Authorization: Bearer your-jwt-token" \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/movements"
# Create animal movement
curl -X POST \
-H "Authorization: Bearer your-jwt-token" \
-H "Content-Type: application/json" \
-d '{
"MAC": "AA:BB:CC:DD:EE:FF",
"movementDate": "2024-01-15",
"fromStage": "gestation",
"toStage": "farrowing"
}' \
"https://api.biocv.info/api/v1/users/user123/animals/AA:BB:CC:DD:EE:FF/movements"
<?php
class LISAPIClient {
private $integratorUID;
private $baseURL;
private $accessToken;
private $refreshToken;
public function __construct($integratorUID, $baseURL = 'https://api.biocv.info/api/v1') {
$this->integratorUID = $integratorUID;
$this->baseURL = $baseURL;
}
public function generateTokens($expiresIn = 3600) {
$response = $this->makeRequest('POST', '/tokens', [
'integratorUID' => $this->integratorUID,
'expiresIn' => $expiresIn,
'refreshToken' => true
]);
if ($response['success']) {
$this->accessToken = $response['data']['accessToken'];
$this->refreshToken = $response['data']['refreshToken'];
return $response['data'];
}
throw new Exception('Failed to generate tokens: ' . $response['error']);
}
private function makeRequest($method, $endpoint, $data = null) {
$url = $this->baseURL . $endpoint;
$headers = [
'Content-Type: application/json'
];
if ($this->accessToken) {
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decoded = json_decode($response, true);
if (!$decoded['success']) {
throw new Exception('API Error: ' . $decoded['error']);
}
return $decoded;
}
public function getAnimals($userId, $page = 1, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals?page={$page}&limit={$limit}");
}
public function getBirthStatistics($userId) {
return $this->makeRequest('GET', "/users/{$userId}/births/statistics");
}
// Animal Production Data methods
public function getAnimalBirths($userId, $animalMac, $page = 1, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/births?page={$page}&limit={$limit}");
}
public function getAnimalBirthById($userId, $animalMac, $birthId) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/births/{$birthId}");
}
public function getRecentAnimalBirths($userId, $animalMac, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/births/recent?limit={$limit}");
}
public function createAnimalBirth($userId, $animalMac, $birthData) {
return $this->makeRequest('POST', "/users/{$userId}/animals/{$animalMac}/births", $birthData);
}
public function getAnimalInseminations($userId, $animalMac, $page = 1, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/inseminations?page={$page}&limit={$limit}");
}
public function createAnimalInsemination($userId, $animalMac, $inseminationData) {
return $this->makeRequest('POST', "/users/{$userId}/animals/{$animalMac}/inseminations", $inseminationData);
}
public function getAnimalPregnancyChecks($userId, $animalMac, $page = 1, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/pregnancy-checks?page={$page}&limit={$limit}");
}
public function createAnimalPregnancyCheck($userId, $animalMac, $checkData) {
return $this->makeRequest('POST', "/users/{$userId}/animals/{$animalMac}/pregnancy-checks", $checkData);
}
public function getAnimalReturnToEstrus($userId, $animalMac, $page = 1, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/return-to-estrus?page={$page}&limit={$limit}");
}
public function createAnimalReturnToEstrus($userId, $animalMac, $eventData) {
return $this->makeRequest('POST', "/users/{$userId}/animals/{$animalMac}/return-to-estrus", $eventData);
}
public function getAnimalWeanings($userId, $animalMac, $page = 1, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/weanings?page={$page}&limit={$limit}");
}
public function createAnimalWeaning($userId, $animalMac, $weaningData) {
return $this->makeRequest('POST', "/users/{$userId}/animals/{$animalMac}/weanings", $weaningData);
}
public function getAnimalMovements($userId, $animalMac, $page = 1, $limit = 10) {
return $this->makeRequest('GET', "/users/{$userId}/animals/{$animalMac}/movements?page={$page}&limit={$limit}");
}
public function createAnimalMovement($userId, $animalMac, $movementData) {
return $this->makeRequest('POST', "/users/{$userId}/animals/{$animalMac}/movements", $movementData);
}
}
// Usage
$client = new LISAPIClient('your-integrator-uid');
try {
$client->generateTokens();
$animals = $client->getAnimals('user123', 1, 20);
echo "Found " . count($animals['data']) . " animals\n";
$stats = $client->getBirthStatistics('user123');
echo "Total births: " . $stats['data']['totalBirths'] . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type LISAPIClient struct {
IntegratorUID string
BaseURL string
AccessToken string
RefreshToken string
HTTPClient *http.Client
}
type TokenRequest struct {
IntegratorUID string `json:"integratorUID"`
ExpiresIn int `json:"expiresIn"`
RefreshToken bool `json:"refreshToken"`
}
type TokenResponse struct {
Success bool `json:"success"`
Data struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresAt int64 `json:"expiresAt"`
TokenType string `json:"tokenType"`
} `json:"data"`
Error string `json:"error"`
}
type APIResponse struct {
Success bool `json:"success"`
Data interface{} `json:"data"`
Error string `json:"error"`
}
func NewLISAPIClient(integratorUID string) *LISAPIClient {
return &LISAPIClient{
IntegratorUID: integratorUID,
BaseURL: "https://api.biocv.info/api/v1",
HTTPClient: &http.Client{Timeout: 30 * time.Second},
}
}
func (c *LISAPIClient) GenerateTokens() error {
tokenReq := TokenRequest{
IntegratorUID: c.IntegratorUID,
ExpiresIn: 3600,
RefreshToken: true,
}
jsonData, _ := json.Marshal(tokenReq)
resp, err := c.HTTPClient.Post(c.BaseURL+"/tokens", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var tokenResp TokenResponse
json.Unmarshal(body, &tokenResp)
if !tokenResp.Success {
return fmt.Errorf("failed to generate tokens: %s", tokenResp.Error)
}
c.AccessToken = tokenResp.Data.AccessToken
c.RefreshToken = tokenResp.Data.RefreshToken
return nil
}
func (c *LISAPIClient) makeRequest(method, endpoint string) (*APIResponse, error) {
if c.AccessToken == "" {
if err := c.GenerateTokens(); err != nil {
return nil, err
}
}
req, _ := http.NewRequest(method, c.BaseURL+endpoint, nil)
req.Header.Set("Authorization", "Bearer "+c.AccessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var apiResp APIResponse
json.Unmarshal(body, &apiResp)
if !apiResp.Success {
return nil, fmt.Errorf("API error: %s", apiResp.Error)
}
return &apiResp, nil
}
func (c *LISAPIClient) GetAnimals(userID string, page, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals?page=%d&limit=%d", userID, page, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) GetBirthStatistics(userID string) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/births/statistics", userID)
return c.makeRequest("GET", endpoint)
}
// Animal Production Data methods
func (c *LISAPIClient) GetAnimalBirths(userID, animalMac string, page, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/births?page=%d&limit=%d", userID, animalMac, page, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) GetAnimalBirthByID(userID, animalMac, birthID string) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/births/%s", userID, animalMac, birthID)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) GetRecentAnimalBirths(userID, animalMac string, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/births/recent?limit=%d", userID, animalMac, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) CreateAnimalBirth(userID, animalMac string, birthData map[string]interface{}) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/births", userID, animalMac)
return c.makeRequest("POST", endpoint, birthData)
}
func (c *LISAPIClient) GetAnimalInseminations(userID, animalMac string, page, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/inseminations?page=%d&limit=%d", userID, animalMac, page, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) CreateAnimalInsemination(userID, animalMac string, inseminationData map[string]interface{}) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/inseminations", userID, animalMac)
return c.makeRequest("POST", endpoint, inseminationData)
}
func (c *LISAPIClient) GetAnimalPregnancyChecks(userID, animalMac string, page, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/pregnancy-checks?page=%d&limit=%d", userID, animalMac, page, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) CreateAnimalPregnancyCheck(userID, animalMac string, checkData map[string]interface{}) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/pregnancy-checks", userID, animalMac)
return c.makeRequest("POST", endpoint, checkData)
}
func (c *LISAPIClient) GetAnimalReturnToEstrus(userID, animalMac string, page, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/return-to-estrus?page=%d&limit=%d", userID, animalMac, page, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) CreateAnimalReturnToEstrus(userID, animalMac string, eventData map[string]interface{}) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/return-to-estrus", userID, animalMac)
return c.makeRequest("POST", endpoint, eventData)
}
func (c *LISAPIClient) GetAnimalWeanings(userID, animalMac string, page, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/weanings?page=%d&limit=%d", userID, animalMac, page, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) CreateAnimalWeaning(userID, animalMac string, weaningData map[string]interface{}) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/weanings", userID, animalMac)
return c.makeRequest("POST", endpoint, weaningData)
}
func (c *LISAPIClient) GetAnimalMovements(userID, animalMac string, page, limit int) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/movements?page=%d&limit=%d", userID, animalMac, page, limit)
return c.makeRequest("GET", endpoint)
}
func (c *LISAPIClient) CreateAnimalMovement(userID, animalMac string, movementData map[string]interface{}) (*APIResponse, error) {
endpoint := fmt.Sprintf("/users/%s/animals/%s/movements", userID, animalMac)
return c.makeRequest("POST", endpoint, movementData)
}
func main() {
client := NewLISAPIClient("your-integrator-uid")
animals, err := client.GetAnimals("user123", 1, 20)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Found %d animals\n", len(animals.Data.([]interface{})))
stats, err := client.GetBirthStatistics("user123")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Birth statistics: %+v\n", stats.Data)
// Animal Production Data
animalMac := "AA:BB:CC:DD:EE:FF"
// Get animal births
births, err := client.GetAnimalBirths("user123", animalMac, 1, 10)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Animal births: %+v\n", births.Data)
// Create birth
birthData := map[string]interface{}{
"MAC": animalMac,
"Living": 10,
"Dead": 0,
"StartDate": "2024-01-15",
"StartTime": "14:30:00",
"Comment": "Normal birth",
}
newBirth, err := client.CreateAnimalBirth("user123", animalMac, birthData)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created birth: %+v\n", newBirth.Data)
}
async function robustAPICall(apiFunction, ...args) {
const maxRetries = 3;
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await apiFunction(...args);
} catch (error) {
lastError = error;
if (error.message.includes('401') && attempt < maxRetries) {
// Token expired, try to refresh
await client.generateTokens();
continue;
}
if (error.message.includes('429') && attempt < maxRetries) {
// Rate limited, wait and retry
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
continue;
}
throw error;
}
}
throw lastError;
}
class CachedLISAPIClient extends LISAPIClient {
constructor(integratorUID, cacheTTL = 300000) { // 5 minutes
super(integratorUID);
this.cache = new Map();
this.cacheTTL = cacheTTL;
}
async getCachedData(key, fetchFunction) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
return cached.data;
}
const data = await fetchFunction();
this.cache.set(key, {
data,
timestamp: Date.now()
});
return data;
}
async getAnimals(userId, page = 1, limit = 10) {
const cacheKey = `animals_${userId}_${page}_${limit}`;
return this.getCachedData(cacheKey, () =>
super.getAnimals(userId, page, limit)
);
}
}
Next: Best Practices - Complete best practices 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 e01e79e · 19.8.2026