├── addon ├── icon.png ├── logo.png ├── Dockerfile ├── root │ └── etc │ │ └── services.d │ │ └── leaf2mqtt │ │ └── run └── config.json ├── .dockerignore ├── .gitignore ├── repository.json ├── .editorconfig ├── docker-compose.yml ├── .github ├── ISSUE_TEMPLATE │ └── bug_report.md └── workflows │ └── leaf2mqtt.yml ├── pubspec.yaml ├── Dockerfile ├── src ├── leaf │ ├── builder │ │ ├── leaf_cockpitstatus_builder.dart │ │ ├── leaf_location_builder.dart │ │ ├── leaf_climate_builder.dart │ │ ├── leaf_builder_base.dart │ │ ├── leaf_battery_builder.dart │ │ └── leaf_stats_builder.dart │ ├── leaf_vehicle.dart │ ├── nissan_connect_na_wrapper.dart │ ├── nissan_connect_wrapper.dart │ ├── leaf_session.dart │ └── carwings_wrapper.dart ├── mqtt_client_wrapper.dart └── leaf_2_mqtt.dart ├── local_settings.env.tmpl ├── pubspec.lock ├── analysis_options.yaml ├── README.md └── LICENSE /addon/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yp87/leaf2mqtt/HEAD/addon/icon.png -------------------------------------------------------------------------------- /addon/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yp87/leaf2mqtt/HEAD/addon/logo.png -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # dart files to ignore 2 | .dart_tool/ 3 | .packages 4 | build/ 5 | 6 | #vscode files to ignore 7 | .vscode -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dart files to ignore 2 | .dart_tool/ 3 | .packages 4 | build/ 5 | 6 | #vscode files to ignore 7 | .vscode 8 | 9 | # per-user config 10 | local_settings.env 11 | -------------------------------------------------------------------------------- /repository.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "LEAF2MQTT Home Assistant add-on repository", 3 | "url": "https://github.com/yp87/leaf2mqtt", 4 | "maintainer": "YP87 " 5 | } 6 | -------------------------------------------------------------------------------- /addon/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG BUILD_VERSION 2 | ARG BUILD_ARCH 3 | 4 | FROM yp87/leaf2mqtt:${BUILD_VERSION} AS build 5 | FROM ghcr.io/hassio-addons/base/${BUILD_ARCH}:stable 6 | 7 | COPY --from=build / / 8 | COPY root/ / 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | leaf2mqtt: 5 | container_name: leaf2mqtt 6 | build: . 7 | image: leaf2mqtt 8 | logging: 9 | options: 10 | max-size: "1M" 11 | max-file: "5" 12 | env_file: 13 | - local_settings.env 14 | restart: unless-stopped 15 | 16 | -------------------------------------------------------------------------------- /addon/root/etc/services.d/leaf2mqtt/run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv bashio 2 | 3 | CONFIG=$(bashio::addon.options) 4 | 5 | bashio::log.info "Setting environment variables..." 6 | 7 | for k in $(bashio::jq "${CONFIG}" 'keys | .[]'); do 8 | export $k="$(bashio::config $k)" 9 | done 10 | 11 | bashio::log "Done." 12 | 13 | bashio::log.info "Starting leaf2mqtt..." 14 | 15 | /app/bin/leaf_2_mqtt 16 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: yp87 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **LEAF_TYPE** 14 | The leaf type you use in your configuration 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: leaf2mqtt 2 | version: 0.0.2 3 | publish_to: 'none' 4 | dependencies: 5 | dartnissanconnectna: 6 | git: https://gitlab.com/tobiaswkjeldsen/dartnissanconnectna 7 | dartnissanconnect: 8 | git: https://gitlab.com/sensor-freak/dartnissanconnect 9 | dartcarwings: 10 | git: https://github.com/Tobiaswk/dartcarwings 11 | mqtt_client: ^9.6.1 12 | logging: ^1.0.1 13 | environment: 14 | sdk: '>=2.10.0 <3.0.0' 15 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM dart:2.19.6-sdk AS build 2 | 3 | RUN apt-get update && \ 4 | apt-get install -y git 5 | 6 | WORKDIR /app 7 | 8 | COPY pubspec.* ./ 9 | RUN dart pub get 10 | 11 | COPY . . 12 | RUN dart pub get --offline 13 | RUN dart compile exe src/leaf_2_mqtt.dart -o src/leaf_2_mqtt 14 | 15 | FROM scratch 16 | COPY --from=build /runtime/ / 17 | COPY --from=build /app/src/leaf_2_mqtt /app/bin/ 18 | 19 | CMD ["/app/bin/leaf_2_mqtt"] 20 | -------------------------------------------------------------------------------- /src/leaf/builder/leaf_cockpitstatus_builder.dart: -------------------------------------------------------------------------------- 1 | import 'leaf_builder_base.dart'; 2 | 3 | class CockpitStatusInfoBuilder extends BuilderBase { 4 | CockpitStatusInfoBuilder() : super(); 5 | CockpitStatusInfoBuilder._withInfo(Map info) : super.withInfo(info); 6 | 7 | @override 8 | List get baseTopics => ['cockpitStatus', 'cockpit']; 9 | 10 | CockpitStatusInfoBuilder withTotalMileage(dynamic latitude) => 11 | _withInfo('totalMileage', latitude); 12 | 13 | CockpitStatusInfoBuilder _withInfo(String infoName, dynamic value) => 14 | CockpitStatusInfoBuilder._withInfo(addInfo(infoName, value)); 15 | } 16 | -------------------------------------------------------------------------------- /src/leaf/builder/leaf_location_builder.dart: -------------------------------------------------------------------------------- 1 | import 'leaf_builder_base.dart'; 2 | 3 | class LocationInfoBuilder extends BuilderBase { 4 | LocationInfoBuilder() : super(); 5 | LocationInfoBuilder._withInfo(Map info) : super.withInfo(info); 6 | 7 | @override 8 | String get baseTopic => 'location'; 9 | 10 | LocationInfoBuilder withLatitude(dynamic latitude) => 11 | _withInfo('latitude', latitude); 12 | 13 | LocationInfoBuilder withLongitude(dynamic longitude) => 14 | _withInfo('longitude', longitude); 15 | 16 | LocationInfoBuilder _withInfo(String infoName, dynamic value) => 17 | LocationInfoBuilder._withInfo(addInfo(infoName, value)); 18 | } 19 | -------------------------------------------------------------------------------- /local_settings.env.tmpl: -------------------------------------------------------------------------------- 1 | ################ 2 | ### Required ### 3 | ################ 4 | 5 | LEAF_USERNAME=my_username@example.com 6 | LEAF_PASSWORD=mYsecurEpassworD123 7 | 8 | LEAF_TYPE=newerThanMay2019 9 | #LEAF_TYPE=olderCanada 10 | #LEAF_TYPE=olderUSA 11 | #LEAF_TYPE=olderEurope 12 | #LEAF_TYPE=olderAustralia 13 | #LEAF_TYPE=olderJapan 14 | 15 | MQTT_HOST=192.168.255.255 16 | 17 | ################ 18 | ### Optional ### 19 | ################ 20 | 21 | #MQTT_PORT=1883 22 | #MQTT_USERNAME=my_mqtt_user 23 | #MQTT_PASSWORD=my_mqtt_password 24 | #MQTT_BASE_TOPIC=leaf 25 | #UPDATE_INTERVAL_MINUTES=60 26 | #CHARGING_UPDATE_INTERVAL_MINUTES=60 27 | #COMMAND_ATTEMPTS=1 28 | #LOG_LEVEL=Warning 29 | 30 | -------------------------------------------------------------------------------- /src/leaf/builder/leaf_climate_builder.dart: -------------------------------------------------------------------------------- 1 | import 'leaf_builder_base.dart'; 2 | 3 | class ClimateInfoBuilder extends BuilderBase { 4 | ClimateInfoBuilder() : super(); 5 | ClimateInfoBuilder._withInfo(Map info) : super.withInfo(info); 6 | 7 | @override 8 | String get baseTopic => 'climate'; 9 | 10 | ClimateInfoBuilder withCabinTemperatureCelsius(double cabinTemperatureCelsius) => 11 | _withInfo('cabinTemperatureC', cabinTemperatureCelsius) 12 | ._withInfo('cabinTemperatureF', (cabinTemperatureCelsius * 9 / 5) + 32); 13 | 14 | ClimateInfoBuilder withHvacRunningStatus(bool isRunning) => 15 | _withInfo('RunningStatus', isRunning) 16 | ._withInfo('runningStatus', isRunning); 17 | 18 | ClimateInfoBuilder _withInfo(String infoName, dynamic value) => 19 | ClimateInfoBuilder._withInfo(addInfo(infoName, value)); 20 | } 21 | -------------------------------------------------------------------------------- /src/leaf/builder/leaf_builder_base.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | abstract class BuilderBase { 4 | BuilderBase() : 5 | _info = {}; 6 | 7 | BuilderBase.withInfo(this._info); 8 | 9 | final Map _info; 10 | 11 | String get baseTopic => ''; 12 | 13 | List get baseTopics => [baseTopic]; 14 | 15 | Map addInfo(String key, dynamic value) { 16 | final Map modifiedInfo = Map.from(_info); 17 | modifiedInfo[key] = value.toString(); 18 | return modifiedInfo; 19 | } 20 | 21 | String removeUnitFromValue(String valueWithUnit) => 22 | valueWithUnit.split(' ')[0]; 23 | 24 | Map build() { 25 | final Map info = 26 | addInfo('lastReceivedDateTimeUtc', DateTime.now().toUtc().toIso8601String()); 27 | info['json'] = json.encode(info); 28 | 29 | return Map.fromEntries( 30 | baseTopics.map((String baseTopic) => 31 | info.map((String key, String value) => 32 | MapEntry('$baseTopic/$key', value))) 33 | .expand((Map element) => element.entries)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /addon/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Leaf2MQTT", 3 | "version": "46", 4 | "slug": "leaf2mqtt", 5 | "description": "Interact with your Nissan Leaf using MQTT", 6 | "startup": "application", 7 | "url": "https://github.com/yp87/leaf2mqtt", 8 | "init": false, 9 | "arch": [ 10 | "aarch64", 11 | "amd64" 12 | ], 13 | "options": { 14 | "LEAF_USERNAME": "", 15 | "LEAF_PASSWORD": "", 16 | "LEAF_TYPE": "", 17 | "MQTT_HOST": "homeassistant.local", 18 | "MQTT_PORT": "", 19 | "MQTT_USERNAME": "", 20 | "MQTT_PASSWORD": "", 21 | "MQTT_BASE_TOPIC": "", 22 | "UPDATE_INTERVAL_MINUTES": "", 23 | "CHARGING_UPDATE_INTERVAL_MINUTES": "", 24 | "COMMAND_ATTEMPTS": "", 25 | "LOG_LEVEL": "" 26 | }, 27 | "schema": { 28 | "LEAF_USERNAME": "str", 29 | "LEAF_PASSWORD": "password", 30 | "LEAF_TYPE": "list(newerThanMay2019|olderCanada|olderUSA|olderEurope|olderAustralia|olderJapan)", 31 | "MQTT_HOST": "str", 32 | "MQTT_PORT": "int?", 33 | "MQTT_USERNAME": "str?", 34 | "MQTT_PASSWORD": "password?", 35 | "MQTT_BASE_TOPIC": "str?", 36 | "UPDATE_INTERVAL_MINUTES": "int(5,)?", 37 | "CHARGING_UPDATE_INTERVAL_MINUTES": "int(5,)?", 38 | "COMMAND_ATTEMPTS": "int(1,)?", 39 | "LOG_LEVEL": "list(All|Info|Warning|Severe)" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /.github/workflows/leaf2mqtt.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docker image 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | paths: 7 | - 'pubspec.*' 8 | - 'src/**' 9 | - 'Dockerfile' 10 | - '.github/workflows/**' 11 | branches: 12 | - main 13 | 14 | jobs: 15 | push_to_registry: 16 | name: Push Docker image to Docker Hub 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Check out the repo 20 | uses: actions/checkout@v2 21 | 22 | - name: Set up QEMU 23 | uses: docker/setup-qemu-action@v1 24 | 25 | - name: Set up Docker Buildx 26 | uses: docker/setup-buildx-action@v1 27 | 28 | - name: Log in to Docker Hub 29 | uses: docker/login-action@v1.10.0 30 | with: 31 | username: ${{ secrets.DOCKERHUBUSERNAME }} 32 | password: ${{ secrets.DOCKERHUBACCESSTOKEN }} 33 | 34 | - name: Extract metadata (tags, labels) for Docker 35 | id: meta 36 | uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38 37 | with: 38 | images: yp87/leaf2mqtt 39 | tags: | 40 | type=raw,value=${{ github.run_number }} 41 | type=raw,value=latest 42 | 43 | - name: Build and push Docker image 44 | uses: docker/build-push-action@v2 45 | with: 46 | context: . 47 | push: true 48 | platforms: linux/amd64,linux/arm64 49 | tags: ${{ steps.meta.outputs.tags }} 50 | 51 | update_addon: 52 | name: Update Home Assistant add-on 53 | needs: push_to_registry 54 | runs-on: ubuntu-latest 55 | permissions: 56 | contents: write 57 | steps: 58 | - name: Checkout code 59 | uses: actions/checkout@v2 60 | 61 | - name: Change image version number 62 | uses: jossef/action-set-json-field@v1 63 | with: 64 | file: addon/config.json 65 | field: version 66 | value: ${{ github.run_number }} 67 | 68 | - name: Commit changes 69 | uses: stefanzweifel/git-auto-commit-action@v4 70 | with: 71 | commit_message: Update add-on version 72 | -------------------------------------------------------------------------------- /src/leaf/builder/leaf_battery_builder.dart: -------------------------------------------------------------------------------- 1 | import 'leaf_builder_base.dart'; 2 | 3 | class BatteryInfoBuilder extends BuilderBase { 4 | BatteryInfoBuilder() : super(); 5 | BatteryInfoBuilder._withInfo(Map info) : super.withInfo(info); 6 | 7 | @override 8 | String get baseTopic => 'battery'; 9 | 10 | BatteryInfoBuilder withChargePercentage(int chargePercentage) => 11 | _withInfo('percentage', chargePercentage); 12 | 13 | BatteryInfoBuilder withChargingStatus(bool charging) => 14 | _withInfo('charging', charging); 15 | 16 | BatteryInfoBuilder withConnectedStatus(bool connected) => 17 | _withInfo('connected', connected); 18 | 19 | BatteryInfoBuilder withCapacity(double capacity) => 20 | _withInfo('capacity', capacity); 21 | 22 | BatteryInfoBuilder withCruisingRangeAcOffKm(String cruisingRangeAcOffKm) => 23 | _withInfo('cruisingRangeAcOffKm', removeUnitFromValue(cruisingRangeAcOffKm)); 24 | 25 | BatteryInfoBuilder withCruisingRangeAcOffMiles(String cruisingRangeAcOffMiles) => 26 | _withInfo('cruisingRangeAcOffMiles', removeUnitFromValue(cruisingRangeAcOffMiles)); 27 | 28 | BatteryInfoBuilder withCruisingRangeAcOnKm(String cruisingRangeAcOnKm) => 29 | _withInfo('cruisingRangeAcOnKm', removeUnitFromValue(cruisingRangeAcOnKm)); 30 | 31 | BatteryInfoBuilder withCruisingRangeAcOnMiles(String cruisingRangeAcOnMiles) => 32 | _withInfo('cruisingRangeAcOnMiles', removeUnitFromValue(cruisingRangeAcOnMiles)); 33 | 34 | BatteryInfoBuilder withLastUpdatedDateTime(DateTime lastUpdatedDateTime) => 35 | _withInfo('lastUpdatedDateTimeUtc', lastUpdatedDateTime.toUtc().toIso8601String()); 36 | 37 | BatteryInfoBuilder withTimeToFullL2(Duration timeToFullL2) => 38 | _withInfo('timeToFullL2InMinutes', timeToFullL2); 39 | 40 | BatteryInfoBuilder withTimeToFullL2_6kw(Duration timeToFullL2_6kw) => 41 | _withInfo('timeToFullL2_6kwInMinutes', timeToFullL2_6kw); 42 | 43 | BatteryInfoBuilder withTimeToFullTrickle(Duration timeToFullTrickle) => 44 | _withInfo('timeToFullTrickleInMinutes', timeToFullTrickle); 45 | 46 | BatteryInfoBuilder withChargingSpeed(String chargingSpeed) => 47 | _withInfo('chargingSpeed', chargingSpeed); 48 | 49 | BatteryInfoBuilder _withInfo(String infoName, dynamic value) => 50 | BatteryInfoBuilder._withInfo(addInfo(infoName, value)); 51 | } 52 | -------------------------------------------------------------------------------- /src/leaf/builder/leaf_stats_builder.dart: -------------------------------------------------------------------------------- 1 | import 'leaf_builder_base.dart'; 2 | 3 | enum TimeRange { 4 | Daily, 5 | Monthly, 6 | } 7 | 8 | class StatsInfoBuilder extends BuilderBase { 9 | StatsInfoBuilder(this._targetTimeRange) : super(); 10 | StatsInfoBuilder._withInfo(this._targetTimeRange, Map info) : super.withInfo(info); 11 | 12 | final TimeRange _targetTimeRange; 13 | 14 | @override 15 | String get baseTopic => 'stats/${_targetTimeRange.toString().split('.').last.toLowerCase()}'; 16 | 17 | StatsInfoBuilder withTargetDate(DateTime targetDate) => 18 | _withInfo('targetDate', targetDate); 19 | 20 | StatsInfoBuilder withtravelTime(Duration travelTime) => 21 | _withInfo('travelTimeHours', travelTime.inHours); 22 | 23 | StatsInfoBuilder withTravelDistanceMiles(String travelDistanceMiles) => 24 | _withSpecifiedUnitInfo('travelDistanceMiles', travelDistanceMiles); 25 | 26 | StatsInfoBuilder withTravelDistanceKilometers(String travelDistanceKilometers) => 27 | _withSpecifiedUnitInfo('travelDistanceKilometers', travelDistanceKilometers); 28 | 29 | StatsInfoBuilder withMilesPerKwh(String milesPerKwh) => 30 | _withSpecifiedUnitInfo('milesPerKwh', milesPerKwh); 31 | 32 | StatsInfoBuilder withKilometersPerKwh(String kilometersPerKwh) => 33 | _withSpecifiedUnitInfo('kilometersPerKwh', kilometersPerKwh); 34 | 35 | StatsInfoBuilder withKwhUsed(String kwhUsed) => 36 | _withSpecifiedUnitInfo('kwhUsed', kwhUsed); 37 | 38 | StatsInfoBuilder withKwhPerMiles(String kwhPerMiles) => 39 | _withSpecifiedUnitInfo('kwhPerMiles', kwhPerMiles); 40 | 41 | StatsInfoBuilder withKwhPerKilometers(String kwhPerKilometers) => 42 | _withSpecifiedUnitInfo('kwhPerKilometers', kwhPerKilometers); 43 | 44 | StatsInfoBuilder withCo2ReductionKg(String co2ReductionKg) => 45 | _withSpecifiedUnitInfo('co2ReductionKg', co2ReductionKg); 46 | 47 | StatsInfoBuilder withTripsNumber(int tripsNumber) => 48 | _withInfo('tripsNumber', tripsNumber); 49 | 50 | StatsInfoBuilder withKwhGained(String kWhGained) => 51 | _withSpecifiedUnitInfo('kWhGained', kWhGained); 52 | 53 | StatsInfoBuilder _withSpecifiedUnitInfo(String infoName, String valueWithUnit) => 54 | _withInfo(infoName, valueWithUnit.split(' ').first); 55 | 56 | StatsInfoBuilder _withInfo(String infoName, dynamic value) => 57 | StatsInfoBuilder._withInfo(_targetTimeRange, addInfo(infoName, value)); 58 | } 59 | -------------------------------------------------------------------------------- /src/leaf/leaf_vehicle.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | abstract class VehicleInternal extends Vehicle { 4 | VehicleInternal(String nickname, String vin) : super(vin) { 5 | _lastKnownStatus['nickname'] = nickname; 6 | _lastKnownStatus['vin'] = vin; 7 | } 8 | 9 | Map saveAndPrependVin(Map newStatus) { 10 | _lastKnownStatus.addAll(newStatus); 11 | return _prependVin(newStatus); 12 | } 13 | 14 | void setLastKnownStatus(Vehicle lastknownVehicle) => 15 | _lastKnownStatus.addAll(lastknownVehicle._lastKnownStatus); 16 | 17 | @override 18 | Map getLastKnownStatus() => 19 | _prependVin(_lastKnownStatus); 20 | 21 | Map _prependVin(Map status) { 22 | final Map statusWithVin = {}; 23 | 24 | // We also keep all status without vin for the first vehicle 25 | // since most people only have one vehicle. 26 | if (isFirstVehicle()) { 27 | statusWithVin.addAll(status); 28 | } 29 | 30 | status.forEach((String key, String value) => statusWithVin['$vin/$key'] = value); 31 | 32 | return statusWithVin; 33 | } 34 | } 35 | 36 | abstract class Vehicle { 37 | Vehicle(this.vin); 38 | 39 | final String vin; 40 | 41 | bool isFirstVehicle(); 42 | 43 | bool get isCharging => 44 | _findValueOfKeyIn(_lastKnownStatus, 'charging') == 'true'; 45 | 46 | String _findValueOfKeyIn(Map status, String key) { 47 | return status.entries.firstWhere( 48 | (MapEntry status) => 49 | status.key.endsWith(key), orElse: () => null)?.value; 50 | } 51 | 52 | final Map _lastKnownStatus = {}; 53 | Map getLastKnownStatus(); 54 | 55 | Map getVehicleStatus() { 56 | final Map info = { 57 | 'nickname': _lastKnownStatus['nickname'], 58 | 'vin': _lastKnownStatus['vin'], 59 | }; 60 | 61 | info['json'] = json.encode(info); 62 | return info; 63 | } 64 | 65 | Future> fetchDailyStatistics(DateTime targetDate); 66 | Future> fetchMonthlyStatistics(DateTime targetDate); 67 | 68 | Future> fetchBatteryStatus(); 69 | Future startCharging(); 70 | 71 | Future> fetchClimateStatus(); 72 | Future startClimate(int targetTemperatureCelsius); 73 | Future stopClimate(); 74 | 75 | Future> fetchLocation(); 76 | Future> fetchCockpitStatus(); 77 | } 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/mqtt_client_wrapper.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:logging/logging.dart'; 4 | import 'package:mqtt_client/mqtt_client.dart'; 5 | import 'package:mqtt_client/mqtt_server_client.dart'; 6 | 7 | final Logger _log = Logger('MqttClientWrapper'); 8 | 9 | typedef PayloadReceivedhandler = void Function(String payload); 10 | 11 | class MqttClientWrapper { 12 | 13 | MqttClientWrapper() { 14 | final Map envVars = Platform.environment; 15 | 16 | final String mqttHost = envVars['MQTT_HOST'] ?? '127.0.0.1'; 17 | final int mqttPort = int.tryParse(envVars['MQTT_PORT'] ?? '1883') ?? 1883; 18 | _baseTopic = envVars['MQTT_BASE_TOPIC'] ?? 'leaf'; 19 | 20 | _log.info('Creating MQTT client with $mqttHost:$mqttPort listening on $_baseTopic.'); 21 | _mqttClient = MqttServerClient.withPort(mqttHost, 'leaf2mqtt', mqttPort); 22 | _mqttClient.keepAlivePeriod = 60; 23 | } 24 | 25 | MqttServerClient _mqttClient; 26 | String _baseTopic; 27 | final AsciiPayloadConverter _converter = AsciiPayloadConverter(); 28 | 29 | final Map> _payloadReceivedHandlers = >{}; 30 | 31 | ConnectCallback onConnected; 32 | 33 | DisconnectCallback onDisconnected; 34 | 35 | Future connectWithRetry(String mqttUser, String mqttPassword) async { 36 | _log.info('Connecting...'); 37 | _mqttClient.onConnected = onConnected; 38 | 39 | // Set to null to prevent multiple connectWithRetry 40 | // calls since onDisconnected is called when a connection fails. 41 | _mqttClient.onDisconnected = null; 42 | 43 | bool connected = false; 44 | while (!connected) { 45 | try { 46 | final MqttClientConnectionStatus connectionCode = await _mqttClient.connect(mqttUser, mqttPassword); 47 | _log.info('Mqtt connection code: ' + connectionCode.returnCode.toString()); 48 | connected = connectionCode.returnCode == MqttConnectReturnCode.connectionAccepted; 49 | } catch (e, stackTrace) { 50 | _log.warning('An error occured while connecting to MQTT broker. Retrying in 5 seconds.'); 51 | _log.info(e); 52 | _log.finest(stackTrace); 53 | } 54 | 55 | if(connected){ 56 | _mqttClient.onDisconnected = () => connectWithRetry(mqttUser, mqttPassword); 57 | } else { 58 | await Future.delayed(const Duration(seconds: 5)); 59 | } 60 | } 61 | } 62 | 63 | void subscribeToCommandTopic() { 64 | _log.info('Subscribing to command topics'); 65 | _mqttClient.subscribe('$_baseTopic/command/#', MqttQos.exactlyOnce); 66 | _mqttClient.subscribe('$_baseTopic/+/command/#', MqttQos.exactlyOnce); 67 | _mqttClient.updates.listen(_receiveData); 68 | } 69 | 70 | void subscribeTopic(String topic, PayloadReceivedhandler handler){ 71 | _log.fine('Subscribing to $topic'); 72 | _payloadReceivedHandlers.update( 73 | '$_baseTopic/$topic', 74 | (List handlers) { handlers.add(handler); return handlers; }, 75 | ifAbsent: () => [handler]); 76 | } 77 | 78 | void publishMessage(String topic, String value) { 79 | if (!(topic?.isEmpty ?? true) && !(value?.isEmpty ?? true) ) 80 | { 81 | _log.finest('Publishing message $topic $value'); 82 | try { 83 | _mqttClient.publishMessage( 84 | '$_baseTopic/$topic', 85 | MqttQos.atLeastOnce, 86 | _converter.convertToBytes(value), retain: true); 87 | } on ConnectionException catch (_) { 88 | _log.finest('connection error while publishing message'); 89 | // does not matter, we will send back latest states on reconnect. 90 | } catch(e, stackTrace) { 91 | _log.fine('Exception when publishign message: $e'); 92 | _log.finer(stackTrace); 93 | } 94 | } 95 | } 96 | 97 | void _receiveData(List> messages) { 98 | for (final MqttReceivedMessage message in messages) { 99 | final MqttPublishMessage pubMessage = message.payload as MqttPublishMessage; 100 | final String payload = 101 | MqttPublishPayload.bytesToStringAsString(pubMessage.payload.message) 102 | .toLowerCase(); 103 | 104 | _log.finer('Received data: ${message.topic} $payload'); 105 | final List handlers = 106 | _payloadReceivedHandlers[message.topic] ?? List.empty(); 107 | for (final PayloadReceivedhandler handler in handlers) { 108 | handler(payload); 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/leaf/nissan_connect_na_wrapper.dart: -------------------------------------------------------------------------------- 1 | import 'package:dartnissanconnectna/dartnissanconnectna.dart'; 2 | import 'package:logging/logging.dart'; 3 | 4 | import 'builder/leaf_battery_builder.dart'; 5 | import 'builder/leaf_climate_builder.dart'; 6 | import 'builder/leaf_location_builder.dart'; 7 | import 'builder/leaf_stats_builder.dart'; 8 | import 'leaf_session.dart'; 9 | import 'leaf_vehicle.dart'; 10 | 11 | final Logger _log = Logger('NissanConnectNASessionWrapper'); 12 | 13 | class NissanConnectNASessionWrapper extends LeafSessionInternal { 14 | NissanConnectNASessionWrapper(this._countryCode, String username, String password) 15 | : super(username, password); 16 | 17 | NissanConnectSession _session; 18 | final String _countryCode; 19 | 20 | @override 21 | Future login() async { 22 | _session = NissanConnectSession(debug: _log.level <= Level.FINER); 23 | const String fakeAndroidUserAgent = 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; Android SDK built for x86 Build/LMY48X)'; 24 | await _session.login(username: username, password: password, countryCode: _countryCode, userAgent: fakeAndroidUserAgent); 25 | 26 | final List newVehicles = _session.vehicles.map((NissanConnectVehicle vehicle) => 27 | NissanConnectNAVehicleWrapper(vehicle)).toList(); 28 | 29 | setVehicles(newVehicles); 30 | } 31 | } 32 | 33 | class NissanConnectNAVehicleWrapper extends VehicleInternal { 34 | NissanConnectNAVehicleWrapper(NissanConnectVehicle vehicle) : 35 | _session = vehicle.session, 36 | super(vehicle.nickname.toString(), vehicle.vin.toString()); 37 | 38 | final NissanConnectSession _session; 39 | 40 | NissanConnectVehicle _getVehicle() => 41 | _session.vehicles.firstWhere((NissanConnectVehicle v) => v.vin.toString() == vin, 42 | orElse: () => throw Exception('Could not find matching vehicle: $vin number of vehicles: ${_session.vehicles.length}')); 43 | 44 | @override 45 | bool isFirstVehicle() => _session.vehicle.vin == vin; 46 | 47 | @override 48 | Future> fetchDailyStatistics(DateTime targetDate) async => 49 | fetchStatistics(TimeRange.Daily, await _getVehicle().requestDailyStatistics(targetDate)); 50 | 51 | @override 52 | Future> fetchMonthlyStatistics(DateTime targetDate) async => 53 | fetchStatistics(TimeRange.Monthly, await _getVehicle().requestMonthlyStatistics(targetDate)); 54 | 55 | Map fetchStatistics(TimeRange targetTimeRange, NissanConnectStats stats) => 56 | saveAndPrependVin(StatsInfoBuilder(targetTimeRange) 57 | .withTargetDate(stats.date) 58 | .withtravelTime(stats.travelTime) 59 | .withTravelDistanceMiles(stats.travelDistanceMiles) 60 | .withTravelDistanceKilometers(stats.travelDistanceKilometers) 61 | .withMilesPerKwh(stats.milesPerKWh) 62 | .withKilometersPerKwh(stats.kilometersPerKWh) 63 | .withKwhUsed(stats.kWhUsed) 64 | .withKwhPerMiles(stats.kWhPerMiles) 65 | .withKwhPerKilometers(stats.kWhPerKilometers) 66 | .withCo2ReductionKg(stats.co2ReductionKg) 67 | .build()); 68 | 69 | @override 70 | Future> fetchBatteryStatus() async { 71 | final NissanConnectBattery battery = await _getVehicle().requestBatteryStatus(); 72 | 73 | return saveAndPrependVin(BatteryInfoBuilder() 74 | .withChargePercentage(((battery.batteryLevel * 100) / battery.batteryLevelCapacity).round()) 75 | .withConnectedStatus(battery.isConnected) 76 | .withChargingStatus(battery.isCharging) 77 | .withCapacity(battery.batteryLevelCapacity.toDouble()) 78 | .withCruisingRangeAcOffKm(battery.cruisingRangeAcOffKm) 79 | .withCruisingRangeAcOffMiles(battery.cruisingRangeAcOffMiles) 80 | .withCruisingRangeAcOnKm(battery.cruisingRangeAcOnKm) 81 | .withCruisingRangeAcOnMiles(battery.cruisingRangeAcOnMiles) 82 | .withLastUpdatedDateTime(battery.dateTime) 83 | .withTimeToFullL2(battery.timeToFullL2) 84 | .withTimeToFullL2_6kw(battery.timeToFullL2_6kw) 85 | .withTimeToFullTrickle(battery.timeToFullTrickle) 86 | .build()); 87 | } 88 | 89 | @override 90 | Future startCharging() => 91 | _getVehicle().requestChargingStart(); 92 | 93 | @override 94 | Future> fetchClimateStatus() => 95 | Future>.value( 96 | saveAndPrependVin(ClimateInfoBuilder() 97 | .withCabinTemperatureCelsius(_getVehicle().incTemperature) 98 | .build())); 99 | 100 | @override 101 | Future startClimate(int targetTemperatureCelsius) => 102 | _getVehicle().requestClimateControlOn(DateTime.now()); 103 | 104 | @override 105 | Future stopClimate() => 106 | _getVehicle().requestClimateControlOff(); 107 | 108 | @override 109 | Future> fetchLocation() async { 110 | final NissanConnectLocation location = await _getVehicle().requestLocation(DateTime.now().toUtc()); 111 | return saveAndPrependVin(LocationInfoBuilder() 112 | .withLatitude(location.latitude) 113 | .withLongitude(location.longitude) 114 | .build()); 115 | } 116 | 117 | // Note: This is only a dummy method. It returns an empty map. 118 | @override 119 | Future> fetchCockpitStatus() async { 120 | return Future>.value({}); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See https://dart.dev/tools/pub/glossary#lockfile 3 | packages: 4 | async: 5 | dependency: transitive 6 | description: 7 | name: async 8 | sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" 9 | url: "https://pub.dev" 10 | source: hosted 11 | version: "2.11.0" 12 | blowfish_ecb: 13 | dependency: transitive 14 | description: 15 | name: blowfish_ecb 16 | sha256: ed01f5fcec0bd5ba04242263abd61ae0a01f4211f0aa79dd96367254a5cc5f59 17 | url: "https://pub.dev" 18 | source: hosted 19 | version: "0.1.0" 20 | clock: 21 | dependency: transitive 22 | description: 23 | name: clock 24 | sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf 25 | url: "https://pub.dev" 26 | source: hosted 27 | version: "1.1.1" 28 | collection: 29 | dependency: transitive 30 | description: 31 | name: collection 32 | sha256: ef7e3a5529178ce8f37a9d0b11cbbc8b1e025940f9cf9f76c42da6796301219d 33 | url: "https://pub.dev" 34 | source: hosted 35 | version: "1.16.0" 36 | crypto: 37 | dependency: transitive 38 | description: 39 | name: crypto 40 | sha256: cf75650c66c0316274e21d7c43d3dea246273af5955bd94e8184837cd577575c 41 | url: "https://pub.dev" 42 | source: hosted 43 | version: "3.0.1" 44 | dartcarwings: 45 | dependency: "direct main" 46 | description: 47 | path: "." 48 | ref: HEAD 49 | resolved-ref: f54dc13e1910d4e87db6555aef0398cc5e41903c 50 | url: "https://github.com/Tobiaswk/dartcarwings" 51 | source: git 52 | version: "1.0.0" 53 | dartnissanconnect: 54 | dependency: "direct main" 55 | description: 56 | path: "." 57 | ref: HEAD 58 | resolved-ref: ed31b5a3ee6d472aea2a1fb97dbbcf8e90ef04c7 59 | url: "https://gitlab.com/sensor-freak/dartnissanconnect" 60 | source: git 61 | version: "1.0.4" 62 | dartnissanconnectna: 63 | dependency: "direct main" 64 | description: 65 | path: "." 66 | ref: HEAD 67 | resolved-ref: f2a4335c1fdd605ac0d5444539496eedf85c807f 68 | url: "https://gitlab.com/tobiaswkjeldsen/dartnissanconnectna" 69 | source: git 70 | version: "1.0.0" 71 | event_bus: 72 | dependency: transitive 73 | description: 74 | name: event_bus 75 | sha256: "44baa799834f4c803921873e7446a2add0f3efa45e101a054b1f0ab9b95f8edc" 76 | url: "https://pub.dev" 77 | source: hosted 78 | version: "2.0.0" 79 | http: 80 | dependency: transitive 81 | description: 82 | name: http 83 | sha256: "5895291c13fa8a3bd82e76d5627f69e0d85ca6a30dcac95c4ea19a5d555879c2" 84 | url: "https://pub.dev" 85 | source: hosted 86 | version: "0.13.6" 87 | http_parser: 88 | dependency: transitive 89 | description: 90 | name: http_parser 91 | sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" 92 | url: "https://pub.dev" 93 | source: hosted 94 | version: "4.0.2" 95 | intl: 96 | dependency: transitive 97 | description: 98 | name: intl 99 | sha256: "910f85bce16fb5c6f614e117efa303e85a1731bb0081edf3604a2ae6e9a3cc91" 100 | url: "https://pub.dev" 101 | source: hosted 102 | version: "0.17.0" 103 | logging: 104 | dependency: "direct main" 105 | description: 106 | name: logging 107 | sha256: "293ae2d49fd79d4c04944c3a26dfd313382d5f52e821ec57119230ae16031ad4" 108 | url: "https://pub.dev" 109 | source: hosted 110 | version: "1.0.2" 111 | meta: 112 | dependency: transitive 113 | description: 114 | name: meta 115 | sha256: "5202fdd37b4da5fd14a237ed0a01cad6c1efd4c99b5b5a0d3c9237f3728c9485" 116 | url: "https://pub.dev" 117 | source: hosted 118 | version: "1.7.0" 119 | mqtt_client: 120 | dependency: "direct main" 121 | description: 122 | name: mqtt_client 123 | sha256: e3fab601bafebeb2cb10d1bc68ddc0b8de987aa5298515d518329c9d8a034257 124 | url: "https://pub.dev" 125 | source: hosted 126 | version: "9.6.6" 127 | path: 128 | dependency: transitive 129 | description: 130 | name: path 131 | sha256: "240ed0e9bd73daa2182e33c4efc68c7dd53c7c656f3da73515a2d163e151412d" 132 | url: "https://pub.dev" 133 | source: hosted 134 | version: "1.8.1" 135 | source_span: 136 | dependency: transitive 137 | description: 138 | name: source_span 139 | sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" 140 | url: "https://pub.dev" 141 | source: hosted 142 | version: "1.10.0" 143 | string_scanner: 144 | dependency: transitive 145 | description: 146 | name: string_scanner 147 | sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" 148 | url: "https://pub.dev" 149 | source: hosted 150 | version: "1.2.0" 151 | term_glyph: 152 | dependency: transitive 153 | description: 154 | name: term_glyph 155 | sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 156 | url: "https://pub.dev" 157 | source: hosted 158 | version: "1.2.1" 159 | typed_data: 160 | dependency: transitive 161 | description: 162 | name: typed_data 163 | sha256: "53bdf7e979cfbf3e28987552fd72f637e63f3c8724c9e56d9246942dc2fa36ee" 164 | url: "https://pub.dev" 165 | source: hosted 166 | version: "1.3.0" 167 | sdks: 168 | dart: ">=2.19.0 <3.0.0" 169 | -------------------------------------------------------------------------------- /src/leaf/nissan_connect_wrapper.dart: -------------------------------------------------------------------------------- 1 | import 'package:dartnissanconnect/dartnissanconnect.dart'; 2 | import 'package:dartnissanconnect/src/nissanconnect_hvac.dart'; 3 | 4 | import 'builder/leaf_battery_builder.dart'; 5 | import 'builder/leaf_climate_builder.dart'; 6 | import 'builder/leaf_cockpitstatus_builder.dart'; 7 | import 'builder/leaf_location_builder.dart'; 8 | import 'builder/leaf_stats_builder.dart'; 9 | import 'leaf_session.dart'; 10 | import 'leaf_vehicle.dart'; 11 | 12 | class NissanConnectSessionWrapper extends LeafSessionInternal { 13 | NissanConnectSessionWrapper(String username, String password) 14 | : super(username, password); 15 | 16 | NissanConnectSession _session; 17 | 18 | @override 19 | Future login() async { 20 | _session = NissanConnectSession(); 21 | await _session.login(username: username, password: password); 22 | 23 | final List newVvehicles = _session.vehicles.map((NissanConnectVehicle vehicle) => 24 | NissanConnectVehicleWrapper(vehicle)).toList(); 25 | 26 | setVehicles(newVvehicles); 27 | } 28 | } 29 | 30 | class NissanConnectVehicleWrapper extends VehicleInternal { 31 | NissanConnectVehicleWrapper(NissanConnectVehicle vehicle) : 32 | _session = vehicle.session, 33 | super(vehicle.nickname.toString(), vehicle.vin.toString()); 34 | 35 | final NissanConnectSession _session; 36 | 37 | NissanConnectVehicle _getVehicle() => 38 | _session.vehicles.firstWhere((NissanConnectVehicle v) => v.vin.toString() == vin, 39 | orElse: () => throw Exception('Could not find matching vehicle: $vin number of vehicles: ${_session.vehicles.length}')); 40 | 41 | @override 42 | bool isFirstVehicle() => _session.vehicle.vin == vin; 43 | 44 | @override 45 | Future> fetchDailyStatistics(DateTime targetDate) async => 46 | fetchStatistics(TimeRange.Daily, await _getVehicle().requestDailyStatistics(targetDate)); 47 | 48 | @override 49 | Future> fetchMonthlyStatistics(DateTime targetDate) async => 50 | fetchStatistics(TimeRange.Monthly, await _getVehicle().requestMonthlyStatistics(month: targetDate)); 51 | 52 | Map fetchStatistics(TimeRange targetTimeRange, NissanConnectStats stats) => 53 | saveAndPrependVin(StatsInfoBuilder(targetTimeRange) 54 | .withTargetDate(stats.date) 55 | .withtravelTime(stats.travelTime) 56 | .withTravelDistanceMiles(stats.travelDistanceMiles) 57 | .withTravelDistanceKilometers(stats.travelDistanceKilometers) 58 | .withMilesPerKwh(stats.milesPerKWh) 59 | .withKilometersPerKwh(stats.kilometersPerKWh) 60 | .withKwhUsed(stats.kWhUsed) 61 | .withKwhPerMiles(stats.kWhPerMiles) 62 | .withKwhPerKilometers(stats.kWhPerKilometers) 63 | .withTripsNumber(stats.tripsNumber) 64 | .withKwhGained(stats.kWhGained) 65 | .build()); 66 | 67 | @override 68 | Future> fetchBatteryStatus() async { 69 | final NissanConnectBattery battery = await _getVehicle().requestBatteryStatus(); 70 | 71 | final int percentage = 72 | double.tryParse(battery.batteryPercentage.replaceFirst('%', ''))?.round(); 73 | 74 | return saveAndPrependVin(BatteryInfoBuilder() 75 | .withChargePercentage(percentage ?? -1) 76 | .withConnectedStatus(battery.isConnected) 77 | .withChargingStatus(battery.isCharging) 78 | .withCruisingRangeAcOffKm(battery.cruisingRangeAcOffKm) 79 | .withCruisingRangeAcOffMiles(battery.cruisingRangeAcOffMiles) 80 | .withCruisingRangeAcOnKm(battery.cruisingRangeAcOnKm) 81 | .withCruisingRangeAcOnMiles(battery.cruisingRangeAcOnMiles) 82 | .withLastUpdatedDateTime(battery.dateTime) 83 | .withTimeToFullL2(battery.timeToFullNormal) 84 | .withTimeToFullL2_6kw(battery.timeToFullFast) 85 | .withTimeToFullTrickle(battery.timeToFullSlow) 86 | .withChargingSpeed(battery.chargingSpeed.toString()) 87 | .build()); 88 | } 89 | 90 | @override 91 | Future startCharging() => 92 | _getVehicle().requestChargingStart(); 93 | 94 | @override 95 | Future> fetchClimateStatus() async { 96 | final NissanConnectVehicle vehicle = _getVehicle(); 97 | 98 | await vehicle.requestClimateControlStatusRefresh(); 99 | final NissanConnectHVAC hvac = await vehicle.requestClimateControlStatus(); 100 | 101 | return saveAndPrependVin(ClimateInfoBuilder() 102 | .withCabinTemperatureCelsius(hvac.cabinTemperature) 103 | .withHvacRunningStatus(hvac.isRunning) 104 | .build()); 105 | } 106 | 107 | @override 108 | Future startClimate(int targetTemperatureCelsius) => 109 | _getVehicle().requestClimateControlOn( 110 | DateTime.now(), 111 | targetTemperatureCelsius); 112 | 113 | @override 114 | Future stopClimate() => 115 | _getVehicle().requestClimateControlOff(); 116 | 117 | @override 118 | Future> fetchLocation() async { 119 | final NissanConnectLocation location = await _getVehicle().requestLocation(); 120 | return saveAndPrependVin(LocationInfoBuilder() 121 | .withLatitude(location.latitude) 122 | .withLongitude(location.longitude) 123 | .build()); 124 | } 125 | 126 | @override 127 | Future> fetchCockpitStatus() async { 128 | final NissanConnectCockpitStatus cockpitStatus = await _getVehicle().requestCockpitStatus(); 129 | return saveAndPrependVin(CockpitStatusInfoBuilder() 130 | .withTotalMileage(cockpitStatus.totalMileage) 131 | .build()); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/leaf/leaf_session.dart: -------------------------------------------------------------------------------- 1 | import 'package:dartcarwings/dartcarwings.dart'; 2 | import 'package:logging/logging.dart'; 3 | 4 | import 'carwings_wrapper.dart'; 5 | import 'leaf_vehicle.dart'; 6 | import 'nissan_connect_na_wrapper.dart'; 7 | import 'nissan_connect_wrapper.dart'; 8 | 9 | final Logger _log = Logger('LeafSession'); 10 | 11 | enum LeafType { 12 | newerThanMay2019, 13 | olderCanada, 14 | olderUsa, 15 | olderEurope, 16 | olderAustralia, 17 | olderJapan, 18 | } 19 | 20 | LeafSession createLeafSession(LeafType leafType, String username, String password) { 21 | switch (leafType) { 22 | case LeafType.newerThanMay2019: 23 | return NissanConnectSessionWrapper(username, password); 24 | break; 25 | 26 | case LeafType.olderCanada: 27 | return NissanConnectNASessionWrapper('CA', username, password); 28 | break; 29 | 30 | case LeafType.olderUsa: 31 | return NissanConnectNASessionWrapper('US', username, password); 32 | break; 33 | 34 | case LeafType.olderEurope: 35 | return CarwingsWrapper(CarwingsRegion.Europe, username, password); 36 | break; 37 | 38 | case LeafType.olderJapan: 39 | return CarwingsWrapper(CarwingsRegion.Japan, username, password); 40 | break; 41 | 42 | case LeafType.olderAustralia: 43 | return CarwingsWrapper(CarwingsRegion.Australia, username, password); 44 | break; 45 | 46 | default: 47 | throw ArgumentError.value(leafType, 'leafType', 'this LeafType is not supported yet.'); 48 | } 49 | } 50 | 51 | abstract class LeafSessionInternal extends LeafSession { 52 | LeafSessionInternal(this.username, this.password); 53 | 54 | final String username; 55 | final String password; 56 | 57 | List _lastKnownVehicles = []; 58 | 59 | @override 60 | List get vehicles => _lastKnownVehicles; 61 | 62 | void setVehicles(List newVehicles) { 63 | // keep the last states 64 | for (final VehicleInternal lastKnownVehicle in _lastKnownVehicles) { 65 | final VehicleInternal matchingVehicle = 66 | newVehicles.firstWhere((VehicleInternal vehicle) => vehicle.vin == lastKnownVehicle.vin, orElse: () => null); 67 | matchingVehicle?.setLastKnownStatus(lastKnownVehicle); 68 | } 69 | 70 | _lastKnownVehicles = newVehicles; 71 | } 72 | 73 | @override 74 | Map getAllLastKnownStatus() => 75 | _lastKnownVehicles.fold({}, 76 | (Map allLastKnownStatus, VehicleInternal vehicle) { 77 | allLastKnownStatus.addAll(vehicle.getLastKnownStatus()); 78 | return allLastKnownStatus; 79 | } ); 80 | } 81 | 82 | /// The client Connect callback type 83 | typedef ExecutionErrorCallback = void Function(String vin); 84 | typedef ExecutableVehicleActionHandler = Future Function(Vehicle vehicle); 85 | typedef SyncExecutableVehicleActionHandler = T Function(Vehicle vehicle); 86 | abstract class LeafSession { 87 | 88 | ExecutionErrorCallback onExecutionError; 89 | 90 | List get vehicles; 91 | 92 | Vehicle _getVehicle(String vin) => 93 | vehicles.firstWhere((Vehicle vehicle) => vehicle.vin == vin, 94 | orElse: () => throw Exception('Vehicle $vin not found.')); 95 | 96 | Future login(); 97 | 98 | Map getAllLastKnownStatus(); 99 | 100 | T executeSync(SyncExecutableVehicleActionHandler executable, String vin) { 101 | try { 102 | return executable(_getVehicle(vin)); 103 | } catch (e, stackTrace) { 104 | _logException(e, stackTrace); 105 | } 106 | 107 | return null; 108 | } 109 | 110 | Future executeCommandWithRetry(ExecutableVehicleActionHandler executable, String vin, int commandAttempts) async { 111 | bool anyCommandSucceeded = false; 112 | for (int attempts = 0; attempts < commandAttempts; ++attempts) { 113 | try { 114 | anyCommandSucceeded |= await _executeWithRetry((Vehicle vehicle) async { 115 | return await executable(vehicle); 116 | }, vin); 117 | } catch(e, stackTrace) { 118 | _logException(e, stackTrace); 119 | } 120 | } 121 | 122 | if (!anyCommandSucceeded && onExecutionError != null) { 123 | onExecutionError(vin); 124 | } 125 | } 126 | 127 | Future executeWithRetry(ExecutableVehicleActionHandler executable, String vin) async { 128 | try { 129 | return await _executeWithRetry(executable, vin); 130 | } catch(e, stackTrace) { 131 | _logException(e, stackTrace); 132 | if (onExecutionError != null) { 133 | onExecutionError(vin); 134 | } 135 | } 136 | 137 | return null; 138 | } 139 | 140 | Future _executeWithRetry(ExecutableVehicleActionHandler executable, String vin) async { 141 | int attempts = 0; 142 | while (attempts < 2) { 143 | if (attempts > 0) { 144 | try { 145 | _log.finer('Force a login before retrying failed execution.'); 146 | await login(); 147 | } catch(e, stackTrace) { 148 | _logException(e, stackTrace); 149 | } 150 | } 151 | 152 | try { 153 | return await _execute(executable, vin); 154 | } catch (e, stackTrace) { 155 | _logException(e, stackTrace); 156 | } 157 | 158 | ++attempts; 159 | } 160 | 161 | throw Exception('Execution failed.'); 162 | } 163 | 164 | Future _execute(ExecutableVehicleActionHandler executable, String vin) { 165 | _log.finest('Executing'); 166 | return executable(_getVehicle(vin)); 167 | } 168 | 169 | void _logException(dynamic e, StackTrace stackTrace) { 170 | _log.fine(e); 171 | _log.finer(stackTrace); 172 | } 173 | } 174 | 175 | -------------------------------------------------------------------------------- /src/leaf/carwings_wrapper.dart: -------------------------------------------------------------------------------- 1 | import 'package:dartcarwings/dartcarwings.dart'; 2 | 3 | import 'builder/leaf_battery_builder.dart'; 4 | import 'builder/leaf_climate_builder.dart'; 5 | import 'builder/leaf_location_builder.dart'; 6 | import 'builder/leaf_stats_builder.dart'; 7 | import 'leaf_session.dart'; 8 | import 'leaf_vehicle.dart'; 9 | 10 | class CarwingsWrapper extends LeafSessionInternal { 11 | CarwingsWrapper(this._region, String username, String password) 12 | : super(username, password); 13 | 14 | final CarwingsRegion _region; 15 | 16 | CarwingsSession _session; 17 | 18 | @override 19 | Future login() async { 20 | _session = CarwingsSession(); 21 | await _session.login(username: username, password: password, region: _region); 22 | 23 | final List newVehicles = _session.vehicles.map((CarwingsVehicle vehicle) => 24 | CarwingsVehicleWrapper(vehicle)).toList(); 25 | 26 | setVehicles(newVehicles); 27 | } 28 | } 29 | 30 | class CarwingsVehicleWrapper extends VehicleInternal { 31 | CarwingsVehicleWrapper(CarwingsVehicle vehicle) : 32 | _session = vehicle.session, 33 | super(vehicle.nickname.toString(), vehicle.vin.toString()); 34 | 35 | final CarwingsSession _session; 36 | 37 | CarwingsVehicle _getVehicle() => 38 | _session.vehicles.firstWhere((CarwingsVehicle v) => v.vin.toString() == vin, 39 | orElse: () => throw Exception('Could not find matching vehicle: $vin number of vehicles: ${_session.vehicles.length}')); 40 | 41 | @override 42 | bool isFirstVehicle() => _session.vehicle.vin == vin; 43 | 44 | @override 45 | Future> fetchDailyStatistics(DateTime targetDate) async { 46 | final CarwingsStatsDaily stats = await _getVehicle().requestStatisticsDaily(); 47 | 48 | if (stats.electricCostScale == 'miles/kWh') { 49 | return saveAndPrependVin(StatsInfoBuilder(TimeRange.Daily) 50 | .withTargetDate(stats.dateTime) 51 | .withKwhPerMiles(stats.KWhPerMileage) 52 | .withMilesPerKwh(stats.mileagePerKWh) 53 | .build()); 54 | } else { 55 | return saveAndPrependVin(StatsInfoBuilder(TimeRange.Daily) 56 | .withTargetDate(stats.dateTime) 57 | .withKwhPerKilometers(stats.KWhPerMileage) 58 | .withKilometersPerKwh(stats.mileagePerKWh) 59 | .build()); 60 | } 61 | } 62 | 63 | @override 64 | Future> fetchMonthlyStatistics(DateTime targetDate) async { 65 | final CarwingsStatsMonthly stats = await _getVehicle().requestStatisticsMonthly(targetDate); 66 | 67 | if (stats.mileageUnit == 'km') { 68 | return saveAndPrependVin(StatsInfoBuilder(TimeRange.Monthly) 69 | .withTargetDate(stats.dateTime) 70 | .withTripsNumber(int.tryParse(stats.totalNumberOfTrips)) 71 | .withCo2ReductionKg(stats.totalCO2Reduction) 72 | .withKwhUsed(stats.totalConsumptionKWh) 73 | .withTravelDistanceKilometers(stats.totalTravelDistanceMileage) 74 | .withKwhPerKilometers(stats.totalkWhPerMileage) 75 | .withKilometersPerKwh(stats.totalMileagePerKWh) 76 | .build()); 77 | } else if (stats.mileageUnit == 'mi') { 78 | return saveAndPrependVin(StatsInfoBuilder(TimeRange.Monthly) 79 | .withTargetDate(stats.dateTime) 80 | .withTripsNumber(int.tryParse(stats.totalNumberOfTrips)) 81 | .withCo2ReductionKg(stats.totalCO2Reduction) 82 | .withKwhUsed(stats.totalConsumptionKWh) 83 | .withTravelDistanceMiles(stats.totalTravelDistanceMileage) 84 | .withKwhPerMiles(stats.totalkWhPerMileage) 85 | .withMilesPerKwh(stats.totalMileagePerKWh) 86 | .build()); 87 | } else { 88 | return saveAndPrependVin(StatsInfoBuilder(TimeRange.Monthly) 89 | .withTargetDate(stats.dateTime) 90 | .withTripsNumber(int.tryParse(stats.totalNumberOfTrips)) 91 | .withCo2ReductionKg(stats.totalCO2Reduction) 92 | .withKwhUsed(stats.totalConsumptionKWh) 93 | .build()); 94 | } 95 | } 96 | 97 | @override 98 | Future> fetchBatteryStatus() async { 99 | final CarwingsBattery battery = await _getVehicle().requestBatteryStatusLatest(); 100 | 101 | return saveAndPrependVin(BatteryInfoBuilder() 102 | .withChargePercentage(((battery.batteryLevel * 100) / battery.batteryLevelCapacity).round()) 103 | .withConnectedStatus(battery.isConnected) 104 | .withChargingStatus(battery.isCharging) 105 | .withCapacity(battery.batteryLevelCapacity) 106 | .withCruisingRangeAcOffKm(battery.cruisingRangeAcOffKm) 107 | .withCruisingRangeAcOffMiles(battery.cruisingRangeAcOffMiles) 108 | .withCruisingRangeAcOnKm(battery.cruisingRangeAcOnKm) 109 | .withCruisingRangeAcOnMiles(battery.cruisingRangeAcOnMiles) 110 | .withLastUpdatedDateTime(battery.dateTime) 111 | .withTimeToFullL2(battery.timeToFullL2) 112 | .withTimeToFullL2_6kw(battery.timeToFullL2_6kw) 113 | .withTimeToFullTrickle(battery.timeToFullTrickle) 114 | .build()); 115 | } 116 | 117 | @override 118 | Future startCharging() async { 119 | await _getVehicle().requestChargingStart(DateTime.now()); 120 | return true; 121 | } 122 | 123 | @override 124 | Future> fetchClimateStatus() async { 125 | final CarwingsCabinTemperature cabinTemperature = await _getVehicle().requestCabinTemperature(); 126 | final CarwingsHVAC hvac = await _getVehicle().requestHVACStatus(); 127 | 128 | return saveAndPrependVin(ClimateInfoBuilder() 129 | .withCabinTemperatureCelsius(cabinTemperature.temperature) 130 | .withHvacRunningStatus(hvac.isRunning) 131 | .build()); 132 | } 133 | 134 | @override 135 | Future startClimate(int targetTemperatureCelsius) async { 136 | await _getVehicle().requestClimateControlOn(); 137 | return true; 138 | } 139 | 140 | @override 141 | Future stopClimate() async { 142 | await _getVehicle().requestClimateControlOff(); 143 | return true; 144 | } 145 | 146 | @override 147 | Future> fetchLocation() async { 148 | final CarwingsLocation location = await _getVehicle().requestLocation(); 149 | return saveAndPrependVin(LocationInfoBuilder() 150 | .withLatitude(location.latitude) 151 | .withLongitude(location.longitude) 152 | .build()); 153 | } 154 | 155 | // Note: This is only a dummy method. It returns an empty map. 156 | @override 157 | Future> fetchCockpitStatus() async { 158 | return Future>.value({}); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # Specify analysis options. 2 | # 3 | # Until there are meta linter rules, each desired lint must be explicitly enabled. 4 | # See: https://github.com/dart-lang/linter/issues/288 5 | # 6 | # For a list of lints, see: http://dart-lang.github.io/linter/lints/ 7 | # See the configuration guide for more 8 | # https://github.com/dart-lang/sdk/tree/master/pkg/analyzer#configuring-the-analyzer 9 | # 10 | # There are other similar analysis options files in the flutter repos, 11 | # which should be kept in sync with this file: 12 | # 13 | # - analysis_options.yaml (this file) 14 | # - packages/flutter/lib/analysis_options_user.yaml 15 | # - https://github.com/flutter/plugins/blob/master/analysis_options.yaml 16 | # - https://github.com/flutter/engine/blob/master/analysis_options.yaml 17 | # 18 | # This file contains the analysis options used by Flutter tools, such as IntelliJ, 19 | # Android Studio, and the `flutter analyze` command. 20 | 21 | analyzer: 22 | strong-mode: 23 | implicit-casts: false 24 | implicit-dynamic: false 25 | errors: 26 | # treat missing required parameters as a warning (not a hint) 27 | missing_required_param: warning 28 | # treat missing returns as a warning (not a hint) 29 | missing_return: warning 30 | # allow having TODOs in the code 31 | todo: ignore 32 | # allow self-reference to deprecated members (we do this because otherwise we have 33 | # to annotate every member in every test, assert, etc, when we deprecate something) 34 | deprecated_member_use_from_same_package: ignore 35 | # Ignore analyzer hints for updating pubspecs when using Future or 36 | # Stream and not importing dart:async 37 | # Please see https://github.com/flutter/flutter/pull/24528 for details. 38 | sdk_version_async_exported_from_core: ignore 39 | exclude: 40 | - "bin/cache/**" 41 | # the following two are relative to the stocks example and the flutter package respectively 42 | # see https://github.com/dart-lang/sdk/issues/28463 43 | - "lib/i18n/messages_*.dart" 44 | - "lib/src/http/**" 45 | - "test_fixes/**" 46 | 47 | linter: 48 | rules: 49 | # these rules are documented on and in the same order as 50 | # the Dart Lint rules page to make maintenance easier 51 | # https://github.com/dart-lang/linter/blob/master/example/all.yaml 52 | - always_declare_return_types 53 | - always_put_control_body_on_new_line 54 | # - always_put_required_named_parameters_first # we prefer having parameters in the same order as fields https://github.com/flutter/flutter/issues/10219 55 | - always_require_non_null_named_parameters 56 | - always_specify_types 57 | # - always_use_package_imports # we do this commonly 58 | - annotate_overrides 59 | # - avoid_annotating_with_dynamic # conflicts with always_specify_types 60 | # - avoid_as # required for implicit-casts: true 61 | - avoid_bool_literals_in_conditional_expressions 62 | # - avoid_catches_without_on_clauses # we do this commonly 63 | # - avoid_catching_errors # we do this commonly 64 | - avoid_classes_with_only_static_members 65 | # - avoid_double_and_int_checks # only useful when targeting JS runtime 66 | - avoid_empty_else 67 | - avoid_equals_and_hash_code_on_mutable_classes 68 | # - avoid_escaping_inner_quotes # not yet tested 69 | - avoid_field_initializers_in_const_classes 70 | - avoid_function_literals_in_foreach_calls 71 | # - avoid_implementing_value_types # not yet tested 72 | - avoid_init_to_null 73 | # - avoid_js_rounded_ints # only useful when targeting JS runtime 74 | - avoid_null_checks_in_equality_operators 75 | # - avoid_positional_boolean_parameters # not yet tested 76 | # - avoid_print # not yet tested 77 | # - avoid_private_typedef_functions # we prefer having typedef (discussion in https://github.com/flutter/flutter/pull/16356) 78 | # - avoid_redundant_argument_values # not yet tested 79 | - avoid_relative_lib_imports 80 | - avoid_renaming_method_parameters 81 | - avoid_return_types_on_setters 82 | # - avoid_returning_null # there are plenty of valid reasons to return null 83 | # - avoid_returning_null_for_future # not yet tested 84 | - avoid_returning_null_for_void 85 | # - avoid_returning_this # there are plenty of valid reasons to return this 86 | # - avoid_setters_without_getters # not yet tested 87 | - avoid_shadowing_type_parameters 88 | - avoid_single_cascade_in_expression_statements 89 | - avoid_slow_async_io 90 | # - avoid_type_to_string # we do this commonly 91 | - avoid_types_as_parameter_names 92 | # - avoid_types_on_closure_parameters # conflicts with always_specify_types 93 | # - avoid_unnecessary_containers # not yet tested 94 | - avoid_unused_constructor_parameters 95 | - avoid_void_async 96 | # - avoid_web_libraries_in_flutter # not yet tested 97 | - await_only_futures 98 | - camel_case_extensions 99 | - camel_case_types 100 | - cancel_subscriptions 101 | # - cascade_invocations # not yet tested 102 | # - cast_nullable_to_non_nullable # not recognized 103 | # - close_sinks # not reliable enough 104 | # - comment_references # blocked on https://github.com/flutter/flutter/issues/20765 105 | # - constant_identifier_names # needs an opt-out https://github.com/dart-lang/linter/issues/204 106 | - control_flow_in_finally 107 | # - curly_braces_in_flow_control_structures # not required by flutter style 108 | # - diagnostic_describe_all_properties # not yet tested 109 | - directives_ordering 110 | # - do_not_use_environment # we do this commonly 111 | - empty_catches 112 | - empty_constructor_bodies 113 | - empty_statements 114 | - exhaustive_cases 115 | # - file_names # not yet tested 116 | - flutter_style_todos 117 | - hash_and_equals 118 | - implementation_imports 119 | # - invariant_booleans # too many false positives: https://github.com/dart-lang/linter/issues/811 120 | - iterable_contains_unrelated_type 121 | # - join_return_with_assignment # not required by flutter style 122 | - leading_newlines_in_multiline_strings 123 | - library_names 124 | - library_prefixes 125 | # - lines_longer_than_80_chars # not required by flutter style 126 | - list_remove_unrelated_type 127 | # - literal_only_boolean_expressions # too many false positives: https://github.com/dart-lang/sdk/issues/34181 128 | # - missing_whitespace_between_adjacent_strings # not yet tested 129 | - no_adjacent_strings_in_list 130 | # - no_default_cases # too many false positives 131 | - no_duplicate_case_values 132 | - no_logic_in_create_state 133 | # - no_runtimeType_toString # ok in tests; we enable this only in packages/ 134 | - non_constant_identifier_names 135 | # - null_check_on_nullable_type_parameter # not recognized 136 | # - null_closures # not required by flutter style 137 | # - omit_local_variable_types # opposite of always_specify_types 138 | # - one_member_abstracts # too many false positives 139 | # - only_throw_errors # https://github.com/flutter/flutter/issues/5792 140 | - overridden_fields 141 | - package_api_docs 142 | # - package_names # non conforming packages in sdk 143 | - package_prefixed_library_names 144 | # - parameter_assignments # we do this commonly 145 | - prefer_adjacent_string_concatenation 146 | - prefer_asserts_in_initializer_lists 147 | # - prefer_asserts_with_message # not required by flutter style 148 | - prefer_collection_literals 149 | - prefer_conditional_assignment 150 | - prefer_const_constructors 151 | - prefer_const_constructors_in_immutables 152 | - prefer_const_declarations 153 | - prefer_const_literals_to_create_immutables 154 | # - prefer_constructors_over_static_methods # far too many false positives 155 | - prefer_contains 156 | # - prefer_double_quotes # opposite of prefer_single_quotes 157 | - prefer_equal_for_default_values 158 | # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods 159 | - prefer_final_fields 160 | - prefer_final_in_for_each 161 | - prefer_final_locals 162 | - prefer_for_elements_to_map_fromIterable 163 | - prefer_foreach 164 | # - prefer_function_declarations_over_variables # not yet tested 165 | - prefer_generic_function_type_aliases 166 | - prefer_if_elements_to_conditional_expressions 167 | - prefer_if_null_operators 168 | - prefer_initializing_formals 169 | - prefer_inlined_adds 170 | # - prefer_int_literals # not yet tested 171 | # - prefer_interpolation_to_compose_strings # not yet tested 172 | - prefer_is_empty 173 | - prefer_is_not_empty 174 | - prefer_is_not_operator 175 | - prefer_iterable_whereType 176 | # - prefer_mixin # https://github.com/dart-lang/language/issues/32 177 | # - prefer_null_aware_operators # disable until NNBD, see https://github.com/flutter/flutter/pull/32711#issuecomment-492930932 178 | # - prefer_relative_imports # not yet tested 179 | - prefer_single_quotes 180 | - prefer_spread_collections 181 | - prefer_typing_uninitialized_variables 182 | - prefer_void_to_null 183 | # - provide_deprecation_message # not yet tested 184 | # - public_member_api_docs # enabled on a case-by-case basis; see e.g. packages/analysis_options.yaml 185 | - recursive_getters 186 | # - sized_box_for_whitespace # not yet tested 187 | - slash_for_doc_comments 188 | # - sort_child_properties_last # not yet tested 189 | - sort_constructors_first 190 | # - sort_pub_dependencies # prevents separating pinned transitive dependencies 191 | - sort_unnamed_constructors_first 192 | - test_types_in_equals 193 | - throw_in_finally 194 | # - tighten_type_of_initializing_formals # not recognized 195 | # - type_annotate_public_apis # subset of always_specify_types 196 | - type_init_formals 197 | # - unawaited_futures # too many false positives 198 | # - unnecessary_await_in_return # not yet tested 199 | - unnecessary_brace_in_string_interps 200 | - unnecessary_const 201 | # - unnecessary_final # conflicts with prefer_final_locals 202 | - unnecessary_getters_setters 203 | # - unnecessary_lambdas # has false positives: https://github.com/dart-lang/linter/issues/498 204 | - unnecessary_new 205 | - unnecessary_null_aware_assignments 206 | # - unnecessary_null_checks # not yet tested 207 | - unnecessary_null_in_if_null_operators 208 | - unnecessary_nullable_for_final_variable_declarations 209 | - unnecessary_overrides 210 | - unnecessary_parenthesis 211 | # - unnecessary_raw_strings # not yet tested 212 | - unnecessary_statements 213 | - unnecessary_string_escapes 214 | - unnecessary_string_interpolations 215 | - unnecessary_this 216 | - unrelated_type_equality_checks 217 | # - unsafe_html # not yet tested 218 | - use_full_hex_values_for_flutter_colors 219 | # - use_function_type_syntax_for_parameters # not yet tested 220 | - use_is_even_rather_than_modulo 221 | # - use_key_in_widget_constructors # not yet tested 222 | - use_late_for_private_fields_and_variables 223 | - use_raw_strings 224 | - use_rethrow_when_possible 225 | # - use_setters_to_change_properties # not yet tested 226 | # - use_string_buffers # has false positives: https://github.com/dart-lang/sdk/issues/34182 227 | # - use_to_and_as_if_applicable # has false positives, so we prefer to catch this by code-review 228 | - valid_regexps 229 | - void_checks 230 | -------------------------------------------------------------------------------- /src/leaf_2_mqtt.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:io'; 3 | 4 | import 'package:logging/logging.dart'; 5 | 6 | import 'leaf/leaf_session.dart'; 7 | import 'leaf/leaf_vehicle.dart'; 8 | import 'mqtt_client_wrapper.dart'; 9 | 10 | LeafSession _session; 11 | int _commandAttempts = 2; 12 | final Logger _log = Logger('main'); 13 | 14 | Future main() async { 15 | final Map envVars = Platform.environment; 16 | 17 | final String logLevelStr = envVars['LOG_LEVEL'] ?? '${Level.WARNING}'; 18 | Level logLevel = 19 | Level.LEVELS.firstWhere( 20 | (Level level) => level.name.toLowerCase() == logLevelStr.toLowerCase(), 21 | orElse: () => null); 22 | 23 | if (logLevel == null) { 24 | print('LOG_LEVEL environment variable should be set to a valid value from: ${Level.LEVELS}. Defaulting to Warning.'); 25 | logLevel = Level.WARNING; 26 | } 27 | 28 | Logger.root.level = logLevel; 29 | Logger.root.onRecord.listen((LogRecord record) { 30 | print('${record.level.name}: ${record.time}: ${record.loggerName}: ${record.message}'); 31 | }); 32 | 33 | _log.info('V0.11'); 34 | 35 | final String leafUser = envVars['LEAF_USERNAME']; 36 | final String leafPassword = envVars['LEAF_PASSWORD']; 37 | 38 | if ((leafUser?.isEmpty ?? true) || (leafPassword?.isEmpty ?? true)) { 39 | _log.severe('LEAF_USERNAME and LEAF_PASSWORD environment variables must be set.'); 40 | exit(1); 41 | } 42 | 43 | final String leafTypeStr = envVars['LEAF_TYPE'] ?? 'oldUSA'; 44 | final LeafType leafType = 45 | LeafType.values.firstWhere( 46 | (LeafType e) => e.toString().toLowerCase().endsWith(leafTypeStr.toLowerCase()), 47 | orElse: () => null); 48 | 49 | if (leafType == null) { 50 | final String leafTypes = LeafType.values.toString(); 51 | _log.severe('LEAF_TYPE environment variable must be set to a valid value from: $leafTypes'); 52 | exit(2); 53 | } 54 | 55 | _commandAttempts = int.tryParse(envVars['COMMAND_ATTEMPTS'] ?? '1') ?? 1; 56 | 57 | final MqttClientWrapper mqttClient = MqttClientWrapper(); 58 | await mqttClient.connectWithRetry(envVars['MQTT_USERNAME'], envVars['MQTT_PASSWORD']); 59 | 60 | _session = createLeafSession(leafType, leafUser, leafPassword); 61 | _session.onExecutionError = (String vin) => _onExecutionError(mqttClient, vin); 62 | 63 | await _login(mqttClient); 64 | 65 | mqttClient.onConnected = () => _onConnected(mqttClient); 66 | _onConnected(mqttClient); 67 | 68 | // Starting one loop per vehicle because each can have different interval depending on their state. 69 | await Future.wait(_session.vehicles.map((Vehicle vehicle) => startUpdateLoop(mqttClient, vehicle.vin))); 70 | } 71 | 72 | Completer _loginCompleter; 73 | Future _login(MqttClientWrapper mqttClient) async { 74 | if (_loginCompleter != null) { 75 | _log.fine('Already logging in, waiting...'); 76 | // already logging in.. wait for it to complete. 77 | await _loginCompleter.future; 78 | return; 79 | } 80 | 81 | _log.info('Logging in.'); 82 | _loginCompleter = Completer(); 83 | 84 | bool loggedIn = false; 85 | while(!loggedIn) { 86 | try { 87 | await _session.login(); 88 | _log.info('Login successful'); 89 | loggedIn = true; 90 | _loginCompleter.complete(); 91 | _loginCompleter = null; 92 | } catch (e, stacktrace) { 93 | _log.warning('An error occured while logging in. Please make sure you have selected the right LEAF_TYPE, LEAF_USERNAME and LEAF_PASSWORD. Retrying in 5 seconds.'); 94 | _log.fine(e); 95 | _log.fine(stacktrace); 96 | _onExecutionError(mqttClient); 97 | await Future.delayed(const Duration(seconds: 5)); 98 | } 99 | } 100 | } 101 | 102 | Future startUpdateLoop(MqttClientWrapper mqttClient, String vin) async { 103 | _log.info('Starting loop for $vin'); 104 | final Map envVars = Platform.environment; 105 | final int updateIntervalMinutes = int.tryParse(envVars['UPDATE_INTERVAL_MINUTES'] ?? '60') ?? 60; 106 | final int chargingUpdateIntervalMinutes = int.tryParse(envVars['CHARGING_UPDATE_INTERVAL_MINUTES'] ?? '15') ?? 15; 107 | 108 | subscribeToCommands(mqttClient, vin); 109 | 110 | while (true) { 111 | await fetchAndPublishAllStatus(mqttClient, vin); 112 | 113 | int calculatedUpdateIntervalMinutes = updateIntervalMinutes; 114 | if ((_session.executeSync((Vehicle vehicle) => vehicle.isCharging, vin) ?? false) && 115 | chargingUpdateIntervalMinutes < calculatedUpdateIntervalMinutes) { 116 | calculatedUpdateIntervalMinutes = chargingUpdateIntervalMinutes; 117 | } 118 | 119 | await Future.delayed(Duration(minutes: calculatedUpdateIntervalMinutes)); 120 | _log.finer('Loop delay of $calculatedUpdateIntervalMinutes ended for $vin'); 121 | } 122 | } 123 | 124 | void subscribeToCommands(MqttClientWrapper mqttClient, String vin) { 125 | _log.info('Subscribing to commands for $vin'); 126 | void subscribe(String topic, void Function(String payload) handler) { 127 | mqttClient.subscribeTopic('$vin/$topic', handler); 128 | 129 | if (_session.executeSync((Vehicle vehicle) => vehicle.isFirstVehicle(), vin) ?? false) { 130 | // first vehicle also can send command without the vin 131 | mqttClient.subscribeTopic(topic, handler); 132 | } 133 | } 134 | 135 | subscribe('command', (String payload) { 136 | switch (payload) { 137 | case 'update': 138 | fetchAndPublishAllStatus(mqttClient, vin); 139 | break; 140 | default: 141 | } 142 | }); 143 | 144 | subscribe('command/battery', (String payload) { 145 | switch (payload) { 146 | case 'update': 147 | fetchAndPublishBatteryStatus(mqttClient, vin); 148 | break; 149 | case 'startcharging': 150 | _session.executeCommandWithRetry((Vehicle vehicle) => vehicle.startCharging(), vin, _commandAttempts).then( 151 | (_) => Future.delayed(const Duration(seconds: 5)).then( 152 | (_) => fetchAndPublishBatteryStatus(mqttClient, vin))); 153 | break; 154 | default: 155 | } 156 | }); 157 | 158 | subscribe('command/climate', (String payload) { 159 | switch (payload) { 160 | case 'update': 161 | fetchAndPublishClimateStatus(mqttClient, vin); 162 | break; 163 | case 'stop': 164 | _session.executeCommandWithRetry((Vehicle vehicle) => vehicle.stopClimate(), vin, _commandAttempts).then( 165 | (_) => Future.delayed(const Duration(seconds: 5)).then( 166 | (_) => fetchAndPublishClimateStatus(mqttClient, vin))); 167 | break; 168 | default: 169 | if (payload?.startsWith('start') ?? false) { 170 | int targetTemperatureCelsius; 171 | 172 | String targetTemperature = payload.replaceFirst('start', '').trim(); 173 | if (targetTemperature.startsWith('c')) { 174 | targetTemperature = targetTemperature.replaceFirst('c', '').trim(); 175 | targetTemperatureCelsius = double.tryParse(targetTemperature)?.round(); 176 | 177 | } else if (targetTemperature.startsWith('f')) { 178 | targetTemperature = targetTemperature.replaceFirst('f', '').trim(); 179 | final int targetTemperatureFahrenheit = double.tryParse(targetTemperature)?.round(); 180 | 181 | if (targetTemperatureFahrenheit != null) { 182 | targetTemperatureCelsius = ((targetTemperatureFahrenheit - 32) * 5 / 9).round(); 183 | } 184 | } else if (payload == 'start') { 185 | targetTemperatureCelsius = 21; 186 | } 187 | 188 | if (targetTemperatureCelsius != null){ 189 | _session.executeCommandWithRetry((Vehicle vehicle) => 190 | vehicle.startClimate(targetTemperatureCelsius), vin, _commandAttempts).then( 191 | (_) => Future.delayed(const Duration(seconds: 5)).then( 192 | (_) => fetchAndPublishClimateStatus(mqttClient, vin))); 193 | } 194 | } 195 | break; 196 | } 197 | }); 198 | 199 | subscribe('command/stats/daily', (String payload) { 200 | if (payload.startsWith('update')) { 201 | final String targetDatePart = payload.replaceAll('update', '').trim(); 202 | final DateTime targetDate = DateTime.tryParse(targetDatePart.toUpperCase()) ?? DateTime.now(); 203 | fetchAndPublishDailyStats(mqttClient, vin, targetDate); 204 | } 205 | }); 206 | 207 | subscribe('command/stats/monthly', (String payload) { 208 | if (payload.startsWith('update')) { 209 | final String targetDatePart = payload.replaceAll('update', '').trim(); 210 | final DateTime targetDate = DateTime.tryParse(targetDatePart) ?? DateTime.now(); 211 | fetchAndPublishMonthlyStats(mqttClient, vin, targetDate); 212 | } 213 | }); 214 | 215 | subscribe('command/location', (String payload) { 216 | switch (payload) { 217 | case 'update': 218 | fetchAndPublishLocation(mqttClient, vin); 219 | break; 220 | default: 221 | } 222 | }); 223 | 224 | subscribe('command/cockpitStatus', (String payload) { 225 | switch (payload) { 226 | case 'update': 227 | fetchAndPublishCockpitStatus(mqttClient, vin); 228 | break; 229 | default: 230 | } 231 | }); 232 | } 233 | 234 | Future fetchAndPublishDailyStats(MqttClientWrapper mqttClient, String vin, DateTime targetDay) { 235 | _log.finer('fetchAndPublishDailyStats for $vin'); 236 | return _session.executeWithRetry((Vehicle vehicle) => 237 | vehicle.fetchDailyStatistics(targetDay), vin).then(mqttClient.publishStates); 238 | } 239 | 240 | Future fetchAndPublishMonthlyStats(MqttClientWrapper mqttClient, String vin, DateTime targetMonth) { 241 | _log.finer('fetchAndPublishMonthlyStats for $vin'); 242 | return _session.executeWithRetry((Vehicle vehicle) => 243 | vehicle.fetchMonthlyStatistics(targetMonth), vin).then(mqttClient.publishStates); 244 | } 245 | 246 | Future fetchAndPublishBatteryStatus(MqttClientWrapper mqttClient, String vin) { 247 | _log.finer('fetchAndPublishBatteryStatus for $vin'); 248 | return _session.executeWithRetry((Vehicle vehicle) => 249 | vehicle.fetchBatteryStatus(), vin).then(mqttClient.publishStates); 250 | } 251 | 252 | Future fetchAndPublishClimateStatus(MqttClientWrapper mqttClient, String vin) { 253 | _log.finer('fetchAndPublishClimateStatus for $vin'); 254 | return _session.executeWithRetry((Vehicle vehicle) => 255 | vehicle.fetchClimateStatus(), vin).then(mqttClient.publishStates); 256 | } 257 | 258 | Future fetchAndPublishLocation(MqttClientWrapper mqttClient, String vin) { 259 | _log.finer('fetchAndPublishLocation for $vin'); 260 | return _session.executeWithRetry((Vehicle vehicle) => 261 | vehicle.fetchLocation(), vin).then(mqttClient.publishStates); 262 | } 263 | 264 | Future fetchAndPublishCockpitStatus(MqttClientWrapper mqttClient, String vin) { 265 | _log.finer('fetchAndPublishCockpit for $vin'); 266 | return _session.executeWithRetry((Vehicle vehicle) => 267 | vehicle.fetchCockpitStatus(), vin).then(mqttClient.publishStates); 268 | } 269 | 270 | Future fetchAndPublishAllStatus(MqttClientWrapper mqttClient, String vin) { 271 | _log.finer('fetchAndPublishAllStatus for $vin'); 272 | return Future.wait(> [ 273 | Future(() => mqttClient.publishStates( 274 | _session.executeSync((Vehicle vehicle) => vehicle.getVehicleStatus(), vin))), 275 | fetchAndPublishBatteryStatus(mqttClient, vin), 276 | fetchAndPublishClimateStatus(mqttClient, vin), 277 | fetchAndPublishLocation(mqttClient, vin), 278 | fetchAndPublishCockpitStatus(mqttClient, vin) 279 | ]); 280 | } 281 | 282 | void _onConnected(MqttClientWrapper mqttClient) { 283 | _log.info('MQTT connected.'); 284 | mqttClient.subscribeToCommandTopic(); 285 | mqttClient.publishStates(_session.getAllLastKnownStatus()); 286 | } 287 | 288 | void _onExecutionError(MqttClientWrapper mqttClient, [String vin]) { 289 | _log.warning('Could not execute request.'); 290 | final String errorDateTime = DateTime.now().toUtc().toIso8601String(); 291 | mqttClient.publishMessage('lastErrorDateTimeUtc', errorDateTime); 292 | if (vin != null) { 293 | mqttClient.publishMessage('{vin}/lastErrorDateTimeUtc', errorDateTime); 294 | } 295 | } 296 | 297 | extension on MqttClientWrapper { 298 | void publishStates(Map states) { 299 | if (states != null) { 300 | _log.finest('publishStates ${states.toString()}'); 301 | states.forEach(publishMessage); 302 | } 303 | } 304 | } 305 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project is not active anymore. Feel free to copy and modify anything. As of this writing, it looks like this repo is more active: https://github.com/kamiKAC/leaf2mqtt/tree/main. Thank you. 2 | 3 | ![Docker Pulls](https://img.shields.io/docker/pulls/yp87/leaf2mqtt) ![Docker Image Version (latest by date)](https://img.shields.io/docker/v/yp87/leaf2mqtt) 4 | # leaf2mqtt 5 | > :warning: olderCanada and olderUSA support may break at anytime because Nissan keep changing the API key. Thank you Nissan for working against your customers. 6 | 7 | > :warning: If you're not using the Leaf frequently, stop the container or drastically reduce the update frequency, or you could well end up with a flat 12V battery. 8 | 9 | This works for my Canadian made in 2018 LEAF 40kWh. It was also reported to be working on a newer than May 2019 Leaf. 10 | 11 | You must have a working MQTT broker on your LAN. 12 | 13 | Should work with multiple Leafs, but it is untested. Please open an issue with feedback if possible. 14 | 15 | - [Setup](#setup) 16 | * [Pre-built images](#pre-built-images) 17 | * [Building the image](#building-the-image) 18 | * [Running the image](#running-the-image) 19 | - [Status and Commands](#status-and-commands) 20 | * [General](#general) 21 | + [Status](#status) 22 | + [Commands](#commands) 23 | * [Battery](#battery) 24 | + [Status](#status-1) 25 | + [Commands](#commands-1) 26 | * [Climate](#climate) 27 | + [Status](#status-2) 28 | + [Commands](#commands-2) 29 | * [Stats](#stats) 30 | + [Status](#status-3) 31 | + [Commands](#commands-3) 32 | * [Location](#location) 33 | + [Status](#status-4) 34 | + [Commands](#commands-4) 35 | + [Cockpit Status](#cockpit-status) 36 | + [Status](#status-5) 37 | + [Commands](#commands-5) 38 | - [Home Assistant Integration](#home-assistant-integration) 39 | * [Sensor examples](#sensor-examples) 40 | * [Recommended Battery Status Update Script](#recommended-battery-status-update-script) 41 | - [Credits](#credits) 42 | 43 | ## Setup 44 | ### Home Assistant add-on 45 | Click the icon below to add this repository to your Home Assistant instance or follow the procedure highlighted on the [Home Assistant website](https://home-assistant.io/hassio/installing_third_party_addons). 46 | 47 | [![Install leaf2mqtt add-on repo.](https://my.home-assistant.io/badges/supervisor_add_addon_repository.svg)](https://my.home-assistant.io/redirect/supervisor_add_addon_repository/?repository_url=https%3A%2F%2Fgithub.com%2Fyp87%2Fleaf2mqtt) 48 | 49 | ### Pre-built images 50 | You can use pre-built images from here: https://hub.docker.com/r/yp87/leaf2mqtt 51 | 52 | tag example: `yp87/leaf2mqtt:latest` 53 | 54 | ### Building the image 55 | 56 | docker build --tag leaf2mqtt . 57 | 58 | -- OR -- 59 | 60 | cp local_settings.env.tmpl local_settings.env 61 | docker-compose build 62 | 63 | ### Running the image 64 | | Parameter | Optional | Description | 65 | |-----------|----------|-------------| 66 | | LEAF_USERNAME | No | Your NissanConnect username || 67 | | LEAF_PASSWORD | No | Your NissanConnect password | 68 | | LEAF_TYPE | No | newerThanMay2019, olderCanada, olderUSA, olderEurope, olderAustralia or olderJapan | 69 | | MQTT_HOST | No | IP or hostname of your mqtt broker. Localhost or 127.0.0.1 will not work when using Docker, use real host LAN ip | 70 | | MQTT_PORT | Yes | Port of your mqtt broker. Default is 1883 | 71 | | MQTT_USERNAME | Yes | Your mqtt username | 72 | | MQTT_PASSWORD | Yes | Your mqtt password | 73 | | MQTT_BASE_TOPIC | Yes | The root MQTT topic for leaf2mqtt. Default is "leaf" | 74 | | UPDATE_INTERVAL_MINUTES | Yes | Time between automatic status refresh. Default is 60 | 75 | | CHARGING_UPDATE_INTERVAL_MINUTES* | Yes | Time between automatic status refresh when charging. Default is 15 | 76 | | COMMAND_ATTEMPTS | Yes | Number of attempts for any command regardless of success or failure. Since some of the Nissan apis are unreliable, I recommend a value of 5. Default is 1. | 77 | | LOG_LEVEL | Yes | The log verbosity used by leaf2mqtt. Default is "Warning" | 78 | 79 | Example: 80 | 81 | docker run --restart always -e LEAF_USERNAME="myusername@somewhere.com" -e LEAF_PASSWORD="Some P4ssword!" -e LEAF_TYPE="newerThanMay2019" -e MQTT_HOST=192.168.1.111 -e UPDATE_INTERVAL_MINUTES=1440 -e COMMAND_ATTEMPTS=5 --name leaf2mqtt leaf2mqtt 82 | 83 | -- OR -- 84 | 85 | Edit local_settings.env 86 | docker-compose up -d 87 | 88 | :information_source:* The `CHARGING_UPDATE_INTERVAL_MINUTES` value will only be used after the ongoing `UPDATE_INTERVAL_MINUTES` is elapsed and the Leaf is charging. 89 | 90 | ## Status and Commands 91 | In these examples, the `MQTT_BASE_TOPIC` is set to the default (`leaf`). 92 | 93 | ### General 94 | #### Status 95 | | Topic | Type | Description | 96 | | ------ | ---- | ----------- | 97 | | leaf/{vin}/nickname | String | The reported nickname of the leaf | 98 | | leaf/{vin}/vin | String | The reported vin of the leaf | 99 | | leaf/{vin}/lastErrorDateTimeUtc | Iso8601 UTC | The datetime of the last failed command execution or status query | 100 | | leaf/{vin}/json | String | A json representation of all general status | 101 | 102 | #### Commands 103 | | Topic | Payload | Description | 104 | | ----- | ------- | ----------- | 105 | | leaf/{vin}/command | update | Request an update for all status | 106 | 107 | 108 | ### Battery 109 | #### Status 110 | | Topic | Type | Description | 111 | | ------ | ---- | ----------- | 112 | | leaf/{vin}/battery/percentage | Integer | The last reported battery charge of the leaf | 113 | | leaf/{vin}/battery/connected| Boolean | True if the leaf is reported as currently connected. False otherwise | 114 | | leaf/{vin}/battery/charging| Boolean | True if the leaf is reported as currently charging. False otherwise | 115 | | leaf/{vin}/battery/capacity| Double | The reported total capacity of the battery | 116 | | leaf/{vin}/battery/chargingSpeed| String | can be one of None, Slow, Normal or Fast | 117 | | leaf/{vin}/battery/cruisingRangeAcOffKm | Integer | Range left with climate off in kilometers as estimated by the Leaf | 118 | | leaf/{vin}/battery/cruisingRangeAcOffMiles | Integer | Range left with climate off in miles as estimated by the Leaf | 119 | | leaf/{vin}/battery/cruisingRangeAcOnKm | Integer | Range left with climate on in kilometers as estimated by the Leaf | 120 | | leaf/{vin}/battery/cruisingRangeAcOnMiles | Integer | Range left with climate on in miles as estimated by the Leaf | 121 | | leaf/{vin}/battery/timeToFullTrickleInMinutes | String | The reported time (H:MM:SS.mmmmmm) to fully charge when trickling (~1kw) | 122 | | leaf/{vin}/battery/timeToFullL2InMinutes | String | The reported time (H:MM:SS.mmmmmm) to fully charge when charging in half speed L2 (~3kw) | 123 | | leaf/{vin}/battery/timeToFullL2_6kwInMinutes | String | The reported time (H:MM:SS.mmmmmm) to fully charge when charging in full speed L2 (~6kw) | 124 | | leaf/{vin}/battery/lastUpdatedDateTimeUtc | Iso8601 UTC | The datetime when the last battery values were updated | 125 | | leaf/{vin}/battery/lastReceivedDateTimeUtc | Iso8601 UTC | The datetime when leaf2mqtt received the last battery values | 126 | | leaf/{vin}/battery/json | String | A json representation of all battery status | 127 | 128 | #### Commands 129 | | Topic | Payload | Description | 130 | | ----- | ------- | ----------- | 131 | | leaf/{vin}/command/battery | update | Request an update for all battery status | 132 | | leaf/{vin}/command/battery | startCharging | Request the Leaf to start charging | 133 | 134 | ### Climate 135 | #### Status 136 | | Topic | Type | Description | 137 | | ------ | ---- | ----------- | 138 | | leaf/{vin}/climate/cabinTemperatureC | Double | The reported cabin temperature in Celsius | 139 | | leaf/{vin}/climate/cabinTemperatureF | Double | The reported cabin temperature in Fahrenheit | 140 | | leaf/{vin}/climate/runningStatus | Boolean | True if the Leaf is reporting the HVAC as running. False otherwise | 141 | | leaf/{vin}/climate/lastReceivedDateTimeUtc | Iso8601 UTC | The datetime when leaf2mqtt received the last climate values | 142 | | leaf/{vin}/climate/json | String | A json representation of all climate status | 143 | 144 | #### Commands 145 | | Topic | Payload | Description | 146 | | ----- | ------- | ----------- | 147 | | leaf/{vin}/command/climate | update | Request an update for all climate status | 148 | | leaf/{vin}/command/climate | start | Request the Leaf to start climate control | 149 | | leaf/{vin}/command/climate | startC XY | Request the Leaf to start climate control at XY Celsius | 150 | | leaf/{vin}/command/climate | startF XY | Request the Leaf to start climate control at XY Fahrenheit | 151 | | leaf/{vin}/command/climate | stop | Request the Leaf to stop climate control | 152 | 153 | ### Stats 154 | `{TimeRange}` must be `daily` or `monthly`. 155 | 156 | #### Status 157 | | Topic | Type | Description | 158 | | ------ | ---- | ----------- | 159 | | leaf/{vin}/stats/{TimeRange}/targetDate | Iso8601 | The reported target date of the stats | 160 | | leaf/{vin}/stats/{TimeRange}/travelTimeHours | double | The reported time traveled in hours during specified time range | 161 | | leaf/{vin}/stats/{TimeRange}/travelDistanceMiles | double | The reported miles traveled during specified time range | 162 | | leaf/{vin}/stats/{TimeRange}/travelDistanceKilometers | double | The reported kilometers traveled during specified time range | 163 | | leaf/{vin}/stats/{TimeRange}/milesPerKwh | double | The reported miles per kWh during specified time range | 164 | | leaf/{vin}/stats/{TimeRange}/kilometersPerKwh | double | The reported kilometers per kWh during specified time range | 165 | | leaf/{vin}/stats/{TimeRange}/kwhUsed | double | The reported kWh consumption during specified time range | 166 | | leaf/{vin}/stats/{TimeRange}/kwhPerMiles | double | The reported kWh consumption per miles during specified time range | 167 | | leaf/{vin}/stats/{TimeRange}/kwhPerKilometers | double | The reported kWh consumption per km during specified time range | 168 | | leaf/{vin}/stats/{TimeRange}/co2ReductionKg | double | The reported number of co2 in Kg saved during specified time range | 169 | | leaf/{vin}/stats/{TimeRange}/tripsNumber | int | The reported number of trips during specified time range | 170 | | leaf/{vin}/stats/{TimeRange}/kwhGained | Double | The reported total regen in kWh during specified time range | 171 | | leaf/{vin}/stats/{TimeRange}/lastReceivedDateTimeUtc | Iso8601 UTC | The datetime when leaf2mqtt received the last stats values | 172 | | leaf/{vin}/stats/json | String | A json representation of all stats | 173 | 174 | #### Commands 175 | | Topic | Payload | Description | 176 | | ----- | ------- | ----------- | 177 | | leaf/{vin}/command/stats/{TimeRange} | update YYYY-MM-DD HH:MM:SS | Request an update for daily or monthly stats. Date must respect Iso8601 | 178 | 179 | ### Location 180 | #### Status 181 | | Topic | Type | Description | 182 | | ------ | ---- | ----------- | 183 | | leaf/{vin}/location/latitude | String | The reported last known location's latitude in decimal degrees | 184 | | leaf/{vin}/location/longitude | String | The reported last known location's longitude in decimal degrees | 185 | | leaf/{vin}/location/lastReceivedDateTimeUtc | Iso8601 UTC | The datetime when leaf2mqtt received the last location values | 186 | | leaf/{vin}/location/json | String | A json representation of all location status | 187 | 188 | #### Commands 189 | | Topic | Payload | Description | 190 | | ----- | ------- | ----------- | 191 | | leaf/{vin}/command/location | update | Request an update for the last known location | 192 | 193 | ### Cockpit Status 194 | #### Status 195 | | Topic | Type | Description | 196 | | ------ | ---- | ----------- | 197 | | leaf/{vin}/cockpitStatus/totalMileage | Double | The total mileage from the vehicle. The unit (km or miles) depends on the regional area. | 198 | | leaf/{vin}/cockpitStatus/lastReceivedDateTimeUtc | Iso8601 UTC | The datetime when leaf2mqtt received the last cockpit status values | 199 | | leaf/{vin}/cockpitStatus/json | String | A json representation of all cockpit status | 200 | 201 | #### Commands 202 | | Topic | Payload | Description | 203 | | ----- | ------- | ----------- | 204 | | leaf/{vin}/command/cockpitStatus | update | Request an update for the cockpit status | 205 | 206 | :information_source: The status and commands for the first Leaf in the account are also supported by using the same topic without the {vin}. 207 | 208 | :warning: Not all status and commands are supported for a given leaf type due to Carwings, NissanConnectNA or NissanConnect api limitations. 209 | 210 | ## Home Assistant Integration 211 | ### Sensor examples 212 | mqtt: 213 | sensor: 214 | - name: leaf_battery_level 215 | # Since VIN is not specified, it will represent the state from the first vehicle in the account. 216 | state_topic: "leaf/battery/percentage" 217 | unit_of_measurement: "%" 218 | device_class: battery 219 | 220 | - name: leaf_battery_last_updated 221 | # Since VIN is not specified, it will represent the state from the first Leaf in the account. 222 | state_topic: "leaf/battery/lastUpdatedDateTimeUtc" 223 | device_class: timestamp 224 | 225 | - name: leaf_battery_last_received 226 | # You can specify the vin if you prefer or if you have more than one Leaf. 227 | state_topic: "leaf/XXXXXSOMEXVINXXXXX/battery/lastReceivedDateTimeUtc" 228 | device_class: timestamp 229 | 230 | ### Recommended Battery Status Update Script 231 | In Home Assistant, calling a script like this `- service: script.some_script_name` within another script or automation will actually stop the execution of the calling script until `script.some_script_name` terminates, unlike using `script.turn_on`. Knowing this, you can ensure you have the latest state for your leaf before continuing an automation using a script like this: 232 | 233 | update_leaf_battery: 234 | # Using queued will ensure you do not update twice at the same time and will prevent 235 | # subsequent invocations from asking an update right away because of the while's conditions. 236 | # All the callers will also wait for the result. 237 | mode: queued 238 | sequence: 239 | - repeat: 240 | while: 241 | # Used with the sensors in the section above, this condition will 242 | # ensure we continue until the states are really updated. 243 | # It will also prevent subsequent calls from unnecessarily requesting 244 | # an update before the current state is 10 minutes old. 245 | - > 246 | {{ as_timestamp(now()) - 247 | as_timestamp(states('sensor.leaf_battery_last_updated')) > 600 }} 248 | 249 | # We also stop the loop after 4 tries since Nissan servers can send the same 250 | # old data many times in a row. I think this happens when the state did not really changed 251 | # or the Leaf is unreachable. 252 | - "{{ repeat.index <= 4 }}" 253 | 254 | sequence: 255 | # We publish the update command for the car. 256 | # You can also ommit the VIN to target the first Leaf in the account. 257 | # You can also request update for every state for one Leaf by removing the /battery section 258 | - service: mqtt.publish 259 | data: 260 | topic: "leaf/XXXXXSOMEXVINXXXXX/command/battery" 261 | payload: "update" 262 | # We now wait until we actually have received a response or if we timed out. 263 | # This does not mean that the received data is the latest. This is why 264 | # we check sensor.leaf_battery_last_updated in the while condition. 265 | - wait_for_trigger: 266 | - platform: state 267 | entity_id: sensor.leaf_battery_last_received 268 | timeout: 600 269 | # Let's have a cool down to give time to Home Assistant to update all the states. 270 | - delay: "00:00:10" 271 | 272 | ## Credits 273 | - Forked from [Troon/leaf2mqtt](https://github.com/Troon/leaf2mqtt). Thank you for the inspiration! 274 | - Using libraries from [Tobias Westergaard Kjeldsen](https://gitlab.com/tobiaswkjeldsen) to connect with the nissan leaf's APIs. Those libraries are also used for his [MyLeaf app](https://gitlab.com/tobiaswkjeldsen/carwingsflutter). 275 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------