예제 #1
0
    def update(self, enabled, CS, actuators, pcm_cancel_cmd, hud_alert):

        ### Steering Torque
        apply_steer = actuators.steer * SteerLimitParams.STEER_MAX

        apply_steer = apply_std_steer_torque_limits(apply_steer,
                                                    self.apply_steer_last,
                                                    CS.steer_torque_driver,
                                                    SteerLimitParams)

        if not enabled:
            apply_steer = 0

        steer_req = 1 if enabled else 0

        self.apply_steer_last = apply_steer

        can_sends = []

        self.lkas11_cnt = self.cnt % 0x10
        self.clu11_cnt = self.cnt % 0x10
        self.mdps12_cnt = self.cnt % 0x100

        if self.camera_disconnected:
            if (self.cnt % 10) == 0:
                can_sends.append(create_lkas12())
            if (self.cnt % 50) == 0:
                can_sends.append(create_1191())
            if (self.cnt % 7) == 0:
                can_sends.append(create_1156())
        else:
            can_sends.append(
                create_mdps12(self.packer, self.car_fingerprint,
                              self.mdps12_cnt, CS.mdps12, CS.lkas11))
        can_sends.append(
            create_lkas11(self.packer,
                          self.car_fingerprint,
                          apply_steer,
                          steer_req,
                          self.lkas11_cnt,
                          enabled,
                          CS.lkas11,
                          hud_alert,
                          keep_stock=(not self.camera_disconnected)))

        #if pcm_cancel_cmd:
        #can_sends.append(create_clu11(self.packer, CS.clu11, Buttons.CANCEL))
        if CS.stopped and (self.cnt - self.last_resume_cnt) > 5:
            self.last_resume_cnt = self.cnt
            can_sends.append(
                create_clu11(self.packer, CS.clu11, Buttons.RES_ACCEL))

        self.cnt += 1

        return can_sends
예제 #2
0
  def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd, visual_alert,
             left_lane, right_lane, left_lane_depart, right_lane_depart):
    # Steering Torque
    new_steer = actuators.steer * self.p.STEER_MAX
    apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.p)
    self.steer_rate_limited = new_steer != apply_steer

    # disable if steer angle reach 90 deg, otherwise mdps fault in some models
    lkas_active = enabled and abs(CS.out.steeringAngle) < 90.

    # fix for Genesis hard fault at low speed
    if CS.out.vEgo < 16.7 and self.car_fingerprint == CAR.HYUNDAI_GENESIS:
      lkas_active = False

    if not lkas_active:
      apply_steer = 0

    self.apply_steer_last = apply_steer

    sys_warning, sys_state, left_lane_warning, right_lane_warning =\
      process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                        left_lane, right_lane, left_lane_depart, right_lane_depart)

    can_sends = []
    can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled,
                                   left_lane, right_lane,
                                   left_lane_warning, right_lane_warning))

    if pcm_cancel_cmd:
      can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))
    elif CS.out.cruiseState.standstill:
      # send resume at a max freq of 10Hz
      if (frame - self.last_resume_frame)*DT_CTRL > 0.1:
        can_sends.extend([create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL)] * 20)
        self.last_resume_frame = frame

    # 20 Hz LFA MFA message
    if frame % 5 == 0 and self.car_fingerprint in [CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV]:
      can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

    return can_sends
예제 #3
0
  def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd, visual_alert,
             left_lane, right_lane, left_lane_depart, right_lane_depart):
    # Steering Torque
    new_steer = int(round(actuators.steer * self.p.STEER_MAX))
    apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.p)
    self.steer_rate_limited = new_steer != apply_steer

    # disable when temp fault is active, or below LKA minimum speed
    lkas_active = enabled and not CS.out.steerWarning and CS.out.vEgo >= CS.CP.minSteerSpeed

    if not lkas_active:
      apply_steer = 0

    self.apply_steer_last = apply_steer

    sys_warning, sys_state, left_lane_warning, right_lane_warning = \
      process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                        left_lane, right_lane, left_lane_depart, right_lane_depart)

    can_sends = []
    can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled,
                                   left_lane, right_lane,
                                   left_lane_warning, right_lane_warning))

    if pcm_cancel_cmd:
      can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))
    elif CS.out.cruiseState.standstill:
      # send resume at a max freq of 10Hz
      if (frame - self.last_resume_frame) * DT_CTRL > 0.1:
        # send 25 messages at a time to increases the likelihood of resume being accepted
        can_sends.extend([create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL)] * 25)
        self.last_resume_frame = frame

    # 20 Hz LFA MFA message
    if frame % 5 == 0 and self.car_fingerprint in [CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021,
                                                   CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KIA_CEED, CAR.KIA_SELTOS, CAR.KONA_EV,
                                                   CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV]:
      can_sends.append(create_lfahda_mfc(self.packer, enabled))

    return can_sends
예제 #4
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart, set_speed, lead_visible, lead_dist,
               lead_vrel, lead_yrel, sm):

        self.enabled = enabled

        param = self.p

        self.model_speed, self.model_sum = self.SC.calc_va(sm, CS.out.vEgo)

        plan = sm['plan']
        self.dRel = int(plan.dRel1)  #EON Lead
        self.yRel = int(plan.yRel1)  #EON Lead
        self.vRel = int(plan.vRel1 * 3.6 + 0.5)  #EON Lead
        self.dRel2 = int(plan.dRel2)  #EON Lead
        self.yRel2 = int(plan.yRel2)  #EON Lead
        self.vRel2 = int(plan.vRel2 * 3.6 + 0.5)  #EON Lead
        self.lead2_status = plan.status2
        self.target_map_speed = plan.targetSpeed
        self.target_map_speed_camera = plan.targetSpeedCamera
        path_plan = sm['pathPlan']
        self.outScale = path_plan.outputScale
        self.angle_steers = CS.out.steeringAngle
        self.vCruiseSet = path_plan.vCruiseSet

        if CS.out.vEgo > 8:
            if self.variable_steer_max:
                #self.steerMax = interp(int(abs(self.model_speed)), self.model_speed_range, self.steerMax_range)
                self.steerMax = interp(abs(self.angle_steers),
                                       self.angle_range, self.steerMax_range)
            else:
                self.steerMax = int(self.params.get('SteerMaxBaseAdj'))
            if self.variable_steer_delta:
                #self.steerDeltaUp = interp(int(abs(self.model_speed)), self.model_speed_range, self.steerDeltaUp_range)
                #self.steerDeltaDown = interp(int(abs(self.model_speed)), self.model_speed_range, self.steerDeltaDown_range)
                self.steerDeltaUp = interp(abs(self.angle_steers),
                                           self.angle_range,
                                           self.steerDeltaUp_range)
                self.steerDeltaDown = interp(abs(self.angle_steers),
                                             self.angle_range,
                                             self.steerDeltaDown_range)
            else:
                self.steerDeltaUp = int(self.params.get('SteerDeltaUpAdj'))
                self.steerDeltaDown = int(self.params.get('SteerDeltaDownAdj'))
        else:
            self.steerMax = int(self.params.get('SteerMaxBaseAdj'))
            self.steerDeltaUp = int(self.params.get('SteerDeltaUpAdj'))
            self.steerDeltaDown = int(self.params.get('SteerDeltaDownAdj'))

        param.STEER_MAX = min(SteerLimitParams.STEER_MAX,
                              self.steerMax)  # variable steermax
        param.STEER_DELTA_UP = max(int(self.params.get('SteerDeltaUpAdj')),
                                   self.steerDeltaUp)  # variable deltaUp
        param.STEER_DELTA_DOWN = max(int(self.params.get('SteerDeltaDownAdj')),
                                     self.steerDeltaDown)  # variable deltaDown
        #param.STEER_DELTA_UP = SteerLimitParams.STEER_DELTA_UP # fixed deltaUp
        #param.STEER_DELTA_DOWN = SteerLimitParams.STEER_DELTA_DOWN # fixed deltaDown

        # Steering Torque
        if 0 <= self.driver_steering_torque_above_timer < 100:
            new_steer = actuators.steer * self.steerMax * (
                self.driver_steering_torque_above_timer / 100)
        else:
            new_steer = actuators.steer * self.steerMax
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    param)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        self.high_steer_allowed = True if self.car_fingerprint in FEATURES[
            "allow_high_steer"] else False
        if self.opkr_maxanglelimit >= 90:
            lkas_active = enabled and abs(
                CS.out.steeringAngle) < self.opkr_maxanglelimit
        else:
            lkas_active = enabled

        if ((CS.out.leftBlinker and not CS.out.rightBlinker) or
            (CS.out.rightBlinker and
             not CS.out.leftBlinker)) and CS.out.vEgo < LANE_CHANGE_SPEED_MIN:
            self.lanechange_manual_timer = 50
        if CS.out.leftBlinker and CS.out.rightBlinker:
            self.emergency_manual_timer = 50
        #if self.lanechange_manual_timer:
        #  lkas_active = 0
        if self.lanechange_manual_timer > 0:
            self.lanechange_manual_timer -= 1
        if self.emergency_manual_timer > 0:
            self.emergency_manual_timer -= 1

        if abs(CS.out.steeringTorque
               ) > 200 and CS.out.vEgo < LANE_CHANGE_SPEED_MIN:
            self.driver_steering_torque_above = True
        else:
            self.driver_steering_torque_above = False

        if self.driver_steering_torque_above == True:
            self.driver_steering_torque_above_timer -= 1
            if self.driver_steering_torque_above_timer <= 0:
                self.driver_steering_torque_above_timer = 0
        elif self.driver_steering_torque_above == False:
            self.driver_steering_torque_above_timer += 5
            if self.driver_steering_torque_above_timer >= 100:
                self.driver_steering_torque_above_timer = 100

        if not lkas_active:
            apply_steer = 0

        if CS.CP.radarOffCan:
            self.usestockscc = not self.cp_oplongcontrol
        elif (CS.cancel_button_count == 3) and self.cp_oplongcontrol:
            self.usestockscc = not self.usestockscc

        if self.prev_gapButton != CS.cruise_buttons:  # gap change.
            if CS.cruise_buttons == 3:
                self.gapsettingdance -= 1
            if self.gapsettingdance < 1:
                self.gapsettingdance = 4
            self.prev_gapButton = CS.cruise_buttons

        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart)

        speed_conv = CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

        self.clu11_speed = CS.clu11["CF_Clu_Vanz"]

        enabled_speed = 38 if CS.is_set_speed_in_mph else 55

        if self.clu11_speed > enabled_speed or not lkas_active or CS.out.gearShifter != GearShifter.drive:
            enabled_speed = self.clu11_speed

        self.current_veh_speed = int(CS.out.vEgo * speed_conv)

        self.clu11_cnt = frame % 0x10

        can_sends = []

        self.lfa_available = True if self.lfainFingerprint or self.car_fingerprint in FEATURES[
            "send_lfa_mfa"] else False

        if (frame % 10) == 0:
            # tester present - w/ no response (keeps radar disabled)
            can_sends.append(
                [0x7D0, 0, b"\x02\x3E\x80\x00\x00\x00\x00\x00", 0])

        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning,
                          self.lfa_available, 0))

        if CS.CP.mdpsHarness:  # send lkas11 bus 1 if mdps
            can_sends.append(
                create_lkas11(self.packer, frame, self.car_fingerprint,
                              apply_steer, lkas_active, CS.lkas11, sys_warning,
                              sys_state, enabled, left_lane, right_lane,
                              left_lane_warning, right_lane_warning,
                              self.lfa_available, 1))

            can_sends.append(
                create_clu11(self.packer, 1, CS.clu11, Buttons.NONE,
                             enabled_speed, self.clu11_cnt))

        str_log1 = 'CV={:03.0f}  TQ={:03.0f}  R={:03.0f}  ST={:03.0f}/{:01.0f}/{:01.0f}  G={:01.0f}'.format(
            abs(self.model_speed), abs(new_steer), self.timer1.sampleTime(),
            self.steerMax, self.steerDeltaUp, self.steerDeltaDown,
            CS.out.cruiseGapSet)

        if int(self.params.get('OpkrLiveTune')) == 1:
            if int(self.params.get('LateralControlMethod')) == 0:
                self.str_log2 = 'T={:0.2f}/{:0.3f}/{:0.2f}/{:0.5f}'.format(
                    float(int(self.params.get('PidKp')) * 0.01),
                    float(int(self.params.get('PidKi')) * 0.001),
                    float(int(self.params.get('PidKd')) * 0.01),
                    float(int(self.params.get('PidKf')) * 0.00001))
            elif int(self.params.get('LateralControlMethod')) == 1:
                self.str_log2 = 'T={:03.1f}/{:03.1f}/{:03.1f}/{:03.1f}'.format(
                    float(int(self.params.get('InnerLoopGain')) * 0.1),
                    float(int(self.params.get('OuterLoopGain')) * 0.1),
                    float(int(self.params.get('TimeConstant')) * 0.1),
                    float(int(self.params.get('ActuatorEffectiveness')) * 0.1))
            elif int(self.params.get('LateralControlMethod')) == 2:
                self.str_log2 = 'T={:04.0f}/{:05.3f}/{:06.4f}'.format(
                    float(int(self.params.get('Scale')) * 1.0),
                    float(int(self.params.get('LqrKi')) * 0.001),
                    float(int(self.params.get('DcGain')) * 0.0001))

        trace1.printf1('{}  {}'.format(str_log1, self.str_log2))

        run_speed_ctrl = self.opkr_variablecruise and CS.acc_active

        if pcm_cancel_cmd and CS.scc12[
                "ACCMode"] != 0 and not CS.out.standstill:
            self.vdiff = 0.
            self.resumebuttoncnt = 0
            can_sends.append(
                create_clu11(self.packer, CS.CP.sccBus, CS.clu11,
                             Buttons.CANCEL, self.current_veh_speed,
                             self.clu11_cnt))
        elif CS.out.cruiseState.standstill and CS.scc12[
                "ACCMode"] != 0 and CS.vrelative > 0:
            self.vdiff += (CS.vrelative - self.vdiff)
            if (frame - self.lastresumeframe > 5) and (self.vdiff > .1 or
                                                       CS.lead_distance > 4.5):
                can_sends.append(
                    create_clu11(self.packer, CS.CP.sccBus, CS.clu11,
                                 Buttons.RES_ACCEL, self.current_veh_speed,
                                 self.resumebuttoncnt))
                self.resumebuttoncnt += 1
                if self.resumebuttoncnt > 5:
                    self.lastresumeframe = frame
                    self.resumebuttoncnt = 0
        elif run_speed_ctrl:
            is_sc_run = self.SC.update(CS, sm, self)
            if is_sc_run:
                can_sends.append(
                    create_clu11(self.packer, CS.CP.sccBus, CS.clu11,
                                 self.SC.btn_type, self.SC.sc_clu_speed,
                                 self.clu11_cnt))
        else:
            self.vdiff = 0.
            self.resumebuttoncnt = 0

        if frame % 2 == 0 and self.cp_oplongcontrol:
            accel_target = clip(actuators.gas - actuators.brake, -3.5, 2.0)
            self.apply_accel += 0.02 if accel_target > self.apply_accel else -0.02
            stopping = accel_target < 0 and CS.out.vEgo < 0.05
            self.apply_accel = clip(self.apply_accel,
                                    accel_target if accel_target < 0 else 0,
                                    accel_target if accel_target > 0 else 0)
            if not enabled:
                self.apply_accel = 0

        if CS.out.vEgo <= 1:
            self.sm.update(0)
            long_control_state = self.sm['controlsState'].longControlState
            self.acc_standstill = True if long_control_state == LongCtrlState.stopping else False
            if self.acc_standstill == True and not CS.out.gasPressed:
                self.acc_standstill_timer += 1
                if self.acc_standstill_timer >= 200:
                    self.acc_standstill_timer = 200
            elif CS.out.gasPressed:
                self.acc_standstill_timer = 0
            else:
                self.acc_standstill_timer = 0
        elif CS.out.gasPressed or CS.out.vEgo > 1:
            self.acc_standstill = False
            self.acc_standstill_timer = 0
        else:
            self.acc_standstill = False
            self.acc_standstill_timer = 0

        if lead_visible:
            self.lead_visible = True
            self.lead_debounce = 50
        elif self.lead_debounce > 0:
            self.lead_debounce -= 1
        else:
            self.lead_visible = lead_visible

        self.setspeed = set_speed * speed_conv

        if enabled:
            self.sendaccmode = enabled

        if CS.CP.radarDisablePossible:
            self.radarDisableOverlapTimer += 1
            self.radarDisableResetTimer = 0
            if self.radarDisableOverlapTimer >= 30:
                self.radarDisableActivated = True
                if 200 > self.radarDisableOverlapTimer > 36:
                    if frame % 41 == 0 or self.radarDisableOverlapTimer == 37:
                        can_sends.append(
                            create_scc7d0(b'\x02\x10\x03\x00\x00\x00\x00\x00'))
                    elif frame % 43 == 0 or self.radarDisableOverlapTimer == 37:
                        can_sends.append(
                            create_scc7d0(b'\x03\x28\x03\x01\x00\x00\x00\x00'))
                    elif frame % 19 == 0 or self.radarDisableOverlapTimer == 37:
                        can_sends.append(
                            create_scc7d0(b'\x02\x10\x85\x00\x00\x00\x00\x00'))
            else:
                self.counter_init = False
                can_sends.append(
                    create_scc7d0(b'\x02\x10\x90\x00\x00\x00\x00\x00'))
                can_sends.append(
                    create_scc7d0(b'\x03\x29\x03\x01\x00\x00\x00\x00'))
        elif self.radarDisableActivated:
            can_sends.append(
                create_scc7d0(b'\x02\x10\x90\x00\x00\x00\x00\x00'))
            can_sends.append(
                create_scc7d0(b'\x03\x29\x03\x01\x00\x00\x00\x00'))
            self.radarDisableOverlapTimer = 0
            if frame % 50 == 0:
                self.radarDisableResetTimer += 1
                if self.radarDisableResetTimer > 2:
                    self.radarDisableActivated = False
                    self.counter_init = True
        else:
            self.radarDisableOverlapTimer = 0
            self.radarDisableResetTimer = 0

        if (frame % 50 == 0 or self.radarDisableOverlapTimer == 37) and \
                CS.CP.radarDisablePossible and self.radarDisableOverlapTimer >= 30:
            can_sends.append(
                create_scc7d0(b'\x02\x3E\x00\x00\x00\x00\x00\x00'))

        if self.lead_visible:
            self.objdiststat = 1 if lead_dist < 25 else 2 if lead_dist < 40 else \
                               3 if lead_dist < 60 else 4 if lead_dist < 80 else 5
        else:
            self.objdiststat = 0

        # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
        if (CS.CP.sccBus == 2 or not self.usestockscc
                or self.radarDisableActivated) and self.counter_init:
            if frame % 2 == 0:
                self.scc12cnt += 1
                self.scc12cnt %= 0xF
                self.scc11cnt += 1
                self.scc11cnt %= 0x10
                self.fca11supcnt += 1
                self.fca11supcnt %= 0xF

                if self.fca11alivecnt == 1:
                    self.fca11inc = 0
                    if self.fca11cnt13 == 3:
                        self.fca11maxcnt = 0x9
                        self.fca11cnt13 = 0
                    else:
                        self.fca11maxcnt = 0xD
                        self.fca11cnt13 += 1
                else:
                    self.fca11inc += 4

                self.fca11alivecnt = self.fca11maxcnt - self.fca11inc

                can_sends.append(
                    create_scc11(self.packer, enabled, self.setspeed,
                                 self.lead_visible, lead_dist, lead_vrel,
                                 lead_yrel, self.gapsettingdance,
                                 CS.out.standstill, CS.scc11, self.usestockscc,
                                 CS.CP.radarOffCan, self.scc11cnt,
                                 self.sendaccmode))

                if CS.brake_check == 1 or CS.mainsw_check == 1:
                    can_sends.append(
                        create_scc12(self.packer, accel_target, accel_target,
                                     enabled, self.acc_standstill,
                                     CS.out.gasPressed, 1, CS.out.stockAeb,
                                     CS.scc12, self.usestockscc,
                                     CS.CP.radarOffCan, self.scc12cnt))
                else:
                    can_sends.append(
                        create_scc12(self.packer, accel_target, accel_target,
                                     enabled, self.acc_standstill,
                                     CS.out.gasPressed, CS.out.brakePressed,
                                     CS.out.stockAeb, CS.scc12,
                                     self.usestockscc, CS.CP.radarOffCan,
                                     self.scc12cnt))

                can_sends.append(
                    create_scc14(self.packer, enabled, self.usestockscc,
                                 CS.out.stockAeb, self.apply_accel, CS.scc14,
                                 self.objdiststat, CS.out.gasPressed,
                                 self.acc_standstill, CS.out.vEgo))
                if CS.CP.fcaBus == -1:
                    can_sends.append(
                        create_fca11(self.packer, CS.fca11, self.fca11alivecnt,
                                     self.fca11supcnt))

            if frame % 20 == 0:
                can_sends.append(create_scc13(self.packer, CS.scc13))
                if CS.CP.fcaBus == -1:
                    can_sends.append(create_fca12(self.packer))
            if frame % 50 == 0:
                can_sends.append(create_scc42a(self.packer))
        else:
            self.counter_init = True
            self.scc12cnt = CS.scc12init["CR_VSM_Alive"]
            self.scc11cnt = CS.scc11init["AliveCounterACC"]
            self.fca11alivecnt = CS.fca11init["CR_FCA_Alive"]
            self.fca11supcnt = CS.fca11init["Supplemental_Counter"]

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.lfa_available:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        return can_sends
예제 #5
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_line, right_line, left_lane_depart,
               right_lane_depart):

        ### Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.steer_torque_driver,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        ### LKAS button to temporarily disable steering
        if not CS.lkas_error:
            if CS.lkas_button_on != self.lkas_button_last:
                self.lkas_button = not self.lkas_button
            self.lkas_button_last = CS.lkas_button_on

        if self.car_fingerprint == CAR.GENESIS:
            lkas_active = enabled and abs(
                CS.angle_steers) < 90. and not self.lkas_button
        else:
            lkas_active = enabled and not self.lkas_button

        # Fix for sharp turns mdps fault and Genesis hard fault at low speed
        if CS.v_ego < 15.4 and self.car_fingerprint == CAR.GENESIS and not CS.mdps_bus:
            self.turning_signal_timer = 100
        if ((CS.left_blinker_flash or CS.right_blinker_flash)
                and (CS.steer_override or abs(CS.angle_steers) > 15.)
                and CS.v_ego < 15.0):
            self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off
        if self.turning_signal_timer:
            lkas_active = 0
            self.turning_signal_timer -= 1

        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        self.apply_steer_last = apply_steer

        hud_alert, lane_visible, left_lane_warning, right_lane_warning =\
                process_hud_alert(lkas_active, self.lkas_button, self.car_fingerprint, visual_alert,
                left_line, right_line,left_lane_depart, right_lane_depart)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 35 if CS.is_set_speed_in_mph else 55
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        can_sends = []

        lkas11_cnt = frame % 0x10
        clu11_cnt = frame % 0x10
        mdps12_cnt = frame % 0x100
        self.scc12_cnt %= 15

        can_sends.append(
            create_lkas11(self.packer,
                          self.car_fingerprint,
                          0,
                          apply_steer,
                          steer_req,
                          lkas11_cnt,
                          lkas_active,
                          CS.lkas11,
                          hud_alert,
                          lane_visible,
                          left_lane_depart,
                          right_lane_depart,
                          keep_stock=True))
        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas12 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer,
                              self.car_fingerprint,
                              1,
                              apply_steer,
                              steer_req,
                              lkas11_cnt,
                              lkas_active,
                              CS.lkas11,
                              hud_alert,
                              lane_visible,
                              left_lane_depart,
                              right_lane_depart,
                              keep_stock=True))
        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, CS.mdps_bus, CS.clu11, Buttons.NONE,
                             enabled_speed, clu11_cnt))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, CS.scc_bus, CS.clu11, Buttons.CANCEL,
                             clu11_speed, clu11_cnt))
        else:  # send mdps12 to LKAS to prevent LKAS error if no cancel cmd
            can_sends.append(
                create_mdps12(self.packer, self.car_fingerprint, mdps12_cnt,
                              CS.mdps12))

        if self.longcontrol and frame % 2:
            can_sends.append(
                create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt,
                             CS.scc12))
            self.scc12_cnt += 1

        if CS.stopped:
            # run only first time when the car stopped
            if self.last_lead_distance == 0:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance > self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed,
                                 self.resume_cnt))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0

        return can_sends
예제 #6
0
  def update(self, CC, CS):
    actuators = CC.actuators
    hud_control = CC.hudControl

    # Steering Torque
    new_steer = int(round(actuators.steer * self.params.STEER_MAX))
    apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.params)
    self.steer_rate_limited = new_steer != apply_steer

    if not CC.latActive:
      apply_steer = 0

    self.apply_steer_last = apply_steer

    sys_warning, sys_state, left_lane_warning, right_lane_warning = process_hud_alert(CC.enabled, self.car_fingerprint,
                                                                                      hud_control)

    can_sends = []

    if self.CP.carFingerprint in HDA2_CAR:
      # steering control
      can_sends.append(hda2can.create_lkas(self.packer, CC.enabled, self.frame, CC.latActive, apply_steer))

      # cruise cancel
      if (self.frame - self.last_button_frame) * DT_CTRL > 0.25:
        if CC.cruiseControl.cancel:
          for _ in range(20):
            can_sends.append(hda2can.create_buttons(self.packer, CS.buttons_counter+1, True, False))
          self.last_button_frame = self.frame

        # cruise standstill resume
        elif CC.cruiseControl.resume:
          can_sends.append(hda2can.create_buttons(self.packer, CS.buttons_counter+1, False, True))
          self.last_button_frame = self.frame
    else:

      # tester present - w/ no response (keeps radar disabled)
      if self.CP.openpilotLongitudinalControl:
        if self.frame % 100 == 0:
          can_sends.append([0x7D0, 0, b"\x02\x3E\x80\x00\x00\x00\x00\x00", 0])

      can_sends.append(hyundaican.create_lkas11(self.packer, self.frame, self.car_fingerprint, apply_steer, CC.latActive,
                                     CS.lkas11, sys_warning, sys_state, CC.enabled,
                                     hud_control.leftLaneVisible, hud_control.rightLaneVisible,
                                     left_lane_warning, right_lane_warning))

      if not self.CP.openpilotLongitudinalControl:
        if CC.cruiseControl.cancel:
          can_sends.append(hyundaican.create_clu11(self.packer, self.frame, CS.clu11, Buttons.CANCEL))
        elif CC.cruiseControl.resume:
          # send resume at a max freq of 10Hz
          if (self.frame - self.last_button_frame) * DT_CTRL > 0.1:
            # send 25 messages at a time to increases the likelihood of resume being accepted
            can_sends.extend([hyundaican.create_clu11(self.packer, self.frame, CS.clu11, Buttons.RES_ACCEL)] * 25)
            self.last_button_frame = self.frame

      if self.frame % 2 == 0 and self.CP.openpilotLongitudinalControl:
        accel = actuators.accel
        jerk = 0

        if CC.longActive:
          jerk = clip(2.0 * (accel - CS.out.aEgo), -12.7, 12.7)
          if accel < 0:
            accel = interp(accel - CS.out.aEgo, [-1.0, -0.5], [2 * accel, accel])

        accel = clip(accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)

        stopping = actuators.longControlState == LongCtrlState.stopping
        set_speed_in_units = hud_control.setSpeed * (CV.MS_TO_MPH if CS.clu11["CF_Clu_SPEED_UNIT"] == 1 else CV.MS_TO_KPH)
        can_sends.extend(hyundaican.create_acc_commands(self.packer, CC.enabled, accel, jerk, int(self.frame / 2),
                                                        hud_control.leadVisible, set_speed_in_units, stopping, CS.out.gasPressed))
        self.accel = accel

      # 20 Hz LFA MFA message
      if self.frame % 5 == 0 and self.car_fingerprint in (CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021,
                                                          CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KIA_CEED, CAR.KIA_SELTOS, CAR.KONA_EV,
                                                          CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.SANTA_FE_2022,
                                                          CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.GENESIS_G70_2020, CAR.SANTA_FE_PHEV_2022):
        can_sends.append(hyundaican.create_lfahda_mfc(self.packer, CC.enabled))

      # 5 Hz ACC options
      if self.frame % 20 == 0 and self.CP.openpilotLongitudinalControl:
        can_sends.extend(hyundaican.create_acc_opt(self.packer))

      # 2 Hz front radar options
      if self.frame % 50 == 0 and self.CP.openpilotLongitudinalControl:
        can_sends.append(hyundaican.create_frt_radar_opt(self.packer))

    new_actuators = actuators.copy()
    new_actuators.steer = apply_steer / self.params.STEER_MAX
    new_actuators.accel = self.accel

    self.frame += 1
    return new_actuators, can_sends
예제 #7
0
  def update(self, enabled, CS, frame, CC, actuators, pcm_cancel_cmd, visual_alert,
             left_lane, right_lane, left_lane_depart, right_lane_depart, set_speed, lead_visible, controls):

    # *** compute control surfaces ***

    # gas and brake
    apply_accel = actuators.gas - actuators.brake
    apply_accel, self.accel_steady = accel_hysteresis(apply_accel, self.accel_steady)
    apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

    # Steering Torque
    new_steer = actuators.steer * SteerLimitParams.STEER_MAX
    apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque,
                                                SteerLimitParams)

    self.steer_rate_limited = new_steer != apply_steer

    # SPAS limit angle extremes for safety
    if CS.spas_enabled:
      apply_steer_ang_req = clip(actuators.steerAngle, -1 * (STEER_ANG_MAX), STEER_ANG_MAX)
      # SPAS limit angle rate for safety
      if abs(self.apply_steer_ang - apply_steer_ang_req) > STEER_ANG_MAX_RATE:
        if apply_steer_ang_req > self.apply_steer_ang:
          self.apply_steer_ang += STEER_ANG_MAX_RATE
        else:
          self.apply_steer_ang -= STEER_ANG_MAX_RATE
      else:
        self.apply_steer_ang = apply_steer_ang_req
    spas_active = CS.spas_enabled and enabled and (self.spas_always or CS.out.vEgo < 7.0)  # 25km/h

    # disable if steer angle reach 90 deg, otherwise mdps fault in some models
    lkas_active = enabled and abs(CS.out.steeringAngle) < 90. and not spas_active

    # fix for Genesis hard fault at low speed
    if CS.out.vEgo < 60 * CV.KPH_TO_MS and self.car_fingerprint == CAR.GENESIS and not CS.mdps_bus:
      lkas_active = False

    # Disable steering while turning blinker on and speed below 60 kph
    if CS.out.leftBlinker or CS.out.rightBlinker:
      self.turning_signal_timer = 0.5 / DT_CTRL  # Disable for 0.5 Seconds after blinker turned off
    if self.turning_indicator_alert and CS.out.vEgo < 2 * CV.KPH_TO_MS: # set and clear by interface
      lkas_active = 0
    if self.turning_signal_timer > 0:
      self.turning_signal_timer -= 1

    if not lkas_active:
      apply_steer = 0

    self.apply_accel_last = apply_accel
    self.apply_steer_last = apply_steer

    sys_warning, sys_state, left_lane_warning, right_lane_warning = \
      process_hud_alert(lkas_active, self.car_fingerprint, visual_alert,
                        left_lane, right_lane, left_lane_depart, right_lane_depart)

    clu11_speed = CS.clu11["CF_Clu_Vanz"]
    enabled_speed = 38 if CS.is_set_speed_in_mph else 60
    if clu11_speed > enabled_speed or not lkas_active:
      enabled_speed = clu11_speed

    if not (min_set_speed < set_speed < 255 * CV.KPH_TO_MS):
      set_speed = min_set_speed
    set_speed *= CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

    if frame == 0:  # initialize counts from last received count signals
      self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
      self.scc12_cnt = CS.scc12["CR_VSM_Alive"] + 1 if not CS.no_radar else 0

      # TODO: fix this
      # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
      # self.scc_update_frame = frame

    # check if SCC is alive
    # if frame % 7 == 0:
    # if CS.scc11["AliveCounterACC"] == self.prev_scc_cnt:
    # if frame - self.scc_update_frame > 20 and self.scc_live:
    # self.scc_live = False
    # else:
    # self.scc_live = True
    # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
    # self.scc_update_frame = frame

    self.prev_scc_cnt = CS.scc11["AliveCounterACC"]

    self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10
    self.scc12_cnt %= 0xF

    can_sends = []
    can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled, left_lane, right_lane,
                                   left_lane_warning, right_lane_warning, 0))

    if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps or scc is on bus 1
      can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                     CS.lkas11, sys_warning, sys_state, enabled, left_lane, right_lane,
                                     left_lane_warning, right_lane_warning, 1))
    if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
      can_sends.append(create_clu11(self.packer, frame % 0x10, CS.mdps_bus, CS.clu11, Buttons.NONE, enabled_speed))

    if pcm_cancel_cmd and self.longcontrol:
      can_sends.append(create_clu11(self.packer, frame % 0x10, CS.scc_bus, CS.clu11, Buttons.CANCEL, clu11_speed))

    # fix auto resume - by neokii
    if CS.out.cruiseState.standstill:

      if self.last_lead_distance == 0:
        self.last_lead_distance = CS.lead_distance
        self.resume_cnt = 0
        self.resume_wait_timer = 0

      # scc smoother
      elif self.scc_smoother.is_active(frame):
        pass

      elif self.resume_wait_timer > 0:
        self.resume_wait_timer -= 1

      elif CS.lead_distance != self.last_lead_distance:
        can_sends.append(create_clu11(self.packer, self.resume_cnt, CS.scc_bus, CS.clu11, Buttons.RES_ACCEL, clu11_speed))
        self.resume_cnt += 1

        if self.resume_cnt >= 8:
          self.resume_cnt = 0
          self.resume_wait_timer = SccSmoother.get_wait_count()

    # reset lead distnce after the car starts moving
    elif self.last_lead_distance != 0:
      self.last_lead_distance = 0

    # scc smoother
    if not self.longcontrol:
      self.scc_smoother.update(enabled, can_sends, self.packer, CC, CS, frame, apply_accel, controls)

    if CS.mdps_bus:  # send mdps12 to LKAS to prevent LKAS error
      can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

    # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
    if self.longcontrol and (CS.scc_bus or not self.scc_live) and frame % 2 == 0:
      can_sends.append(create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt, self.scc_live, CS.scc12))
      can_sends.append(create_scc11(self.packer, frame, enabled, set_speed, lead_visible, self.scc_live, CS.scc11))
      if CS.has_scc13 and frame % 20 == 0:
        can_sends.append(create_scc13(self.packer, CS.scc13))
      if CS.has_scc14:
        can_sends.append(create_scc14(self.packer, enabled, CS.scc14))
      self.scc12_cnt += 1

    # 20 Hz LFA MFA message
    if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfa_mfa"]:
      can_sends.append(create_lfa_mfa(self.packer, frame, lkas_active))

    if CS.spas_enabled:
      if CS.mdps_bus:
        can_sends.append(create_ems11(self.packer, CS.ems11, spas_active))

      # SPAS11 50hz
      if (frame % 2) == 0:
        if CS.mdps11_stat == 7 and not self.mdps11_stat_last == 7:
          self.en_spas = 7
          self.en_cnt = 0

        if self.en_spas == 7 and self.en_cnt >= 8:
          self.en_spas = 3
          self.en_cnt = 0

        if self.en_cnt < 8 and spas_active:
          self.en_spas = 4
        elif self.en_cnt >= 8 and spas_active:
          self.en_spas = 5

        if not spas_active:
          self.apply_steer_ang = CS.mdps11_strang
          self.en_spas = 3
          self.en_cnt = 0

        self.mdps11_stat_last = CS.mdps11_stat
        self.en_cnt += 1
        can_sends.append(create_spas11(self.packer, self.car_fingerprint, (frame // 2), self.en_spas, self.apply_steer_ang, CS.mdps_bus))

      # SPAS12 20Hz
      if (frame % 5) == 0:
        can_sends.append(create_spas12(CS.mdps_bus))

    return can_sends
예제 #8
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart):
        # Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled and abs(CS.out.steeringAngle) < 90.

        # fix for Genesis hard fault at low speed
        if CS.out.vEgo < 16.7 and self.car_fingerprint == CAR.HYUNDAI_GENESIS:
            lkas_active = 0

        if not lkas_active:
            apply_steer = 0

        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart)

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning))

        if pcm_cancel_cmd:
            can_sends.append(
                create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))

        elif CS.out.cruiseState.standstill:
            # run only first time when the car stopped
            if self.last_lead_distance == 0:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance != self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.clu11,
                                 Buttons.RES_ACCEL))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in [
                CAR.SONATA, CAR.PALISADE, CAR.IONIQ
        ]:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        return can_sends
예제 #9
0
    def update(self, enabled, CS, frame, CC, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart, set_speed, lead_visible, controls):

        # *** compute control surfaces ***

        # gas and brake
        apply_accel = actuators.gas - actuators.brake
        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * CarControllerParams.ACCEL_SCALE,
                           CarControllerParams.ACCEL_MIN,
                           CarControllerParams.ACCEL_MAX)

        # Steering Torque
        new_steer = int(round(actuators.steer * SteerLimitParams.STEER_MAX))
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    SteerLimitParams)

        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled and abs(CS.out.steeringAngleDeg) < 90.

        # fix for Genesis hard fault at low speed
        if CS.out.vEgo < 60 * CV.KPH_TO_MS and self.car_fingerprint == CAR.GENESIS and not CS.mdps_bus:
            lkas_active = False

        # Disable steering while turning blinker on and speed below 60 kph
        if CS.out.leftBlinker or CS.out.rightBlinker:
            self.turning_signal_timer = 0.5 / DT_CTRL  # Disable for 0.5 Seconds after blinker turned off
        if self.turning_indicator_alert and CS.out.vEgo < 2 * CV.KPH_TO_MS:  # set and clear by interface
            lkas_active = 0
        if self.turning_signal_timer > 0:
            self.turning_signal_timer -= 1

        if not lkas_active:
            apply_steer = 0

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning = \
          process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        controls.clu_speed_ms = clu11_speed * CV.KPH_TO_MS

        if not (min_set_speed < set_speed < 255 * CV.KPH_TO_MS):
            set_speed = min_set_speed
        set_speed *= CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
            self.scc12_cnt = CS.scc12[
                "CR_VSM_Alive"] + 1 if not CS.no_radar else 0

            # TODO: fix this
            # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
            # self.scc_update_frame = frame

        # check if SCC is alive
        # if frame % 7 == 0:
        # if CS.scc11["AliveCounterACC"] == self.prev_scc_cnt:
        # if frame - self.scc_update_frame > 20 and self.scc_live:
        # self.scc_live = False
        # else:
        # self.scc_live = True
        # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
        # self.scc_update_frame = frame

        self.prev_scc_cnt = CS.scc11["AliveCounterACC"]

        self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10
        self.scc12_cnt %= 0xF

        #    apply_steer = interp(CS.out.vEgo, [0., 3.], [0., 1.])

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning, 0))

        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer, frame, self.car_fingerprint,
                              apply_steer, lkas_active, CS.lkas11, sys_warning,
                              sys_state, enabled, left_lane, right_lane,
                              left_lane_warning, right_lane_warning, 1))

        if frame % 2 and CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame // 2 % 0x10, CS.mdps_bus,
                             CS.clu11, Buttons.NONE, enabled_speed))

        if pcm_cancel_cmd and (self.longcontrol and not self.mad_mode_enabled):
            can_sends.append(
                create_clu11(self.packer, frame % 0x10, CS.scc_bus, CS.clu11,
                             Buttons.CANCEL, clu11_speed))

        # fix auto resume - by neokii
        if CS.out.cruiseState.standstill:

            if self.last_lead_distance == 0:
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
                self.resume_wait_timer = 0

            # scc smoother
            elif self.scc_smoother.is_active(frame):
                pass

            elif self.resume_wait_timer > 0:
                self.resume_wait_timer -= 1

            elif CS.lead_distance != self.last_lead_distance:
                can_sends.append(
                    create_clu11(self.packer, self.resume_cnt, CS.scc_bus,
                                 CS.clu11, Buttons.RES_ACCEL, clu11_speed))
                self.resume_cnt += 1

                if self.resume_cnt >= 8:
                    self.resume_cnt = 0
                    self.resume_wait_timer = SccSmoother.get_wait_count()

        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0

        # scc smoother
        self.scc_smoother.update(enabled, can_sends, self.packer, CC, CS,
                                 frame, apply_accel, controls)

        if CS.mdps_bus:  # send mdps12 to LKAS to prevent LKAS error
            can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        controls.apply_accel = apply_accel
        aReqValue = CS.scc12["aReqValue"]
        controls.aReqValue = aReqValue

        if aReqValue < controls.aReqValueMin:
            controls.aReqValueMin = controls.aReqValue

        if aReqValue > controls.aReqValueMax:
            controls.aReqValueMax = controls.aReqValue

        # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
        if self.longcontrol and CS.cruiseState_enabled and (
                CS.scc_bus or not self.scc_live) and frame % 2 == 0:

            apply_accel, lead_drel = self.scc_smoother.get_fused_accel(
                apply_accel, aReqValue, controls.sm)
            controls.fused_accel = apply_accel
            controls.lead_drel = lead_drel

            can_sends.append(
                create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt,
                             self.scc_live, CS.scc12))
            can_sends.append(
                create_scc11(self.packer, frame, enabled, set_speed,
                             controls.sm['radarState'], self.scc_live,
                             CS.scc11))

            if CS.has_scc13 and frame % 20 == 0:
                can_sends.append(create_scc13(self.packer, CS.scc13))
            if CS.has_scc14:
                can_sends.append(create_scc14(self.packer, enabled, CS.scc14))
            self.scc12_cnt += 1

            # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfa_mfa"]:
            can_sends.append(create_lfahda_mfc(self.packer, enabled))

        return can_sends
예제 #10
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart, set_speed, lead_visible, lead_dist,
               lead_vrel, lead_yrel):

        self.enabled = enabled
        # gas and brake
        self.accel_lim_prev = self.accel_lim
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

        self.accel_lim = apply_accel
        apply_accel = accel_rate_limit(self.accel_lim, self.accel_lim_prev)

        # Steering Torque
        new_steer = actuators.steer * self.p.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    self.p)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        self.high_steer_allowed = True if self.car_fingerprint in FEATURES[
            "allow_high_steer"] else False
        lkas_active = enabled and ((abs(CS.out.steeringAngle) < 90.)
                                   or self.high_steer_allowed)

        # fix for Genesis hard fault at low speed
        if CS.out.vEgo < 55 * CV.KPH_TO_MS and self.car_fingerprint == CAR.HYUNDAI_GENESIS and CS.CP.minSteerSpeed > 0.:
            lkas_active = False

        if ((CS.out.leftBlinker and not CS.out.rightBlinker) or
            (CS.out.rightBlinker
             and not CS.out.leftBlinker)) and CS.out.vEgo <= 39 * CV.KPH_TO_MS:
            self.lanechange_manual_timer = 10
        if CS.out.leftBlinker and CS.out.rightBlinker:
            self.emergency_manual_timer = 10
        if abs(CS.out.steeringTorque) > 200:
            self.driver_steering_torque_above_timer = 15
        if self.lanechange_manual_timer or self.driver_steering_torque_above_timer:
            lkas_active = 0
        if self.lanechange_manual_timer > 0:
            self.lanechange_manual_timer -= 1
        if self.emergency_manual_timer > 0:
            self.emergency_manual_timer -= 1
        if self.driver_steering_torque_above_timer > 0:
            self.driver_steering_torque_above_timer -= 1

        if not lkas_active:
            apply_steer = 0

        if CS.CP.radarOffCan:
            self.usestockscc = not self.cp_oplongcontrol
        elif (CS.cancel_button_count == 3) and self.cp_oplongcontrol:
            self.usestockscc = not self.usestockscc

        if not self.usestockscc:
            self.gapcount += 1
            if self.gapcount == 50 and self.gapsettingdance == 2:
                self.gapsettingdance = 1
                self.gapcount = 0
            elif self.gapcount == 50 and self.gapsettingdance == 1:
                self.gapsettingdance = 4
                self.gapcount = 0
            elif self.gapcount == 50 and self.gapsettingdance == 4:
                self.gapsettingdance = 3
                self.gapcount = 0
            elif self.gapcount == 50 and self.gapsettingdance == 3:
                self.gapsettingdance = 2
                self.gapcount = 0

        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart)

        speed_conv = CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

        self.clu11_speed = CS.clu11["CF_Clu_Vanz"]

        enabled_speed = 38 if CS.is_set_speed_in_mph else 55

        if self.clu11_speed > enabled_speed or not lkas_active or CS.out.gearShifter != GearShifter.drive:
            enabled_speed = self.clu11_speed

        self.current_veh_speed = int(CS.out.vEgo * speed_conv)

        self.clu11_cnt = frame % 0x10

        can_sends = []

        self.lfa_available = True if self.lfainFingerprint or self.car_fingerprint in FEATURES[
            "send_lfa_mfa"] else False

        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning,
                          self.lfa_available, 0))

        if CS.CP.mdpsHarness:  # send lkas11 bus 1 if mdps
            can_sends.append(
                create_lkas11(self.packer, frame, self.car_fingerprint,
                              apply_steer, lkas_active, CS.lkas11, sys_warning,
                              sys_state, enabled, left_lane, right_lane,
                              left_lane_warning, right_lane_warning,
                              self.lfa_available, 1))

            can_sends.append(
                create_clu11(self.packer, 1, CS.clu11, Buttons.NONE,
                             enabled_speed, self.clu11_cnt))

        if pcm_cancel_cmd and CS.scc12[
                "ACCMode"] != 0 and not CS.out.standstill:
            self.vdiff = 0.
            self.resumebuttoncnt = 0
            can_sends.append(
                create_clu11(self.packer, CS.CP.sccBus, CS.clu11,
                             Buttons.CANCEL, self.current_veh_speed,
                             self.clu11_cnt))
        elif CS.out.cruiseState.standstill and CS.scc12[
                "ACCMode"] != 0 and CS.vrelative > 0:
            self.vdiff += (CS.vrelative - self.vdiff)
            if (frame - self.lastresumeframe > 5) and (self.vdiff > .2 or
                                                       CS.lead_distance > 5.5):
                can_sends.append(
                    create_clu11(self.packer, CS.CP.sccBus, CS.clu11,
                                 Buttons.RES_ACCEL, self.current_veh_speed,
                                 self.resumebuttoncnt))
                self.resumebuttoncnt += 1
                if self.resumebuttoncnt > 5:
                    self.lastresumeframe = frame
                    self.resumebuttoncnt = 0
        else:
            self.vdiff = 0.
            self.resumebuttoncnt = 0

        if CS.out.vEgo < 5.:
            self.sm.update(0)
            long_control_state = self.sm['controlsState'].longControlState
            self.acc_standstill = True if long_control_state == LongCtrlState.stopping else False
        else:
            self.acc_standstill = False

        if lead_visible:
            self.lead_visible = True
            self.lead_debounce = 50
        elif self.lead_debounce > 0:
            self.lead_debounce -= 1
        else:
            self.lead_visible = lead_visible

        self.setspeed = set_speed * speed_conv

        if enabled:
            self.sendaccmode = enabled

        if CS.CP.radarDisablePossible:
            self.radarDisableOverlapTimer += 1
            self.radarDisableResetTimer = 0
            if self.radarDisableOverlapTimer >= 30:
                self.radarDisableActivated = True
                if 200 > self.radarDisableOverlapTimer > 36:
                    if frame % 41 == 0 or self.radarDisableOverlapTimer == 37:
                        can_sends.append(
                            create_scc7d0(b'\x02\x10\x03\x00\x00\x00\x00\x00'))
                    elif frame % 43 == 0 or self.radarDisableOverlapTimer == 37:
                        can_sends.append(
                            create_scc7d0(b'\x03\x28\x03\x01\x00\x00\x00\x00'))
                    elif frame % 19 == 0 or self.radarDisableOverlapTimer == 37:
                        can_sends.append(
                            create_scc7d0(b'\x02\x10\x85\x00\x00\x00\x00\x00')
                        )  # this disables RADAR for
            else:
                self.counter_init = False
                can_sends.append(
                    create_scc7d0(b'\x02\x10\x90\x00\x00\x00\x00\x00')
                )  # this enables RADAR
                can_sends.append(
                    create_scc7d0(b'\x03\x29\x03\x01\x00\x00\x00\x00'))
        elif self.radarDisableActivated:
            can_sends.append(create_scc7d0(
                b'\x02\x10\x90\x00\x00\x00\x00\x00'))  # this enables RADAR
            can_sends.append(
                create_scc7d0(b'\x03\x29\x03\x01\x00\x00\x00\x00'))
            self.radarDisableOverlapTimer = 0
            if frame % 50 == 0:
                self.radarDisableResetTimer += 1
                if self.radarDisableResetTimer > 2:
                    self.radarDisableActivated = False
                    self.counter_init = True
        else:
            self.radarDisableOverlapTimer = 0
            self.radarDisableResetTimer = 0

        if (frame % 50 == 0 or self.radarDisableOverlapTimer == 37) and \
                CS.CP.radarDisablePossible and self.radarDisableOverlapTimer >= 30:
            can_sends.append(
                create_scc7d0(b'\x02\x3E\x00\x00\x00\x00\x00\x00'))

        if self.lead_visible:
            self.objdiststat = 1 if lead_dist < 25 else 2 if lead_dist < 40 else \
                               3 if lead_dist < 60 else 4 if lead_dist < 80 else 5
        else:
            self.objdiststat = 0

        # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
        if (CS.CP.sccBus == 2 or not self.usestockscc
                or self.radarDisableActivated) and self.counter_init:
            if frame % 2 == 0:
                self.scc12cnt += 1
                self.scc12cnt %= 0xF
                self.scc11cnt += 1
                self.scc11cnt %= 0x10
                self.fca11supcnt += 1
                self.fca11supcnt %= 0xF

                if self.fca11alivecnt == 1:
                    self.fca11inc = 0
                    if self.fca11cnt13 == 3:
                        self.fca11maxcnt = 0x9
                        self.fca11cnt13 = 0
                    else:
                        self.fca11maxcnt = 0xD
                        self.fca11cnt13 += 1
                else:
                    self.fca11inc += 4

                self.fca11alivecnt = self.fca11maxcnt - self.fca11inc

                can_sends.append(
                    create_scc11(self.packer, enabled, self.setspeed,
                                 self.lead_visible, lead_dist, lead_vrel,
                                 lead_yrel, self.gapsettingdance,
                                 CS.out.standstill, CS.scc11, self.usestockscc,
                                 CS.CP.radarOffCan, self.scc11cnt,
                                 self.sendaccmode))

                can_sends.append(
                    create_scc12(self.packer, apply_accel, enabled,
                                 self.acc_standstill, CS.out.gasPressed,
                                 CS.out.brakePressed, CS.out.stockAeb,
                                 CS.scc12, self.usestockscc, CS.CP.radarOffCan,
                                 self.scc12cnt))

                can_sends.append(
                    create_scc14(self.packer, enabled, self.usestockscc,
                                 CS.out.stockAeb, apply_accel, CS.scc14,
                                 self.objdiststat, CS.out.gasPressed,
                                 self.acc_standstill, CS.out.vEgo))
                if CS.CP.fcaBus == -1:
                    can_sends.append(
                        create_fca11(self.packer, CS.fca11, self.fca11alivecnt,
                                     self.fca11supcnt))

            if frame % 20 == 0:
                can_sends.append(create_scc13(self.packer, CS.scc13))
                if CS.CP.fcaBus == -1:
                    can_sends.append(create_fca12(self.packer))
            if frame % 50 == 0:
                can_sends.append(create_scc42a(self.packer))
        else:
            self.counter_init = True
            self.scc12cnt = CS.scc12init["CR_VSM_Alive"]
            self.scc11cnt = CS.scc11init["AliveCounterACC"]
            self.fca11alivecnt = CS.fca11init["CR_FCA_Alive"]
            self.fca11supcnt = CS.fca11init["Supplemental_Counter"]

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.lfa_available:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        return can_sends
예제 #11
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart, dragonconf):
        # Steering Torque
        new_steer = int(round(actuators.steer * self.p.STEER_MAX))
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    self.p)
        self.steer_rate_limited = new_steer != apply_steer

        # disable when temp fault is active, or below LKA minimum speed
        lkas_active = enabled and not CS.out.steerWarning and CS.out.vEgo >= CS.CP.minSteerSpeed

        # fix for Genesis hard fault at low speed
        if not self.dp_hkg_smart_mdps and CS.out.vEgo < 16.7 and self.car_fingerprint == CAR.HYUNDAI_GENESIS:
            lkas_active = False

        if not lkas_active:
            apply_steer = 0

        # dp
        blinker_on = CS.out.leftBlinker or CS.out.rightBlinker
        if not enabled:
            self.blinker_end_frame = 0
        if self.last_blinker_on and not blinker_on:
            self.blinker_end_frame = frame + dragonconf.dpSignalOffDelay
        apply_steer = common_controller_ctrl(
            enabled, dragonconf, blinker_on or frame < self.blinker_end_frame,
            apply_steer, CS.out.vEgo)
        self.last_blinker_on = blinker_on

        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning = \
          process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart)

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning))

        if pcm_cancel_cmd:
            can_sends.append(
                create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))
        elif CS.out.cruiseState.standstill:
            # send resume at a max freq of 10Hz
            if (frame - self.last_resume_frame) * DT_CTRL > 0.1:
                # send 25 messages at a time to increases the likelihood of resume being accepted
                can_sends.extend([
                    create_clu11(self.packer, frame, CS.clu11,
                                 Buttons.RES_ACCEL)
                ] * 25)
                self.last_resume_frame = frame

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in [
                CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV,
                CAR.KONA_EV, CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KIA_CEED,
                CAR.KIA_SELTOS, CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021
        ]:
            can_sends.append(create_lfahda_mfc(self.packer, enabled))

        return can_sends
예제 #12
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart):
        # Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled  #and abs(CS.out.steeringAngle) < 90.

        # fix for Genesis hard fault at low speed
        #if CS.out.vEgo < 16.7 and self.car_fingerprint == CAR.HYUNDAI_GENESIS:
        #lkas_active = False

        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed:
            enabled_speed = clu11_speed

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
        self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, self.lkas11_cnt, self.car_fingerprint,
                          apply_steer, steer_req, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning, 0))

        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer, self.lkas11_cnt,
                              self.car_fingerprint, apply_steer, steer_req,
                              CS.lkas11, sys_warning, sys_state, enabled,
                              left_lane, right_lane, left_lane_warning,
                              right_lane_warning, 1))
        if frame % 2 and CS.mdps_bus == 1:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11,
                             Buttons.NONE, enabled_speed))

        if CS.mdps_bus:
            can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        str_log1 = 'torg:{:3.0f}'.format(apply_steer)
        str_log2 = 'new_steer={:.0f} tm={:.1f} '.format(
            new_steer, self.timer1.sampleTime())
        trace1.printf('{} {}'.format(str_log1, str_log2))

        #print( 'st={} cmd={} long={}  steer={} req={}'.format(CS.out.cruiseState.standstill, pcm_cancel_cmd, self.CP.openpilotLongitudinalControl, apply_steer, steer_req ) )

        if pcm_cancel_cmd and self.CP.openpilotLongitudinalControl:
            can_sends.append(
                create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))
        elif CS.out.cruiseState.standstill:
            if self.last_lead_distance == 0:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
            # SCC won't resume anyway when the lead distace is less than 3.7m
            # send resume at a max freq of 5Hz
            #if CS.lead_distance > 3.7 and (frame - self.last_resume_frame)*DT_CTRL > 0.2:
            if CS.lead_distance != self.last_lead_distance and (
                    frame - self.last_resume_frame) * DT_CTRL > 0.2:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.last_resume_frame = frame

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in [
                CAR.SONATA, CAR.PALISADE, CAR.IONIQ
        ]:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        return can_sends
예제 #13
0
  def update(self, CC, CS, frame, sm, CP ):

    if self.CP != CP:
      self.CP = CP

    self.param_load()
    
    enabled = CC.enabled
    actuators = CC.actuators
    pcm_cancel_cmd = CC.cruiseControl.cancel
    
    self.dRel, self.yRel, self.vRel = SpdController.get_lead( sm )

    if self.SC is not None:
      self.model_speed, self.model_sum = self.SC.calc_va(  sm, CS.out.vEgo  )
    else:
      self.model_speed = self.model_sum = 0

    # Steering Torque
    if self.param_OpkrEnableLearner:
      new_steer = actuators.steer * SteerLimitParams.STEER_MAX
      apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, SteerLimitParams)
      self.steer_rate_limited = new_steer != apply_steer
    else:
      path_plan = sm['pathPlan']
      self.cV_tune( CS.out.vEgo, self.model_speed )
      param = SteerLimitParams()
      param.STEER_MAX = min( param.STEER_MAX, self.MAX )
      param.STEER_DELTA_UP = min( param.STEER_DELTA_UP, self.UP )
      param.STEER_DELTA_DOWN = min( param.STEER_DELTA_DOWN, self.DN )
      new_steer = actuators.steer * param.STEER_MAX
      apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, param)    
      self.steer_rate_limited = new_steer != apply_steer


    # disable if steer angle reach 90 deg, otherwise mdps fault in some models
    lkas_active = enabled and abs(CS.out.steeringAngle) < 90. #TenesiDel -> and self.lkas_button_on

    # fix for Genesis hard fault at low speed 테네시 추가
    if CS.out.vEgo < 60 * CV.KPH_TO_MS and self.car_fingerprint == CAR.GENESIS and not CS.mdps_bus:
      lkas_active = False

#    if (( CS.out.leftBlinker and not CS.out.rightBlinker) or ( CS.out.rightBlinker and not CS.out.leftBlinker)) and CS.out.vEgo > 60 * CV.KPH_TO_MS: # 깜빡이 작동시에도 상히조향 유지 수정해보기
#      self.lanechange_manual_timer = 10
#    if CS.out.leftBlinker and CS.out.rightBlinker:
#      self.emergency_manual_timer = 10
#    if abs(CS.out.steeringTorque) > self.driver_steering_torque_above and CS.out.vEgo > 60: # 깜빡이 작동시에도 상히조향 유지 수정해보기
#      self.driver_steering_torque_above_timer = 30
#    if self.lanechange_manual_timer or self.driver_steering_torque_above_timer:
#      lkas_active = 0
#    if self.lanechange_manual_timer > 0:
#      self.lanechange_manual_timer -= 1
#    if self.emergency_manual_timer > 0:
#      self.emergency_manual_timer -= 1
#    if self.driver_steering_torque_above_timer > 0:
#      self.driver_steering_torque_above_timer -= 1

    # Disable steering while turning blinker on and speed below 60 kph #201011 상시조향 작업 작동성공
    if CS.out.leftBlinker or CS.out.rightBlinker:
      if self.car_fingerprint not in [CAR.K5, CAR.K5_HEV]: # 테네시 추가 OPTIMA -> K5
        self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off
      elif CS.left_blinker_flash or CS.right_blinker_flash:  # Optima has blinker flash signal only
        self.turning_signal_timer = 100
    if self.turning_signal_timer and CS.out.vEgo > 70 * CV.KPH_TO_MS:  # TenesiADD Blinker tune 시속60미만에서는 상시조향
      lkas_active = 0
    if self.turning_signal_timer:  # TenesiADD
      self.turning_signal_timer -= 1 #201011 상시조향 작업 작동성공

    if not lkas_active:
      apply_steer = 0

    steer_req = 1 if apply_steer else 0      

    self.apply_steer_last = apply_steer

    sys_warning, sys_state = self.process_hud_alert( lkas_active, CC )

    clu11_speed = CS.clu11["CF_Clu_Vanz"]
    enabled_speed = 38 if CS.is_set_speed_in_mph  else 55
    if clu11_speed > enabled_speed:
      enabled_speed = clu11_speed

    can_sends = []
    if frame == 0: # initialize counts from last received count signals
      self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1
    self.lkas11_cnt %= 0x10

    can_sends.append(create_lkas11(self.packer, self.lkas11_cnt, self.car_fingerprint, apply_steer, steer_req,
                                   CS.lkas11, sys_warning, sys_state, CC, enabled, 0 ))
    if CS.mdps_bus or CS.scc_bus == 1: # send lkas11 bus 1 if mdps is on bus 1                               
      can_sends.append(create_lkas11(self.packer, self.lkas11_cnt, self.car_fingerprint, apply_steer, steer_req,
                                   CS.lkas11, sys_warning, sys_state, CC, enabled, 1 ))

    if CS.mdps_bus: # send clu11 to mdps if it is not on bus 0                                   
    #if frame % 2 and CS.mdps_bus == 1: # send clu11 to mdps if it is not on bus 0                                   
      can_sends.append(create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11, Buttons.NONE, enabled_speed))
    
    #if CS.mdps_bus:
    can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))                                   

    str_log1 = '곡률={:05.1f}/{:=+06.3f}  토크={:=+04.0f}/{:=+04.0f}'.format(  self.model_speed, self.model_sum, new_steer, CS.out.steeringTorque )
    if self.param_OpkrEnableLearner:
      str_log2 = '프레임율={:03.0f}  STMAX={:03.0f}'.format( self.timer1.sampleTime(), SteerLimitParams.STEER_MAX, )
    else:
      str_log2 = '프레임율={:03.0f}  ST={:03.0f}/{:01.0f}/{:01.0f}  SR={:05.2f}'.format( self.timer1.sampleTime(), self.MAX, self.UP, self.DN, path_plan.steerRatio )
    trace1.printf( '{}  {}'.format( str_log1, str_log2 ) )

    if CS.out.cruiseState.modeSel == 0 and self.mode_change_switch == 4:
      self.mode_change_timer = 50
      self.mode_change_switch = 0
    elif CS.out.cruiseState.modeSel == 1 and self.mode_change_switch == 0:
      self.mode_change_timer = 50
      self.mode_change_switch = 1
    elif CS.out.cruiseState.modeSel == 2 and self.mode_change_switch == 1:
      self.mode_change_timer = 50
      self.mode_change_switch = 2
    elif CS.out.cruiseState.modeSel == 3 and self.mode_change_switch == 2:
      self.mode_change_timer = 50
      self.mode_change_switch = 3
    elif CS.out.cruiseState.modeSel == 4 and self.mode_change_switch == 3:
      self.mode_change_timer = 50
      self.mode_change_switch = 4
    if self.mode_change_timer > 0:
      self.mode_change_timer -= 1

    run_speed_ctrl = self.param_OpkrAccelProfile and CS.acc_active and self.SC != None and (CS.out.cruiseState.modeSel == 1 or CS.out.cruiseState.modeSel == 2 or CS.out.cruiseState.modeSel == 3)
    if not run_speed_ctrl:
      if CS.out.cruiseState.modeSel == 0:
        self.steer_mode = "오파모드"
      elif CS.out.cruiseState.modeSel == 1:
        self.steer_mode = "차간+커브"
      elif CS.out.cruiseState.modeSel == 2:
        self.steer_mode = "차간ONLY"
      elif CS.out.cruiseState.modeSel == 3:
        self.steer_mode = "자동RES"
      elif CS.out.cruiseState.modeSel == 4:
        self.steer_mode = "순정모드"
      if CS.out.steerWarning == 0:
        self.mdps_status = "정상"
      elif CS.out.steerWarning == 1:
        self.mdps_status = "오류"
      if CS.lkas_button_on == 0:
        self.lkas_switch = "OFF"
      elif CS.lkas_button_on == 1:
        self.lkas_switch = "ON"
      else:
        self.lkas_switch = "-"
      
      if CS.out.cruiseState.modeSel == 3:
        str_log2 = '주행모드={:s}  MDPS상태={:s}  LKAS버튼={:s}  AUTORES=(VS:{:03.0f}/CN:{:01.0f}/RD:{:03.0f}/BK:{})'.format( self.steer_mode, self.mdps_status, self.lkas_switch, CS.VSetDis, self.res_cnt, self.res_delay, CS.out.brakeLights )
      else:
        str_log2 = '주행모드={:s}  MDPS상태={:s}  LKAS버튼={:s}'.format( self.steer_mode, self.mdps_status, self.lkas_switch )
      trace1.printf2( '{}'.format( str_log2 ) )

    #print( 'st={} cmd={} long={}  steer={} req={}'.format(CS.out.cruiseState.standstill, pcm_cancel_cmd, self.CP.openpilotLongitudinalControl, apply_steer, steer_req ) )


    if pcm_cancel_cmd and self.CP.openpilotLongitudinalControl:
      can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.CANCEL, clu11_speed))
    elif CS.out.cruiseState.standstill and not self.car_fingerprint == CAR.NIRO_EV:
      # run only first time when the car stopped
      if self.last_lead_distance == 0 or not self.param_OpkrAutoResume:
        # get the lead distance from the Radar
        self.last_lead_distance = CS.lead_distance
        self.resume_cnt = 0
      # when lead car starts moving, create 6 RES msgs
      elif CS.lead_distance != self.last_lead_distance and (frame - self.last_resume_frame) > 5:
        can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.RES_ACCEL, clu11_speed))
        self.resume_cnt += 1
        # interval after 6 msgs
        if self.resume_cnt > 5:
          self.last_resume_frame = frame
          self.resume_cnt = 0
    elif CS.out.cruiseState.standstill and self.car_fingerprint == CAR.NIRO_EV:
      if CS.lead_distance > 3.7 and (frame - self.last_resume_frame)*DT_CTRL > 0.2 and self.param_OpkrAutoResume:
        can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.RES_ACCEL, clu11_speed))
        self.last_resume_frame = frame

    # reset lead distnce after the car starts moving
    elif self.last_lead_distance != 0:
      self.last_lead_distance = 0
    elif run_speed_ctrl and self.SC != None:
      is_sc_run = self.SC.update( CS, sm, self )
      if is_sc_run:
        can_sends.append(create_clu11(self.packer, self.resume_cnt, CS.scc_bus, CS.clu11, self.SC.btn_type, self.SC.sc_clu_speed ))
        self.resume_cnt += 1
      else:
        self.resume_cnt = 0
    
    if CS.out.cruiseState.modeSel == 3:
      if CS.out.brakeLights and CS.VSetDis > 30:
        self.res_cnt = 0
        self.res_delay = 50
      elif self.res_delay:
        self.res_delay -= 1
      elif not self.res_delay and self.res_cnt < 6 and CS.VSetDis > 30 and CS.out.vEgo > 30 * CV.KPH_TO_MS:
        if self.res_cnt < 1:
          can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.CANCEL, clu11_speed))
        can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.RES_ACCEL, clu11_speed))
        self.res_cnt += 1
      else:
        self.res_cnt = 7
        self.res_delay = 0

    # 20 Hz LFA MFA message
    if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfa_mfa"]:
      can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

    self.lkas11_cnt += 1
    return can_sends
예제 #14
0
    def update(self, CC, CS, frame, sm, CP):
        if self.CP != CP:
            self.CP = CP

        self.param_load()

        enabled = CC.enabled
        actuators = CC.actuators
        pcm_cancel_cmd = CC.cruiseControl.cancel

        path_plan = sm['pathPlan']

        abs_angle_steers = abs(actuators.steerAngle)

        self.dRel, self.yRel, self.vRel = SpdController.get_lead(sm)
        if self.SC is not None:
            self.model_speed, self.model_sum = self.SC.calc_va(sm, CS.out.vEgo)
        else:
            self.model_speed = self.model_sum = 0

        # Steering Torque
        param = self.steerParams_torque(CS, abs_angle_steers, path_plan, CC)

        new_steer = actuators.steer * param.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    param)
        self.steer_rate_limited = new_steer != apply_steer

        apply_steer_limit = param.STEER_MAX
        if self.steer_torque_ratio < 1:
            apply_steer_limit = int(self.steer_torque_ratio * param.STEER_MAX)
            apply_steer = self.limit_ctrl(apply_steer, apply_steer_limit, 0)

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled and abs(
            CS.out.steeringAngle) < 180.  #and self.lkas_button

        # fix for Genesis hard fault at low speed
        #if CS.out.vEgo < 16.666667 and self.car_fingerprint == CAR.GENESIS:
        #  lkas_active = 0

        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        self.apply_steer_last = apply_steer

        sys_warning, sys_state = self.process_hud_alert(lkas_active, CC)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        can_sends = []
        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1
        self.lkas11_cnt %= 0x10

        can_sends.append(
            create_lkas11(self.packer, self.lkas11_cnt, self.car_fingerprint,
                          apply_steer, steer_req, CS.lkas11, sys_warning,
                          sys_state, CC, enabled, 0))
        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps is on bus 1
            can_sends.append(
                create_lkas11(self.packer, self.lkas11_cnt,
                              self.car_fingerprint, apply_steer, steer_req,
                              CS.lkas11, sys_warning, sys_state, CC, enabled,
                              1))
        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11,
                             Buttons.NONE, enabled_speed))

        #if pcm_cancel_cmd and self.longcontrol:
        #  can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.CANCEL, clu11_speed))
        #else: # send mdps12 to LKAS to prevent LKAS error if no cancel cmd
        can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        #str_log1 = 'CV={:5.1f}/{:5.3f} torg:{:5.0f}'.format(  self.model_speed, self.model_sum, apply_steer )
        str_log1 = 'CV={:5.1f} torg:{:6.1f}'.format(self.model_speed,
                                                    apply_steer)
        #str_log2 = 'limit={:.0f} tm={:.1f} '.format( apply_steer_limit, self.timer1.sampleTime()  )
        str_log2 = ' limit={:6.1f}/tm={:3.1f} MAX={:5.1f} UP/DN={:3.1f}/{:3.1f} '.format(
            apply_steer_limit, self.timer1.sampleTime(), self.MAX, self.UP,
            self.DN)
        trace1.printf('{} {}'.format(str_log1, str_log2))

        run_speed_ctrl = self.param_OpkrAccelProfile and CS.acc_active and self.SC != None
        if not run_speed_ctrl:
            str_log2 = 'U={:.0f}  LK={:.0f} dir={} steer={:5.0f} '.format(
                CS.Mdps_ToiUnavail, CS.lkas_button_on,
                self.steer_torque_ratio_dir, CS.out.steeringTorque)
            trace1.printf2('{}'.format(str_log2))

        if pcm_cancel_cmd and self.CP.longcontrolEnabled:
            can_sends.append(
                create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))

        elif CS.out.cruiseState.standstill:
            # run only first time when the car stopped
            if self.last_lead_distance == 0 or not self.param_OpkrAutoResume:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance != self.last_lead_distance < CS.lead_distance > 4.8 and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.resume_cnt += 1
                # interval after 10 msgs
                if self.resume_cnt > 10:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0
                    self.clu11_cnt = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0
        elif run_speed_ctrl and self.SC != None:
            is_sc_run = self.SC.update(CS, sm, self)
            if is_sc_run:
                can_sends.append(
                    create_clu11(self.packer, self.resume_cnt, CS.scc_bus,
                                 CS.clu11, self.SC.btn_type,
                                 self.SC.sc_clu_speed))
                self.resume_cnt += 1
            else:
                self.resume_cnt = 0

            str1 = 'run={} cruise_set_mode={} kph={:.1f}/{:.1f} DO={:.0f}/{:.0f} '.format(
                is_sc_run, self.SC.cruise_set_mode,
                self.SC.cruise_set_speed_kph, CS.VSetDis, CS.driverOverride,
                CS.cruise_buttons)
            str2 = 'btn_type={:.0f} speed={:.1f} cnt={:.0f}'.format(
                self.SC.btn_type, self.SC.sc_clu_speed, self.resume_cnt)
            str_log = str1 + str2
            self.traceCC.add(str_log)

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in [
                CAR.PALISADE, CAR.SELTOS
        ]:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        # counter inc
        self.lkas11_cnt += 1
        return can_sends
예제 #15
0
  def update(self, enabled, CS, frame, CC, actuators, pcm_cancel_cmd, visual_alert,
             left_lane, right_lane, left_lane_depart, right_lane_depart, set_speed, lead_visible, sm):

    # *** compute control surfaces ***

    # gas and brake
    apply_accel = actuators.gas - actuators.brake

    apply_accel, self.accel_steady = accel_hysteresis(apply_accel, self.accel_steady)
    apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

    self.dRel, self.yRel, self.vRel = SpdController.get_lead(sm)
    self.model_speed, self.model_sum = self.SC.calc_va(sm, CS.out.vEgo)


    # Steering Torque

    steerAngleAbs = abs(actuators.steerAngle)
    limitParams = copy.copy(SteerLimitParams)
    limitParams.STEER_MAX = int(interp(steerAngleAbs, [5., 10., 20., 30., 70.], [255, SteerLimitParams.STEER_MAX, 500, 600, 800]))
    limitParams.STEER_DELTA_UP = int(interp(steerAngleAbs, [5., 20., 50.], [2, 3, 3]))
    limitParams.STEER_DELTA_DOWN = int(interp(steerAngleAbs, [5., 20., 50.], [4, 5, 5]))

    if self.driver_steering_torque_above_timer:
      new_steer = actuators.steer * limitParams.STEER_MAX * (self.driver_steering_torque_above_timer / 100)
    else:
      new_steer = actuators.steer * limitParams.STEER_MAX
    apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, limitParams)
    self.steer_rate_limited = new_steer != apply_steer

    CC.applyAccel = apply_accel
    CC.applySteer = apply_steer

    # SPAS limit angle extremes for safety
    if CS.spas_enabled:
      apply_steer_ang_req = clip(actuators.steerAngle, -1*(STEER_ANG_MAX), STEER_ANG_MAX)
      # SPAS limit angle rate for safety
      if abs(self.apply_steer_ang - apply_steer_ang_req) > STEER_ANG_MAX_RATE:
        if apply_steer_ang_req > self.apply_steer_ang:
          self.apply_steer_ang += STEER_ANG_MAX_RATE
        else:
          self.apply_steer_ang -= STEER_ANG_MAX_RATE
      else:
        self.apply_steer_ang = apply_steer_ang_req
    spas_active = CS.spas_enabled and enabled and (self.spas_always or CS.out.vEgo < 7.0) # 25km/h

    # disable if steer angle reach 90 deg, otherwise mdps fault in some models
    # temporarily disable steering when LKAS button off 
    #lkas_active = enabled and abs(CS.out.steeringAngle) < 90. and not spas_active
    lkas_active = enabled and not spas_active #and abs(CS.out.steeringAngle) < 90. 

    if (( CS.out.leftBlinker and not CS.out.rightBlinker) or ( CS.out.rightBlinker and not CS.out.leftBlinker)) and CS.out.vEgo < LANE_CHANGE_SPEED_MIN:
      self.lanechange_manual_timer = 10
    if CS.out.leftBlinker and CS.out.rightBlinker:
      self.emergency_manual_timer = 10
    if abs(CS.out.steeringTorque) > 200:
      self.driver_steering_torque_above_timer = 100
    if self.lanechange_manual_timer:
      lkas_active = 0
    if self.lanechange_manual_timer > 0:
      self.lanechange_manual_timer -= 1
    if self.emergency_manual_timer > 0:
      self.emergency_manual_timer -= 1
    if self.driver_steering_torque_above_timer > 0:
      self.driver_steering_torque_above_timer -= 1

    if not lkas_active:
      apply_steer = 0

    self.apply_accel_last = apply_accel
    self.apply_steer_last = apply_steer

    sys_warning, sys_state, left_lane_warning, right_lane_warning =\
      process_hud_alert(lkas_active, self.car_fingerprint, visual_alert,
                        left_lane, right_lane, left_lane_depart, right_lane_depart,
                        self.lkas_button_on)

    clu11_speed = CS.clu11["CF_Clu_Vanz"]
    enabled_speed = 38 if CS.is_set_speed_in_mph  else 55
    if clu11_speed > enabled_speed or not lkas_active:
      enabled_speed = clu11_speed

    if not(min_set_speed < set_speed < 255 * CV.KPH_TO_MS):
      set_speed = min_set_speed 
    set_speed *= CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

    if frame == 0: # initialize counts from last received count signals
      self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
      self.scc12_cnt = CS.scc12["CR_VSM_Alive"] + 1 if not CS.no_radar else 0

      #TODO: fix this
      # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
      # self.scc_update_frame = frame

    # check if SCC is alive
    # if frame % 7 == 0:
      # if CS.scc11["AliveCounterACC"] == self.prev_scc_cnt:
        # if frame - self.scc_update_frame > 20 and self.scc_live:
          # self.scc_live = False
      # else:
        # self.scc_live = True
        # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
        # self.scc_update_frame = frame

    self.prev_scc_cnt = CS.scc11["AliveCounterACC"]

    self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10
    self.scc12_cnt %= 0xF

    can_sends = []
    can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled, left_lane, right_lane,
                                   left_lane_warning, right_lane_warning, 0))

    if CS.mdps_bus or CS.scc_bus == 1: # send lkas11 bus 1 if mdps or scc is on bus 1
      can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled, left_lane, right_lane,
                                   left_lane_warning, right_lane_warning, 1))
    if frame % 2 and CS.mdps_bus: # send clu11 to mdps if it is not on bus 0
      can_sends.append(create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11, Buttons.NONE, enabled_speed))


    str_log1 = '곡률={:03.0f}  토크={:03.0f}  프레임률={:03.0f} ST={:03.0f}/{:01.0f}/{:01.0f}'.format(abs(self.model_speed), abs(new_steer), self.timer1.sampleTime(), SteerLimitParams.STEER_MAX, SteerLimitParams.STEER_DELTA_UP, SteerLimitParams.STEER_DELTA_DOWN)
    trace1.printf1('{}  {}'.format(str_log1, self.str_log2))

    if CS.out.cruiseState.modeSel == 0 and self.mode_change_switch == 3:
      self.mode_change_timer = 50
      self.mode_change_switch = 0
    elif CS.out.cruiseState.modeSel == 1 and self.mode_change_switch == 0:
      self.mode_change_timer = 50
      self.mode_change_switch = 1
    elif CS.out.cruiseState.modeSel == 2 and self.mode_change_switch == 1:
      self.mode_change_timer = 50
      self.mode_change_switch = 2
    elif CS.out.cruiseState.modeSel == 3 and self.mode_change_switch == 2:
      self.mode_change_timer = 50
      self.mode_change_switch = 3
    if self.mode_change_timer > 0:
      self.mode_change_timer -= 1

    run_speed_ctrl = self.opkr_variablecruise and CS.acc_active and (CS.out.cruiseState.modeSel == 1 or CS.out.cruiseState.modeSel == 2 or CS.out.cruiseState.modeSel == 3)
    if not run_speed_ctrl:
      if CS.out.cruiseState.modeSel == 0:
        self.steer_mode = "오파모드"
      elif CS.out.cruiseState.modeSel == 1:
        self.steer_mode = "차간+커브"
      elif CS.out.cruiseState.modeSel == 2:
        self.steer_mode = "차간ONLY"
      elif CS.out.cruiseState.modeSel == 3:
        self.steer_mode = "편도1차선"
      if CS.out.steerWarning == 0:
        self.mdps_status = "정상"
      elif CS.out.steerWarning == 1:
        self.mdps_status = "오류"
      if CS.lkas_button_on == 0:
        self.lkas_switch = "OFF"
      elif CS.lkas_button_on == 1:
        self.lkas_switch = "ON"
      else:
        self.lkas_switch = "-"
      if self.cruise_gap != CS.cruiseGapSet:
        self.cruise_gap = CS.cruiseGapSet

      str_log3 = '주행모드={:s}  MDPS상태={:s}  LKAS버튼={:s}  크루즈갭={:1.0f}'.format( self.steer_mode, self.mdps_status, self.lkas_switch, self.cruise_gap)
      trace1.printf2( '{}'.format( str_log3 ) )


    if pcm_cancel_cmd and self.longcontrol:
      can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.CANCEL, clu11_speed))

    if CS.out.cruiseState.standstill:
      if self.last_lead_distance == 0 or not self.opkr_autoresume:
        self.last_lead_distance = CS.lead_distance
        self.resume_cnt = 0
        self.resume_wait_timer = 0

      elif self.resume_wait_timer > 0:
        self.resume_wait_timer -= 1

      elif CS.lead_distance != self.last_lead_distance:
        can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.RES_ACCEL, clu11_speed))
        self.resume_cnt += 1

        if self.resume_cnt > 5:
          self.resume_cnt = 0
          self.resume_wait_timer = int(0.25 / DT_CTRL)

      elif self.cruise_gap_prev == 0 and run_speed_ctrl: 
        self.cruise_gap_prev = CS.cruiseGapSet
        self.cruise_gap_set_init = 1
      elif CS.cruiseGapSet != 1.0 and run_speed_ctrl:
        self.cruise_gap_switch_timer += 1
        if self.cruise_gap_switch_timer > 100:
          can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.GAP_DIST, clu11_speed))
          self.cruise_gap_switch_timer = 0

    # reset lead distnce after the car starts moving
    elif self.last_lead_distance != 0:
      self.last_lead_distance = 0
    elif run_speed_ctrl:
      is_sc_run = self.SC.update(CS, sm, self)
      if is_sc_run:
        can_sends.append(create_clu11(self.packer, self.resume_cnt, CS.scc_bus, CS.clu11, self.SC.btn_type, self.SC.sc_clu_speed))
        self.resume_cnt += 1
      else:
        self.resume_cnt = 0
      if self.dRel > 17 and self.cruise_gap_prev != CS.cruiseGapSet and self.cruise_gap_set_init == 1:
        self.cruise_gap_switch_timer += 1
        if self.cruise_gap_switch_timer > 50:
          can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.GAP_DIST, clu11_speed))
          self.cruise_gap_switch_timer = 0
      elif self.cruise_gap_prev == CS.cruiseGapSet:
        self.cruise_gap_set_init = 0
        self.cruise_gap_prev = 0

    if CS.mdps_bus: # send mdps12 to LKAS to prevent LKAS error
      can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

    # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
    if self.longcontrol and (CS.scc_bus or not self.scc_live) and frame % 2 == 0: 
      can_sends.append(create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt, self.scc_live, CS.scc12))
      can_sends.append(create_scc11(self.packer, frame, enabled, set_speed, lead_visible, self.scc_live, CS.scc11))
      if CS.has_scc13 and frame % 20 == 0:
        can_sends.append(create_scc13(self.packer, CS.scc13))
      if CS.has_scc14:
        can_sends.append(create_scc14(self.packer, enabled, CS.scc14))
      self.scc12_cnt += 1

    # 20 Hz LFA MFA message
    if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfa_mfa"]:
      can_sends.append(create_lfa_mfa(self.packer, frame, lkas_active))

    if CS.spas_enabled:
      if CS.mdps_bus:
        can_sends.append(create_ems11(self.packer, CS.ems11, spas_active))

      # SPAS11 50hz
      if (frame % 2) == 0:
        if CS.mdps11_stat == 7 and not self.mdps11_stat_last == 7:
          self.en_spas = 7
          self.en_cnt = 0

        if self.en_spas == 7 and self.en_cnt >= 8:
          self.en_spas = 3
          self.en_cnt = 0
  
        if self.en_cnt < 8 and spas_active:
          self.en_spas = 4
        elif self.en_cnt >= 8 and spas_active:
          self.en_spas = 5

        if not spas_active:
          self.apply_steer_ang = CS.mdps11_strang
          self.en_spas = 3
          self.en_cnt = 0

        self.mdps11_stat_last = CS.mdps11_stat
        self.en_cnt += 1
        can_sends.append(create_spas11(self.packer, self.car_fingerprint, (frame // 2), self.en_spas, self.apply_steer_ang, CS.mdps_bus))

      # SPAS12 20Hz
      if (frame % 5) == 0:
        can_sends.append(create_spas12(CS.mdps_bus))

    return can_sends
예제 #16
0
    def update(self, c, CS, frame, sm, CP):
        if self.CP != CP:
            self.CP = CP

        self.param_load()
        enabled = c.enabled
        actuators = c.actuators
        pcm_cancel_cmd = c.cruiseControl.cancel

        path_plan = sm['pathPlan']
        self.dRel, self.yRel, self.vRel = SpdController.get_lead(sm)
        if self.SC is not None:
            self.model_speed, self.model_sum = self.SC.calc_va(sm, CS.out.vEgo)
        else:
            self.model_speed = self.model_sum = 0

        # Steering Torque
        param, dst_steer = self.steerParams_torque(CS, c.actuators, path_plan)
        new_steer = actuators.steer * param.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    param)
        self.steer_rate_limited = new_steer != apply_steer

        apply_steer_limit = param.STEER_MAX
        if self.steer_torque_ratio < 1:
            apply_steer_limit = int(self.steer_torque_ratio * param.STEER_MAX)
            apply_steer = self.limit_ctrl(apply_steer, apply_steer_limit, 0)

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled and CS.main_on and CS.out.cruiseState.enabled and abs(
            CS.out.steeringAngle) < 180.  #and self.lkas_button

        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0
        self.apply_steer_last = apply_steer

        sys_warning, self.hud_sys_state = self.process_hud_alert(
            lkas_active, c)

        can_sends = []
        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1
        self.lkas11_cnt %= 0x10

        can_sends.append(
            create_lkas11(self.packer, self.lkas11_cnt, self.car_fingerprint,
                          apply_steer, steer_req, CS.lkas11, sys_warning,
                          self.hud_sys_state, c))

        # send mdps12 to LKAS to prevent LKAS error if no cancel cmd
        can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        str_log1 = 'torg:{:5.0f}/{:5.0f}/{:5.0f}  CV={:5.1f}'.format(
            apply_steer, new_steer, dst_steer, self.model_speed)
        str_log2 = 'limit={:.0f} tm={:.1f} '.format(apply_steer_limit,
                                                    self.timer1.sampleTime())
        trace1.printf('{} {}'.format(str_log1, str_log2))

        run_speed_ctrl = self.param_OpkrAccelProfile and CS.acc_active and self.SC != None
        if not run_speed_ctrl:
            str_log2 = 'LKAS={:.0f}  steer={:5.0f} '.format(
                CS.lkas_button_on, CS.out.steeringTorque)
            trace1.printf2('{}'.format(str_log2))

        if pcm_cancel_cmd and self.CP.longcontrolEnabled:
            can_sends.append(
                create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))

        elif CS.out.cruiseState.standstill:
            # run only first time when the car stopped
            if self.last_lead_distance == 0 or not self.param_OpkrAutoResume:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance != self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, self.resume_cnt, CS.clu11,
                                 Buttons.RES_ACCEL))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0
        elif run_speed_ctrl and self.SC != None:
            is_sc_run = self.SC.update(CS, sm, self)
            if is_sc_run:
                can_sends.append(
                    create_clu11(self.packer, self.resume_cnt, CS.clu11,
                                 self.SC.btn_type, self.SC.sc_clu_speed))
                self.resume_cnt += 1
            else:
                self.resume_cnt = 0

            str1 = 'run={} cruise_set_mode={} kph={:.1f}/{:.1f} DO={:.0f}/{:.0f} '.format(
                is_sc_run, self.SC.cruise_set_mode,
                self.SC.cruise_set_speed_kph, CS.VSetDis, CS.driverOverride,
                CS.cruise_buttons)
            str2 = 'btn_type={:.0f} speed={:.1f} cnt={:.0f}'.format(
                self.SC.btn_type, self.SC.sc_clu_speed, self.resume_cnt)
            str_log = str1 + str2
            self.traceCC.add(str_log)

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in [
                CAR.SONATA, CAR.PALISADE
        ]:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        # counter inc
        self.lkas11_cnt += 1
        return can_sends
예제 #17
0
    def test_correctness(self):
        # Test all commands, randomize the params.
        for _ in range(1000):
            # Hyundai
            car_fingerprint = hyundai_checksum["crc8"][0]
            apply_steer = (random.randint(0, 2) % 2 == 0)
            steer_req = (random.randint(0, 2) % 2 == 0)
            cnt = random.randint(0, 65536)
            enabled = (random.randint(0, 2) % 2 == 0)
            lkas11 = {
                "CF_Lkas_LdwsSysState": random.randint(0, 65536),
                "CF_Lkas_SysWarning": random.randint(0, 65536),
                "CF_Lkas_LdwsLHWarning": random.randint(0, 65536),
                "CF_Lkas_LdwsRHWarning": random.randint(0, 65536),
                "CF_Lkas_HbaLamp": random.randint(0, 65536),
                "CF_Lkas_FcwBasReq": random.randint(0, 65536),
                "CF_Lkas_ToiFlt": random.randint(0, 65536),
                "CF_Lkas_HbaSysState": random.randint(0, 65536),
                "CF_Lkas_FcwOpt": random.randint(0, 65536),
                "CF_Lkas_HbaOpt": random.randint(0, 65536),
                "CF_Lkas_FcwSysState": random.randint(0, 65536),
                "CF_Lkas_FcwCollisionWarning": random.randint(0, 65536),
                "CF_Lkas_FusionState": random.randint(0, 65536),
                "CF_Lkas_FcwOpt_USM": random.randint(0, 65536),
                "CF_Lkas_LdwsOpt_USM": random.randint(0, 65536)
            }
            hud_alert = random.randint(0, 65536)
            lane_visible = random.randint(0, 65536)
            left_lane_depart = (random.randint(0, 2) % 2 == 0)
            right_lane_depart = (random.randint(0, 2) % 2 == 0)
            keep_stock = (random.randint(0, 2) % 2 == 0)
            m_old = hyundaican.create_lkas11(self.hyundai_cp_old,
                                             car_fingerprint, apply_steer,
                                             steer_req, cnt, enabled, lkas11,
                                             hud_alert, lane_visible,
                                             left_lane_depart,
                                             right_lane_depart, keep_stock)
            m = hyundaican.create_lkas11(self.hyundai_cp, car_fingerprint,
                                         apply_steer, steer_req, cnt, enabled,
                                         lkas11, hud_alert, lane_visible,
                                         left_lane_depart, right_lane_depart,
                                         keep_stock)
            self.assertEqual(m_old, m)

            clu11 = {
                "CF_Clu_CruiseSwState": random.randint(0, 65536),
                "CF_Clu_CruiseSwMain": random.randint(0, 65536),
                "CF_Clu_SldMainSW": random.randint(0, 65536),
                "CF_Clu_ParityBit1": random.randint(0, 65536),
                "CF_Clu_VanzDecimal": random.randint(0, 65536),
                "CF_Clu_Vanz": random.randint(0, 65536),
                "CF_Clu_SPEED_UNIT": random.randint(0, 65536),
                "CF_Clu_DetentOut": random.randint(0, 65536),
                "CF_Clu_RheostatLevel": random.randint(0, 65536),
                "CF_Clu_CluInfo": random.randint(0, 65536),
                "CF_Clu_AmpInfo": random.randint(0, 65536),
                "CF_Clu_AliveCnt1": random.randint(0, 65536),
            }
            button = random.randint(0, 65536)
            m_old = hyundaican.create_clu11(self.hyundai_cp_old, clu11, button,
                                            cnt)
            m = hyundaican.create_clu11(self.hyundai_cp, clu11, button, cnt)
            self.assertEqual(m_old, m)
예제 #18
0
    def update(self, enabled, CS, frame, CC, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart, set_speed, lead_visible, sm):

        # *** compute control surfaces ***

        # gas and brake
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

        param = self.p

        self.model_speed, self.model_sum = self.SC.calc_va(sm, CS.out.vEgo)

        plan = sm['plan']
        self.dRel = int(plan.dRel1)  #EON Lead
        self.yRel = int(plan.yRel1)  #EON Lead
        self.vRel = int(plan.vRel1 * 3.6 + 0.5)  #EON Lead
        self.dRel2 = int(plan.dRel2)  #EON Lead
        self.yRel2 = int(plan.yRel2)  #EON Lead
        self.vRel2 = int(plan.vRel2 * 3.6 + 0.5)  #EON Lead
        self.lead2_status = plan.status2
        self.target_map_speed = plan.targetSpeed
        self.target_map_speed_camera = plan.targetSpeedCamera

        self.accActive = CS.acc_active

        path_plan = sm['pathPlan']
        self.outScale = path_plan.outputScale
        self.vCruiseSet = path_plan.vCruiseSet

        self.angle_steers_des = path_plan.angleSteers - path_plan.angleOffset
        self.angle_steers = CS.out.steeringAngle
        self.angle_diff = abs(self.angle_steers_des) - abs(self.angle_steers)

        if abs(self.outScale) >= 1 and CS.out.vEgo > 8:
            self.steerMax_prev = interp(self.angle_diff,
                                        self.angle_differ_range,
                                        self.steerMax_range)
            if self.steerMax_prev > self.steerMax:
                self.steerMax = self.steerMax_prev
            self.steerDeltaUp_prev = interp(self.angle_diff,
                                            self.angle_differ_range,
                                            self.steerDeltaUp_range)
            if self.steerDeltaUp_prev > self.steerDeltaUp:
                self.steerDeltaUp = self.steerDeltaUp_prev
            self.steerDeltaDown_prev = interp(self.angle_diff,
                                              self.angle_differ_range,
                                              self.steerDeltaDown_range)
            if self.steerDeltaDown_prev > self.steerDeltaDown:
                self.steerDeltaDown = self.steerDeltaDown_prev

        #if abs(self.outScale) >= 0.9 and CS.out.vEgo > 8:
        #  self.steerMax_timer += 1
        #  self.steerDeltaUp_timer += 1
        #  self.steerDeltaDown_timer += 1
        #  if self.steerMax_timer > 5:
        #    self.steerMax += int(CS.out.vEgo//2)
        #    self.steerMax_timer = 0
        #    if self.steerMax >= int(self.params.get('SteerMaxAdj')):
        #      self.steerMax = int(self.params.get('SteerMaxAdj'))
        #  if self.steerDeltaUp_timer > 50:
        #    self.steerDeltaUp += 1
        #    self.steerDeltaUp_timer = 0
        #    if self.steerDeltaUp >= 7:
        #      self.steerDeltaUp = 7
        #  if self.steerDeltaDown_timer > 25:
        #    self.steerDeltaDown += 1
        #    self.steerDeltaDown_timer = 0
        #    if self.steerDeltaDown >= 15:
        #      self.steerDeltaDown = 15
        else:
            self.steerMax_timer += 1
            self.steerDeltaUp_timer += 1
            self.steerDeltaDown_timer += 1
            if self.steerMax_timer > 20:
                self.steerMax -= 5
                self.steerMax_timer = 0
                if self.steerMax < int(self.params.get('SteerMaxBaseAdj')):
                    self.steerMax = int(self.params.get('SteerMaxBaseAdj'))
            if self.steerDeltaUp_timer > 100:
                self.steerDeltaUp -= 1
                self.steerDeltaUp_timer = 0
                if self.steerDeltaUp <= int(
                        self.params.get('SteerDeltaUpAdj')):
                    self.steerDeltaUp = int(self.params.get('SteerDeltaUpAdj'))
            if self.steerDeltaDown_timer > 50:
                self.steerDeltaDown -= 1
                self.steerDeltaDown_timer = 0
                if self.steerDeltaDown <= int(
                        self.params.get('SteerDeltaDownAdj')):
                    self.steerDeltaDown = int(
                        self.params.get('SteerDeltaDownAdj'))

        param.STEER_MAX = min(SteerLimitParams.STEER_MAX, self.steerMax)
        param.STEER_DELTA_UP = max(int(self.params.get('SteerDeltaUpAdj')),
                                   self.steerDeltaUp)
        param.STEER_DELTA_DOWN = max(int(self.params.get('SteerDeltaDownAdj')),
                                     self.steerDeltaDown)

        # Steering Torque
        if 0 <= self.driver_steering_torque_above_timer < 100:
            new_steer = actuators.steer * self.steerMax * (
                self.driver_steering_torque_above_timer / 100)
        else:
            new_steer = actuators.steer * self.steerMax
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    param)
        self.steer_rate_limited = new_steer != apply_steer

        CC.applyAccel = apply_accel
        CC.applySteer = apply_steer

        # SPAS limit angle extremes for safety
        if CS.spas_enabled:
            apply_steer_ang_req = clip(actuators.steerAngle,
                                       -1 * (STEER_ANG_MAX), STEER_ANG_MAX)
            # SPAS limit angle rate for safety
            if abs(self.apply_steer_ang -
                   apply_steer_ang_req) > STEER_ANG_MAX_RATE:
                if apply_steer_ang_req > self.apply_steer_ang:
                    self.apply_steer_ang += STEER_ANG_MAX_RATE
                else:
                    self.apply_steer_ang -= STEER_ANG_MAX_RATE
            else:
                self.apply_steer_ang = apply_steer_ang_req
        spas_active = CS.spas_enabled and enabled and (
            self.spas_always or CS.out.vEgo < 7.0)  # 25km/h

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        if self.opkr_maxanglelimit >= 90:
            lkas_active = enabled and abs(
                CS.out.steeringAngle
            ) < self.opkr_maxanglelimit and not spas_active
        else:
            lkas_active = enabled and not spas_active

        if ((CS.out.leftBlinker and not CS.out.rightBlinker) or
            (CS.out.rightBlinker and
             not CS.out.leftBlinker)) and CS.out.vEgo < LANE_CHANGE_SPEED_MIN:
            self.lanechange_manual_timer = 50
        if CS.out.leftBlinker and CS.out.rightBlinker:
            self.emergency_manual_timer = 50
        if self.lanechange_manual_timer:
            lkas_active = 0
        if self.lanechange_manual_timer > 0:
            self.lanechange_manual_timer -= 1
        if self.emergency_manual_timer > 0:
            self.emergency_manual_timer -= 1

        if abs(CS.out.steeringTorque
               ) > 200 and CS.out.vEgo < LANE_CHANGE_SPEED_MIN:
            self.driver_steering_torque_above = True
        else:
            self.driver_steering_torque_above = False

        if self.driver_steering_torque_above == True:
            self.driver_steering_torque_above_timer -= 1
            if self.driver_steering_torque_above_timer <= 0:
                self.driver_steering_torque_above_timer = 0
        elif self.driver_steering_torque_above == False:
            self.driver_steering_torque_above_timer += 5
            if self.driver_steering_torque_above_timer >= 100:
                self.driver_steering_torque_above_timer = 100

        if not lkas_active:
            apply_steer = 0

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        if CS.acc_active and CS.lead_distance > 149 and self.dRel < (
            (CS.out.vEgo * CV.MS_TO_KPH) +
                3) and self.vRel < -5 and CS.out.vEgo > 7:
            self.need_brake_timer += 1
            if self.need_brake_timer > 50:
                self.need_brake = True
        else:
            self.need_brake = False
            self.need_brake_timer = 0

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(lkas_active, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart,
                            self.lkas_button_on)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 55
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        if not (min_set_speed < set_speed < 255 * CV.KPH_TO_MS):
            set_speed = min_set_speed
        set_speed *= CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
            self.scc12_cnt = CS.scc12[
                "CR_VSM_Alive"] + 1 if not CS.no_radar else 0

            #TODO: fix this
            # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
            # self.scc_update_frame = frame

        # check if SCC is alive
        # if frame % 7 == 0:
        # if CS.scc11["AliveCounterACC"] == self.prev_scc_cnt:
        # if frame - self.scc_update_frame > 20 and self.scc_live:
        # self.scc_live = False
        # else:
        # self.scc_live = True
        # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
        # self.scc_update_frame = frame

        self.prev_scc_cnt = CS.scc11["AliveCounterACC"]

        self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10
        self.scc12_cnt %= 0xF

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning, 0))

        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer, frame, self.car_fingerprint,
                              apply_steer, lkas_active, CS.lkas11, sys_warning,
                              sys_state, enabled, left_lane, right_lane,
                              left_lane_warning, right_lane_warning, 1))
        if frame % 2 and CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11,
                             Buttons.NONE, enabled_speed))

        str_log1 = 'CV={:03.0f}  TQ={:03.0f}  R={:03.0f}  ST={:03.0f}/{:01.0f}/{:01.0f}'.format(
            abs(self.model_speed), abs(new_steer), self.timer1.sampleTime(),
            self.steerMax, self.steerDeltaUp, self.steerDeltaDown)
        trace1.printf1('{}  {}'.format(str_log1, self.str_log2))

        if CS.out.cruiseState.modeSel == 0 and self.mode_change_switch == 3:
            self.mode_change_timer = 50
            self.mode_change_switch = 0
        elif CS.out.cruiseState.modeSel == 1 and self.mode_change_switch == 0:
            self.mode_change_timer = 50
            self.mode_change_switch = 1
        elif CS.out.cruiseState.modeSel == 2 and self.mode_change_switch == 1:
            self.mode_change_timer = 50
            self.mode_change_switch = 2
        elif CS.out.cruiseState.modeSel == 3 and self.mode_change_switch == 2:
            self.mode_change_timer = 50
            self.mode_change_switch = 3
        if self.mode_change_timer > 0:
            self.mode_change_timer -= 1

        run_speed_ctrl = self.opkr_variablecruise and CS.acc_active and (
            CS.out.cruiseState.modeSel == 1 or CS.out.cruiseState.modeSel == 2
            or CS.out.cruiseState.modeSel == 3)
        if not run_speed_ctrl:
            if CS.out.cruiseState.modeSel == 0:
                self.steer_mode = "오파모드"
            elif CS.out.cruiseState.modeSel == 1:
                self.steer_mode = "차간+커브"
            elif CS.out.cruiseState.modeSel == 2:
                self.steer_mode = "차간ONLY"
            elif CS.out.cruiseState.modeSel == 3:
                self.steer_mode = "편도1차선"
            if CS.out.steerWarning == 0:
                self.mdps_status = "정상"
            elif CS.out.steerWarning == 1:
                self.mdps_status = "오류"
            if CS.lkas_button_on == 0:
                self.lkas_switch = "OFF"
            elif CS.lkas_button_on == 1:
                self.lkas_switch = "ON"
            else:
                self.lkas_switch = "-"
            if self.cruise_gap != CS.cruiseGapSet:
                self.cruise_gap = CS.cruiseGapSet
            if CS.lead_distance < 149:
                self.leadcar_status = "O"
            else:
                self.leadcar_status = "-"

            str_log2 = 'MODE={:s}  MDPS={:s}  LKAS={:s}  CSG={:1.0f}  LEAD={:s}'.format(
                self.steer_mode, self.mdps_status, self.lkas_switch,
                self.cruise_gap, self.leadcar_status)
            trace1.printf2('{}'.format(str_log2))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                             Buttons.CANCEL, clu11_speed))

        if CS.out.cruiseState.standstill:
            self.standstill_status = 1
            if self.opkr_autoresumeoption == 1 and self.opkr_autoresume:
                # run only first time when the car stopped
                if self.last_lead_distance == 0:
                    # get the lead distance from the Radar
                    self.last_lead_distance = CS.lead_distance
                    self.resume_cnt = 0
                    self.res_switch_timer = 0
                    self.standstill_fault_reduce_timer += 1
                elif self.res_switch_timer > 0:
                    self.res_switch_timer -= 1
                    self.standstill_fault_reduce_timer += 1
                # standstill 진입하자마자 바로 누르지 말고 최소 1초의 딜레이를 주기 위함
                elif 100 < self.standstill_fault_reduce_timer and CS.lead_distance != self.last_lead_distance:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.RES_ACCEL, clu11_speed))
                    self.resume_cnt += 1
                    if self.resume_cnt > 5:
                        self.resume_cnt = 0
                        self.res_switch_timer = randint(10, 15)
                    self.standstill_fault_reduce_timer += 1
                # gap save
                elif 160 < self.standstill_fault_reduce_timer and self.cruise_gap_prev == 0 and self.opkr_autoresume:
                    self.cruise_gap_prev = CS.cruiseGapSet
                    self.cruise_gap_set_init = 1
                # gap adjust to 1 for fast start
                elif 160 < self.standstill_fault_reduce_timer and CS.cruiseGapSet != 1.0 and self.opkr_autoresume:
                    self.cruise_gap_switch_timer += 1
                    if self.cruise_gap_switch_timer > 100:
                        can_sends.append(
                            create_clu11(self.packer, frame, CS.scc_bus,
                                         CS.clu11, Buttons.GAP_DIST,
                                         clu11_speed))
                        self.cruise_gap_switch_timer = 0
                elif self.opkr_autoresume:
                    self.standstill_fault_reduce_timer += 1
            elif self.opkr_autoresumeoption == 0 and self.opkr_autoresume:
                # run only first time when the car stopped
                if self.last_lead_distance == 0:
                    # get the lead distance from the Radar
                    self.last_lead_distance = CS.lead_distance
                    self.resume_cnt = 0
                # when lead car starts moving, create 6 RES msgs
                elif CS.lead_distance != self.last_lead_distance and (
                        frame -
                        self.last_resume_frame) > 5 and self.opkr_autoresume:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.RES_ACCEL, clu11_speed))
                    self.resume_cnt += 1
                    # interval after 6 msgs
                    if self.resume_cnt > 5:
                        self.last_resume_frame = frame
                        self.resume_cnt = 0
                elif self.cruise_gap_prev == 0 and self.opkr_autoresume:
                    self.cruise_gap_prev = CS.cruiseGapSet
                    self.cruise_gap_set_init = 1
                elif CS.cruiseGapSet != 1.0 and self.opkr_autoresume:
                    self.cruise_gap_switch_timer += 1
                    if self.cruise_gap_switch_timer > 100:
                        can_sends.append(
                            create_clu11(self.packer, frame, CS.scc_bus,
                                         CS.clu11, Buttons.GAP_DIST,
                                         clu11_speed))
                        self.cruise_gap_switch_timer = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0
        elif run_speed_ctrl:
            is_sc_run = self.SC.update(CS, sm, self)
            if is_sc_run:
                can_sends.append(
                    create_clu11(self.packer, self.resume_cnt, CS.scc_bus,
                                 CS.clu11, self.SC.btn_type,
                                 self.SC.sc_clu_speed))
                self.resume_cnt += 1
            else:
                self.resume_cnt = 0
            # gap restore
            if self.dRel > 17 and self.vRel < 5 and self.cruise_gap_prev != CS.cruiseGapSet and self.cruise_gap_set_init == 1 and self.opkr_autoresume:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 50:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0
            elif self.cruise_gap_prev == CS.cruiseGapSet and self.opkr_autoresume:
                self.cruise_gap_set_init = 0
                self.cruise_gap_prev = 0
            #if CS.out.vEgo > 8 and self.lead2_status and self.dRel - self.dRel2 > 3 and self.cut_in_detection == 0 and self.cruise_gap_prev2 == 0:
            #  self.cut_in_detection = 1
            #  self.cruise_gap_prev2 = CS.cruiseGapSet
            #elif CS.out.vEgo > 8 and self.cut_in_detection == 1 and CS.cruiseGapSet != 1.0:
            #  self.cruise_gap_switch_timer2 += 1
            #  if self.cruise_gap_switch_timer2 > 150:
            #    can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.GAP_DIST, clu11_speed))
            #    self.cruise_gap_switch_timer2 = 0
            #elif CS.out.vEgo > 8 and self.cut_in_detection == 1 and CS.cruiseGapSet == 1.0:
            #  self.cruise_gap_switch_timer2 += 1
            #  if self.cruise_gap_switch_timer2 > 600:
            #    if self.cruise_gap_prev2 != CS.cruiseGapSet:
            #      self.cruise_gap_switch_timer3 += 1
            #      if self.cruise_gap_switch_timer3 > 50:
            #        can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.GAP_DIST, clu11_speed))
            #        self.cruise_gap_switch_timer3 = 0
            #elif self.cruise_gap_prev2 == CS.cruiseGapSet:
            #  self.cut_in_detection == 0
            #  self.cruise_gap_prev2 = 0
            #  self.cruise_gap_switch_timer2 = 0
            #  self.cruise_gap_switch_timer3 = 0

        if CS.out.brakeLights and CS.out.vEgo == 0 and not CS.acc_active:
            self.standstill_status_timer += 1
            if self.standstill_status_timer > 200:
                self.standstill_status = 1
                self.standstill_status_timer = 0
        if self.standstill_status == 1 and CS.out.vEgo > 1:
            self.standstill_status = 0
            self.standstill_fault_reduce_timer = 0
            self.v_set_dis_prev = 180
            self.last_resume_frame = frame
            self.res_switch_timer = 0
            self.resume_cnt = 0

        if CS.mdps_bus:  # send mdps12 to LKAS to prevent LKAS error
            can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
        if self.longcontrol and (CS.scc_bus
                                 or not self.scc_live) and frame % 2 == 0:
            can_sends.append(
                create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt,
                             self.scc_live, CS.scc12))
            can_sends.append(
                create_scc11(self.packer, frame, enabled, set_speed,
                             lead_visible, self.scc_live, CS.scc11))
            if CS.has_scc13 and frame % 20 == 0:
                can_sends.append(create_scc13(self.packer, CS.scc13))
            if CS.has_scc14:
                can_sends.append(create_scc14(self.packer, enabled, CS.scc14))
            self.scc12_cnt += 1

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfa_mfa"]:
            can_sends.append(create_lfa_mfa(self.packer, frame, lkas_active))

        if CS.spas_enabled:
            if CS.mdps_bus:
                can_sends.append(
                    create_ems11(self.packer, CS.ems11, spas_active))

            # SPAS11 50hz
            if (frame % 2) == 0:
                if CS.mdps11_stat == 7 and not self.mdps11_stat_last == 7:
                    self.en_spas = 7
                    self.en_cnt = 0

                if self.en_spas == 7 and self.en_cnt >= 8:
                    self.en_spas = 3
                    self.en_cnt = 0

                if self.en_cnt < 8 and spas_active:
                    self.en_spas = 4
                elif self.en_cnt >= 8 and spas_active:
                    self.en_spas = 5

                if not spas_active:
                    self.apply_steer_ang = CS.mdps11_strang
                    self.en_spas = 3
                    self.en_cnt = 0

                self.mdps11_stat_last = CS.mdps11_stat
                self.en_cnt += 1
                can_sends.append(
                    create_spas11(self.packer, self.car_fingerprint,
                                  (frame // 2), self.en_spas,
                                  self.apply_steer_ang, CS.mdps_bus))

            # SPAS12 20Hz
            if (frame % 5) == 0:
                can_sends.append(create_spas12(CS.mdps_bus))

        return can_sends
예제 #19
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_line, right_line, left_lane_depart,
               right_lane_depart):

        # *** compute control surfaces ***

        # gas and brake
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

        ### Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.steer_torque_driver,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        ### LKAS button to temporarily disable steering
        if not CS.lkas_error:
            if CS.lkas_button_on != self.lkas_button_last:
                self.lkas_button = not self.lkas_button
            self.lkas_button_last = CS.lkas_button_on

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        if self.car_fingerprint == CAR.GENESIS:
            lkas_active = enabled and abs(
                CS.angle_steers) < 90. and self.lkas_button
        else:
            lkas_active = enabled and self.lkas_button

        # Fix for sharp turns mdps fault and Genesis hard fault at low speed
        if CS.v_ego < 13.7 and self.car_fingerprint == CAR.GENESIS and not CS.mdps_bus:
            self.turning_signal_timer = 100
        if ((CS.left_blinker_flash or CS.right_blinker_flash)
                and (CS.steer_override or abs(CS.angle_steers) > 10.)
                and CS.v_ego <
                17.5):  # Disable steering when blinker on and belwo ALC speed
            self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off
        if self.turning_signal_timer:
            lkas_active = 0
            self.turning_signal_timer -= 1
        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        hud_alert, lane_visible, left_lane_warning, right_lane_warning =\
                process_hud_alert(lkas_active, self.lkas_button, self.car_fingerprint, visual_alert,
                left_line, right_line,left_lane_depart, right_lane_depart)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 34 if CS.is_set_speed_in_mph else 55
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        can_sends = []

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1
            self.scc12_cnt = CS.scc12[
                "CR_VSM_Alive"] + 1 if not CS.no_radar else 0

        self.lkas11_cnt %= 0x10
        self.scc12_cnt %= 0xF
        self.clu11_cnt = frame % 0x10
        self.mdps12_cnt = frame % 0x100

        can_sends.append(
            create_lkas11(self.packer,
                          self.car_fingerprint,
                          0,
                          apply_steer,
                          steer_req,
                          self.lkas11_cnt,
                          lkas_active,
                          CS.lkas11,
                          hud_alert,
                          lane_visible,
                          left_lane_depart,
                          right_lane_depart,
                          keep_stock=True))
        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas12 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer,
                              self.car_fingerprint,
                              1,
                              apply_steer,
                              steer_req,
                              self.lkas11_cnt,
                              lkas_active,
                              CS.lkas11,
                              hud_alert,
                              lane_visible,
                              left_lane_depart,
                              right_lane_depart,
                              keep_stock=True))
        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, CS.mdps_bus, CS.clu11, Buttons.NONE,
                             enabled_speed, self.clu11_cnt))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, CS.scc_bus, CS.clu11, Buttons.CANCEL,
                             clu11_speed, self.clu11_cnt))
        else:  # send mdps12 to LKAS to prevent LKAS error if no cancel cmd
            can_sends.append(
                create_mdps12(self.packer, self.car_fingerprint,
                              self.mdps12_cnt, CS.mdps12))

        if CS.scc_bus and self.longcontrol and frame % 2:  # send scc12 to car if SCC not on bus 0 and longcontrol enabled
            can_sends.append(
                create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt,
                             CS.scc12))
            self.scc12_cnt += 1

        if CS.stopped:
            # run only first time when the car stopped
            if self.last_lead_distance == 0:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance > self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed,
                                 self.resume_cnt))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0

        self.lkas11_cnt += 1

        return can_sends
예제 #20
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart, set_speed, lead_visible, lead_dist,
               lead_vrel, lead_yrel, sm):

        # *** compute control surfaces ***

        # gas and brake
        self.accel_lim_prev = self.accel_lim
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

        self.accel_lim = apply_accel
        apply_accel = accel_rate_limit(self.accel_lim, self.accel_lim_prev)

        param = self.p

        #self.model_speed = 255 - self.SC.calc_va(sm, CS.out.vEgo)
        #atom model_speed
        #self.model_speed = self.SC.cal_model_speed(sm, CS.out.vEgo)
        if frame % 10 == 0:
            self.curve_speed = self.SC.cal_curve_speed(sm, CS.out.vEgo)

        plan = sm['longitudinalPlan']
        self.dRel = int(plan.dRel1)  #EON Lead
        self.yRel = int(plan.yRel1)  #EON Lead
        self.vRel = int(plan.vRel1 * 3.6 + 0.5)  #EON Lead
        self.dRel2 = int(plan.dRel2)  #EON Lead
        self.yRel2 = int(plan.yRel2)  #EON Lead
        self.vRel2 = int(plan.vRel2 * 3.6 + 0.5)  #EON Lead
        self.lead2_status = plan.status2

        lateral_plan = sm['lateralPlan']
        self.outScale = lateral_plan.outputScale
        self.vCruiseSet = lateral_plan.vCruiseSet

        #self.model_speed = interp(abs(lateral_plan.vCurvature), [0.0002, 0.01], [255, 30])
        #Hoya
        self.model_speed = interp(abs(lateral_plan.vCurvature),
                                  [0.0, 0.0002, 0.00074, 0.0025, 0.008, 0.02],
                                  [255, 255, 130, 90, 60, 20])

        if CS.out.vEgo > 8:
            if self.variable_steer_max:
                self.steerMax = interp(int(abs(self.model_speed)),
                                       self.model_speed_range,
                                       self.steerMax_range)
            else:
                self.steerMax = self.steerMax_base
            if self.variable_steer_delta:
                self.steerDeltaUp = interp(int(abs(self.model_speed)),
                                           self.model_speed_range,
                                           self.steerDeltaUp_range)
                self.steerDeltaDown = interp(int(abs(self.model_speed)),
                                             self.model_speed_range,
                                             self.steerDeltaDown_range)
            else:
                self.steerDeltaUp = self.steerDeltaUp_base
                self.steerDeltaDown = self.steerDeltaDown_base
        else:
            self.steerMax = self.steerMax_base
            self.steerDeltaUp = self.steerDeltaUp_base
            self.steerDeltaDown = self.steerDeltaDown_base

        param.STEER_MAX = min(CarControllerParams.STEER_MAX,
                              self.steerMax)  # variable steermax
        param.STEER_DELTA_UP = min(CarControllerParams.STEER_DELTA_UP,
                                   self.steerDeltaUp)  # variable deltaUp
        param.STEER_DELTA_DOWN = min(CarControllerParams.STEER_DELTA_DOWN,
                                     self.steerDeltaDown)  # variable deltaDown

        # Steering Torque
        if 0 <= self.driver_steering_torque_above_timer < 100:
            new_steer = int(
                round(actuators.steer * self.steerMax *
                      (self.driver_steering_torque_above_timer / 100)))
        else:
            new_steer = int(round(actuators.steer * self.steerMax))
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    param)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        if self.opkr_maxanglelimit >= 90 and not self.steer_wind_down_enabled:
            lkas_active = enabled and abs(
                CS.out.steeringAngleDeg
            ) < self.opkr_maxanglelimit and CS.out.gearShifter == GearShifter.drive
        else:
            lkas_active = enabled and not CS.out.steerWarning and CS.out.gearShifter == GearShifter.drive

        if (
            (CS.out.leftBlinker and not CS.out.rightBlinker) or
            (CS.out.rightBlinker and not CS.out.leftBlinker)
        ) and CS.out.vEgo < LANE_CHANGE_SPEED_MIN and self.opkr_turnsteeringdisable:
            self.lanechange_manual_timer = 50
        if CS.out.leftBlinker and CS.out.rightBlinker:
            self.emergency_manual_timer = 50
        if self.lanechange_manual_timer:
            lkas_active = 0
        if self.lanechange_manual_timer > 0:
            self.lanechange_manual_timer -= 1
        if self.emergency_manual_timer > 0:
            self.emergency_manual_timer -= 1

        if abs(CS.out.steeringTorque
               ) > 180 and CS.out.vEgo < LANE_CHANGE_SPEED_MIN:
            self.driver_steering_torque_above = True
        else:
            self.driver_steering_torque_above = False

        if self.driver_steering_torque_above == True:
            self.driver_steering_torque_above_timer -= 1
            if self.driver_steering_torque_above_timer <= 0:
                self.driver_steering_torque_above_timer = 0
        elif self.driver_steering_torque_above == False:
            self.driver_steering_torque_above_timer += 5
            if self.driver_steering_torque_above_timer >= 100:
                self.driver_steering_torque_above_timer = 100

        if not lkas_active:
            apply_steer = 0
            if self.apply_steer_last != 0:
                self.steer_wind_down = 1
        if lkas_active or CS.out.steeringPressed:
            self.steer_wind_down = 0

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        if CS.acc_active and CS.lead_distance > 149 and self.dRel < ((CS.out.vEgo * CV.MS_TO_KPH)+5) < 100 and \
         self.vRel < -(CS.out.vEgo * CV.MS_TO_KPH * 0.16) and CS.out.vEgo > 7 and abs(CS.out.steeringAngleDeg) < 10 and not self.longcontrol:
            self.need_brake_timer += 1
            if self.need_brake_timer > 50:
                self.need_brake = True
        else:
            self.need_brake = False
            self.need_brake_timer = 0

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(lkas_active, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed or not lkas_active or CS.out.gearShifter != GearShifter.drive:
            enabled_speed = clu11_speed

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, self.steer_wind_down,
                          CS.lkas11, sys_warning, sys_state, enabled,
                          left_lane, right_lane, left_lane_warning,
                          right_lane_warning, 0, self.ldws_fix,
                          self.steer_wind_down_enabled))

        if CS.CP.mdpsBus:  # send lkas11 bus 1 if mdps is bus 1
            can_sends.append(
                create_lkas11(self.packer, frame, self.car_fingerprint,
                              apply_steer, lkas_active, self.steer_wind_down,
                              CS.lkas11, sys_warning, sys_state, enabled,
                              left_lane, right_lane, left_lane_warning,
                              right_lane_warning, 1, self.ldws_fix,
                              self.steer_wind_down_enabled))
            if frame % 2:  # send clu11 to mdps if it is not on bus 0
                can_sends.append(
                    create_clu11(self.packer, frame, CS.clu11, Buttons.NONE,
                                 enabled_speed, CS.CP.mdpsBus))

        if CS.out.cruiseState.modeSel == 0 and self.mode_change_switch == 4:
            self.mode_change_timer = 50
            self.mode_change_switch = 0
        elif CS.out.cruiseState.modeSel == 1 and self.mode_change_switch == 0:
            self.mode_change_timer = 50
            self.mode_change_switch = 1
        elif CS.out.cruiseState.modeSel == 2 and self.mode_change_switch == 1:
            self.mode_change_timer = 50
            self.mode_change_switch = 2
        elif CS.out.cruiseState.modeSel == 3 and self.mode_change_switch == 2:
            self.mode_change_timer = 50
            self.mode_change_switch = 3
        elif CS.out.cruiseState.modeSel == 4 and self.mode_change_switch == 3:
            self.mode_change_timer = 50
            self.mode_change_switch = 4
        if self.mode_change_timer > 0:
            self.mode_change_timer -= 1

        run_speed_ctrl = self.opkr_variablecruise and CS.acc_active and (
            CS.out.cruiseState.modeSel > 0)
        if not run_speed_ctrl:
            if CS.out.cruiseState.modeSel == 0:
                self.steer_mode = "오파모드"
            elif CS.out.cruiseState.modeSel == 1:
                self.steer_mode = "차간+커브"
            elif CS.out.cruiseState.modeSel == 2:
                self.steer_mode = "차간ONLY"
            elif CS.out.cruiseState.modeSel == 3:
                self.steer_mode = "편도1차선"
            elif CS.out.cruiseState.modeSel == 4:
                self.steer_mode = "맵감속ONLY"
            if CS.out.steerWarning == 0:
                self.mdps_status = "정상"
            elif CS.out.steerWarning == 1:
                self.mdps_status = "오류"
            if CS.lkas_button_on == 0:
                self.lkas_switch = "OFF"
            elif CS.lkas_button_on == 1:
                self.lkas_switch = "ON"
            else:
                self.lkas_switch = "-"
            if self.cruise_gap != CS.cruiseGapSet:
                self.cruise_gap = CS.cruiseGapSet
            if CS.lead_distance < 149:
                self.leadcar_status = "O"
            else:
                self.leadcar_status = "-"

            str_log2 = 'MODE={:s}  MDPS={:s}  LKAS={:s}  CSG={:1.0f}  LEAD={:s}  FR={:03.0f}'.format(self.steer_mode, \
             self.mdps_status, self.lkas_switch, self.cruise_gap, self.leadcar_status, self.timer1.sampleTime())
            trace1.printf2('{}'.format(str_log2))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL,
                             clu11_speed, CS.CP.sccBus))

        if CS.out.cruiseState.standstill:
            self.standstill_status = 1
            if self.opkr_autoresume:
                # run only first time when the car stopped
                if self.last_lead_distance == 0:
                    # get the lead distance from the Radar
                    self.last_lead_distance = CS.lead_distance
                    self.resume_cnt = 0
                    self.res_switch_timer = 0
                    self.standstill_fault_reduce_timer += 1
                elif self.res_switch_timer > 0:
                    self.res_switch_timer -= 1
                    self.standstill_fault_reduce_timer += 1
                # at least 1 sec delay after entering the standstill
                elif 100 < self.standstill_fault_reduce_timer and CS.lead_distance != self.last_lead_distance:
                    self.acc_standstill_timer = 0
                    self.acc_standstill = False
                    can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL)) if not self.longcontrol \
                     else can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL, clu11_speed, CS.CP.sccBus))
                    self.resume_cnt += 1
                    if self.resume_cnt > 5:
                        self.resume_cnt = 0
                        self.res_switch_timer = randint(10, 15)
                    self.standstill_fault_reduce_timer += 1
                # gap save
                elif 160 < self.standstill_fault_reduce_timer and self.cruise_gap_prev == 0 and self.opkr_autoresume and self.opkr_cruisegap_auto_adj:
                    self.cruise_gap_prev = CS.cruiseGapSet
                    self.cruise_gap_set_init = 1
                # gap adjust to 1 for fast start
                elif 160 < self.standstill_fault_reduce_timer and CS.cruiseGapSet != 1.0 and self.opkr_autoresume and self.opkr_cruisegap_auto_adj:
                    self.cruise_gap_switch_timer += 1
                    if self.cruise_gap_switch_timer > 100:
                        can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.GAP_DIST)) if not self.longcontrol \
                         else can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.GAP_DIST, clu11_speed, CS.CP.sccBus))
                        self.cruise_gap_switch_timer = 0
                elif self.opkr_autoresume:
                    self.standstill_fault_reduce_timer += 1
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0
        elif run_speed_ctrl:
            is_sc_run = self.SC.update(CS, sm, self)
            if is_sc_run:
                can_sends.append(create_clu11(self.packer, self.resume_cnt, CS.clu11, self.SC.btn_type, self.SC.sc_clu_speed)) if not self.longcontrol \
                 else can_sends.append(create_clu11(self.packer, self.resume_cnt, CS.clu11, self.SC.btn_type, self.SC.sc_clu_speed, CS.CP.sccBus))
                self.resume_cnt += 1
            else:
                self.resume_cnt = 0
            if self.opkr_cruisegap_auto_adj:
                # gap restore
                if self.dRel > 17 and self.vRel < 5 and self.cruise_gap_prev != CS.cruiseGapSet and self.cruise_gap_set_init == 1 and self.opkr_autoresume:
                    self.cruise_gap_switch_timer += 1
                    if self.cruise_gap_switch_timer > 50:
                        can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.GAP_DIST)) if not self.longcontrol \
                         else can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.GAP_DIST, clu11_speed, CS.CP.sccBus))
                        self.cruise_gap_switch_timer = 0
                elif self.cruise_gap_prev == CS.cruiseGapSet and self.opkr_autoresume:
                    self.cruise_gap_set_init = 0
                    self.cruise_gap_prev = 0

        if CS.cruise_buttons == 4:
            self.cancel_counter += 1
        elif CS.acc_active:
            self.cancel_counter = 0
            if self.res_speed_timer > 0:
                self.res_speed_timer -= 1
            else:
                self.v_cruise_kph_auto_res = 0
                self.res_speed = 0

        if self.model_speed > 95 and self.cancel_counter == 0 and not CS.acc_active and not CS.out.brakeLights and int(CS.VSetDis) > 30 and \
         (CS.lead_distance < 149 or int(CS.clu_Vanz) > 30) and int(CS.clu_Vanz) >= 3 and self.auto_res_timer <= 0 and self.opkr_cruise_auto_res:
            if self.opkr_cruise_auto_res_option == 0:
                can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL)) if not self.longcontrol \
                 else can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL, clu11_speed, CS.CP.sccBus))  # auto res
                self.res_speed = int(CS.clu_Vanz * 1.1)
                self.res_speed_timer = 350
            elif self.opkr_cruise_auto_res_option == 1:
                can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.SET_DECEL)) if not self.longcontrol \
                 else can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.SET_DECEL, clu11_speed, CS.CP.sccBus)) # auto res but set_decel to set current speed
                self.v_cruise_kph_auto_res = int(CS.clu_Vanz)
                self.res_speed_timer = 50
            if self.auto_res_timer <= 0:
                self.auto_res_timer = randint(10, 15)
        elif self.auto_res_timer > 0 and self.opkr_cruise_auto_res:
            self.auto_res_timer -= 1

        if CS.out.brakeLights and CS.out.vEgo == 0 and not CS.acc_active:
            self.standstill_status_timer += 1
            if self.standstill_status_timer > 200:
                self.standstill_status = 1
                self.standstill_status_timer = 0
        if self.standstill_status == 1 and CS.out.vEgo > 1:
            self.standstill_status = 0
            self.standstill_fault_reduce_timer = 0
            self.last_resume_frame = frame
            self.res_switch_timer = 0
            self.resume_cnt = 0

        if CS.out.vEgo <= 1:
            self.sm.update(0)
            long_control_state = self.sm['controlsState'].longControlState
            if long_control_state == LongCtrlState.stopping and CS.out.vEgo < 0.1 and not CS.out.gasPressed:
                self.acc_standstill_timer += 1
                if self.acc_standstill_timer >= 200:
                    self.acc_standstill_timer = 200
                    self.acc_standstill = True
            else:
                self.acc_standstill_timer = 0
                self.acc_standstill = False
        elif CS.out.gasPressed or CS.out.vEgo > 1:
            self.acc_standstill = False
            self.acc_standstill_timer = 0
        else:
            self.acc_standstill = False
            self.acc_standstill_timer = 0

        if CS.CP.mdpsBus:  # send mdps12 to LKAS to prevent LKAS error
            can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        if CS.CP.sccBus != 0 and self.counter_init and self.longcontrol:
            if frame % 2 == 0:
                self.scc12cnt += 1
                self.scc12cnt %= 0xF
                self.scc11cnt += 1
                self.scc11cnt %= 0x10
                self.fca11supcnt += 1
                self.fca11supcnt %= 0xF
                if self.fca11alivecnt == 1:
                    self.fca11inc = 0
                    if self.fca11cnt13 == 3:
                        self.fca11maxcnt = 0x9
                        self.fca11cnt13 = 0
                    else:
                        self.fca11maxcnt = 0xD
                        self.fca11cnt13 += 1
                else:
                    self.fca11inc += 4
                self.fca11alivecnt = self.fca11maxcnt - self.fca11inc
                lead_objspd = CS.lead_objspd  # vRel (km/h)
                aReqValue = CS.scc12["aReqValue"]
                if 0 < CS.out.radarDistance <= 149:
                    if aReqValue > 0.:
                        stock_weight = interp(CS.out.radarDistance, [3., 25.],
                                              [0.8, 0.])
                    elif aReqValue < 0.:
                        stock_weight = interp(CS.out.radarDistance, [3., 25.],
                                              [1., 0.])
                        if lead_objspd < 0:
                            vRel_weight = interp(abs(lead_objspd), [0, 25],
                                                 [1, 2])
                            stock_weight = interp(
                                CS.out.radarDistance,
                                [3.**vRel_weight, 25. * vRel_weight], [1., 0.])
                    else:
                        stock_weight = 0.
                    apply_accel = apply_accel * (
                        1. - stock_weight) + aReqValue * stock_weight
                else:
                    stock_weight = 0.
                can_sends.append(
                    create_scc11(self.packer, frame, set_speed, lead_visible,
                                 self.scc_live, lead_dist, lead_vrel,
                                 lead_yrel, self.car_fingerprint,
                                 CS.out.vEgo * CV.MS_TO_KPH,
                                 self.acc_standstill, CS.scc11))
                if (CS.brake_check
                        or CS.cancel_check) and self.car_fingerprint not in [
                            CAR.NIRO_EV
                        ]:
                    can_sends.append(
                        create_scc12(self.packer, apply_accel, enabled,
                                     self.scc_live, CS.out.gasPressed, 1,
                                     CS.out.stockAeb, self.car_fingerprint,
                                     CS.out.vEgo * CV.MS_TO_KPH, CS.scc12))
                else:
                    can_sends.append(
                        create_scc12(self.packer, apply_accel, enabled,
                                     self.scc_live, CS.out.gasPressed,
                                     CS.out.brakePressed, CS.out.stockAeb,
                                     self.car_fingerprint,
                                     CS.out.vEgo * CV.MS_TO_KPH, CS.scc12))
                can_sends.append(
                    create_scc14(self.packer, enabled, CS.scc14,
                                 CS.out.stockAeb, lead_visible, lead_dist,
                                 CS.out.vEgo, self.acc_standstill,
                                 self.car_fingerprint))
                if CS.CP.fcaBus == -1:
                    can_sends.append(
                        create_fca11(self.packer, CS.fca11, self.fca11alivecnt,
                                     self.fca11supcnt))
            if frame % 20 == 0:
                can_sends.append(create_scc13(self.packer, CS.scc13))
                if CS.CP.fcaBus == -1:
                    can_sends.append(create_fca12(self.packer))
            if frame % 50 == 0:
                can_sends.append(create_scc42a(self.packer))
        elif CS.CP.sccBus == 2 and self.longcontrol:
            self.counter_init = True
            self.scc12cnt = CS.scc12init["CR_VSM_Alive"]
            self.scc11cnt = CS.scc11init["AliveCounterACC"]
            self.fca11alivecnt = CS.fca11init["CR_FCA_Alive"]
            self.fca11supcnt = CS.fca11init["Supplemental_Counter"]

        aq_value = CS.scc12["aReqValue"] if CS.CP.sccBus == 0 else apply_accel
        if self.apks_enabled:
            str_log1 = 'M/C={:03.0f}/{:03.0f}  TQ={:03.0f}  ST={:03.0f}/{:01.0f}/{:01.0f}  AQ={:+04.2f}'.format(abs(self.model_speed), self.curve_speed, \
             abs(new_steer), max(self.steerMax, abs(new_steer)), self.steerDeltaUp, self.steerDeltaDown, aq_value)
        else:
            str_log1 = 'M/C={:03.0f}/{:03.0f}  TQ={:03.0f}  ST={:03.0f}/{:01.0f}/{:01.0f}  AQ={:+04.2f}  S={:.0f}/{:.0f}'.format(abs(self.model_speed), self.curve_speed, \
             abs(new_steer), max(self.steerMax, abs(new_steer)), self.steerDeltaUp, self.steerDeltaDown, aq_value, int(CS.is_highway), CS.safety_sign_check)

        trace1.printf1('{}  {}'.format(str_log1, self.str_log2))

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in FEATURES[
                "send_lfahda_mfa"]:
            can_sends.append(create_lfahda_mfc(self.packer, frame,
                                               lkas_active))

        return can_sends
예제 #21
0
  def update(self, enabled, CS, frame, CC, actuators, pcm_cancel_cmd, visual_alert,
             left_lane, right_lane, left_lane_depart, right_lane_depart, set_speed, lead_visible, sm):

    # *** compute control surfaces ***

    # gas and brake
    apply_accel = actuators.gas - actuators.brake

    apply_accel, self.accel_steady = accel_hysteresis(apply_accel, self.accel_steady)
    apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

    param = self.p

    #self.model_speed = 255 - self.SC.calc_va(sm, CS.out.vEgo)
    #atom model_speed
    #self.model_speed = self.SC.cal_model_speed(sm, CS.out.vEgo)
    #self.curve_speed = self.SC.cal_curve_speed(sm, CS.out.vEgo, frame)

    plan = sm['longitudinalPlan']
    self.dRel = int(plan.dRel1) #EON Lead
    self.yRel = int(plan.yRel1) #EON Lead
    self.vRel = int(plan.vRel1 * 3.6 + 0.5) #EON Lead
    self.dRel2 = int(plan.dRel2) #EON Lead
    self.yRel2 = int(plan.yRel2) #EON Lead
    self.vRel2 = int(plan.vRel2 * 3.6 + 0.5) #EON Lead
    self.lead2_status = plan.status2
    self.target_map_speed_camera = plan.targetSpeedCamera
    
    self.accActive = CS.acc_active

    lateral_plan = sm['lateralPlan']
    self.outScale = lateral_plan.outputScale
    self.vCruiseSet = lateral_plan.vCruiseSet
    
    #self.model_speed = interp(abs(lateral_plan.vCurvature), [0.0002, 0.01], [255, 30])
    #Hoya
    self.model_speed = interp(abs(lateral_plan.vCurvature), [0.0, 0.0002, 0.00074, 0.0025, 0.008, 0.02], [255, 255, 130, 90, 60, 20])

    if CS.out.vEgo > 8:
      if self.variable_steer_max:
        self.steerMax = interp(int(abs(self.model_speed)), self.model_speed_range, self.steerMax_range)
      else:
        self.steerMax = int(self.params.get("SteerMaxBaseAdj", encoding='utf8'))
      if self.variable_steer_delta:
        self.steerDeltaUp = interp(int(abs(self.model_speed)), self.model_speed_range, self.steerDeltaUp_range)
        self.steerDeltaDown = interp(int(abs(self.model_speed)), self.model_speed_range, self.steerDeltaDown_range)
      else:
        self.steerDeltaUp = int(self.params.get("SteerDeltaUpBaseAdj", encoding='utf8'))
        self.steerDeltaDown = int(self.params.get("SteerDeltaDownBaseAdj", encoding='utf8'))
    else:
      self.steerMax = int(self.params.get("SteerMaxBaseAdj", encoding='utf8'))
      self.steerDeltaUp = int(self.params.get("SteerDeltaUpBaseAdj", encoding='utf8'))
      self.steerDeltaDown = int(self.params.get("SteerDeltaDownBaseAdj", encoding='utf8'))

    param.STEER_MAX = min(CarControllerParams.STEER_MAX, self.steerMax) # variable steermax
    param.STEER_DELTA_UP = min(CarControllerParams.STEER_DELTA_UP, self.steerDeltaUp) # variable deltaUp
    param.STEER_DELTA_DOWN = min(CarControllerParams.STEER_DELTA_DOWN, self.steerDeltaDown) # variable deltaDown
    #param.STEER_DELTA_UP = CarControllerParams.STEER_DELTA_UP # fixed deltaUp
    #param.STEER_DELTA_DOWN = CarControllerParams.STEER_DELTA_DOWN # fixed deltaDown

    # Steering Torque
    if 0 <= self.driver_steering_torque_above_timer < 100:
      new_steer = int(round(actuators.steer * self.steerMax * (self.driver_steering_torque_above_timer / 100)))
    else:
      new_steer = int(round(actuators.steer * self.steerMax))
    apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, param)
    self.steer_rate_limited = new_steer != apply_steer

    # SPAS limit angle extremes for safety
    if CS.spas_enabled:
      apply_steer_ang_req = clip(actuators.steeringAngleDeg, -1*(STEER_ANG_MAX), STEER_ANG_MAX)
      # SPAS limit angle rate for safety
      if abs(self.apply_steer_ang - apply_steer_ang_req) > STEER_ANG_MAX_RATE:
        if apply_steer_ang_req > self.apply_steer_ang:
          self.apply_steer_ang += STEER_ANG_MAX_RATE
        else:
          self.apply_steer_ang -= STEER_ANG_MAX_RATE
      else:
        self.apply_steer_ang = apply_steer_ang_req
    spas_active = CS.spas_enabled and enabled and (self.spas_always or CS.out.vEgo < 7.0) # 25km/h

    # disable if steer angle reach 90 deg, otherwise mdps fault in some models
    if self.opkr_maxanglelimit >= 90:
      lkas_active = enabled and abs(CS.out.steeringAngleDeg) < self.opkr_maxanglelimit and not spas_active
    else:
      lkas_active = enabled and not spas_active

    if (( CS.out.leftBlinker and not CS.out.rightBlinker) or ( CS.out.rightBlinker and not CS.out.leftBlinker)) and CS.out.vEgo < LANE_CHANGE_SPEED_MIN and self.opkr_turnsteeringdisable:
      self.lanechange_manual_timer = 50
    if CS.out.leftBlinker and CS.out.rightBlinker:
      self.emergency_manual_timer = 50
    if self.lanechange_manual_timer:
      lkas_active = 0
    if self.lanechange_manual_timer > 0:
      self.lanechange_manual_timer -= 1
    if self.emergency_manual_timer > 0:
      self.emergency_manual_timer -= 1

    if abs(CS.out.steeringTorque) > 180 and CS.out.vEgo < LANE_CHANGE_SPEED_MIN:
      self.driver_steering_torque_above = True
    else:
      self.driver_steering_torque_above = False

    if self.driver_steering_torque_above == True:
      self.driver_steering_torque_above_timer -= 1
      if self.driver_steering_torque_above_timer <= 0:
        self.driver_steering_torque_above_timer = 0
    elif self.driver_steering_torque_above == False:
      self.driver_steering_torque_above_timer += 5
      if self.driver_steering_torque_above_timer >= 100:
        self.driver_steering_torque_above_timer = 100

    if not lkas_active:
      apply_steer = 0

    self.apply_accel_last = apply_accel
    self.apply_steer_last = apply_steer

    if CS.acc_active and CS.lead_distance > 149 and self.dRel < ((CS.out.vEgo * CV.MS_TO_KPH)+5) < 100 and self.vRel < -5 and CS.out.vEgo > 7 and abs(lateral_plan.steerAngleDesireDeg) < 15:
      self.need_brake_timer += 1
      if self.need_brake_timer > 50:
        self.need_brake = True
    else:
      self.need_brake = False
      self.need_brake_timer = 0

    sys_warning, sys_state, left_lane_warning, right_lane_warning =\
      process_hud_alert(lkas_active, self.car_fingerprint, visual_alert,
                        left_lane, right_lane, left_lane_depart, right_lane_depart,
                        self.lkas_button_on)

    clu11_speed = CS.clu11["CF_Clu_Vanz"]
    enabled_speed = 38 if CS.is_set_speed_in_mph  else 55
    if clu11_speed > enabled_speed or not lkas_active:
      enabled_speed = clu11_speed

    if not(min_set_speed < set_speed < 255 * CV.KPH_TO_MS):
      set_speed = min_set_speed 
    set_speed *= CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

    if frame == 0: # initialize counts from last received count signals
      self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
      self.scc12_cnt = CS.scc12["CR_VSM_Alive"] + 1 if not CS.no_radar else 0

      #TODO: fix this
      # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
      # self.scc_update_frame = frame

    # check if SCC is alive
    # if frame % 7 == 0:
      # if CS.scc11["AliveCounterACC"] == self.prev_scc_cnt:
        # if frame - self.scc_update_frame > 20 and self.scc_live:
          # self.scc_live = False
      # else:
        # self.scc_live = True
        # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
        # self.scc_update_frame = frame

    self.prev_scc_cnt = CS.scc11["AliveCounterACC"]

    self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10
    self.scc12_cnt %= 0xF

    can_sends = []
    can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled, left_lane, right_lane,
                                   left_lane_warning, right_lane_warning, 0))

    if CS.mdps_bus or CS.scc_bus == 1: # send lkas11 bus 1 if mdps or scc is on bus 1
      can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled, left_lane, right_lane,
                                   left_lane_warning, right_lane_warning, 1))
    if frame % 2 and CS.mdps_bus: # send clu11 to mdps if it is not on bus 0
      can_sends.append(create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11, Buttons.NONE, enabled_speed))

    str_log1 = 'CV={:03.0f}  TQ={:03.0f}  R={:03.0f}  ST={:03.0f}/{:01.0f}/{:01.0f}'.format(abs(self.model_speed), abs(new_steer), self.timer1.sampleTime(), self.steerMax, self.steerDeltaUp, self.steerDeltaDown)

    if self.params.get("OpkrLiveTune", encoding='utf8') == "1":
      if int(self.params.get("LateralControlMethod", encoding='utf8')) == 0:
        self.str_log2 = 'T={:0.2f}/{:0.3f}/{:0.2f}/{:0.5f}'.format(float(int(self.params.get("PidKp", encoding='utf8')) * 0.01), float(int(self.params.get("PidKi", encoding='utf8')) * 0.001), float(int(self.params.get("PidKd", encoding='utf8')) * 0.01), float(int(self.params.get("PidKf", encoding='utf8')) * 0.00001))
      elif int(self.params.get("LateralControlMethod", encoding='utf8')) == 1:
        self.str_log2 = 'T={:03.1f}/{:03.1f}/{:03.1f}/{:03.1f}'.format(float(int(self.params.get("InnerLoopGain", encoding='utf8')) * 0.1), float(int(self.params.get("OuterLoopGain", encoding='utf8')) * 0.1), float(int(self.params.get("TimeConstant", encoding='utf8')) * 0.1), float(int(self.params.get("ActuatorEffectiveness", encoding='utf8')) * 0.1))
      elif int(self.params.get("LateralControlMethod", encoding='utf8')) == 2:
        self.str_log2 = 'T={:04.0f}/{:05.3f}/{:06.4f}'.format(float(int(self.params.get("Scale", encoding='utf8')) * 1.0), float(int(self.params.get("LqrKi", encoding='utf8')) * 0.001), float(int(self.params.get("DcGain", encoding='utf8')) * 0.0001))

    trace1.printf1('{}  {}'.format(str_log1, self.str_log2))

    if CS.out.cruiseState.modeSel == 0 and self.mode_change_switch == 3:
      self.mode_change_timer = 50
      self.mode_change_switch = 0
    elif CS.out.cruiseState.modeSel == 1 and self.mode_change_switch == 0:
      self.mode_change_timer = 50
      self.mode_change_switch = 1
    elif CS.out.cruiseState.modeSel == 2 and self.mode_change_switch == 1:
      self.mode_change_timer = 50
      self.mode_change_switch = 2
    elif CS.out.cruiseState.modeSel == 3 and self.mode_change_switch == 2:
      self.mode_change_timer = 50
      self.mode_change_switch = 3
    if self.mode_change_timer > 0:
      self.mode_change_timer -= 1

    run_speed_ctrl = self.opkr_variablecruise and CS.acc_active and (CS.out.cruiseState.modeSel == 1 or CS.out.cruiseState.modeSel == 2 or CS.out.cruiseState.modeSel == 3)
    if not run_speed_ctrl:
      if CS.out.cruiseState.modeSel == 0:
        self.steer_mode = "OpenPilot"
      elif CS.out.cruiseState.modeSel == 1:
        self.steer_mode = "Dist+Curv"
      elif CS.out.cruiseState.modeSel == 2:
        self.steer_mode = "DistOnly"
      elif CS.out.cruiseState.modeSel == 3:
        self.steer_mode = "OneWay"
      if CS.out.steerWarning == 0:
        self.mdps_status = "OK"
      elif CS.out.steerWarning == 1:
        self.mdps_status = "ERR"
      if CS.lkas_button_on == 0:
        self.lkas_switch = "OFF"
      elif CS.lkas_button_on == 1:
        self.lkas_switch = "ON"
      else:
        self.lkas_switch = "-"
      if self.cruise_gap != CS.cruiseGapSet:
        self.cruise_gap = CS.cruiseGapSet
      if CS.lead_distance < 149:
        self.leadcar_status = "O"
      else:
        self.leadcar_status = "-"

      str_log2 = 'MODE={:s}  MDPS={:s}  LKAS={:s}  CSG={:1.0f}  LEAD={:s}'.format(self.steer_mode, self.mdps_status, self.lkas_switch, self.cruise_gap, self.leadcar_status)
      trace1.printf2( '{}'.format( str_log2 ) )

    if pcm_cancel_cmd and self.longcontrol:
      can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.CANCEL, clu11_speed))

    if CS.out.cruiseState.standstill:
      self.standstill_status = 1
      if self.opkr_autoresume:
        # run only first time when the car stopped
        if self.last_lead_distance == 0:
          # get the lead distance from the Radar
          self.last_lead_distance = CS.lead_distance
          self.resume_cnt = 0
          self.res_switch_timer = 0
          self.standstill_fault_reduce_timer += 1
        elif self.res_switch_timer > 0:
          self.res_switch_timer -= 1
          self.standstill_fault_reduce_timer += 1
        # at least 1 sec delay after entering the standstill
        elif 100 < self.standstill_fault_reduce_timer and CS.lead_distance != self.last_lead_distance:
          can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.RES_ACCEL, clu11_speed))
          self.resume_cnt += 1
          if self.resume_cnt > 5:
            self.resume_cnt = 0
            self.res_switch_timer = randint(10, 15)
          self.standstill_fault_reduce_timer += 1
        # gap save
        elif 160 < self.standstill_fault_reduce_timer and self.cruise_gap_prev == 0 and self.opkr_autoresume: 
          self.cruise_gap_prev = CS.cruiseGapSet
          self.cruise_gap_set_init = 1
        # gap adjust to 1 for fast start
        elif 160 < self.standstill_fault_reduce_timer and CS.cruiseGapSet != 1.0 and self.opkr_autoresume:
          self.cruise_gap_switch_timer += 1
          if self.cruise_gap_switch_timer > 100:
            can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.GAP_DIST, clu11_speed))
            self.cruise_gap_switch_timer = 0
        elif self.opkr_autoresume:
          self.standstill_fault_reduce_timer += 1
    # reset lead distnce after the car starts moving
    elif self.last_lead_distance != 0:
      self.last_lead_distance = 0
    elif run_speed_ctrl:
      is_sc_run = self.SC.update(CS, sm, self)
      if is_sc_run:
        can_sends.append(create_clu11(self.packer, self.resume_cnt, CS.scc_bus, CS.clu11, self.SC.btn_type, self.SC.sc_clu_speed))
        self.resume_cnt += 1
      else:
        self.resume_cnt = 0
      # gap restore
      if self.dRel > 17 and self.vRel < 5 and self.cruise_gap_prev != CS.cruiseGapSet and self.cruise_gap_set_init == 1 and self.opkr_autoresume:
        self.cruise_gap_switch_timer += 1
        if self.cruise_gap_switch_timer > 50:
          can_sends.append(create_clu11(self.packer, frame, CS.scc_bus, CS.clu11, Buttons.GAP_DIST, clu11_speed))
          self.cruise_gap_switch_timer = 0
      elif self.cruise_gap_prev == CS.cruiseGapSet and self.opkr_autoresume:
        self.cruise_gap_set_init = 0
        self.cruise_gap_prev = 0
    
    if CS.out.brakeLights and CS.out.vEgo == 0 and not CS.acc_active:
      self.standstill_status_timer += 1
      if self.standstill_status_timer > 200:
        self.standstill_status = 1
        self.standstill_status_timer = 0
    if self.standstill_status == 1 and CS.out.vEgo > 1:
      self.standstill_status = 0
      self.standstill_fault_reduce_timer = 0
      self.v_set_dis_prev = 180
      self.last_resume_frame = frame
      self.res_switch_timer = 0
      self.resume_cnt = 0

    if CS.mdps_bus: # send mdps12 to LKAS to prevent LKAS error
      can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

    # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
    if self.longcontrol and (CS.scc_bus or not self.scc_live) and frame % 2 == 0: 
      can_sends.append(create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt, self.scc_live, CS.scc12))
      can_sends.append(create_scc11(self.packer, frame, enabled, set_speed, lead_visible, self.scc_live, CS.scc11))
      if CS.has_scc13 and frame % 20 == 0:
        can_sends.append(create_scc13(self.packer, CS.scc13))
      if CS.has_scc14:
        can_sends.append(create_scc14(self.packer, enabled, CS.scc14))
      self.scc12_cnt += 1

    # 20 Hz LFA MFA message
    if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfahda_mfa"]:
      can_sends.append(create_lfahda_mfc(self.packer, frame, lkas_active))

    if CS.spas_enabled:
      if CS.mdps_bus:
        can_sends.append(create_ems11(self.packer, CS.ems11, spas_active))

      # SPAS11 50hz
      if (frame % 2) == 0:
        if CS.mdps11_stat == 7 and not self.mdps11_stat_last == 7:
          self.en_spas = 7
          self.en_cnt = 0

        if self.en_spas == 7 and self.en_cnt >= 8:
          self.en_spas = 3
          self.en_cnt = 0
  
        if self.en_cnt < 8 and spas_active:
          self.en_spas = 4
        elif self.en_cnt >= 8 and spas_active:
          self.en_spas = 5

        if not spas_active:
          self.apply_steer_ang = CS.mdps11_strang
          self.en_spas = 3
          self.en_cnt = 0

        self.mdps11_stat_last = CS.mdps11_stat
        self.en_cnt += 1
        can_sends.append(create_spas11(self.packer, self.car_fingerprint, (frame // 2), self.en_spas, self.apply_steer_ang, CS.mdps_bus))

      # SPAS12 20Hz
      if (frame % 5) == 0:
        can_sends.append(create_spas12(CS.mdps_bus))

    return can_sends
예제 #22
0
    def update(self, CC, CS, frame, sm, CP):

        if self.CP != CP:
            self.CP = CP

        enabled = CC.enabled
        actuators = CC.actuators
        pcm_cancel_cmd = CC.cruiseControl.cancel

        self.dRel, self.yRel, self.vRel = SpdController.get_lead(sm)

        self.model_speed, self.model_sum = self.SC.calc_va(sm, CS.out.vEgo)

        # Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled and abs(CS.out.steeringAngle) < 90.

        if ((CS.out.leftBlinker and not CS.out.rightBlinker) or
            (CS.out.rightBlinker
             and not CS.out.leftBlinker)) and CS.out.vEgo <= 59 * CV.KPH_TO_MS:
            self.lanechange_manual_timer = 10
        if CS.out.leftBlinker and CS.out.rightBlinker:
            self.emergency_manual_timer = 10
        if abs(CS.out.steeringTorque) > 200:
            self.driver_steering_torque_above_timer = 15
        if self.lanechange_manual_timer or self.driver_steering_torque_above_timer:
            lkas_active = 0
        if self.lanechange_manual_timer > 0:
            self.lanechange_manual_timer -= 1
        if self.emergency_manual_timer > 0:
            self.emergency_manual_timer -= 1
        if self.driver_steering_torque_above_timer > 0:
            self.driver_steering_torque_above_timer -= 1

        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        self.apply_steer_last = apply_steer

        sys_warning, sys_state = self.process_hud_alert(lkas_active, CC)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 55
        if clu11_speed > enabled_speed:
            enabled_speed = clu11_speed

        can_sends = []
        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1
        self.lkas11_cnt %= 0x10

        can_sends.append(
            create_lkas11(self.packer, self.lkas11_cnt, self.car_fingerprint,
                          apply_steer, steer_req, CS.lkas11, sys_warning,
                          sys_state, CC, enabled, 0))
        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps is on bus 1
            can_sends.append(
                create_lkas11(self.packer, self.lkas11_cnt,
                              self.car_fingerprint, apply_steer, steer_req,
                              CS.lkas11, sys_warning, sys_state, CC, enabled,
                              1))

        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            #if frame % 2 and CS.mdps_bus == 1: # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11,
                             Buttons.NONE, enabled_speed))

        #if CS.mdps_bus:
        can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        str_log1 = '곡률={:05.1f}'.format(self.model_speed)
        str_log2 = '프레임율={:03.0f}  TPMS=FL:{:04.1f}/FR:{:04.1f}/RL:{:04.1f}/RR:{:04.1f}'.format(
            self.timer1.sampleTime(), CS.tpmsPressureFl, CS.tpmsPressureFr,
            CS.tpmsPressureRl, CS.tpmsPressureRr)
        trace1.printf('{}  {}'.format(str_log1, str_log2))

        if CS.out.cruiseState.modeSel == 0 and self.mode_change_switch == 4:
            self.mode_change_timer = 50
            self.mode_change_switch = 0
        elif CS.out.cruiseState.modeSel == 1 and self.mode_change_switch == 0:
            self.mode_change_timer = 50
            self.mode_change_switch = 1
        elif CS.out.cruiseState.modeSel == 2 and self.mode_change_switch == 1:
            self.mode_change_timer = 50
            self.mode_change_switch = 2
        elif CS.out.cruiseState.modeSel == 3 and self.mode_change_switch == 2:
            self.mode_change_timer = 50
            self.mode_change_switch = 3
        elif CS.out.cruiseState.modeSel == 4 and self.mode_change_switch == 3:
            self.mode_change_timer = 50
            self.mode_change_switch = 4
        if self.mode_change_timer > 0:
            self.mode_change_timer -= 1

        run_speed_ctrl = self.param_OpkrAccelProfile and CS.acc_active and self.SC != None and (
            CS.out.cruiseState.modeSel == 1 or CS.out.cruiseState.modeSel == 2
            or CS.out.cruiseState.modeSel == 3)
        if not run_speed_ctrl:
            if CS.out.cruiseState.modeSel == 0:
                self.steer_mode = "오파모드"
            elif CS.out.cruiseState.modeSel == 1:
                self.steer_mode = "차간+커브"
            elif CS.out.cruiseState.modeSel == 2:
                self.steer_mode = "차간ONLY"
            elif CS.out.cruiseState.modeSel == 3:
                self.steer_mode = "정체구간"
            elif CS.out.cruiseState.modeSel == 4:
                self.steer_mode = "순정모드"
            if CS.out.steerWarning == 0:
                self.mdps_status = "정상"
            elif CS.out.steerWarning == 1:
                self.mdps_status = "오류"
            if CS.lkas_button_on == 0:
                self.lkas_switch = "OFF"
            elif CS.lkas_button_on == 1:
                self.lkas_switch = "ON"
            else:
                self.lkas_switch = "-"

            if CS.out.cruiseState.modeSel == 3:
                str_log2 = '주행모드={:s}  MDPS상태={:s}  LKAS버튼={:s}  CG:{:1.0f}'.format(
                    self.steer_mode, self.mdps_status, self.lkas_switch,
                    CS.cruiseGapSet)
            else:
                str_log2 = '주행모드={:s}  MDPS상태={:s}  LKAS버튼={:s}'.format(
                    self.steer_mode, self.mdps_status, self.lkas_switch)
            trace1.printf2('{}'.format(str_log2))

        #print( 'st={} cmd={} long={}  steer={} req={}'.format(CS.out.cruiseState.standstill, pcm_cancel_cmd, self.CP.openpilotLongitudinalControl, apply_steer, steer_req ) )

        if pcm_cancel_cmd and self.CP.openpilotLongitudinalControl:
            can_sends.append(
                create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                             Buttons.CANCEL, clu11_speed))
        elif CS.out.cruiseState.standstill:
            # run only first time when the car stopped
            if self.last_lead_distance == 0 or not self.param_OpkrAutoResume:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance != self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0

            elif self.cruise_gap_prev == 0:
                self.cruise_gap_prev = CS.cruiseGapSet
                self.cruise_gap_set_init = 1
            elif CS.cruiseGapSet != 1.0:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 100:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0

        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0
            self.cruise_gap = 0
        elif run_speed_ctrl and self.SC != None:
            is_sc_run = self.SC.update(CS, sm, self)
            if is_sc_run:
                can_sends.append(
                    create_clu11(self.packer, self.resume_cnt, CS.scc_bus,
                                 CS.clu11, self.SC.btn_type,
                                 self.SC.sc_clu_speed))
                self.resume_cnt += 1
            else:
                self.resume_cnt = 0
            if self.dRel > 17 and self.cruise_gap_prev != CS.cruiseGapSet and self.cruise_gap_set_init == 1 and CS.out.cruiseState.modeSel != 3:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 50:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0
            elif self.cruise_gap_prev == CS.cruiseGapSet:
                self.cruise_gap_set_init = 0
                self.cruise_gap_prev = 0

        if CS.out.cruiseState.modeSel == 3 and CS.acc_active:
            if 20 > self.dRel > 18 and self.vRel < 0 and CS.cruiseGapSet != 4.0:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 30:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0
            elif 16 > self.dRel > 14 and self.vRel < 0 and CS.cruiseGapSet != 3.0:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 30:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0
            elif 12 > self.dRel > 10 and self.vRel < 0 and CS.cruiseGapSet != 2.0:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 30:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0
            elif 9 > self.dRel > 7 and self.vRel < 0 and CS.cruiseGapSet != 1.0:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 30:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0
            elif 15 > self.dRel > 4 and self.vRel > 0 and CS.cruiseGapSet != 1.0:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 30:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0
            elif 25 > self.dRel > 18 and self.vRel >= 0 and CS.cruiseGapSet != 2.0:
                self.cruise_gap_switch_timer += 1
                if self.cruise_gap_switch_timer > 30:
                    can_sends.append(
                        create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                     Buttons.GAP_DIST, clu11_speed))
                    self.cruise_gap_switch_timer = 0

        # 20 Hz LFA MFA message
        #if frame % 5 == 0 and self.car_fingerprint in [CAR.IONIQ]:
        #  can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        self.lkas11_cnt += 1
        return can_sends
예제 #23
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart):

        # *** compute control surfaces ***

        # gas and brake
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

        # Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        # temporarily disable steering when LKAS button off
        # lkas_active = enabled and abs(CS.out.steeringAngle) < 90. and self.lkas_button_on
        lkas_active = enabled and self.lkas_button_on

        # fix for Genesis hard fault at low speed
        if CS.out.vEgo < 60 * CV.KPH_TO_MS and self.car_fingerprint == CAR.HYUNDAI_GENESIS and not CS.mdps_bus:
            lkas_active = 0

        # Disable steering while turning blinker on and speed below 60 kph
        if CS.out.leftBlinker or CS.out.rightBlinker:
            if self.car_fingerprint not in [CAR.KIA_OPTIMA, CAR.KIA_OPTIMA_H]:
                self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off
            elif CS.left_blinker_flash or CS.right_blinker_flash:  # Optima has blinker flash signal only
                self.turning_signal_timer = 100
        #if self.turning_signal_timer and CS.out.vEgo < 60 * CV.KPH_TO_MS:
        if self.turning_signal_timer:
            lkas_active = 0
        if self.turning_signal_timer:
            self.turning_signal_timer -= 1
        if not lkas_active:
            apply_steer = 0

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(lkas_active, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart,
                            self.lkas_button_on)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
            self.scc12_cnt = CS.scc12[
                "CR_VSM_Alive"] + 1 if not CS.no_radar else 0

        self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10
        self.scc12_cnt %= 0xF

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning, 0))

        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer, frame, self.car_fingerprint,
                              apply_steer, lkas_active, CS.lkas11, sys_warning,
                              sys_state, enabled, left_lane, right_lane,
                              left_lane_warning, right_lane_warning, 1))
        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11,
                             Buttons.NONE, enabled_speed))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                             Buttons.CANCEL, clu11_speed))
        elif CS.mdps_bus:  # send mdps12 to LKAS to prevent LKAS error if no cancel cmd
            can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        if CS.scc_bus and self.longcontrol and frame % 2:  # send scc12 to car if SCC not on bus 0 and longcontrol enabled
            can_sends.append(
                create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt,
                             CS.scc12))
            self.scc12_cnt += 1

        if CS.out.cruiseState.standstill:
            # run only first time when the car stopped
            if self.last_lead_distance == 0:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif (self.last_lead_distance + 0.9) < CS.lead_distance > 4.8 and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.clu11_cnt = 0

        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in [
                CAR.SONATA, CAR.PALISADE, CAR.SONATA_H, CAR.SANTA_FE
        ]:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        return can_sends
예제 #24
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_line, right_line, sm, LaC):

        path_plan = sm['pathPlan']
        # *** compute control surfaces ***
        v_ego_kph = CS.v_ego * CV.MS_TO_KPH

        # gas and brake
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = self.accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)
        abs_angle_steers = abs(
            actuators.steerAngle)  #  abs(CS.angle_steers)  #

        param = SteerLimitParams()

        if path_plan.laneChangeState != LaneChangeState.off:
            #param.STEER_MAX *= 0.99
            param.STEER_DELTA_UP = 1
            param.STEER_DELTA_DOWN = 5

        #v_curvature
        elif LaC.v_curvature < 200:
            self.timer_curvature = 300
        elif abs_angle_steers < 1 and self.timer_curvature <= 0:
            xp = [0.5, 1]
            fp = [240, 255]
            param.STEER_MAX = interp(abs_angle_steers, xp, fp)

            if abs_angle_steers < 1 or v_ego_kph < 5:
                param.STEER_DELTA_UP = 2
                param.STEER_DELTA_DOWN = 4

        if self.timer_curvature:
            self.timer_curvature -= 1

        ### Steering Torque
        new_steer = actuators.steer * param.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.steer_torque_driver,
                                                    param)
        self.steer_rate_limited = new_steer != apply_steer

        if abs(CS.steer_torque_driver) > self.steer_torque_over_max:  #200:
            self.steer_torque_over_timer += 1
            if self.steer_torque_over_timer > 5:
                self.steer_torque_over = True
                self.steer_torque_over_timer = 100
        elif self.steer_torque_over_timer:
            self.steer_torque_over_timer -= 1
        else:
            self.steer_torque_over = False

        ### LKAS button to temporarily disable steering
        #if not CS.lkas_error:
        #  if self.lkas_button != CS.lkas_button_on:
        #     self.lkas_button = CS.lkas_button_on

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        if self.car_fingerprint == CAR.GENESIS:
            lkas_active = enabled and abs(CS.angle_steers) < 90.
        else:
            lkas_active = enabled and abs(CS.angle_steers) < 100.

        # fix for Genesis hard fault at low speed
        if v_ego_kph < 60 and self.car_fingerprint == CAR.GENESIS and not CS.mdps_bus:
            lkas_active = 0

        low_speed = self.low_speed_car
        #if not self.lkas_button:
        #    low_speed = False
        #elif not CS.cruiseState.enabled:
        #    low_speed = False
        if CS.stopped:
            low_speed = False
        elif CS.v_ego > (CS.CP.minSteerSpeed + 0.7):
            low_speed = False
        elif CS.v_ego < (CS.CP.minSteerSpeed + 0.2):
            low_speed = True

        if self.low_speed_car != low_speed:
            self.low_speed_car = low_speed

        # streer over check
        if enabled and abs(CS.angle_steers) > 100. or CS.steer_error:
            self.streer_angle_over = True
            self.steer_timer = 250
        elif abs(CS.angle_steers) < 7.5 or not self.steer_timer:
            self.streer_angle_over = False
        elif self.steer_timer:
            self.steer_timer -= 1

        # Disable steering while turning blinker on and speed below 60 kph
        if CS.left_blinker_on or CS.right_blinker_on:
            self.steer_torque_over = False
            self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off
        elif CS.left_blinker_flash or CS.right_blinker_flash:
            self.steer_torque_over = False
            self.turning_signal_timer = 100

        # turning indicator alert logic
        if self.lane_change_enabled:
            self.turning_indicator = self.turning_signal_timer and CS.v_ego < LaneChangeParms.LANE_CHANGE_SPEED_MIN
        else:
            self.turning_indicator = self.turning_signal_timer

        if self.turning_signal_timer:
            self.turning_signal_timer -= 1

        if left_line:
            self.hud_timer_left = 100
        elif self.hud_timer_left:
            self.hud_timer_left -= 1

        if right_line:
            self.hud_timer_right = 100
        elif self.hud_timer_right:
            self.hud_timer_right -= 1

        if path_plan.laneChangeState != LaneChangeState.off:
            if LaC.v_curvature > 200:
                self.lkas_active_timer1 = 300
                apply_steer = self.limit_ctrl(apply_steer, 100, 0)
        elif not self.hud_timer_left and not self.hud_timer_right:
            self.lkas_active_timer1 = 200  #  apply_steer = 70
        elif path_plan.laneChangeState != LaneChangeState.off:
            self.steer_torque_over = False

        # disable lkas
        if not CS.main_on:
            lkas_active = 0
            self.turning_signal_timer = 0
            self.turning_indicator = False
            self.steer_torque_over = False
        elif CS.stopped:
            lkas_active = 0
        elif self.steer_torque_over:
            lkas_active = 0

        if self.streer_angle_over:
            lkas_active = 0
        elif self.turning_indicator:
            lkas_active = 0

        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        steer_limit = param.STEER_MAX  #param.STEER_MAX
        if not lkas_active:
            self.lkas_active_timer1 = 200
        elif self.lkas_active_timer1 < 400:
            self.lkas_active_timer1 += 1
            ratio_steer = self.lkas_active_timer1 / 400
            if ratio_steer < 1:
                steer_limit = ratio_steer * param.STEER_MAX
                apply_steer = self.limit_ctrl(apply_steer, steer_limit, 0)

        dRel, yRel, vRel = self.SC.get_lead(sm, CS)
        vRel = int(vRel * 3.6 + 0.5)

        lead_objspd = CS.lead_objspd
        str_log1 = 'CV={:03.0f}/{:06.3f} TQ=V:{:04.0f}/S:{:04.0f}'.format(
            LaC.v_curvature, LaC.model_sum, apply_steer,
            CS.steer_torque_driver)
        str_log2 = 'D={:05.1f} V={:03.0f} S_LIM={:03.0f} S_MAX={:03.0f}'.format(
            dRel, vRel, steer_limit, param.STEER_MAX)
        trace1.printf('{} {}'.format(str_log1, str_log2))

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        hud_alert, lane_visible = self.process_hud_alert(
            lkas_active, self.lkas_button, visual_alert, self.hud_timer_left,
            self.hud_timer_right, CS)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        can_sends = []

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1

        self.lkas11_cnt %= 0x10
        self.clu11_cnt = frame % 0x10
        self.mdps12_cnt = frame % 0x100

        can_sends.append(
            create_lkas11(self.packer,
                          self.car_fingerprint,
                          0,
                          apply_steer,
                          steer_req,
                          self.lkas11_cnt,
                          lkas_active,
                          CS.lkas11,
                          hud_alert,
                          lane_visible,
                          keep_stock=True))
        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas12 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer,
                              self.car_fingerprint,
                              1,
                              apply_steer,
                              steer_req,
                              self.lkas11_cnt,
                              lkas_active,
                              CS.lkas11,
                              hud_alert,
                              lane_visible,
                              keep_stock=True))
        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, CS.mdps_bus, CS.clu11, Buttons.NONE,
                             enabled_speed, self.clu11_cnt))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, CS.scc_bus, CS.clu11, Buttons.CANCEL,
                             clu11_speed, self.clu11_cnt))
        else:  # send mdps12 to LKAS to prevent LKAS error if no cancel cmd
            can_sends.append(
                create_mdps12(self.packer, self.car_fingerprint,
                              self.mdps12_cnt, CS.mdps12))

        # AVM
        #if CS.mdps_bus:
        #if not CS.cp_AVM.can_valid:
        #can_sends.append(create_AVM(self.packer, self.car_fingerprint, CS.avm, CS ))

        if CS.stopped:
            #self.model_speed = 300
            # run only first time when the car stopped
            if self.last_lead_distance == 0:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance != self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed,
                                 self.resume_cnt))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0
        elif CS.driverOverride == 2 or not CS.pcm_acc_status or CS.clu_CruiseSwState == 1 or CS.clu_CruiseSwState == 2:
            #self.model_speed = 300
            self.resume_cnt = 0
            self.sc_btn_type = Buttons.NONE
            self.sc_wait_timer2 = 10
            self.sc_active_timer2 = 0
        elif self.sc_wait_timer2:
            self.sc_wait_timer2 -= 1
        elif self.speed_control_enabled:
            #acc_mode, clu_speed = self.long_speed_cntrl( v_ego_kph, CS, actuators )
            btn_type, clu_speed = self.SC.update(
                v_ego_kph, CS, sm, actuators, dRel, yRel, vRel,
                LaC.v_curvature)  # speed controller spdcontroller.py

            if CS.clu_Vanz < 5:
                self.sc_btn_type = Buttons.NONE
            elif self.sc_btn_type != Buttons.NONE:
                pass
            elif btn_type != Buttons.NONE:
                self.resume_cnt = 0
                self.sc_active_timer2 = 0
                self.sc_btn_type = btn_type
                self.sc_clu_speed = clu_speed

            if self.sc_btn_type != Buttons.NONE:
                self.sc_active_timer2 += 1
                if self.sc_active_timer2 > 10:
                    self.sc_wait_timer2 = 5
                    self.resume_cnt = 0
                    self.sc_active_timer2 = 0
                    self.sc_btn_type = Buttons.NONE
                else:
                    #self.traceCC.add( 'sc_btn_type={}  clu_speed={}  set={:.0f} vanz={:.0f}'.format( self.sc_btn_type, self.sc_clu_speed,  CS.VSetDis, clu11_speed  ) )
                    can_sends.append(
                        create_clu11(self.packer, CS.scc_bus, CS.clu11,
                                     self.sc_btn_type, self.sc_clu_speed,
                                     self.resume_cnt))
                    self.resume_cnt += 1

        self.lkas11_cnt += 1

        return can_sends
예제 #25
0
  def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd, visual_alert, hud_speed,
             left_lane, right_lane, left_lane_depart, right_lane_depart):
    # Steering Torque
    new_steer = int(round(actuators.steer * self.p.STEER_MAX))
    apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.p)
    self.steer_rate_limited = new_steer != apply_steer

    # disable when temp fault is active, or below LKA minimum speed
    lkas_active = enabled and not CS.out.steerWarning and CS.out.vEgo >= CS.CP.minSteerSpeed

    if not lkas_active:
      apply_steer = 0

    self.apply_steer_last = apply_steer

    sys_warning, sys_state, left_lane_warning, right_lane_warning = \
      process_hud_alert(enabled, self.car_fingerprint, visual_alert,
                        left_lane, right_lane, left_lane_depart, right_lane_depart)

    can_sends = []

    # tester present - w/ no response (keeps radar disabled)
    if CS.CP.openpilotLongitudinalControl:
      if (frame % 100) == 0:
        can_sends.append([0x7D0, 0, b"\x02\x3E\x80\x00\x00\x00\x00\x00", 0])

    can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,
                                   CS.lkas11, sys_warning, sys_state, enabled,
                                   left_lane, right_lane,
                                   left_lane_warning, right_lane_warning))

    if not CS.CP.openpilotLongitudinalControl:
      if pcm_cancel_cmd:
        can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))
      elif CS.out.cruiseState.standstill:
        # send resume at a max freq of 10Hz
        if (frame - self.last_resume_frame) * DT_CTRL > 0.1:
          # send 25 messages at a time to increases the likelihood of resume being accepted
          can_sends.extend([create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL)] * 25)
          self.last_resume_frame = frame

    if frame % 2 == 0 and CS.CP.openpilotLongitudinalControl:
      lead_visible = False
      accel = actuators.accel if enabled else 0

      jerk = clip(2.0 * (accel - CS.out.aEgo), -12.7, 12.7)

      if accel < 0:
        accel = interp(accel - CS.out.aEgo, [-1.0, -0.5], [2 * accel, accel])

      accel = clip(accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)

      stopping = (actuators.longControlState == LongCtrlState.stopping)
      set_speed_in_units = hud_speed * (CV.MS_TO_MPH if CS.clu11["CF_Clu_SPEED_UNIT"] == 1 else CV.MS_TO_KPH)
      can_sends.extend(create_acc_commands(self.packer, enabled, accel, jerk, int(frame / 2), lead_visible, set_speed_in_units, stopping))
      self.accel = accel

    # 20 Hz LFA MFA message
    if frame % 5 == 0 and self.car_fingerprint in [CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021,
                                                   CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KIA_CEED, CAR.KIA_SELTOS, CAR.KONA_EV,
                                                   CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.SANTA_FE_2022,
                                                   CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.GENESIS_G70_2020]:
      can_sends.append(create_lfahda_mfc(self.packer, enabled))

    # 5 Hz ACC options
    if frame % 20 == 0 and CS.CP.openpilotLongitudinalControl:
      can_sends.extend(create_acc_opt(self.packer))

    # 2 Hz front radar options
    if frame % 50 == 0 and CS.CP.openpilotLongitudinalControl:
      can_sends.append(create_frt_radar_opt(self.packer))

    new_actuators = actuators.copy()
    new_actuators.steer = apply_steer / self.p.STEER_MAX
    new_actuators.accel = self.accel

    return new_actuators, can_sends
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_lane, right_lane, left_lane_depart,
               right_lane_depart, set_speed, lead_visible):

        # *** compute control surfaces ***

        # gas and brake
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

        # Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        # SPAS limit angle extremes for safety
        if CS.spas_enabled:
            apply_steer_ang_req = clip(actuators.steerAngle,
                                       -1 * (STEER_ANG_MAX), STEER_ANG_MAX)
            # SPAS limit angle rate for safety
            if abs(self.apply_steer_ang -
                   apply_steer_ang_req) > STEER_ANG_MAX_RATE:
                if apply_steer_ang_req > self.apply_steer_ang:
                    self.apply_steer_ang += STEER_ANG_MAX_RATE
                else:
                    self.apply_steer_ang -= STEER_ANG_MAX_RATE
            else:
                self.apply_steer_ang = apply_steer_ang_req
        spas_active = CS.spas_enabled and enabled and (
            self.spas_always or CS.out.vEgo < 7.0)  # 25km/h

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        # temporarily disable steering when LKAS button off
        lkas_active = enabled and abs(
            CS.out.steeringAngle
        ) < 90. and self.lkas_button_on and not spas_active

        # fix for Genesis hard fault at low speed
        if CS.out.vEgo < 60 * CV.KPH_TO_MS and self.car_fingerprint == CAR.HYUNDAI_GENESIS and not CS.mdps_bus:
            lkas_active = False

        # Disable steering while turning blinker on and speed below 60 kph
        if CS.out.leftBlinker or CS.out.rightBlinker:
            if self.car_fingerprint not in [CAR.KIA_OPTIMA, CAR.KIA_OPTIMA_H]:
                self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off
            elif CS.left_blinker_flash or CS.right_blinker_flash:  # Optima has blinker flash signal only
                self.turning_signal_timer = 100
        if self.turning_indicator_alert:  # set and clear by interface
            lkas_active = 0
        if self.turning_signal_timer > 0:
            self.turning_signal_timer -= 1

        if not lkas_active:
            apply_steer = 0

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        sys_warning, sys_state, left_lane_warning, right_lane_warning =\
          process_hud_alert(lkas_active, self.car_fingerprint, visual_alert,
                            left_lane, right_lane, left_lane_depart, right_lane_depart,
                            self.lkas_button_on)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        if not (min_set_speed < set_speed < 255 * CV.KPH_TO_MS):
            set_speed = min_set_speed
        set_speed *= CV.MS_TO_MPH if CS.is_set_speed_in_mph else CV.MS_TO_KPH

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"]
            self.scc12_cnt = CS.scc12[
                "CR_VSM_Alive"] + 1 if not CS.no_radar else 0

            #TODO: fix this
            # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
            # self.scc_update_frame = frame

        # check if SCC is alive
        # if frame % 7 == 0:
        # if CS.scc11["AliveCounterACC"] == self.prev_scc_cnt:
        # if frame - self.scc_update_frame > 20 and self.scc_live:
        # self.scc_live = False
        # else:
        # self.scc_live = True
        # self.prev_scc_cnt = CS.scc11["AliveCounterACC"]
        # self.scc_update_frame = frame

        self.prev_scc_cnt = CS.scc11["AliveCounterACC"]

        self.lkas11_cnt = (self.lkas11_cnt + 1) % 0x10
        self.scc12_cnt %= 0xF

        can_sends = []
        can_sends.append(
            create_lkas11(self.packer, frame, self.car_fingerprint,
                          apply_steer, lkas_active, CS.lkas11, sys_warning,
                          sys_state, enabled, left_lane, right_lane,
                          left_lane_warning, right_lane_warning, 0))

        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer, frame, self.car_fingerprint,
                              apply_steer, lkas_active, CS.lkas11, sys_warning,
                              sys_state, enabled, left_lane, right_lane,
                              left_lane_warning, right_lane_warning, 1))
        if frame % 2 and CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11,
                             Buttons.NONE, enabled_speed))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                             Buttons.CANCEL, clu11_speed))
        elif CS.out.cruiseState.standstill:
            # SCC won't resume anyway when the lead distace is less than 3.7m
            # send resume at a max freq of 5Hz
            if CS.lead_distance > 3.7 and (
                    frame - self.last_resume_frame) * DT_CTRL > 0.2:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.last_resume_frame = frame

        if CS.mdps_bus:  # send mdps12 to LKAS to prevent LKAS error
            can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        # send scc to car if longcontrol enabled and SCC not on bus 0 or ont live
        if self.longcontrol and (CS.scc_bus
                                 or not self.scc_live) and frame % 2 == 0:
            can_sends.append(
                create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt,
                             self.scc_live, CS.scc12))
            can_sends.append(
                create_scc11(self.packer, frame, enabled, set_speed,
                             lead_visible, self.scc_live, CS.scc11))
            if CS.has_scc13 and frame % 20 == 0:
                can_sends.append(create_scc13(self.packer, CS.scc13))
            if CS.has_scc14:
                can_sends.append(create_scc14(self.packer, enabled, CS.scc14))
            self.scc12_cnt += 1

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfa_mfa"]:
            can_sends.append(create_lfa_mfa(self.packer, frame, lkas_active))

        if CS.spas_enabled:
            if CS.mdps_bus:
                can_sends.append(
                    create_ems11(self.packer, CS.ems11, spas_active))

            # SPAS11 50hz
            if (frame % 2) == 0:
                if CS.mdps11_stat == 7 and not self.mdps11_stat_last == 7:
                    self.en_spas == 7
                    self.en_cnt = 0

                if self.en_spas == 7 and self.en_cnt >= 8:
                    self.en_spas = 3
                    self.en_cnt = 0

                if self.en_cnt < 8 and spas_active:
                    self.en_spas = 4
                elif self.en_cnt >= 8 and spas_active:
                    self.en_spas = 5

                if not spas_active:
                    self.apply_steer_ang = CS.mdps11_strang
                    self.en_spas = 3
                    self.en_cnt = 0

                self.mdps11_stat_last = CS.mdps11_stat
                self.en_cnt += 1
                can_sends.append(
                    create_spas11(self.packer, self.car_fingerprint,
                                  (frame // 2), self.en_spas,
                                  self.apply_steer_ang, CS.mdps_bus))

            # SPAS12 20Hz
            if (frame % 5) == 0:
                can_sends.append(create_spas12(CS.mdps_bus))

        # DIY cruise speed code
        sm.update(0)

        lead_data = sm['radarState'].leadOne
        lead_one = sm['radarState'].leadOne
        lead_two = sm['radarState'].leadTwo

        if lead_one.status == True:
            lead_data = lead_one

        if lead_two.status == True and ((lead_one.dRel - lead_two.dRel) > 3.0):
            lead_data = lead_two

        lead_rel_dist = lead_data.dRel
        lead_rel_vel = lead_data.vRel
        lead_vel = lead_data.vLead

        cruise_curr_set_speed = CS.out.cruiseState.speed  #currently set cruise speed in m/s
        d_cru_vego = 1.11  #4km/h diff between cruise/realspeed  #cruise_curr_set_speed - CS.out.vEgo
        min_dist = 10.  #min dist to lead car to engage in meters
        max_dist = 300.  #max dist to lead car to disable acceleration and allow only deceleration
        max_cru_speed = 36.11  #limit set max cruise speed to 130km/h
        press_button_speed = 40  #press buttons at 400 milliseconds interval

        if (
                cruise_curr_set_speed - lead_vel
        ) > 8.33:  #>30km/h faster button presses on deceleration and big cruise speed gap
            press_button_speed = 5
        elif (cruise_curr_set_speed - lead_vel) > 5.55:  #>20km/h
            press_button_speed = 10
        elif (cruise_curr_set_speed - lead_vel) > 2.77:  #>10km/h
            press_button_speed = 20

        if lead_vel > (
                cruise_curr_set_speed - d_cru_vego
        ) and lead_rel_dist > 0. and cruise_curr_set_speed < max_cru_speed and (
                frame % press_button_speed == 0
                or frame % press_button_speed == 1):
            if not CS.out.cruiseState.available:  #prevent pressing up and resume prev speed
                can_sends.append(
                    create_clu11(self.packer, frame, 0, CS.clu11,
                                 Buttons.SET_DECEL, clu11_speed))  #button down
            elif lead_rel_dist > min_dist and lead_rel_dist < max_dist:
                can_sends.append(
                    create_clu11(self.packer, frame, 0, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))  #button up
        elif lead_vel < (cruise_curr_set_speed -
                         d_cru_vego) and lead_rel_dist > 0. and (
                             frame % press_button_speed == 0
                             or frame % press_button_speed == 1):
            can_sends.append(
                create_clu11(self.packer, frame, 0, CS.clu11,
                             Buttons.SET_DECEL, clu11_speed))  #button down

        return can_sends
예제 #27
0
  def update(self, enabled, CS, actuators, pcm_cancel_cmd, hud_alert):
    ### Error State Resets ###
    disable_steer = False
    can_sends = []

    ### Learn Checksum ###

    if not self.checksum_found:
      # Learn Checksum from the Camera
      if self.checksum == "NONE":
        self.checksum = learn_checksum(self.packer, CS.lkas11)
        if self.checksum == "NONE" and self.checksum_learn_cnt < 50:
          self.checksum_learn_cnt += 1
          return
        else:
          cloudlog.info("Discovered Checksum %s" % self.checksum)
          self.checksum_found = True

      # If MDPS is faulted from bad checksum, then cycle through all Checksums until 1 works
      if CS.steer_error == 1:
        self.camera_disconnected = True
        cloudlog.warning("Camera Not Detected: Brute Forcing Checksums")
        if self.checksum_learn_cnt > 300:
          self.checksum_learn_cnt = 50
          if self.checksum == "NONE":
            cloudlog.info("Testing 6B Checksum")
            self.checksum = "6B"
          elif self.checksum == "6B":
            cloudlog.info("Testing 7B Checksum")
            self.checksum = "7B"
          elif self.checksum == "7B":
            cloudlog.info("Testing CRC8 Checksum")
            self.checksum = "crc8"
          else:
            self.checksum = "NONE"
            return
        else:
          self.checksum_learn_cnt += 1
      else:
        cloudlog.info("Discovered Checksum %s" % self.checksum)
        self.checksum_found = True

    ### Minimum Steer Speed ###

    # Apply Usage of Minimum Steer Speed
    if CS.low_speed_alert:
      disable_steer = True

    ### Turning Indicators ###
    if (CS.left_blinker_on == 1 or CS.right_blinker_on == 1):
      self.turning_signal_timer = 100 # Disable for 1.0 Seconds after blinker turned off

    if self.turning_signal_timer > 0:
      disable_steer = True
      self.turning_signal_timer -= 1

    ### Steering Torque ###
    apply_steer = actuators.steer * SteerLimitParams.STEER_MAX
    apply_steer = limit_steer_rate(apply_steer, self.apply_steer_last, CS.steer_torque_driver, SteerLimitParams)

    if not enabled or disable_steer:
      apply_steer = 0
      steer_req = 0
    else:
      steer_req = 1

    self.apply_steer_last = apply_steer

    '''
    ### Auto Speed Limit ###

    # Read Speed Limit and define if adjustment needed
    if (self.cnt % 50) == 0 and self.speed_enable:
      if not (enabled and CS.acc_active):
        self.speed_adjusted = False
      map_data = messaging.recv_one_or_none(self.map_data_sock)
      if map_data is not None:
        if bool(self.params.get("IsMetric")):
          self.speed_conv = CV.MS_TO_KPH
        else:
          self.speed_conv = CV.MS_TO_MPH

        if map_data.liveMapData.speedLimitValid:
          last_speed = self.map_speed
          v_speed = int(map_data.liveMapData.speedLimit * self.speed_offset)
          self.map_speed = v_speed * self.speed_conv
          if last_speed != self.map_speed:
            self.speed_adjusted = False
        else:
          self.map_speed = 0
          self.speed_adjusted = True
    else:
      self.map_speed = 0
      self.speed_adjusted = True

    # Spam buttons for Speed Adjustment
    if CS.acc_active and not self.speed_adjusted and self.map_speed > (8.5 * self.speed_conv) and (self.cnt % 9 == 0 or self.cnt % 9 == 1):
      if (CS.cruise_set_speed * self.speed_conv) > (self.map_speed * 1.005):
        can_sends.append(create_clu11(self.packer, CS.clu11, Buttons.SET_DECEL, (1 if self.cnt % 9 == 1 else 0)))
      elif (CS.cruise_set_speed * self.speed_conv) < (self.map_speed / 1.005):
        can_sends.append(create_clu11(self.packer, CS.clu11, Buttons.RES_ACCEL, (1 if self.cnt % 9 == 1 else 0)))
      else:
        self.speed_adjusted = True

    # Cancel Adjustment on Pedal
    if CS.pedal_gas:
      self.speed_adjusted = True

    '''

    ### Generate CAN Messages ###

    self.lkas11_cnt = self.cnt % 0x10
#   self.clu11_cnt = self.cnt % 0x10
    self.mdps12_cnt = self.cnt % 0x100

    if self.camera_disconnected:
      if (self.cnt % 10) == 0:
        can_sends.append(create_lkas12())
      if (self.cnt % 50) == 0:
        can_sends.append(create_1191())
      if (self.cnt % 7) == 0:
        can_sends.append(create_1156())

    can_sends.append(create_lkas11(self.packer, self.car_fingerprint, apply_steer, steer_req, self.lkas11_cnt,
                                   enabled, CS.lkas11, hud_alert, (not self.camera_disconnected), self.checksum))

    if not self.camera_disconnected:
      can_sends.append(create_mdps12(self.packer, self.car_fingerprint, self.mdps12_cnt, CS.mdps12, CS.lkas11, \
                                    self.checksum))

#    if pcm_cancel_cmd:
#      can_sends.append(create_clu11(self.packer, CS.clu11, Buttons.CANCEL, 0))
    if CS.stopped and (self.cnt - self.last_resume_cnt) > 20:
      if (self.cnt - self.last_resume_cnt) > 20:
        self.last_resume_cnt = self.cnt
      can_sends.append(create_clu11(self.packer, CS.clu11, Buttons.RES_ACCEL, self.clu11_cnt))

    self.cnt += 1

    return can_sends
예제 #28
0
    def update(self, CC, CS, frame, sm, CP):

        if self.CP != CP:
            self.CP = CP

        self.param_load()

        enabled = CC.enabled
        actuators = CC.actuators
        pcm_cancel_cmd = CC.cruiseControl.cancel

        self.dRel, self.yRel, self.vRel = SpdController.get_lead(sm)

        if self.SC is not None:
            self.model_speed, self.model_sum = self.SC.calc_va(sm, CS.out.vEgo)
        else:
            self.model_speed = self.model_sum = 0

        # Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.out.steeringTorque,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled and abs(CS.out.steeringAngle) < 180.  #90

        if ((CS.out.leftBlinker and not CS.out.rightBlinker) or
            (CS.out.rightBlinker
             and not CS.out.leftBlinker)) and CS.out.vEgo < 60 * CV.KPH_TO_MS:
            self.lanechange_manual_timer = 10
        if CS.out.leftBlinker and CS.out.rightBlinker:
            self.emergency_manual_timer = 10
        if abs(CS.out.steeringTorque) > 409:  #360: #180
            self.driver_steering_torque_above_timer = 100
        if self.lanechange_manual_timer or self.driver_steering_torque_above_timer:
            lkas_active = 0
        if self.lanechange_manual_timer > 0:
            self.lanechange_manual_timer -= 1
        if self.emergency_manual_timer > 0:
            self.emergency_manual_timer -= 1
        if self.driver_steering_torque_above_timer > 0:
            self.driver_steering_torque_above_timer -= 1

        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        self.apply_steer_last = apply_steer

        sys_warning, sys_state = self.process_hud_alert(lkas_active, CC)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 55
        if clu11_speed > enabled_speed:
            enabled_speed = clu11_speed

        can_sends = []
        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1
        self.lkas11_cnt %= 0x10

        can_sends.append(
            create_lkas11(self.packer, self.lkas11_cnt, self.car_fingerprint,
                          apply_steer, steer_req, CS.lkas11, sys_warning,
                          sys_state, CC, enabled, 0))
        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas11 bus 1 if mdps is on bus 1
            can_sends.append(
                create_lkas11(self.packer, self.lkas11_cnt,
                              self.car_fingerprint, apply_steer, steer_req,
                              CS.lkas11, sys_warning, sys_state, CC, enabled,
                              1))

        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            #if frame % 2 and CS.mdps_bus == 1: # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, frame, CS.mdps_bus, CS.clu11,
                             Buttons.NONE, enabled_speed))

        #if CS.mdps_bus:
        can_sends.append(create_mdps12(self.packer, frame, CS.mdps12))

        str_log1 = '곡률={:04.1f}/{:=+06.3f}  토크={:=+04.0f}/{:=+04.0f}'.format(
            self.model_speed, self.model_sum, new_steer, CS.out.steeringTorque)
        str_log2 = '프레임율={:03.0f}'.format(self.timer1.sampleTime())
        trace1.printf('{}  {}'.format(str_log1, str_log2))

        if CS.out.cruiseState.modeSel == 0 and self.mode_change_switch == 4:
            self.mode_change_timer = 50
            self.mode_change_switch = 0
        elif CS.out.cruiseState.modeSel == 1 and self.mode_change_switch == 0:
            self.mode_change_timer = 50
            self.mode_change_switch = 1
        elif CS.out.cruiseState.modeSel == 2 and self.mode_change_switch == 1:
            self.mode_change_timer = 50
            self.mode_change_switch = 2
        elif CS.out.cruiseState.modeSel == 3 and self.mode_change_switch == 2:
            self.mode_change_timer = 50
            self.mode_change_switch = 3
        elif CS.out.cruiseState.modeSel == 4 and self.mode_change_switch == 3:
            self.mode_change_timer = 50
            self.mode_change_switch = 4
        if self.mode_change_timer > 0:
            self.mode_change_timer -= 1

        run_speed_ctrl = self.param_OpkrAccelProfile and CS.acc_active and self.SC != None
        if not run_speed_ctrl:
            if CS.out.cruiseState.modeSel == 0:
                self.steer_mode = "오파모드"
            elif CS.out.cruiseState.modeSel == 1:
                self.steer_mode = "차간+커브"
            elif CS.out.cruiseState.modeSel == 2:
                self.steer_mode = "차간ONLY"
            elif CS.out.cruiseState.modeSel == 3:
                self.steer_mode = "자동RES"
            elif CS.out.cruiseState.modeSel == 4:
                self.steer_mode = "순정모드"
            if CS.out.steerWarning == 0:
                self.mdps_status = "정상"
            elif CS.out.steerWarning == 1:
                self.mdps_status = "오류"
            if CS.lkas_button_on == 0:
                self.lkas_switch = "OFF"
            elif CS.lkas_button_on == 1:
                self.lkas_switch = "ON"
            else:
                self.lkas_switch = "-"
            str_log2 = '주행모드={:s}  MDPS상태={:s}  LKAS버튼={:s}'.format(
                self.steer_mode, self.mdps_status, self.lkas_switch)
            trace1.printf2('{}'.format(str_log2))

        #print( 'st={} cmd={} long={}  steer={} req={}'.format(CS.out.cruiseState.standstill, pcm_cancel_cmd, self.CP.openpilotLongitudinalControl, apply_steer, steer_req ) )

        if pcm_cancel_cmd and self.CP.openpilotLongitudinalControl:
            can_sends.append(
                create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                             Buttons.CANCEL, clu11_speed))
        elif CS.out.cruiseState.standstill and not self.car_fingerprint == CAR.NIRO_EV:
            # run only first time when the car stopped
            if self.last_lead_distance == 0 or not self.param_OpkrAutoResume:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance != self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.resume_cnt = 0
        elif CS.out.cruiseState.standstill and self.car_fingerprint == CAR.NIRO_EV:
            if CS.lead_distance > 3.7 and (
                    frame - self.last_resume_frame
            ) * DT_CTRL > 0.2 and self.param_OpkrAutoResume:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.last_resume_frame = frame

        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0
        elif run_speed_ctrl and self.SC != None:
            is_sc_run = self.SC.update(CS, sm, self)
            if is_sc_run:
                can_sends.append(
                    create_clu11(self.packer, self.resume_cnt, CS.scc_bus,
                                 CS.clu11, self.SC.btn_type,
                                 self.SC.sc_clu_speed))
                self.resume_cnt += 1
            else:
                self.resume_cnt = 0

        if CS.out.cruiseState.modeSel == 3:
            if CS.out.brakeLights and CS.VSetDis > 30:
                self.res_cnt = 0
                self.res_delay = 50
            elif self.res_delay:
                self.res_delay -= 1
            elif not self.res_delay and self.res_cnt < 0 and CS.VSetDis > 30 and CS.out.vEgo > 30 * CV.KPH_TO_MS:
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.CANCEL, clu11_speed))
                can_sends.append(
                    create_clu11(self.packer, frame, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed))
                self.res_cnt += 1
            else:
                self.res_cnt = 7
                self.res_delay = 0

        # 20 Hz LFA MFA message
        if frame % 5 == 0 and self.car_fingerprint in FEATURES["send_lfa_mfa"]:
            can_sends.append(create_lfa_mfa(self.packer, frame, enabled))

        self.lkas11_cnt += 1
        return can_sends
예제 #29
0
    def update(self, sendcan, enabled, CS, actuators, pcm_cancel_cmd,
               hud_alert):

        if not self.enable_camera:
            return

        if CS.camcan > 0:
            if self.checksum == "NONE":
                self.checksum = learn_checksum(self.packer, CS.lkas11)
                print("Discovered Checksum", self.checksum)
                if self.checksum == "NONE":
                    return
        elif CS.steer_error == 1:
            if self.checksum_learn_cnt > 200:
                self.checksum_learn_cnt = 0
                if self.checksum == "NONE":
                    print("Testing 6B Checksum")
                    self.checksum == "6B"
                elif self.checksum == "6B":
                    print("Testing 7B Checksum")
                    self.checksum == "7B"
                elif self.checksum == "7B":
                    print("Testing CRC8 Checksum")
                    self.checksum == "crc8"
                else:
                    self.checksum == "NONE"
            else:
                self.checksum_learn_cnt += 1

        force_enable = False

        # I don't care about your opinion, deal with it!
        if (CS.cstm_btns.get_button_status("alwon") > 0) and CS.acc_active:
            enabled = True
            force_enable = True

        if (self.car_fingerprint in FEATURES["soft_disable"]
                and CS.v_wheel < 16.8):
            enabled = False
            force_enable = False

        if (CS.left_blinker_on == 1 or CS.right_blinker_on == 1):
            self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off

        #update custom UI buttons and alerts
        CS.UE.update_custom_ui()
        if (self.cnt % 100 == 0):
            CS.cstm_btns.send_button_info()
            CS.UE.uiSetCarEvent(CS.cstm_btns.car_folder, CS.cstm_btns.car_name)

        # Get the angle from ALCA.
        alca_enabled = False
        alca_steer = 0.
        alca_angle = 0.
        turn_signal_needed = 0
        # Update ALCA status and custom button every 0.1 sec.
        if self.ALCA.pid == None:
            self.ALCA.set_pid(CS)
        self.ALCA.update_status(CS.cstm_btns.get_button_status("alca") > 0)

        alca_angle, alca_steer, alca_enabled, turn_signal_needed = self.ALCA.update(
            enabled, CS, self.cnt, actuators)
        if force_enable and not CS.acc_active:
            apply_steer = int(
                round(actuators.steer * SteerLimitParams.STEER_MAX))
        else:
            apply_steer = int(round(alca_steer * SteerLimitParams.STEER_MAX))

        # SPAS limit angle extremes for safety
        apply_steer_ang_req = np.clip(actuators.steerAngle,
                                      -1 * (SteerLimitParams.STEER_ANG_MAX),
                                      SteerLimitParams.STEER_ANG_MAX)
        # SPAS limit angle rate for safety
        if abs(self.apply_steer_ang - apply_steer_ang_req) > 0.6:
            if apply_steer_ang_req > self.apply_steer_ang:
                self.apply_steer_ang += 0.5
            else:
                self.apply_steer_ang -= 0.5
        else:
            self.apply_steer_ang = apply_steer_ang_req

        # Limit steer rate for safety
        apply_steer = limit_steer_rate(apply_steer, self.apply_steer_last,
                                       SteerLimitParams,
                                       CS.steer_torque_driver)

        if alca_enabled:
            self.turning_signal_timer = 0

        if self.turning_signal_timer > 0:
            self.turning_signal_timer = self.turning_signal_timer - 1
            turning_signal = 1
        else:
            turning_signal = 0

        # Use LKAS or SPAS
        if CS.mdps11_stat == 7 or CS.v_wheel > 2.7:
            self.lkas = True
        elif CS.v_wheel < 0.1:
            self.lkas = False
        if self.spas_present:
            self.lkas = True

        # If ALCA is disabled, and turning indicators are turned on, we do not want OP to steer,
        if not enabled or (turning_signal and not alca_enabled):
            if self.lkas:
                apply_steer = 0
            else:
                self.apply_steer_ang = 0.0
                self.en_cnt = 0

        steer_req = 1 if enabled and self.lkas else 0

        self.apply_steer_last = apply_steer

        can_sends = []

        self.lkas11_cnt = self.cnt % 0x10
        self.clu11_cnt = self.cnt % 0x10
        self.mdps12_cnt = self.cnt % 0x100
        self.spas_cnt = self.cnt % 0x200

        can_sends.append(create_lkas11(self.packer, self.car_fingerprint, apply_steer, steer_req, self.lkas11_cnt, \
                                      enabled if self.lkas else False, False if CS.camcan == 0 else CS.lkas11, hud_alert, (CS.cstm_btns.get_button_status("cam") > 0), \
                                      (False if CS.camcan == 0 else True), self.checksum))

        if CS.camcan > 0:
            can_sends.append(create_mdps12(self.packer, self.car_fingerprint, self.mdps12_cnt, CS.mdps12, CS.lkas11, \
                                          CS.camcan, self.checksum))

        # SPAS11 50hz
        if (self.cnt % 2) == 0 and not self.spas_present:
            if CS.mdps11_stat == 7 and not self.mdps11_stat_last == 7:
                self.en_spas == 7
                self.en_cnt = 0

            if self.en_spas == 7 and self.en_cnt >= 8:
                self.en_spas = 3
                self.en_cnt = 0

            if self.en_cnt < 8 and enabled and not self.lkas:
                self.en_spas = 4
            elif self.en_cnt >= 8 and enabled and not self.lkas:
                self.en_spas = 5

            if self.lkas or not enabled:
                self.apply_steer_ang = CS.mdps11_strang
                self.en_spas = 3
                self.en_cnt = 0

            self.mdps11_stat_last = CS.mdps11_stat
            self.en_cnt += 1
            can_sends.append(
                create_spas11(self.packer, (self.spas_cnt / 2), self.en_spas,
                              self.apply_steer_ang, self.checksum))

        # SPAS12 20Hz
        if (self.cnt % 5) == 0 and not self.spas_present:
            can_sends.append(create_spas12(self.packer))

        # Force Disable
        if pcm_cancel_cmd and (not force_enable):
            can_sends.append(
                create_clu11(self.packer, CS.clu11, Buttons.CANCEL, 0))
        elif CS.stopped and (self.cnt - self.last_resume_cnt) > 5:
            self.last_resume_cnt = self.cnt
            can_sends.append(
                create_clu11(self.packer, CS.clu11, Buttons.RES_ACCEL, 0))

        # Speed Limit Related Stuff  Lot's of comments for others to understand!
        # Run this twice a second
        if (self.cnt % 50) == 0:
            if self.params.get("LimitSetSpeed") == "1" and self.params.get(
                    "SpeedLimitOffset") is not None:
                # If Not Enabled, or cruise not set, allow auto speed adjustment again
                if not (enabled and CS.acc_active_real):
                    self.speed_adjusted = False
                # Attempt to read the speed limit from zmq
                map_data = messaging.recv_one_or_none(self.map_data_sock)
                # If we got a message
                if map_data != None:
                    # See if we use Metric or dead kings extremeties for measurements, and set a variable to the conversion value
                    if bool(self.params.get("IsMetric")):
                        self.speed_conv = CV.MS_TO_KPH
                    else:
                        self.speed_conv = CV.MS_TO_MPH

                    # If the speed limit is valid
                    if map_data.liveMapData.speedLimitValid:
                        last_speed = self.map_speed
                        # Get the speed limit, and add the offset to it,
                        v_speed = (map_data.liveMapData.speedLimit +
                                   float(self.params.get("SpeedLimitOffset")))
                        ## Stolen curvature code from planner.py, and updated it for us
                        v_curvature = 45.0
                        if map_data.liveMapData.curvatureValid:
                            v_curvature = math.sqrt(
                                1.85 /
                                max(1e-4, abs(map_data.liveMapData.curvature)))
                        # Use the minimum between Speed Limit and Curve Limit, and convert it as needed
                        #self.map_speed = min(v_speed, v_curvature) * self.speed_conv
                        self.map_speed = v_speed * self.speed_conv
                        # Compare it to the last time the speed was read.  If it is different, set the flag to allow it to auto set our speed
                        if last_speed != self.map_speed:
                            self.speed_adjusted = False
                    else:
                        # If it is not valid, set the flag so the cruise speed won't be changed.
                        self.map_speed = 0
                        self.speed_adjusted = True
            else:
                self.speed_adjusted = True

        # Ensure we have cruise IN CONTROL, so we don't do anything dangerous, like turn cruise on
        # Ensure the speed limit is within range of the stock cruise control capabilities
        # Do the spamming 10 times a second, we might get from 0 to 10 successful
        # Only do this if we have not yet set the cruise speed
        if CS.acc_active_real and not self.speed_adjusted and self.map_speed > (
                8.5 * self.speed_conv) and (self.cnt % 9 == 0
                                            or self.cnt % 9 == 1):
            # Use some tolerance because of Floats being what they are...
            if (CS.cruise_set_speed * self.speed_conv) > (self.map_speed *
                                                          1.005):
                can_sends.append(
                    create_clu11(self.packer, CS.clu11, Buttons.SET_DECEL,
                                 (1 if self.cnt % 9 == 1 else 0)))
            elif (CS.cruise_set_speed * self.speed_conv) < (self.map_speed /
                                                            1.005):
                can_sends.append(
                    create_clu11(self.packer, CS.clu11, Buttons.RES_ACCEL,
                                 (1 if self.cnt % 9 == 1 else 0)))
            # If nothing needed adjusting, then the speed has been set, which will lock out this control
            else:
                self.speed_adjusted = True

        ### If Driver Overrides using accelerator (or gas for the antiquated), cancel auto speed adjustment
        if CS.pedal_gas:
            self.speed_adjusted = True
        ### Send messages to canbus
        sendcan.send(
            can_list_to_can_capnp(can_sends, msgtype='sendcan').to_bytes())

        self.cnt += 1
예제 #30
0
    def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd,
               visual_alert, left_line, right_line, left_lane_depart,
               right_lane_depart):

        # *** compute control surfaces ***

        # gas and brake
        apply_accel = actuators.gas - actuators.brake

        apply_accel, self.accel_steady = accel_hysteresis(
            apply_accel, self.accel_steady)
        apply_accel = clip(apply_accel * ACCEL_SCALE, ACCEL_MIN, ACCEL_MAX)

        ### Steering Torque
        new_steer = actuators.steer * SteerLimitParams.STEER_MAX
        apply_steer = apply_std_steer_torque_limits(new_steer,
                                                    self.apply_steer_last,
                                                    CS.steer_torque_driver,
                                                    SteerLimitParams)
        self.steer_rate_limited = new_steer != apply_steer

        # SPAS limit angle extremes for safety
        apply_steer_ang_req = clip(actuators.steer, -1 * (STEER_ANG_MAX),
                                   STEER_ANG_MAX)
        # SPAS limit angle rate for safety
        if abs(self.apply_steer_ang - apply_steer_ang_req) > 1.5:
            if apply_steer_ang_req > self.apply_steer_ang:
                self.apply_steer_ang += 0.5
            else:
                self.apply_steer_ang -= 0.5
        else:
            self.apply_steer_ang = apply_steer

        # LKAS button to temporarily disable steering
        if not CS.lkas_error:
            if CS.lkas_button_on != self.lkas_button_last:
                self.lkas_button = not self.lkas_button
            self.lkas_button_last = CS.lkas_button_on

        # disable if steer angle reach 90 deg, otherwise mdps fault in some models
        lkas_active = enabled and abs(
            CS.angle_steers) < 90. and self.lkas_button

        # fix for Genesis hard fault at low speed
        if CS.v_ego < 16.7 and self.car_fingerprint == CAR.GENESIS and not CS.mdps_bus:
            lkas_active = 0

        # Disable steering while turning blinker on and speed below 60 kph
        if CS.left_blinker_on or CS.right_blinker_on:
            if self.car_fingerprint not in [CAR.KIA_OPTIMA, CAR.KIA_OPTIMA_H]:
                self.turning_signal_timer = 100  # Disable for 1.0 Seconds after blinker turned off
            elif CS.left_blinker_flash or CS.right_blinker_flash:  # Optima has blinker flash signal only
                self.turning_signal_timer = 100
        if self.turning_signal_timer and CS.v_ego < 16.7:
            lkas_active = 0
        if self.turning_signal_timer:
            self.turning_signal_timer -= 1
        if not lkas_active:
            apply_steer = 0

        steer_req = 1 if apply_steer else 0

        self.apply_accel_last = apply_accel
        self.apply_steer_last = apply_steer

        hud_alert, lane_visible, left_lane_warning, right_lane_warning =\
                process_hud_alert(lkas_active, self.lkas_button, self.car_fingerprint, visual_alert,
                left_line, right_line,left_lane_depart, right_lane_depart)

        clu11_speed = CS.clu11["CF_Clu_Vanz"]
        enabled_speed = 38 if CS.is_set_speed_in_mph else 60
        if clu11_speed > enabled_speed or not lkas_active:
            enabled_speed = clu11_speed

        can_sends = []

        if frame == 0:  # initialize counts from last received count signals
            self.lkas11_cnt = CS.lkas11["CF_Lkas_MsgCount"] + 1
            self.scc12_cnt = CS.scc12[
                "CR_VSM_Alive"] + 1 if not CS.no_radar else 0

        self.lkas11_cnt %= 0x10
        self.scc12_cnt %= 0xF
        self.clu11_cnt = frame % 0x10
        self.mdps12_cnt = frame % 0x100
        self.spas_cnt = frame % 0x200

        # SPAS11 50hz

        if (frame % 2) == 0:
            if CS.mdps11_stat == 7 and not self.mdps11_stat_last == 7:
                self.en_spas == 7
                self.en_cnt = 0

            if self.en_spas == 7 and self.en_cnt >= 8:
                self.en_spas = 3
                self.en_cnt = 0

            if self.en_cnt < 8 and enabled and not self.lkas:
                self.en_spas = 4
            elif self.en_cnt >= 8 and enabled and not self.lkas:
                self.en_spas = 5

            if self.lkas or not enabled:
                self.apply_steer_ang = CS.mdps11_strang
                self.en_spas = 3
                self.en_cnt = 0

            self.mdps11_stat_last = CS.mdps11_stat
            self.en_cnt += 1
            can_sends.append(
                create_spas11(self.packer, (frame // 2), self.en_spas,
                              self.apply_steer_ang, self.checksum))
            #can_sends.append(create_spas11(self.packer, (self.spas_cnt / 2), self.en_spas, apply_steer, 'crc8'))

        # SPAS12 20Hz
        if (frame % 5) == 0:
            can_sends.append(create_spas12(self.packer))

        #can_sends.append(create_ems11(self.packer, CS.ems11, enabled))

        #can_sends.append(create_vsm11(self.packer, CS.vsm11, enabled, 1, steer_req, 1, self.lkas11_cnt))
        #can_sends.append(create_790())
        #can_sends.append([790, 0, b'\x00\x00\xff\xff\x00\xff\xff\xff', 0])

        #print('send car data',CS.vsm11, enabled, 1, steer_req, self.lkas11_cnt)
        #can_sends.append(create_vsm11(self.packer, CS.vsm11, 1, 2, steer_req,0, self.clu11_cnt))
        #can_sends.append(create_vsm11(self.packer, CS.vsm11, 1, 2, steer_req,1, self.clu11_cnt))

        #can_sends.append(create_clu11(self.packer, CS.scc_bus, CS.clu11, Buttons.NONE, clu11_speed, self.clu11_cnt))

        #can_sends.append(create_clu11(self.packer, CS.scc_bus, CS.clu11, Buttons.CANCEL, clu11_speed, self.clu11_cnt))

        #can_sends.append(create_vsm2(self.packer, CS.vsm2, 1, apply_steer,0, self.lkas11_cnt))
        #can_sends.append(create_vsm2(self.packer, CS.vsm2, 1, apply_steer,1, self.lkas11_cnt))

        can_sends.append(
            create_lkas11(self.packer,
                          self.car_fingerprint,
                          0,
                          apply_steer,
                          steer_req,
                          self.lkas11_cnt,
                          lkas_active,
                          CS.lkas11,
                          hud_alert,
                          lane_visible,
                          left_lane_depart,
                          right_lane_depart,
                          keep_stock=True))
        if CS.mdps_bus or CS.scc_bus == 1:  # send lkas12 bus 1 if mdps or scc is on bus 1
            can_sends.append(
                create_lkas11(self.packer,
                              self.car_fingerprint,
                              1,
                              apply_steer,
                              steer_req,
                              self.lkas11_cnt,
                              lkas_active,
                              CS.lkas11,
                              hud_alert,
                              lane_visible,
                              left_lane_depart,
                              right_lane_depart,
                              keep_stock=True))
        if CS.mdps_bus:  # send clu11 to mdps if it is not on bus 0
            can_sends.append(
                create_clu11(self.packer, CS.mdps_bus, CS.clu11, Buttons.NONE,
                             enabled_speed, self.clu11_cnt))

        if pcm_cancel_cmd and self.longcontrol:
            can_sends.append(
                create_clu11(self.packer, CS.scc_bus, CS.clu11, Buttons.CANCEL,
                             clu11_speed, self.clu11_cnt))
        #else:  send mdps12 to LKAS to prevent LKAS error if no cancel cmd
        #can_sends.append(create_mdps12(self.packer, self.car_fingerprint, self.mdps12_cnt, CS.mdps12))

        if CS.scc_bus and self.longcontrol and frame % 2:  # send scc12 to car if SCC not on bus 0 and longcontrol enabled
            can_sends.append(
                create_scc12(self.packer, apply_accel, enabled, self.scc12_cnt,
                             CS.scc12))
            self.scc12_cnt += 1

        if CS.stopped:
            # run only first time when the car stopped
            if self.last_lead_distance == 0:
                # get the lead distance from the Radar
                self.last_lead_distance = CS.lead_distance
                self.resume_cnt = 0
            # when lead car starts moving, create 6 RES msgs
            elif CS.lead_distance > self.last_lead_distance and (
                    frame - self.last_resume_frame) > 5:
                can_sends.append(
                    create_clu11(self.packer, CS.scc_bus, CS.clu11,
                                 Buttons.RES_ACCEL, clu11_speed,
                                 self.clu11_cnt))
                self.resume_cnt += 1
                # interval after 6 msgs
                if self.resume_cnt > 5:
                    self.last_resume_frame = frame
                    self.clu11_cnt = 0
        # reset lead distnce after the car starts moving
        elif self.last_lead_distance != 0:
            self.last_lead_distance = 0

        self.lkas11_cnt += 1

        return can_sends