zhulik / aiotractive

Asynchronous Python client for the Tractive REST API
MIT License
21 stars 6 forks source link

HowTo Start? #32

Open sl4m01 opened 5 months ago

sl4m01 commented 5 months ago

Dear all, i am really happy i found this API script. I do have a cat using the current tractive tracker. But i am a pyhton beginner, therefor i am afraid i would need some help to start. Maybe someone could help me? :)

I am using a raspberry pi 4b and ssh connection. Performed pip install aiotractive and installed the script. Than i created a python file sudo nano test.py and enter the following code:

import asyncio

from aiotractive import Tractive

async def main():
  async with Tractive("my@mail.com", "mypassword") as client:
    print(32) #just to test
    await client.authenticate()
    trackers = await client.trackers()
    tracker = trackers[0]
    await tracker.details()

# interact with the client here
    pass

if __name__ == "__main__":
  asyncio.run(main())

Saved and than i performed python test.py, no errors but only getting 32 (because of the test print command). The same using python3 test.py

If i do sudo python test.py i am getting following errors: Traceback (most recent call last): File "/home/test.py", line 4, in <module> from aiotractive import Tractive ModuleNotFoundError: No module named 'aiotractive'

Now i am pretty lost and dont know what to do or what to expect as a result. At least, if i type my mail or password wrong i am getting an authorization error as a result. Also getting an error if i type the tracker ID wrong. But i am just getting no results displayed in the ssh console.

Is the way i am doing this correct? Can someone help me? This would be very nice! Best regards Simon

FukjemiCZ commented 5 months ago

Hi, I use this library like this https://github.com/FukjemiCZ/TractiveScraper I have an application that stores data in a time database.

It works for me in K8s. You can find the installation in the docker image

Get inspired and then send me a link to your app.


That error message means you didn't install the library. Put in the same path where you have test.py pip install aiotractive You can notice in my example response that pip tells you in the output what version of python it used

pi@localhost-> pip install aiotractive
Requirement already satisfied: aiohttp>=3.8.1 in /opt/homebrew/lib/python3.11/site-packages (from aiotractive) (3.8.6)
Requirement already satisfied: yarl>=1.7.2 in /opt/homebrew/lib/python3.11/site-packages (from aiotractive) (1.9.2)
Requirement already satisfied: attrs>=17.3.0 in /opt/homebrew/lib/python3.11/site-packages (from aiohttp>=3.8.1->aiotractive) (23.1.0)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /opt/homebrew/lib/python3.11/site-packages (from aiohttp>=3.8.1->aiotractive) (3.3.2)
Requirement already satisfied: multidict<7.0,>=4.5 in /opt/homebrew/lib/python3.11/site-packages (from aiohttp>=3.8.1->aiotractive) (6.0.4)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /opt/homebrew/lib/python3.11/site-packages (from aiohttp>=3.8.1->aiotractive) (4.0.3)
Requirement already satisfied: frozenlist>=1.1.1 in /opt/homebrew/lib/python3.11/site-packages (from aiohttp>=3.8.1->aiotractive) (1.4.0)
Requirement already satisfied: aiosignal>=1.1.2 in /opt/homebrew/lib/python3.11/site-packages (from aiohttp>=3.8.1->aiotractive) (1.3.1)
Requirement already satisfied: idna>=2.0 in /opt/homebrew/lib/python3.11/site-packages (from yarl>=1.7.2->aiotractive) (3.4)

and then python3.11 test.py

sl4m01 commented 5 months ago

Hello, i managed to get it working with this library. Maybe to help others who are struggeling i post my code. First I performed the steps in my first comment:

  1. Installed the library pip install aiotractive
  2. Created a python script sudo nano tractive.py

I wanted to read some information frequently of the tracker and send them via mqtt to my smarthome:

import asyncio
from paho.mqtt import client as mqtt_client
import random

from aiotractive import Tractive

broker = '192.168.0.xxx'
port = 1883
topic = "python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = 'username'
password = 'password'

def connect_mqtt():
    # def on_connect(client, userdata, flags, rc):
    # For paho-mqtt 2.0.0, you need to add the properties parameter.
    def on_connect(client, userdata, flags, rc, properties):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    # Set Connecting Client ID
    #client = mqtt_client.Client(client_id)

    # For paho-mqtt 2.0.0, you need to set callback_api_version.
    client = mqtt_client.Client(client_id=client_id, callback_api_version=mqtt_client.CallbackAPIVersion.VERSION>

    # client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

async def main():
  async with Tractive("mail@mail.com", "password") as client:
    await client.authenticate()
    tracker = client.tracker("TRACKERID")
    detail = await tracker.details()
    #print(detail)
    info = await tracker.hw_info()
    #print(info)
    position = await tracker.pos_report()
    #print(position['latlong'])

    latlong = str(position['latlong'])
    latlong = latlong.strip("[]")
    latlong = latlong.split(", ")
    lat = latlong[0]
    long = latlong[1]
#    print(lat)
 #   print(long)

    battery_save_mode = str(detail['battery_save_mode'])
    battery_state = str(detail['battery_state'])
    battery_level = str(info['battery_level'])
    time = str(position['time'])
    time_rcvd = str(position['time_rcvd'])
    speed = str(position['speed'])
    sensor_used = str(position['sensor_used'])
    power_saving_zone_id = str(position['power_saving_zone_id'])
    altitude = str(position['altitude'])
    print(altitude)
  #  detail_str = str(detail)
    client = connect_mqtt()
    client.loop_start()
    client.publish("Charlie/lat", lat);
    client.publish("Charlie/long", long);
    client.publish("Charlie/battery_save_mode", battery_save_mode);
    client.publish("Charlie/battery_state", battery_state);
    client.publish("Charlie/battery_level", battery_level);
    client.publish("Charlie/time", time);
    client.publish("Charlie/time_rcvd", time_rcvd);
    client.publish("Charlie/speed", speed);
    client.publish("Charlie/sensor_used", sensor_used);
    client.publish("Charlie/power_saving_zone_id", power_saving_zone_id);
    client.publish("Charlie/altitude", altitude);
    client.loop_stop()
    pass

if __name__ == "__main__":
  asyncio.run(main())

Than i put this script into crontab crontab -e and let it run every 5 minutes */5 * * * * python3 /home/tractive.py

My code is not optimzed or cleaned-up. But its working for me and brings the information into mqtt. From there on i run some automations and do a amazon alexa integration.

danielwuensche commented 3 weeks ago

Seems like you got it working in the end, so I don't know if you still need someone to answer your initial questions.

Saved and than i performed python test.py, no errors but only getting 32 (because of the test print command). The same using python3 test.py

In your sample code, only "32" is written because that's what you told it to. main() does some things, but it's not told to print results, or to return any data. I guess you wanted it to print the result of await tracker.details(), you would have to wrap that line in a print()-Statement like print(await tracker.details()) or return the data and print it outside of the main()-function. For data to appear in your console-output, it needs to be printed at some point.

If i do sudo python test.py i am getting following errors: Traceback (most recent call last): File "/home/test.py", line 4, in <module> from aiotractive import Tractive ModuleNotFoundError: No module named 'aiotractive'

Running pip install aiotractive makes the package available for the user who ran the command, it only exists for that user. If you run your script with sudo, the script is run as the root-user, not your user. As you didn't install the package for the root-user, it's not available in this case. For security reasons, never install packages via pip as root as this means that whatever is being installed from the internet, has the highest possible permissions on your system.

If you don't have an open issue regarding this project, please close the issue.