OBD2 Python Getting Speed - python

I'm having a little trouble with getting the correct speed out of my Python OBD2 reading program. It stays at 13 even if I'm not moving. I have based my code off of pi2go on git hub. Though no matter what the speed_float value is always 13 once converted from hex to a float.
def speed(self, oldValues):
""" Gets the speed of the vehicle """
if self.serialIO is None:
return "Serial IO not setup."
self.serialWrite("0D")
speed_list = self.serialRead()
if speed_list == -1 or speed_list == 0:
print("There is an issue with reading the speed of the vehicle.")
return 0
else:
speed_hex = speed_list[0]
speed_float = float(int("0x" + speed_hex, 0))
print("Speed float = " + str(speed_float))
if speedFormat == "mph":
# display speed in miles per hour
#speed_float = speed_float * 0.621371
speed_float = speed_float * 1.609 - 20.917 #made it go to zero by subtracting 20.917
print("mph = " + str(speed_float))
elif speedFormat == "kph":
# display speed in kilometers per hour
print("kph = " + str(speed_float))
return speed_float
else:
# error
print("Configuration is wrong. Please check config.py for speedFormat")
return speed_float
After I made the mph value zero it stays at zero. It never changes. The equation above that makes it something like 8.0. My issue is how do I get the actual speed.

After wasting time at work on researching this issue I was having, I found a Java open source project on git hub doing the same thing. Instead of using the first location of the list it used the second. Instead of
speed_hex = speed_list[0]
I changed it to
speed_hex = speed_list[1]
It now works correctly.

Related

- Python Issue: Working with an Array key-value inside a While statement, is overwritting the content even if different names are detected

Explanation:
I'm trying to do a Progress bar, where you can control it by updating some values on an Excel, and it shows the changes live in a .svg file.
Issue:
I've a loop that can repeat itself sometimes, but the names of the Listed key-value inside the Array are changed between 2 options.
The issue is that, even if I've those 2 options separately, and even with the Print showing the values correctly, the data stored inside is in the same key-value as the 1st time the Loop entered the method.
Here is where I declare the ArrayList, among some others properties:
class RangeBar(GraphicsPort):
_opacity = {
"firstPhase": 1,
"thirdPhase": 1
}
Some code of the main() where the While statement is working:
if (rb._empty["firstPhase"] == False):
print("Start Phase 1 Loop")
rb.partialPhase(False, "firstPhase")
print("Exit Phase 1 Loop")
if (rb._empty["fillPhase"] == False):
print("Start Phase 2 Loop")
rb.fillPhase(False, "fillPhase")
print("Exit Phase 2 Loop")
if (rb._empty["thirdPhase"] == False):
print("Start Phase 3 Loop")
rb.partialPhase(False, "thirdPhase")
print("Exit Phase 3 Loop")
Code of the partialPhase method (the one where this happens):
def partialPhase(self, baseCellModified, phase):
if (baseCellModified != False):
self.setValue(baseCellModified)
self._opacity[phase] = baseCellModified / 100
self.sheet_action("update_sheet_data",cell="C3",number=100)
if (phase == "firstPhase"):
self.setValue(86.9)
if (phase == "thirdPhase"):
self.setValue(12.9)
print("New opacity for 'phase':",phase,"from: 'self._opacity[phase]':", self._opacity[phase])
self.sheet_action("opacity_update", opacity=str(self._opacity[phase]))
self.sheet_action("update_sheet_data",cell="D3",number=self.getValue())
svg = str(self.__utils)
text_file = open("./1.svg", "w")
text_file.write(svg)
text_file.close()
timeToAction = self.sheet_action("get_sheet_data", type="numb", cell="F3") * 60
time.sleep(timeToAction)
while self._opacity[phase] > 0:
timeToAction = self.sheet_action("get_sheet_data", type="numb", cell="F3") * 60
changeCell = self.sheet_action("get_sheet_data", type="numb", cell="E3")
action = self.identifyAction("G3")
if (action == "decrement"):
self._opacity[phase] -= (changeCell / 8)
print("'phase' is showing opacity of:", phase)
print("'self._opacity[phase]' is showing:", self._opacity[phase])
if (action == "increment"):
self._opacity[phase] += (changeCell / 8)
if self._opacity[phase] < 0:
print("Entering opacity minor to 0")
print("'phase' is showing opacity of:", phase)
print("'self._opacity[phase]' is showing:", self._opacity[phase])
self._opacity[phase] = 0
self._empty[phase] = True
if (phase == "thirdPhase"):
self._critical = True
self.sheet_action("opacity_update", opacity=str(self._opacity[phase]))
self.sheet_action("update_sheet_data",cell="D3",number=self.getValue())
svg = str(self.__utils)
text_file = open("./1.svg", "w")
text_file.write(str(self.__utils))
text_file.close()
time.sleep(timeToAction)
.svg to start from:
some prints from 1st phase:
After setting it to 0
After exiting Phase 2 (fill empty)
Now it happens the error, the Opacity of "firstPhase" turned 1, and it looks like this:
And now the code interacts with the 'firstPhase' all time, even if 'thirdPhase' appears in the prints, as the 'phase' it's getting this value.
Until it disappears again:
Thanks for take your time to read me, and sorry for the large text 🙌🏼.
At the end of the while loop declare _opacity = {}, we need to make that empty, else for each run it adds the value in it.
I did a Newbie miss that I didn't even noticed.
The code I passed was good, but a method I was calling, was hardcoded from previous tests, and I didn't noticed it.
The phase which I wanted to change, was "thirdPhase" all the time, so it was constantly changing the opacity of the thirdPhase, even if I passed a different opacity, the phase remained the same.
I'm sorry if I wasted someone time on this 🙌🏼 and thanks for the attention.

Moviepy doubles the speed of the video without affecting audio. I suspect a framerate issue but I havent been able to fix it

Right now here is all I'm having moviepy do:
full_video = VideoFileClip(input_video_path)
full_video.write_videofile("output.mp4")
quit()
It just takes the video and writes it to another file with no changes. But when the input video looks like this the output ends up looking like this with the video speed doubled but the audio just the same. I could take the audio and video separately, halve the speed of the video then put them back together but is there a way I can correct for whatever problem is causing this?
edit 2: It is the VideoFileClip method causing the speedup most likely, not the write_videofile method. When I try
full_video = VideoFileClip(input_video_path)
print( full_video.fps )
full_video.preview(fps = full_video.fps)
quit()
it is still double speed in the preview.
edit 3: The problem only happens with videos captured with Windows game bar. I tried a different video and it worked just fine with no speedup. I'll probably just find a different way to capture the screen recordings to fix it but I dont know what the root problem was
edit 1: the full code
from moviepy.editor import *
# get all dash times
times_path = "times.txt"
input_video_path = "input.mp4"
offset_time = 0
clip_length = float( input("Enter clip length: ") )
def get_times(path, offset):
dash_times_str = []
with open(path, "r") as file:
dash_times_str = file.readlines()
count = 0
# Strips the newline character
# also add offset time
temp = []
for line in dash_times_str:
count += 1
temp.append ("{}".format(line.strip()))
dash_times_str = temp
dash_times = []
for time in dash_times_str:
dash_times.append( float(time) + offset )
return dash_times
dash_times = get_times(times_path, offset_time)
def get_offset_time():
a = float(input("Enter time for first dash in video"))
b = dash_times[0]
return a-b
offset_time = get_offset_time()
full_video = VideoFileClip(input_video_path)
counter = 0
times_count = len(dash_times)
clips = []
for dash_time in dash_times:
clip = full_video.subclip(dash_time,dash_time+clip_length)
clips.append(clip)
counter+=1
print("Clip " + str(counter) + " out of " + str(times_count))
final_clip = concatenate_videoclips(clips)
final_clip.write_videofile("output.mp4")
I haven't been able to go deep down in the source code to figure out why this is, but I could indeed duplicate your bug with videos recorded with the Windows game bar.
I also agree with you that it seems to be tied directly to the VideoFileClip method.
I got my code to work by writing it like this:
full_video = VideoFileClip(input_video_path, fps_source="fps")
with the key detail being the (fps_source = "fps") bit.

Running the same program until condition satisfied

I am trying to create a small program that searches a folder of images, chooses one, checks its size and finishes if the chosen image is at least 5KB. If it is not then I need it to loop back to the choosing step (and then the size check, and so on..)
I am using functions for the choosing and the size-check but when I try to use them in a while loop I get all sorts of indentation errors and now I'm very confused. I've commented the section where I was using the function, but really I guess I want the whole thing to loop back, to the comment at the top..
Here's my code -
#CHOOSE POINT
def chosen():
random.choice(os.listdir(r"/Users/me/p1/images"))
def size():
os.path.getsize(r"/Users/me/p1/images/"+chosen)
thresh = 5000
while size < thresh:
print(chosen + " is too small")
# loop back to CHOOSE POINT
else:
print(chosen + " is at least 5KB")
Am I thinking about this all wrong? Will using the function in my while-loop do what I want? What's the best way to achieve what I'm trying to do? I'm quite new to this and getting very confused.
The first thing to realise is that code like this:
def chosen():
random.choice(os.listdir(r"/Users/me/p1/images"))
is only the definition of a function. It only runs each time you actually call it, with chosen().
Secondly, random.choice() will make a random choice from the list provided (although it's fairly inefficient to keep reading that from disk every time you call it, and it's unclear why you'd pick one at random, but that's OK), but since you don't actually return the value, the function isn't very useful. A choice is made and then discarded. Instead you probably wanted:
def chosen():
return random.choice(os.listdir(r"/Users/me/p1/images"))
Thirdly, this function definition:
def size():
os.path.getsize(r"/Users/me/p1/images/"+chosen)
It tries to use chosen, but that's just the name of a function you previously defined. You probably want get the size of an actual file that was chosen, which the function needs to be provided with as a parameter:
def size(fn):
return os.path.getsize(r"/Users/me/p1/images/"+fn)
Now to use those functions:
file_size = 0
threshold = 5000
while file_size < threshold:
a_file = chosen()
file_size = size(a_file)
if file_size < threshold:
print(a_file + " is too small")
else:
print(a_file + " is at least 5KB")
print('Done')
The variable file_size is initialised to 0, to make sure the loop starts. The loop will keep going until the condition is met at the start.
Every time, chosen() is executed, the returned value is remembers as the variable a_file, which you can then use in the rest of the code to refer back to.
It then gets passed to size(), to obtain a size and finally, the test is performed to print the right message.
A more efficient way to achieve the same:
threshold = 5000
while True:
a_file = chosen()
file_size = size(a_file)
if file_size < threshold:
print(a_file + " is too small")
else:
break
print(a_file + " is at least 5KB")
The break just exits the while loop which would keep going forever since it tests for True. This avoid testing the same thing twice.
So, you'd end up with:
import random
import os
def chosen():
return random.choice(os.listdir(r"/Users/me/p1/images/"))
def size(fn):
return os.path.getsize(r"/Users/me/p1/images/"+fn)
threshold = 5000
while True:
a_file = chosen()
file_size = size(a_file)
if file_size < threshold:
print(a_file + " is too small")
else:
break
print(a_file + " is at least 5KB")

How to convert bar count to time, in midi? (music)

Given a midi file, how can one convert the bar count to time?
Generally, how can one easily map the bar count, in entire numbers, to the time in seconds in the song
Using pretty midi, my solution
import pretty_midi as pm
def get_bar_to_time_dict(self,song,id):
def get_numerator_for_sig_change(signature_change,id):
# since sometime pretty midi count are wierd
if int(signature_change.numerator)==6 and int(signature_change.denominator)==8:
# 6/8 goes to 2 for sure
return 2
return signature_change.numerator
# we have to take into account time-signature-changes
changes = song.time_signature_changes
beats = song.get_beats()
bar_to_time_dict = dict()
# first bar is on first position
current_beat_index = 0
current_bar = 1
bar_to_time_dict[current_bar] = beats[current_beat_index]
for index_time_sig, _ in enumerate(changes):
numerator = get_numerator_for_sig_change(changes[index_time_sig],id)
# keep adding to dictionary until the time signature changes, or we are in the last change, in that case iterate till end of beats
while index_time_sig == len(changes) - 1 or beats[current_beat_index] < changes[index_time_sig + 1].time:
# we have to increase in numerator steps, minus 1 for counting logic of natural counting
current_beat_index += numerator
if current_beat_index > len(beats) - 1:
# we labeled all beats so end function
return bar_to_time_dict
current_bar += 1
bar_to_time_dict[current_bar] = beats[current_beat_index]
return bar_to_time_dict
song = pm.PrettyMIDI('some_midi_file.midi')
get_bar_to_time_dict(song)
If anyone knows a function in pretty midi or music21 that solves the same issue please let me know, couldn't find one.
EDIT: There was also an issue with 6/8 beats, I think this covers all edge cases(not 100% sure)

Spotipy request speed in while loop

count = 0
while True:
if count > 20:
count = 0
current_track = spotify.current_user_playing_track()
if current_track is None:
display_string = ""
else:
display_string = current_track['item']['name']+" - "+current_track['item']['artists'][0]['name']+" | "
if display_string != previous_track:
sphd.clear()
sphd.write_string(display_string,brightness=0.1)
previous_track = display_string[:]
time.sleep(0.05)
sphd.show()
sphd.scroll(1)
count += 1
The code above is run on a Pi Zero to get the currently playing track every second and display it on a scrollphathd display. The problem is that the process of getting the track causes the display to freeze for about 0.25s. Is there any way of running the loop to get the track separately to refreshing the display's scrolling or any way to speed up getting the track? Thanks for any help in advance.
Possibly the reason of that freeze is the low performance that the Raspberry Pi Zero has.

Categories

Resources