Plugin help

Posted on
Sun Dec 31, 2023 10:01 am
neilk offline
Posts: 715
Joined: Jul 13, 2015
Location: Reading, UK

Re: Plugin help

Martin,
Can you try ‘python3 toyota.py’ as those are not Python errors.
Neil

Posted on
Sun Dec 31, 2023 10:03 am
FlyingDiver offline
User avatar
Posts: 7222
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: Plugin help

I suspect you have a broken homebrew-installed Python installation, based on the brew error in the output.

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Posted on
Sun Dec 31, 2023 10:05 am
mwoodage offline
User avatar
Posts: 174
Joined: Dec 19, 2014
Location: Devon UK

Re: Plugin help

Hi Neil,
Yes when i try python3 toyota.py i get

Code: Select all
Last login: Sun Dec 31 15:46:57 on ttys000
/Users/martin/.zprofile:6: no such file or directory: /opt/homebrew/bin/brew
martin@Martins-Mac-mini-2 Totota % python3 toyota.py
Logging in...
Retrieving cars...
Traceback (most recent call last):
  File "/Users/martin/Totota/toyota.py", line 111, in <module>
    loop.run_until_complete(get_information())
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 664, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/Users/martin/Totota/toyota.py", line 75, in get_information
    cars = await client.get_vehicles()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/mytoyota/client.py", line 212, in get_vehicles
    vehicles = await self.api.get_vehicles_endpoint()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/mytoyota/api.py", line 35, in get_vehicles_endpoint
    return await self.controller.request(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/mytoyota/controller.py", line 245, in request
    raise ToyotaApiError(
mytoyota.exceptions.ToyotaApiError: HTTP: 400 - {"code":"TME_B2C_ERR_UNHANDLED_ERROR","message":"Something went very very wrong! :-( due to TAAS response: Bad Request","stack":"AppError: Something went very very wrong! :-( due to TAAS response: Bad Request\n    at defaultHandler (/var/lib/nodejs/src/lib/error.js:61:19)\n    at /var/lib/nodejs/node_modules/@tme/datadog/node_modules/dd-trace/packages/datadog-instrumentations/src/router.js:50:25\n    at defaultHandler (/var/lib/nodejs/node_modules/@tme/datadog/node_modules/dd-trace/packages/datadog-shimmer/src/shimmer.js:26:21)\n    at Layer.handle_error (/var/lib/nodejs/node_modules/express/lib/router/layer.js:71:5)\n    at trim_prefix (/var/lib/nodejs/node_modules/express/lib/router/index.js:326:13)\n    at /var/lib/nodejs/node_modules/express/lib/router/index.js:286:9\n    at Function.process_params (/var/lib/nodejs/node_modules/express/lib/router/index.js:346:12)\n    at Function.process_params (/var/lib/nodejs/node_modules/@tme/datadog/node_modules/dd-trace/packages/datadog-instrumentations/src/express.js:70:23)\n    at next (/var/lib/nodejs/node_modules/express/lib/router/index.js:280:10)\n    at Layer.handle_error (/var/lib/nodejs/node_modules/express/lib/router/layer.js:67:12)","name":"AppError","info":{"code":"TAAS_SERVICE_STATUS_400","message":"TAAS response: Bad Request","stack":"TmeError: TAAS response: Bad Request\n    at Taas._replyToTaasError (/var/lib/nodejs/node_modules/@tme/taas/lib/taas.js:362:23)\n    at Taas.getUserByToken (/var/lib/nodejs/node_modules/@tme/taas/lib/taas.js:184:40)\n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n    at async TaasStrategy.deserializeUser (/var/lib/nodejs/node_modules/@tme/taas-passport/lib/taas-strategy.js:69:26)","name":"TmeError","data":{"body":{"httpErrorCode":400,"message":"Brand provided is not recognised"},"path":"/user/getUserByToken"},"status":400,"source":"TAAS"},"statusCode":400}
martin@Martins-Mac-mini-2 Totota %

Posted on
Sun Dec 31, 2023 10:07 am
mwoodage offline
User avatar
Posts: 174
Joined: Dec 19, 2014
Location: Devon UK

Re: Plugin help

Hi Joe,
Funny you should say that because i wondered what the brew error was at the top of the error log - i've been googling to try to fix it this afternoon.....

Posted on
Sun Dec 31, 2023 10:08 am
FlyingDiver offline
User avatar
Posts: 7222
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: Plugin help

First, edit your .zprofile file and delete line 6 referring to homebrew.

Also, why do you have Python 3.12 installed? You should be using the version of Python installed by Indigo, which is currently 3.10. See my previous comment about a broken homebrew install.

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Posted on
Sun Dec 31, 2023 10:17 am
mwoodage offline
User avatar
Posts: 174
Joined: Dec 19, 2014
Location: Devon UK

Re: Plugin help

Ok, i'll check the home brew bit and get back to you - however I've just got to nip out for an hour!!

Posted on
Mon Jan 01, 2024 12:15 pm
mwoodage offline
User avatar
Posts: 174
Joined: Dec 19, 2014
Location: Devon UK

Re: Plugin help

Hello, Neil, Joe,
So after a lot of head scratching and googling last night and today, i've now managed to get my .zprofile and python versions correct. Hopefully!
However i'm still getting the same errors as before and shown below, so not sure what's wrong.

I think, given that most of us are back to work tomorrow, I going to leave this for a few days until i can dedicate more time to looking into it. I really appreciate your help over the last couple of days - hopefully we can look at it again in the near future.

Thanks again
Martin


Code: Select all
Last login: Mon Jan  1 18:04:49 on ttys000
martin@Martins-Mac-mini-2 Totota % python3 toyota.py
Logging in...
Retrieving cars...
Traceback (most recent call last):
  File "/Users/martin/Totota/toyota.py", line 109, in <module>
    loop.run_until_complete(get_information())
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 641, in run_until_complete
    return future.result()
  File "/Users/martin/Totota/toyota.py", line 73, in get_information
    cars = await client.get_vehicles()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/mytoyota/client.py", line 212, in get_vehicles
    vehicles = await self.api.get_vehicles_endpoint()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/mytoyota/api.py", line 35, in get_vehicles_endpoint
    return await self.controller.request(
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/mytoyota/controller.py", line 245, in request
    raise ToyotaApiError(
mytoyota.exceptions.ToyotaApiError: HTTP: 400 - {"code":"TME_B2C_ERR_UNHANDLED_ERROR","message":"Something went very very wrong! :-( due to TAAS response: Bad Request","stack":"AppError: Something went very very wrong! :-( due to TAAS response: Bad Request\n    at defaultHandler (/var/lib/nodejs/src/lib/error.js:61:19)\n    at /var/lib/nodejs/node_modules/@tme/datadog/node_modules/dd-trace/packages/datadog-instrumentations/src/router.js:50:25\n    at defaultHandler (/var/lib/nodejs/node_modules/@tme/datadog/node_modules/dd-trace/packages/datadog-shimmer/src/shimmer.js:26:21)\n    at Layer.handle_error (/var/lib/nodejs/node_modules/express/lib/router/layer.js:71:5)\n    at trim_prefix (/var/lib/nodejs/node_modules/express/lib/router/index.js:326:13)\n    at /var/lib/nodejs/node_modules/express/lib/router/index.js:286:9\n    at Function.process_params (/var/lib/nodejs/node_modules/express/lib/router/index.js:346:12)\n    at Function.process_params (/var/lib/nodejs/node_modules/@tme/datadog/node_modules/dd-trace/packages/datadog-instrumentations/src/express.js:70:23)\n    at next (/var/lib/nodejs/node_modules/express/lib/router/index.js:280:10)\n    at Layer.handle_error (/var/lib/nodejs/node_modules/express/lib/router/layer.js:67:12)","name":"AppError","info":{"code":"TAAS_SERVICE_STATUS_400","message":"TAAS response: Bad Request","stack":"TmeError: TAAS response: Bad Request\n    at Taas._replyToTaasError (/var/lib/nodejs/node_modules/@tme/taas/lib/taas.js:362:23)\n    at Taas.getUserByToken (/var/lib/nodejs/node_modules/@tme/taas/lib/taas.js:184:40)\n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n    at async TaasStrategy.deserializeUser (/var/lib/nodejs/node_modules/@tme/taas-passport/lib/taas-strategy.js:69:26)","name":"TmeError","data":{"body":{"httpErrorCode":400,"message":"Brand provided is not recognised"},"path":"/user/getUserByToken"},"status":400,"source":"TAAS"},"statusCode":400}
martinwoodage@Martins-Mac-mini-2 Totota %


Code: Select all
#!/usr/bin/env python
import asyncio

# Adding the import line from the variable example from the new HTTP api "Updating a variables value" and removed the pretty print as it won't be needed
from urllib.request import Request, urlopen
import json
from mytoyota.client import MyT


# Again from the example add your details below, including the correct variable ID for mileage, fuel, battery and latitude
REFLECTORNAME = "http://********.indigodomo.net"
APIKEY = "**************************"
MILEAGEVARIABLE = 924494111
FUELVARIABLE = 1757439952
BATTERYVARIABLE = 1970916222
LATITUDEVARIABLE = 998494523


# now define a function (so we don't need to repeat the code to set each variable, we will call it later but it is the code from the http api python example

def set_indigo_variable(VARIABLEID, VALUE):
    message = json.dumps({
        "id": "optional-user-generated-id",
        "message": "indigo.variable.updateValue",
        "objectId": VARIABLEID,
        "parameters": {
            # this is modified to use VALUE that is passed to the function to updated the indigo variable rather than "Some string value" in the example code
            "value": VALUE
        }
    }).encode("utf8")
    req = Request(f"https://************.indigodomo.net/v2/api/command", data=message)
    req.add_header('Authorization', f"Bearer {APIKEY}")
    with urlopen(req) as request:
        reply = json.load(request)
        print(reply)



# Set your username and password here OR
# in a file called credentials.json in the format
#   {
#       "username": "<username>",
#       "password": "<password>"
#   }
username = '****************'
password = '*************'
try:
    credentials = json.load(open("credentials.json"))
    username = credentials["username"]
    password = credentials["password"]
except FileNotFoundError:
    pass
except json.decoder.JSONDecodeError:
    pass

if username is None or password is None:
    print(
        "Did you forget to set your username and password? Or supply the credentials file"
    )
    exit()

# Pretty indigo.server.loger used below

client = MyT(username=username, password=password, brand="T")


async def get_information():
    print("Logging in...")
    await client.login()

    print("Retrieving cars...")
    # Returns cars registered to your account + information about each car.
    cars = await client.get_vehicles()

    for car in cars:
        await car.update()

        # Alias
        print("Alias: "+car.alias)
        # Set alias
        # await car.set_alias("RAV4")

        # Basic information
        mileage = car.dashboard.odometer
        print(f"Mileage :{mileage}")
        # now call the function passing it the correct variable ID and the mileage value returned (Same approach for the others)
        set_indigo_variable(MILEAGEVARIABLE, str(mileage))
        # Or retrieve the energy level (electric or gasoline)
        fuel = car.dashboard.fuel_level
        print(f"Fuel :{fuel}")
        set_indigo_variable(FUELVARIABLE, str(fuel))
        battery = car.dashboard.battery_level
        print(f"Battery : {battery}")
        set_indigo_variable(BATTERYVARIABLE, str(battery))
        # Or Parking information:
        latitude = car.location.latitude
        print(f"Latitude :{latitude}")
        set_indigo_variable(LATITUDEVARIABLE, str(latitude))

        # Notifications => True retrieve all, False just unread
        # notifications = car.notifications(True)[:5]
        # if notifications:
        #  indigo.server.log("Notifications:")
        # for notification in notifications:
        #    indigo.server.log(f"    {notification.date} : {notification.message}")


loop = asyncio.new_event_loop()
loop.run_until_complete(get_information())
loop.close()

Posted on
Tue Jan 02, 2024 2:11 am
neilk offline
Posts: 715
Joined: Jul 13, 2015
Location: Reading, UK

Re: Plugin help

Hi Martin,
That makes sense, my suggested plan :-

1) We go back to the basics and get the original test script to work 'as is' from GitHub as you did originally. This rule out any of the changes, version differences and your python install

2) I create a separate script that updates the variables with a test value with no Toyota stuff and we get that working

3) We then add the two together !

We will get it sorted !

Neil

Posted on
Wed Jan 03, 2024 6:32 am
neilk offline
Posts: 715
Joined: Jul 13, 2015
Location: Reading, UK

Re: Plugin help

Martin,
As per the plan, this script should update your variables with "test values"

Code: Select all
#!/usr/bin/env python3

#
from urllib.request import Request, urlopen
import json


# Again from the example add your details below, including the correct variable ID for mileage, fuel, battery and latitude
# For the reflector name, just include the unique portion before the first . rather than the full URL
REFLECTORNAME = "xxxxxxxxxxxx"
APIKEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxf"
# Update with your variable ID;s
MILEAGEVARIABLE = 520855978
FUELVARIABLE = 1598525448
BATTERYVARIABLE = 1947159701
LATITUDEVARIABLE = 93775207

# now define a function (so we don't need to repeat the code to set each variable, we will call it later but it is the code from the http api python example

def set_indigo_variable(VARIABLEID, VALUE):
    message = json.dumps({
        "id": "toyota",
        "message": "indigo.variable.updateValue",
        "objectId": VARIABLEID,
        "parameters": {
            # this is modified to use VALUE that is passed to the function to updated the indigo variable rather than "Some string value" in the example code
            "value": VALUE
        }
    }).encode("utf8")
    req = Request(f"https://{REFLECTORNAME}.indigodomo.net/v2/api/command", data=message)
    req.add_header('Authorization', f"Bearer {APIKEY}")
    with urlopen(req) as request:
        reply = json.load(request)
        print(reply)

mileage = 1234568
print(f"Mileage :{mileage}")
# now call the function passing it the correct variable ID and the mileage value returned (Same approach for the others)
set_indigo_variable(MILEAGEVARIABLE, str(mileage))
# Or retrieve the energy level (electric or gasoline)
fuel = 80
print(f"Fuel :{fuel}")
set_indigo_variable(FUELVARIABLE, str(fuel))
battery = 90
print(f"Battery : {battery}")
set_indigo_variable(BATTERYVARIABLE, str(battery))
# Or Parking information:
latitude = 12345
print(f"Latitude :{latitude}")
set_indigo_variable(LATITUDEVARIABLE, str(latitude))





Save that as "indigo_variables.py", and run it by (in the directory you created


Code: Select all
python3 indigo_variables.py


If successful it should output like

Code: Select all
Mileage :1234568
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}
Fuel :80
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}
Battery : 90
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}
Latitude :12345
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}


Now we will make it executable (this will just run with no message and it only needs to be done once)

Code: Select all
chmod +x indigo_variable.py


and now it should also run by typing

Code: Select all
./indigo_variable.py


If this works, we can then download the latest test script from https://github.com/DurgNomis-drol/mytoyota/blob/master/simple_client_example.py

And add your credentials and run it.

If that works then please post the results (as I think it will have changed since your earlier versions looking at the edits) and we can then add the bits you need to update the indigo variables.

Neil

Posted on
Wed Jan 03, 2024 12:21 pm
mwoodage offline
User avatar
Posts: 174
Joined: Dec 19, 2014
Location: Devon UK

Re: Plugin help

Success! :D

I've carried out the items as noted in your last post and it's working.......

martin@Martins-Mac-mini-2 Totota % ./indigo_variables.py
Mileage :1234568
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}
Fuel :80
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}
Battery : 90
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}
Latitude :12345
{'success': 'message sent to the Indigo Server, check the Event Log for details', 'id': 'toyota'}
martin@Martins-Mac-mini-2 Totota %


Screenshot 2024-01-03 at 18.06.08.png
Screenshot 2024-01-03 at 18.06.08.png (15.51 KiB) Viewed 644 times


I now need to add the two scripts together - do i just copy and paste the latest scrip from https://github.com/DurgNomis-drol/mytoyota/blob/master/simple_client_example.py or does that need some changes to it?

Thanks so much for your help on this Neil - it's very much appreciated :D

Martin

Posted on
Wed Jan 03, 2024 12:43 pm
neilk offline
Posts: 715
Joined: Jul 13, 2015
Location: Reading, UK

Re: Plugin help

Brilliant - is the latest Toyota script working as well (if so can you post the output) and the version you are using (I would suggest the latest one from GitHub)

I will then combine the two in a new version (I will need to do it, I am basically going to replace the "prints" with the calls to update the variables and add the other supporting code, setup etc needed for both). I just want to make sure it works "as is" first, so we can then figure out any issues I may introduce.

Neil

Posted on
Wed Jan 03, 2024 2:48 pm
mwoodage offline
User avatar
Posts: 174
Joined: Dec 19, 2014
Location: Devon UK

Re: Plugin help

Hi Neil,
Thanks for the reply - I've had a quick look at this and the latest Toyota script from GitHub is not working - unfortunatly i've not got time today to have a look but will look again tomorrow evening.

Speak soon
Martin

Posted on
Wed Jan 03, 2024 3:06 pm
neilk offline
Posts: 715
Joined: Jul 13, 2015
Location: Reading, UK

Re: Plugin help

No worries - I think it is changing a fair bit. If it means going back to an earlier version that is fine, I just want a base we know works.

Neil

Posted on
Fri Jan 05, 2024 11:41 am
mwoodage offline
User avatar
Posts: 174
Joined: Dec 19, 2014
Location: Devon UK

Re: Plugin help

Hi Neil,
apologies for the slow reply, i've had two large projects start at work this week so not been able to pay much attention to this :shock:

Anyhow, i've now been able to get the script working again from https://github.com/DurgNomis-drol/mytoyota/blob/master/simple_client_example.py :D

So, this script, which is the latest version available,

Code: Select all
"""Simple test of new API Changes."""
import asyncio
import json
import pprint
from datetime import date, timedelta

from mytoyota.client import MyT
from mytoyota.models.summary import SummaryType

pp = pprint.PrettyPrinter(indent=4)

# Set your username and password in a file on top level called "credentials.json" in the format:
#   {
#       "username": "<username>",
#       "password": "<password>"
#   }


def load_credentials():
    """Load credentials from 'credentials.json'."""
    try:
        with open("credentials.json", encoding="utf-8") as f:
            return json.load(f)
    except (FileNotFoundError, json.decoder.JSONDecodeError):
        return None


credentials = load_credentials()
if not credentials:
    raise ValueError(
        "Did you forget to set your username and password? Or supply the credentials file"
    )

USERNAME = credentials["username"]
PASSWORD = credentials["password"]

client = MyT(username=USERNAME, password=PASSWORD)


async def get_information():
    """Test login and output from endpoints."""
    print("Logging in...")
    await client.login()

    print("Retrieving cars...")
    cars = await client.get_vehicles(metric=False)

    for car in cars:
        await car.update()

        # Dashboard Information
        pp.pprint(f"Dashboard: {car.dashboard}")
        # Location Information
        #pp.pprint(f"Location: {car.location}")
        # Lock Status
        #pp.pprint(f"Lock Status: {car.lock_status}")
        # Notifications
        #pp.pprint(f"Notifications: {[[x] for x in car.notifications]}")
        # Summary
        # pp.pprint(
        #    f"Summary: {[[x] for x in await car.get_summary(date.today() - timedelta(days=7), date.today(), summary_type=SummaryType.DAILY)]}"  # noqa: E501 # pylint: disable=C0301
        # )
        # pp.pprint(
        #    f"Summary: {[[x] for x in await car.get_summary(date.today() - timedelta(days=7 * 4), date.today(), summary_type=SummaryType.WEEKLY)]}"  # noqa: E501 # pylint: disable=C0301
        # )
        #pp.pprint(
        #    f"Summary: {[[x] for x in await car.get_summary(date.today() - timedelta(days=6 * 30), date.today(), summary_type=SummaryType.MONTHLY)]}"  # noqa: E501
        #)
        # pp.pprint(
        #    f"Summary: {[[x] for x in await car.get_summary(date.today() - timedelta(days=365), date.today(), summary_type=SummaryType.YEARLY)]}"  # noqa: E501 # pylint: disable=C0301
        # )

        # Trips
        #pp.pprint(
        #    f"Trips: f{await car.get_trips(date.today() - timedelta(days=7), date.today(), full_route=True)}"  # noqa: E501
        #)

        # Dump all the information collected so far:
        # pp.pprint(car._dump_all())


loop = asyncio.new_event_loop()
loop.run_until_complete(get_information())
loop.close()


Produces this....

Code: Select all
martin@Martins-Mac-mini-2 mytoyota % python3 simple_client_example.py
Logging in...
Retrieving cars...
('Dashboard: odometer=4552.0 fuel_level=64 battery_level=94 fuel_range=260.0 '
 'battery_range=48.094 battery_range_with_ac=44.728 range=304.472 '
 'charging_status=none remaining_charge_time=None warning_lights=[]')
martin@Martins-Mac-mini-2 mytoyota %


Which is perfect and exactly the information i need. You'll notice i've #out some of the information that is available, such as trips and daily summaries, is it produces so much info that i'm not interested in.
I'm running this file in /Users/martin/Documents/GitHub/mytoyota, which is where Github downloads everything too.

However when I copy the same file into /Users/martin/Toyota, which is where we're running the ./indigo_variables.py i get this,
Code: Select all
martin@Martins-Mac-mini-2 Totota % python3 simple_client_example.py
Traceback (most recent call last):
  File "/Users/martin/Totota/simple_client_example.py", line 8, in <module>
    from mytoyota.models.summary import SummaryType
ModuleNotFoundError: No module named 'mytoyota.models.summary'
martin@Martins-Mac-mini-2 Totota %

I'm assuming this is because i'm not running it in the same environment as all the other GitHub information that the script requires?

So we now have both the Mytoyota and the ./indigo_variables.py scripts working although in different locations! Is this something that we can work with?

Speak soon - and again many thanks for your help with this :D
Martin

Posted on
Fri Jan 05, 2024 2:28 pm
FlyingDiver offline
User avatar
Posts: 7222
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: Plugin help

In the first location, is there a folder called mytoyota? If so, copy it to the second location and try again.

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Who is online

Users browsing this forum: No registered users and 10 guests