Skip to content
psilo909 edited this page Jan 28, 2017 · 38 revisions

Tankerkoenig

Requirements / Basic Information (location of README)

This plugin requires lib requests. You can install this lib with:

sudo pip3 install requests --upgrade

You need your own personal API key for TankerKoenig. For your own key register to https://creativecommons.tankerkoenig.de

BASIC Information on Configuration etc see:
Thread im KNX-User-Forum: https://knx-user-forum.de/forum/supportforen/smarthome-py/938924-benzinpreis-plugin
README.md: https://github.com/smarthomeNG/plugins/tree/develop/tankerkoenig

Further possibilities: Integration of petrol station list into SmartVISU:

sh.py

logic.conf:

[PetrolStationCSVLogic]
    filename = petrol_station_csv_logic.py
    cycle = 360
    crontab = init

Logic "petrol_station_csv_logic.py":

import csv

with open('/var/www/smartvisu/temp/petrol_stations.csv', 'w') as csvfile:
    fieldnames = ['place', 'brand', 'houseNumber', 'street', 'id', 'lng', 'name', 'lat', 'price', 'dist', 'isOpen', 'postCode']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for element in sh.tankerkoenig.get_petrol_stations(sh._lat, sh._lon, 'diesel', 'price', rad='10'):
        writer.writerow(element)

SmartVisu:

New file: /var/www/smartvisu/lib/fuel/service/fuel_tankerkoenig.php

<?php
require_once '../../../lib/includes.php';
require_once const_path_system.'fuel/fuel.php';


/**
 * This class reads the petrol station list
 */
class fuel_tankerkoenig extends fuel
{
	private $csv;

	/**
	 *
	 */
	private function my_str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = null, $eol = null)
	{
		$temp = fopen("php://memory", "rw");
		fwrite($temp, $input);
		fseek($temp, 0);
		$r = array();
		while (($data = fgetcsv($temp, 4096, $delimiter, $enclosure)) !== false)
		{
			$r[] = $data;
		}

		fclose($temp);

		return $r;
	}

	/**
	 *
	 */
	private function handlecsv()
	{
		// cut off the first header line
		$this->csv = preg_replace("/^(.*\n){1}/", "", $this->csv);

		// convert into array
		$this->csv = $this->my_str_getcsv($this->csv);   
		$this->debug($this->csv, "csv");

		$i = 1;
		foreach ($this->csv as $parts)
		{
                        $this->data[] = array(
                            'pos' => $i++,
                            'place' => $parts[0],
                            'brand' => $parts[1],
                            'housenumber' => $parts[2],
                            'street' => $parts[3],
                            'id' => $parts[4],
                            'lng' => $parts[5],
                            'name' => $parts[6],
                            'lat' => $parts[7],
                            'price' => round($parts[8],3),
                            'dist' => $parts[9],
                            'isOpen' => $parts[10],
                            'postCode' => $parts[11]
			);
        	}
                
	}

	/**
	 *
	 */
	public function run()
	{		
		// get csv
		$this->csv = file_get_contents('/var/www/smartvisu/temp/petrol_stations.csv');

		// handle csv
		if (strlen($this->csv) > 10)
			$this->handlecsv();

		// free vals	
		$this->csv = '';
	}

} // class end


// -----------------------------------------------------------------------------
// call the service
// -----------------------------------------------------------------------------

$service = new fuel_tankerkoenig(array_merge($_GET, $_POST));
echo $service->json();

?>

New file in /var/www/smartvisu/lib/fuel.php

<?php
require_once const_path_system.'service.php';

/**
 * This class is the base class of all fuel data systems
 */
class fuel extends service
{
	/**
	 * initialization of some parameters
	 */
	public function init($request)
	{
		$this->debug = ($request['debug'] == 1);
	}

	/**
	 * prepare the data
	 */
	public function prepare()
	{
        foreach ($this->data as $id => $ds)
        {
            if ($ds['name'] != '')
            {
				if ($ds['brand'] == '' || $ds['brand'] == 'Freie' || $ds['brand'] == 'Freie Tankstelle') {
					if (strpos($ds['name'], "BK-Tankstelle") !== false ) {                          
						$ds['brand'] = 'BK';
					} else if (strpos($ds['name'], "AEZ") !== false ) {                          
						$ds['brand'] = 'aez';
					} else if (strpos($ds['name'], "Sued") !== false ) {                          
						$ds['brand'] = 'ST';
					}
				}
                if ($ds['brand'] != '' and is_file(const_path.'pics/fuel/'.$ds['brand'].'.jpg'))
                    $ds['pic'] = $ds['brand'].'.jpg';
                elseif ($ds['brand'] != '' and is_file(const_path.'pics/fuel/'.$ds['brand'].'.png'))
                    $ds['pic'] = $ds['brand'].'.png';
                else
                    $ds['pic'] = 'fuel_station.svg';

				if (strlen($ds['name']) > 22) {
					$ds['text'] = substr($ds['name'],0,22)."...";
				} else {
					$ds['text'] = $ds['name'];
				}
				$ds['gmaps_link'] = "http://www.google.com/maps/place/".$ds['lat'].",".$ds['lng'];

                if ($ds['isOpen'] == 'True')
                {
                    $ds['openpic'] = 'open.png';
                    $ds['openalt'] = trans('fuel', 'open');
                } else
                {
                    $ds['openpic'] = 'closed.png';
                    $ds['openalt'] = trans('fuel', 'closed');
                }   

                                $ds['address'] = $ds['place'].", ".$ds['street']." ".$ds['housenumber'];

                $ret[] = $ds;
            }
        }
        $this->data = $ret;
	}
}
?>

Neues Widget fuel.html:

/**
* Displays the list of petrol stations from a fuel data provided
*
* @param unique id for this widget
* @param a title to display
* @param the number of displayed lines, default 10
* @param the refresh interval for this widget (using relative time format), default 15m
*/
{% macro list(id, title, count, repeat) %}
	{% set uid = uid(page, id) %}

	<div id="{{ uid }}-phonelist" data-widget="fuel.list" class="phonelist" data-repeat="{{ repeat|default('15m') }}">
		{% if title %} <h2>{{ title }}</h2> {% endif %}
		<ul data-role="listview">
		</ul>
	</div>

	<script type="text/javascript">
		$(document).delegate('div[data-widget="fuel.list"]', {
			'init' : function (event) {
				$.getJSON('lib/fuel/service/fuel_tankerkoenig.php', function (data) {
					var ret;
					var line = '';
					var sum = 1;

					for (var i in data) {
						data[i].price = data[i].price.toString()
						ret = '<img class="icon ' + data[i].openalt + '" src="pics/fuel/' + data[i].pic + '" />';
						ret += '<img class="dir" src="lib/fuel/pics/' + data[i].openpic + '" />';
						ret += '<h3>' + data[i].text + '&nbsp;</h3>';
						ret += '<p>' + data[i].address + '&nbsp;</p>';
						ret += '<span class="ui-li-count fuelpreis">' + data[i].price.substr(0, 4) + '<sup>' + data[i].price.substr(4, 1) + '</sup>' + data[i].price.substr(5) + ' €</span>';
						ret = '<a ' + (data[i].gmaps_link ? 'href="' + data[i].gmaps_link : '') + '">' + ret + '</a>';

						line += '<li data-icon="false">' + ret + '</li>';
						if (sum++ == {{ count|default(10) }}) {
							break;
						}
					}

					$('#{{ uid }}-phonelist ul').html(line).trigger('prepare').listview('refresh').trigger('redraw');
				})
				.error(notify.json);
			},

			'repeat': function(event) {
				$('#{{ uid }}-phonelist').trigger('init');
			}
		});

		$('#{{ page }}').on('pagecreate', function (event, ui) {
			$('#{{ uid }}-phonelist').trigger('init');
		});
	</script>
{% endmacro %}

New localized texts, e.g. in lang\lang_de.txt:

// ----- Fuel -----------------------------------------------------------------
$lang['fuel']['open']			= 'offen';
$lang['fuel']['closed']			= 'geschlossen';

Store Logos (named as .png or .jpg) in \pics\fuel
Store two images for closed (closed.png) and open (open.png) - e.g. a small red and green circle - in \lib\fuel\pics

Usage, e.g. in index.html:

{% import "fuel.html" as fuel %}
{{ fuel.list('fuellist', 'Benzinpreise (Diesel)', 3) }}

Ältere Artikel zu Items

Ältere Logik Beispiele


Release Notes

Die aktuellen Release Notes und die Release Notes der zurückliegenden Versionen sind in der Dokumentation im Abschnitt Release Notes zu finden.

Updates

Work in Progress und Planungen


Clone this wiki locally