Skip to content
Snippets Groups Projects
sensorconnector.dart 5.6 KiB
Newer Older
import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'datamodel.dart';

class SensorConnector {
Maximilian Betz's avatar
Maximilian Betz committed
  //final String baseUrl = 'https://sandbox.sensor.awi.de/rest/';
  final String baseUrl = 'https://sensor.awi.de/rest/';
  final String loginUrl = 'sensors/contacts/login';
  final String collectionsUrl = 'sensors/collections/getAllCollections?pointInTime=2018-07-03T12%3A30%3A55.389Z';
  final String eventTypesUrl = 'sensors/events/getAllEventTypes';
  final String collectionItemsUrl = 'sensors/collections/getItemsOfCollection/';  // + collectionId
  final String putEventUrl = 'sensors/events/putEvent/';  // + eventId;

  Future<String> getAuthToken(String username, String password) async {
    String url = baseUrl + loginUrl;
    String? token;

    Map<String, dynamic> body = {
      'username': username,
      'authPassword': password
    };
    String encodedBody = body.keys.map((key) => "$key=${body[key]}").join("&");

    try {
      final response = await http.post(Uri.parse(url),
          body: encodedBody,
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          encoding: Encoding.getByName("utf-8")
      );
      if (response.statusCode == 200) {
        token = response.headers['set-cookie']?.split(';')[0];
        debugPrint('Login success. Token: ' + token!.toString());
        return token;
      }
      else {
        debugPrint('Failed to login'
            'Header: ' + response.headers.toString() +
            ' StatusCode: ' + response.statusCode.toString() +
            ' Body: ' + response.body.toString());
        throw Exception('Failed to login');
      }
    } on SocketException catch (e){
      throw Exception('No connection');
    }catch (e){
      rethrow;
    }
  }
  Future<List<Collection>> fetchCollections() async {
    String url = baseUrl + collectionsUrl;
    List<Collection> collectionList = [];

      final response = await http.get(Uri.parse(url)).timeout(const Duration(seconds: 3));  //TODO: check if this timeout works
      if (response.statusCode == 200) {
        collectionList = (json.decode(response.body) as List)
            .map((i) => Collection.fromJson(i))
            .toList();
        debugPrint("Fetching Collections Success: $collectionList");
        collectionList.sort((a, b) => a.collectionName.compareTo(b.collectionName)); // Sort alphanumeric
        return collectionList;
      } else {
        throw Exception('Failed to fetch Collections. Header: ${response.headers} StatusCode: ${response.statusCode} Body: ${response.body}');
      }
    } on SocketException catch (e){
      throw Exception('No connection');
    }on TimeoutException catch (e){
      throw Exception('Connection Timeout');
    }catch (e){
      rethrow;
    }
  }

  Future<List<EventType>> fetchEventTypes() async {
    String url = baseUrl + eventTypesUrl;
    List<EventType> eventTypeList = [];

    try{
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        for (var entry in data) {
          eventTypeList.add(EventType.fromSensorJson(entry));
        }
        debugPrint("Fetching Event Types Success: $eventTypeList");
        return eventTypeList;
      } else{
        throw Exception('Failed to fetch event types. Header: ${response.headers} StatusCode: ${response.statusCode} Body: ${response.body}');
Maximilian Betz's avatar
Maximilian Betz committed
      }

    } on SocketException catch (e){
      throw Exception('No connection');
    }catch (e){
      rethrow;
  Future<List<Device>> fetchCollectionDevices(int collectionId) async {
    String url = baseUrl + collectionItemsUrl + collectionId.toString();
    List<Device> collectionDevices = [];

    try{
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        List<dynamic> data = json.decode(response.body);
        for (var entry in data) {
          collectionDevices.add(Device.fromJson(entry));
        }
        debugPrint("Fetching Collection Devices Success: $collectionDevices");
        collectionDevices.sort((a, b) => a.urn.compareTo(b.urn)); // Sort alphanumeric
        return collectionDevices;
      } else {
        throw Exception('Failed to load Collection Devices. Header: ${response.headers} StatusCode: ${response.statusCode} Body: ${response.body}');
    } on SocketException catch (e){
      throw Exception('No connection');
    }catch (e){
      rethrow;
    }
  }


  Future<bool> putEvent(Event event, String authToken) async {
    // Create url with corresponding device id:
    String url = baseUrl + putEventUrl + event.urnId.toString() + '?createVersion=false';

    try{
      final response = await http.put(Uri.parse(url),
        headers: {
          "Content-Type": "application/json",
          "Cookie": authToken
        },
        body: event.toSensorJson().toString(),
        encoding: Encoding.getByName("utf-8"),
      );
      if (response.statusCode == 201) {
        return true;
      } else if (response.statusCode == 401) {
Maximilian Betz's avatar
Maximilian Betz committed
        throw Exception('No write access for UrnId: ' + event.urnId.toString());
      }
      else {
        debugPrint(response.statusCode.toString());
        throw Exception('Failed to put event. '
            'Header: ' + response.headers.toString() +
            ' StatusCode: ' +response.statusCode.toString() +
            ' Body: ' +response.body.toString());
      }
    } on SocketException catch (e){
      throw Exception('No connection');
    }catch (e){
      rethrow;