Skip to content

Commit

Permalink
Feature/tinklad throttling + linting (commaai#118)
Browse files Browse the repository at this point in the history
* Throttle tinlkad's attemptToSendPendingMessages

* Remove get_git_remote from registration. It's defined in version already.

* tinklad linting

* tesla linting
  • Loading branch information
rafcabezas authored Nov 6, 2019
1 parent 9c4b0fa commit 4557733
Show file tree
Hide file tree
Showing 10 changed files with 31 additions and 32 deletions.
4 changes: 2 additions & 2 deletions selfdrive/car/tesla/ACC_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def _calc_follow_button(self, CS, lead_car,speed_limit_kph, speed_limit_valid, s
print ("Ratio: {0:.1f}% lead: {1:.1f}m avail: {2:.1f}kph vRel: {3:.1f}kph Angle: {4:.1f}deg".format(
ratio, lead_dist_m, available_speed_kph, lead_car.vRel * CV.MS_TO_KPH, CS.angle_steers))
self.last_update_time = current_time_ms
if msg != None:
if msg is not None:
print ("ACC: " + msg)
return button

Expand All @@ -371,7 +371,7 @@ def _should_autoengage_cc(self, CS, lead_car=None):
and CS.v_ego >= self.MIN_CRUISE_SPEED_MS
and _current_time_millis() > self.fast_decel_time + 2000)

slow_lead = lead_car and lead_car.dRel > 0 and lead_car.vRel < 0 or self._fast_decel_required(CS, lead_car)
slow_lead = lead_car and lead_car.dRel > 0 and lead_car.vRel < 0 or self._fast_decel_required(CS, lead_car) # pylint: disable=chained-comparison

# "Autoresume" mode allows cruise to engage even after brake events, but
# shouldn't trigger DURING braking.
Expand Down
4 changes: 2 additions & 2 deletions selfdrive/car/tesla/PCC_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,7 @@ def calc_follow_speed_ms(self, CS, alca_enabled):
elif lead_dist_m < MIN_SAFE_DIST_M:
new_speed_kph = MIN_PCC_V_KPH
# In a 10 meter cruise zone, lets match the car in front
elif lead_dist_m > MIN_SAFE_DIST_M and lead_dist_m < safe_dist_m + 2: # BB we might want to try this and rel_speed_kph > 0:
elif safe_dist_m + 2 > lead_dist_m > MIN_SAFE_DIST_M: # BB we might want to try this and rel_speed_kph > 0:
min_vrel_kph_map = OrderedDict([
# (distance in m, min allowed relative kph)
(0.5 * safe_dist_m, 3.0),
Expand Down Expand Up @@ -625,7 +625,7 @@ def calc_follow_speed_ms(self, CS, alca_enabled):
# Don't accelerate during manual turns, curves or ALCA.
new_speed_kph = min(new_speed_kph, self.last_speed_kph)
#BB Last safety check. Zero if below MIN_SAFE_DIST_M
if (lead_dist_m > 0) and (lead_dist_m < MIN_SAFE_DIST_M) and (rel_speed_kph < 3.):
if (MIN_SAFE_DIST_M > lead_dist_m > 0) and (rel_speed_kph < 3.):
new_speed_kph = MIN_PCC_V_KPH
self.last_speed_kph = new_speed_kph
return new_speed_kph * CV.KPH_TO_MS
Expand Down
6 changes: 3 additions & 3 deletions selfdrive/car/tesla/interface.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python
from cereal import car, tesla
from common.numpy_fast import clip, interp
from common.realtime import sec_since_boot, DT_CTRL
from common.realtime import DT_CTRL
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.drive_helpers import create_event, EventTypes as ET, get_events
from selfdrive.controls.lib.vehicle_model import VehicleModel
Expand Down Expand Up @@ -451,10 +451,10 @@ def update(self, c, can_strings):
# NO_ENTRY events, so controlsd will display alerts. Also not send enable events
# too close in time, so a no_entry will not be followed by another one.
# TODO: button press should be the only thing that triggers enble
if ((cur_time - self.last_enable_pressed) < 0.2 and
if ((cur_time - self.last_enable_pressed) < 0.2 and # pylint: disable=chained-comparison
(cur_time - self.last_enable_sent) > 0.2 and
ret.cruiseState.enabled) or \
(enable_pressed and get_events(events, [ET.NO_ENTRY])):
(enable_pressed and get_events(events, [ET.NO_ENTRY])):
if ret.seatbeltUnlatched:
self.CC.DAS_211_accNoSeatBelt = 1
self.CC.warningCounter = 300
Expand Down
3 changes: 2 additions & 1 deletion selfdrive/car/tesla/radar_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class RadarInterface(RadarInterfaceBase):
tinklaClient = TinklaClient()

def __init__(self,CP):
super().__init__(self)
# radar
self.pts = {}
self.extPts = {}
Expand Down Expand Up @@ -84,7 +85,7 @@ def update(self, can_strings):
time.sleep(0.05)
return car.RadarData.new_message(),self.extPts.values()

if can_strings != None:
if can_strings is not None:
vls = self.rcp.update_strings(can_strings)
self.updated_messages.update(vls)

Expand Down
3 changes: 2 additions & 1 deletion selfdrive/car/tesla/readconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,4 +408,5 @@ def get_value(self, name_of_variable):
# Legacy support
def read_config_file(into, config_path = default_config_file_path):
config_file = ConfigFile()
config_file.read(into, config_path)
config_file.read(into, config_path)

13 changes: 9 additions & 4 deletions selfdrive/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import errno
import signal
import subprocess
import time
from selfdrive.tinklad.tinkla_interface import TinklaClient
from cereal import tinkla
from selfdrive.car.tesla.readconfig import CarSettings
Expand Down Expand Up @@ -321,7 +322,7 @@ def system(cmd):
output=e.output[-1024:],
returncode=e.returncode)

def sendUserInfoToTinkla(params):
def sendUserInfoToTinkla(params, tinklaClient):
carSettings = CarSettings()
gitRemote = params.get("GitRemote")
gitBranch = params.get("GitBranch")
Expand Down Expand Up @@ -368,9 +369,9 @@ def manager_thread():
logger_dead = False

# Tinkla interface
global tinklaClient
last_loop_iteration_time = 0
tinklaClient = TinklaClient()
sendUserInfoToTinkla(params)
sendUserInfoToTinkla(params=params, tinklaClient=tinklaClient)

while 1:
msg = messaging.recv_sock(thermal_sock, wait=True)
Expand All @@ -382,7 +383,11 @@ def manager_thread():
start_managed_process("uploader")

# Attempt to send pending messages if there's any that queued while offline
tinklaClient.attemptToSendPendingMessages()
# Seems this loop runs every second or so, throttle to once every 30s
now = time.time()
if now - last_loop_iteration_time >= 30:
tinklaClient.attemptToSendPendingMessages()
last_loop_iteration_time = now

if msg.thermal.freeSpace < 0.05:
logger_dead = True
Expand Down
8 changes: 0 additions & 8 deletions selfdrive/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,6 @@ def get_subscriber_info():
return ""
return ret

def get_git_remote():
try:
local_branch = subprocess.run(["git", "name-rev", "--name-only", "HEAD"], capture_output=True).stdout.decode("utf-8").strip()
tracking_remote = subprocess.run(["git", "config", "branch."+local_branch+".remote"],capture_output=True).stdout.decode("utf-8").strip()
return subprocess.run(["git", "config", "remote."+tracking_remote+".url"],capture_output=True).stdout.decode("utf-8").strip()
except subprocess.CalledProcessError:
return ""

def register():
params = Params()
params.put("Version", version)
Expand Down
16 changes: 8 additions & 8 deletions selfdrive/tinklad/airtable_publisher.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,17 @@ async def send_info(self, info, isData= False):
data_dict = self.__generate_airtable_user_info_dict(info)

# Early return if no changes
if self.latest_info_dict != None:
if self.latest_info_dict is not None:
print(LOG_PREFIX + "latest_info. data=%s" % (self.latest_info_dict))
if data_dict == self.latest_info_dict:
print(LOG_PREFIX + "send_info no update necessary*")
return

print(LOG_PREFIX + "Sending info. data=%s" % (data_dict))
if self.userRecordId != None:
if self.userRecordId is not None:
await self.__update_user(data_dict)

if info.openPilotId != None and info.openPilotId != '':
if (info.openPilotId is not None) and info.openPilotId != '':
self.openPilotId = info.openPilotId

response = await self.at.get(USERS_TABLE, limit=1, filter_by_formula=("{openPilotId} = '%s'" % (self.openPilotId)))
Expand All @@ -76,7 +76,7 @@ async def send_info(self, info, isData= False):
print(LOG_PREFIX + "*send_info competed*")

async def send_event(self, event):
if self.openPilotId is None and self.latest_info_dict != None:
if self.openPilotId is None and self.latest_info_dict is not None:
self.openPilotId = self.latest_info_dict[self.userKeys.openPilotId]

event_dict = self.__generate_airtable_user_event_dict(event)
Expand All @@ -103,7 +103,7 @@ def __generate_airtable_user_event_dict(self, event):
value = event.value.intValue
elif value == self.eventValueTypes.floatValue:
value = event.value.floatValue
openPilotId = event.openPilotId if (event.openPilotId != None) else (self.openPilotId if (self.openPilotId != None) else "")
openPilotId = event.openPilotId if (event.openPilotId is not None) else (self.openPilotId if (self.openPilotId is not None) else "")
dictionary = event.to_dict()
dictionary[self.eventKeys.value] = value
dictionary[self.eventKeys.openPilotId] = openPilotId
Expand All @@ -118,14 +118,14 @@ async def __update_user(self, data):

def __is_notfound_response(self, response):
try:
return response["error"] != None and response["error"]["code"] == 422
return response["error"] is not None and response["error"]["code"] == 422
except: # pylint: disable=bare-except
count = response["records"].__len__()
return count == 0

def __is_error_response(self, response):
try:
return response["error"] != None
return response["error"] is not None
except: # pylint: disable=bare-except
return False

Expand Down Expand Up @@ -179,7 +179,7 @@ def create_payload(data):
return {'fields': data}


class Airtable(object):
class Airtable():
def __init__(self, base_id, api_key, dict_class=OrderedDict):
"""Create a client to connect to an Airtable Base.
Expand Down
2 changes: 1 addition & 1 deletion selfdrive/tinklad/pqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def _destroy(self):
shutil.rmtree(self.path)
os.makedirs(self.path)

def _qsize(self, len=len): # pylint: disable=redefined-builtin
def _qsize(self, len=len): # pylint: disable=redefined-builtin,arguments-differ
return self.info['size']

def _put(self, item):
Expand Down
4 changes: 2 additions & 2 deletions selfdrive/tinklad/tinklad.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ async def messageLoop(self, sock):
print(LOG_PREFIX + "Unsupported message version: %0.2f (supported version: %0.2f)" % (tinklaInterface.version, cereal.tinkla.interfaceVersion))
continue
messageType = tinklaInterface.message.which()
if messageType != messageKeys.action:
print(LOG_PREFIX + "> Received message. Type: '%s'" % messageType)
#if messageType != messageKeys.action:
print(LOG_PREFIX + "> Received message. Type: '%s'" % messageType)
if messageType == messageKeys.userInfo:
info = tinklaInterface.message.userInfo
await self.setUserInfo(info)
Expand Down

0 comments on commit 4557733

Please sign in to comment.