Traccar.org (GPS/GPRS Tracker) custom platform

Apologies, that was the problem :slight_smile: still don’t see where the info goes to? Should my trackers show up in known devices?

RESOLVED: Just upgraded traccar and everything came to life :slight_smile:

Anyone running their own traccar server, willing to have another user? The demo servers offered by traccar have become unreliable.

I might also look into hosting one on AWS, as it might be pretty inexpensive.
Traccar want’s $10/mo for private server access; seems expensive to me (or maybe I’m just cheap :slight_smile:).

Hello,
I am having little problem with this component, with latest HASS it suddenly stopped to show device on map. I can see traccar is alive, it is fetching data, I can see address, GPS, time in sensor details but there is no icon on map.
Don’t you have the same problem ?
I did not find anything interesting in logs.
thanks

It won’t report if you’re near your home point… (but you likely knew that?)

oh, you are right. thanks :slight_smile:

You can run it on the same device as you run Home Assistant. I’m running mine on an RPI 3 without any problems so far.

Thanks man, don’t you need to open a port in the firewall though? Any idea what port?

Yes, and the port depends on what device you are using.

Usually you only need one or two ports open.

Hi I am having trouble getting taccar working with hass. I haven’t got the odb2 device to work yet, but are using themobile device for testing.

Config:
- platform: traccar
username: [email protected] (are admin)
password: password
host: http://192.168.86.70:8082

/api/devices:
[{"id":1,"attributes":{},"groupId":0,"name":"Kristian Pixel","uniqueId":"989529","status":"online","lastUpdate":"2018-03-22T10:12:51.562+0000","positionId":102,"geofenceIds":[],"phone":"","model":"","contact":"","category":null,"disabled":false},{"id":2,"attributes":{},"groupId":0,"name":"OBD2","uniqueId":"352887077307340","status":"offline","lastUpdate":null,"positionId":0,"geofenceIds":[],"phone":"","model":"","contact":"","category":null,"disabled":false}]

/api/positions:
[{"id":98,"attributes": "batteryLevel":84.0,"distance":0.0,"totalDistance":55735.03,"motion":false},"deviceId":1,"type":null,"protocol":"osmand","serverTime":"2018-03-22T09:50:47.831+0000","deviceTime":"2018-03-22T09:50:04.000+0000","fixTime":"2018-03-22T09:50:04.000+0000","outdated":false,"valid":true,"latitude":59.9301432,"longitude":10.7120166,"altitude":131.39999389648438,"speed":0.0,"course":0.0,"address":"6 Sørkedalsveien, Oslo, Oslo, NO","accuracy":21.625,"network":null}]

Error from hass:

2018-03-22 10:44:35 ERROR (MainThread) [homeassistant.components.device_tracker] Error setting up platform traccar
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/homeassistant/components/device_tracker/__init__.py", line 188, in async_setup_platform
    disc_info)
  File "/usr/lib/python3.6/asyncio/futures.py", line 332, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.6/asyncio/tasks.py", line 250, in _wakeup
    future.result()
  File "/usr/lib/python3.6/asyncio/futures.py", line 245, in result
    raise self._exception
  File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/device_tracker/traccar.py", line 28, in setup_scanner
    TraccarDeviceScanner(hass, config, see)
  File "/config/custom_components/device_tracker/traccar.py", line 41, in __init__
    self._update_info()
  File "/config/custom_components/device_tracker/traccar.py", line 49, in _update_info
    self._device_data = json.loads(self._devices.text)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

2018-03-22 10:44:36 INFO (MainThread) [homeassistant.core] Bus:Handling <Event system_log_event[L]: timestamp=1521711875.9140463, level=ERROR, message=Error setting up platform traccar, exception=Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/homeassistant/components/device_tracker/__init__.py", line 188, in async_setup_platform
    disc_info)
  File "/usr/lib/python3.6/asyncio/futures.py", line 332, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.6/asyncio/tasks.py", line 250, in _wakeup
    future.result()
  File "/usr/lib/python3.6/asyncio/futures.py", line 245, in result
    raise self._exception
  File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/device_tracker/traccar.py", line 28, in setup_scanner
    TraccarDeviceScanner(hass, config, see)
  File "/config/custom_components/device_tracker/traccar.py", line 41, in __init__
    self._update_info()
  File "/config/custom_components/device_tracker/traccar.py", line 49, in _update_info
    self._device_data = json.loads(self._devices.text)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
, source=custom_components/device_tracker/traccar.py>

traccar.py:

#-*- coding: utf-8 -*-
"""
Support for the TRACCAR platform.
"""
import logging
import requests, json
import voluptuous as vol

CONF_HOST = "host"

from homeassistant.components.device_tracker import (
    PLATFORM_SCHEMA, ATTR_ATTRIBUTES)
from homeassistant.const import CONF_NAME, CONF_USERNAME, CONF_PASSWORD
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_utc_time_change
from homeassistant.util import slugify

_LOGGER = logging.getLogger(__name__)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_USERNAME): cv.string,
    vol.Required(CONF_PASSWORD): cv.string,
    vol.Required(CONF_HOST): cv.string
})

def setup_scanner(hass, config: dict, see, discovery_info=None):
    """Validate the configuration and return a Traccar scanner."""
    TraccarDeviceScanner(hass, config, see)
    return True

class TraccarDeviceScanner(object):
    """A class representing a Traccar device."""

    def __init__(self, hass, config: dict, see) -> None:
        """Initialize the Traccar device scanner."""
        self.hass = hass
        self._host = config.get(CONF_HOST)
        self._username = config.get(CONF_USERNAME)
        self._password = config.get(CONF_PASSWORD)
        self.see = see
        self._update_info()
        track_utc_time_change(self.hass, self._update_info,
                              second=range(0, 60, 30))

    def _update_info(self, now=None) -> None:
        """Update the device info."""
        _LOGGER.debug('Updating devices %s', now)
        self._devices = requests.get(self._host + '/api/devices', auth=(self._username, self._password),headers = ({'Accept': 'application/json'}))
        self._device_data = json.loads(self._devices.text)
        self._positions = requests.get(self._host + '/api/positions', auth=(self._username, self._password), headers = ({'Accept': 'application/json'}))
        self._positions_data = json.loads(self._positions.text)
        for dev_id in self._device_data:
            _id=dev_id['name']
            _name = dev_id['name']
            for position_id in self._positions_data:
                if position_id['id'] == dev_id['positionId']:
                    _gps=(position_id['latitude'], position_id['longitude'])
                    _gps_accuracy=position_id['accuracy']
                    _attrs = {
                        'totalDistance': position_id['attributes']['totalDistance'],
                        'protocol': position_id['protocol'],
                        'speed': position_id['speed'],
                        'address': position_id['address'],
                        'status':  dev_id['status'],
                        'lastUpdate': dev_id['lastUpdate']
                        }
                    self.see(
                        dev_id=slugify(_id),
                        host_name=slugify(_name),
                        gps=_gps,
                        gps_accuracy=_gps_accuracy,
                        attributes=_attrs
                    )

What did you name your device in Traccar?

The custom platform does not work, if you use special characters like "’, in the name.

Also easiest way to check if the traccar api is actually working, is by going to the http://192.168.86.70:8082/api/devices

The name is OBD, the respons from /api/devices are in my first post.

I have had this component setup for a while now using an OBD plug and SIM card in my car. Works great!

This evening I just setup the Traccar Android app on my phone and all is working great within the Traccar server, however I can’t seem to get my phone to show up in HomeAssistant. I have checked api/devices and api/positions and both my Car and Phone are showing in the output, however HomeAssistant does some to be picking it up.
Out of interest I added it into known_devices.yaml with the correct ID name and formatting as my work device, and HomeAssistant doesn’t seem to be pulling any info.

Has anyone tested this using the Traccar Android app or with more than 1 device?

Managed to fix it myself.
Enabled HomeAssistant error logging on the component and saw that I was getting KeyError: ‘ip’

Saw above that some else had the error and then the python file was updated.
Updated, restarted (and now changed from ‘id’ to ‘name’ and everything is working awesome!

@koen01, it might pay to update your original post/link as it seems to be linking to an older version of the file on Github in an old branch. Something I didn’t pick up when I originally checked for updates >< haha

@Pawny; thank you for suggesting but I can’t seem to edit the opening post?
Does someone know how to do this? The edit option isn’t available on the first post?

Ah, that’s annoying. Just tried to see if I could edit a post/thread I made a while back and I also can’t edit it.

Hi guys,

Looking for some help in setting up this custom component as i am receiving the following error log:

Error setting up platform traccar
Traceback (most recent call last):
File “/usr/lib/python3.6/site-packages/homeassistant/components/device_tracker/init.py”, line 184, in async_setup_platform
disc_info)
File “/usr/lib/python3.6/concurrent/futures/thread.py”, line 56, in run
result = self.fn(*self.args, **self.kwargs)
File “/config/custom_components/device_tracker/traccar.py”, line 28, in setup_scanner
TraccarDeviceScanner(hass, config, see)
File “/config/custom_components/device_tracker/traccar.py”, line 41, in init
self._update_info()
File “/config/custom_components/device_tracker/traccar.py”, line 49, in _update_info
self._device_data = json.loads(self._devices.text)
File “/usr/lib/python3.6/json/init.py”, line 354, in loads
return _default_decoder.decode(s)
File “/usr/lib/python3.6/json/decoder.py”, line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File “/usr/lib/python3.6/json/decoder.py”, line 357, in raw_decode
raise JSONDecodeError(“Expecting value”, s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I have checked the API is working and that the account has admin privileges,
I also have checked username and passwords, Removed https for http of the web address in the config,

Unsure where to start as I am very new to this, Any help would be greatly appreciated!

1 Like

Edit: Looks like I fell for the same issue as the previous poster. The original link is an out of date one and has issues. Once the latest copy is downloaded, its fine.

Just wanted to give a huge shoutout to @koen01 and @Bob_NL for helping me getting this to work.

Without the custom component and without Bob’s insight of port 5023 for my case, I would have been stuck for days.

:+1:

2 Likes

You’re welcome!