file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
cadop/HumanGenerator/exts/siborg.create.human/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "0.0.2" preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # The title and description fields are primarily for displaying extension info in UI title = "HumanGenerator" description="Human Generator for Omniverse. Create and customize humans in your Omniverse scenes." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Services" feature = true # Keywords for the extension keywords = ["kit", "makehuman","human","character","generator","person"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.usd" = {} "omni.anim.skelJoint" = {} "omni.kit.browser.core" = {} "omni.kit.browser.folder.core" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "siborg.create.human" [settings] exts."siborg.create.human.browser.asset".instanceable = [] exts."siborg.create.human.browser.asset".timeout = 10 [python.pipapi] use_online_index = true # Use this to specify a list of additional repositories if your pip package is hosted somewhere other # than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument repositories = ["https://test.pypi.org/simple/"] requirements = ["makehuman==1.2.2"]
1,558
TOML
28.980769
105
0.734275
cadop/HumanGenerator/exts/siborg.create.human/docs/README.md
# Overview HumanGenerator generates parametric, rigged, outfitted humans in NVIDIA Omniverse. This project relies on the Makehuman project from https://github.com/makehumancommunity/makehuman. # Getting Started The easiest way to get started is using Omniverse Create. Navigate to the Extensions window and click on "Community". Search for `HumanGenerator` and you should see our extension show up. The extension may take a few minutes to install as it will download makehuman and install it in the Omniverse's local Python instance. For use, check out the walkthrough video on Github. ## License *Our license restrictions are due to the AGPL of MakeHuman. In line with the statements from MakeHuman, the targets and resulting characters are CC0, meaning you can use whatever you create for free, without restrictions. It is only the codebase that is AGPL.
871
Markdown
44.894734
259
0.797933
cadop/crowds/README.md
![preview](https://user-images.githubusercontent.com/11399119/226725400-fa9054e3-a13f-4a9f-8294-d08cbee51519.PNG) This repository is for the omniverse extension for crowd simulation. If you are looking for a project that can be run without omniverse, checkout [Python-only crowd simulation](https://github.com/cadop/warpcrowd) A crowd simulator API with a default demo scene. The main python API can be used in a few ways. There is an examples folder showing a few use-cases. Users can also switch between social forces and PAM as the crowds algorithm. The extension will load an populate some demo configuration. It will create an Xform called CrowdGoals. To add a goal for the crowd. Create an xform under the "CrowdGoals". We automatically check for those prims as the method of determing crowd goals. For every additional xform under CrowdGoals, we evenly split the crowd to assign those goals. There are two options for the crowd objects. The default uses geompoints, which is faster and runs its own integration of the forces for position and velocity. It does not interact with any physics in the scene. Alternatively the "Rigid Body" can be used, which creates physical spheres that interact with the scene. Press Play to see the crowd. The default number of demo agents is a 3x3 grid (9 agents). The current simulator in python may struggle above 25 agents, depending on CPU configuration. We plan to support more methods in the future, as well as more crowd simulators. Contributions are welcome.
1,525
Markdown
88.764701
348
0.796066
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/simulator.py
import numpy as np from numpy import random from omni.physx import get_physx_interface import omni import carb from pxr import UsdGeom, Gf, Sdf, UsdShade import warp as wp import copy import usdrt from siborg.simulate.crowd.crowds import CrowdConfig from siborg.simulate.crowd.models import socialforces from siborg.simulate.crowd.models import pam wp.init() from siborg.simulate.crowd.models import socialforces_warp as crowd_force class Simulator(CrowdConfig): def __init__(self, world=None): super().__init__() self.world = world # a default dt that is surely overwritten later self._dt = 1/60.0 # set radius self.radius = 0.7 self.radius_min = 0.5 self.radius_max = 1.0 # A subscription to the physics simulation, used when this class # is asked to manage the updates self._simulation_event = None # Will use a physics scene self.rigidbody = False self.use_pam = False self.on_gpu = False self.use_instancer = False self.add_jane = False self.use_heading = False # Tracks if user wants to update agent position on each sim step self.update_agents_sim = False self.update_viz = False self.instancer_paths = ["/World/PointInstancer_Bob", "/World/PointInstancer_Jane"] self.point_instancer_sets = [] self.agent_instance_path_bob = '/World/Scope/CrowdBob' self.agent_instance_path_jane = '/World/Scope/CrowdJane' self.instance_forward_vec = (1.0,0.0,0.0) # TODO get from instance object self.instance_up_vec = (0.0,1.0,0.0) # TODO Fix to be flexible later self.vel_epsilon = 0.05 self._get_world_up() def _get_world_up(self): stage = omni.usd.get_context().get_stage() up = UsdGeom.GetStageUpAxis(stage) if up =='X': self.world_up = 0 if up =='Y': self.world_up = 1 if up =='Z': self.world_up = 2 return def register_simulation(self): self._callbacks() # we need to update the agents, otherwise won't see these results self.update_agents_sim = True self.update_viz = True def _callbacks(self): self._simulation_event = get_physx_interface( ).subscribe_physics_step_events( self._on_simulation_update) def _unregister(self): try: self._simulation_event.unsubscribe() except: self._simulation_event = None def _on_simulation_update(self, dt): if self.agent_bodies is None: return self._dt = dt self.run() def set_xform_goal(self, p): '''set the goal based on a subscribed xform Example of usage watcher = omni.usd.get_watcher() self._goal_subscriber = watcher.subscribe_to_change_info_path( Sdf.Path('/World/Goal.xformOp:translate'), self.Sim.set_xform_goal) Parameters ---------- p : str(prim path) a subscribed path ''' stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(str(p).split('.')[0]) goal_point = omni.usd.utils.get_world_transform_matrix(prim).ExtractTranslation() # Set agent destination self.goals = np.asarray([goal_point for x in range(self.nagents)]) def integrate(self, x, v, f, dt): ''' take position, velocity, force, and dt to compute updated position and velocity ''' v1 = v + ( (f * 1.0) * dt ) # new velocity x1 = x + (v1 * dt) # new position return x1, v1 def update_goals(self, new_goal): '''update the goals of agents Parameters ---------- new_goal : ndarray([x,y,z]) can either be one goal that is applied to all agents, or a list of the same size as number of agents ''' if len(new_goal) == 1: self.goals = np.asarray([new_goal for x in range(self.nagents)]) else: self.goals = new_goal def compute_step(self, agent): # Set the model to PAM if asked if self.use_pam: model = pam else: model = socialforces # Get the neighbors of this agent to use in computing forces pn = model.get_neighbors(self.agents_pos[agent], self.agents_pos, self.agents_percept[agent])[1] _force = model.compute_force(self.agents_pos[agent], self.agents_radi[agent], self.agents_vel[agent], self.agents_mass[agent], self.goals[agent], self.agents_pos[pn], self.agents_vel[pn], self.agents_radi[pn], self._dt) return _force def run(self): '''Runs the simulation for one step Updates agent positions and velocities if instance flag is true Returns ------- ndarray[x,y,z] forces ''' self.force_list = [] for agent in range(self.nagents): _force = self.compute_step(agent) # remove world (up) forces _force[self.world_up] = 0 # Store all forces to be applied to agents self.force_list.append(_force) self.step_processing() def step_processing(self): '''Process the computed step for simulation Returns ------- _type_ _description_ ''' # only update agent positions if user requests, otherwise they might want to # update using forces themselves if self.update_agents_sim: # If using rigid body, apply forces to agents if self.rigidbody: self.apply_force(self.force_list) else: self.internal_integration() if self.use_instancer: self.set_instance_agents() else: self.set_geompoints() def internal_integration(self): # Integrate for new position for i in range(self.nagents): self.agents_pos[i], self.agents_vel[i] = self.integrate(self.agents_pos[i], self.agents_vel[i], self.force_list[i], self._dt) def apply_force(self, force_list): '''Used for when rigidbody agents are used Parameters ---------- force_list : List[x,y,z] list of forces in order of the agents ''' # Apply forces to simulation # with Sdf.ChangeBlock(): # for idx, force in enumerate(force_list): # self._add_force(force, self.agent_bodies[idx], self.agent_bodies[idx].position) self._add_force3(force_list, self.agent_bodies) # Update positions and velocities for i in range(self.nagents): self.agents_pos[i] = self.agent_bodies[i].position self.agents_vel[i] = self.agent_bodies[i].velocity def _add_force(self, force, rigid_body, position): force = carb.Float3(force) position = carb.Float3(position) get_physx_interface().apply_force_at_pos(rigid_body.skinMeshPath, force, position) def _add_force2(self, force, rigid_body, position): # force = Gf.Vec3d(force) _ = force[0] force = Gf.Vec3d(float(force[0]), float(force[1]),float(force[2])) rigid_body.forceAttr.Set(force) #position def _add_force3(self, force_list, rigid_body): # force = Gf.Vec3d(force) # stage = usdrt.Usd.Stage.Attach(omni.usd.get_context().get_stage_id()) # # prim = stage.GetPrimAtPath("/World/boxActor") # attr = prim.CreateAttribute("_worldForce", usdrt.Sdf.ValueTypeNames.Float3, True) # if attr: # attr.Set(usdrt.Gf.Vec3f(50000.0, 0.0, 0.0)) # prefixes = set(prefix for path in paths for prefix in path.GetPrefixes()) # with Sdf.ChangeBlock(): # for path in prefixes: # prim_spec = Sdf.CreatePrimInLayer(layer, path) # prim_spec.specifier = Sdf.SpecifierDef # prim_spec.typeName = UsdGeom.Xform.__name__ for idx, body in enumerate(rigid_body): force = force_list[idx] force = usdrt.Gf.Vec3d(float(force[0]), float(force[1]),float(force[2])) # body.forceAttr.Set(force) #position if body.world_force_attr: body.world_force_attr.Set(force) def create_geompoints(self, stage_path=None, color=None): '''create and manage geompoints representing agents Parameters ---------- stage_path : str, optional if not set, will use /World/Points, by default None color : (r,g,b), optional if not set, will make color red, by default None ''' if stage_path: stage_loc = stage_path else: stage_loc = "/World/Points" self.stage = omni.usd.get_context().get_stage() self.agent_point_prim = UsdGeom.Points.Define(self.stage, stage_loc) self.agent_point_prim.CreatePointsAttr() width_attr = self.agent_point_prim.CreateWidthsAttr() width_attr.Set(self.agents_radi) # width_attr.Set([1 for x in range(self.nagents)]) self.agent_point_prim.CreateDisplayColorAttr() # For RTX renderers, this only works for UsdGeom.Tokens.constant color_primvar = self.agent_point_prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant) if color: point_color = color else: point_color = (1,0,0) color_primvar.Set([point_color]) def set_geompoints(self): # Set the position with an offset based on the radius # Since it is a sphere, we render_pos = np.copy(self.agents_pos) render_pos[:,1] += (self.agents_radi/2) self.agent_point_prim.GetPointsAttr().Set(render_pos) def create_instance_agents(self): if self.add_jane: bob_size = int(self.nagents/2) bob_pos = self.agents_pos[:bob_size] point_instancer = self._single_agent_instance(bob_pos, bob_size, self.agent_instance_path_bob, self.instancer_paths[0]) self.point_instancer_sets.append(point_instancer) # TODO find way to split colors of instances jane_size = int(self.nagents/2) jane_pos = self.agents_pos[bob_size:] point_instancer = self._single_agent_instance(jane_pos, jane_size , self.agent_instance_path_jane, self.instancer_paths[1]) self.point_instancer_sets.append(point_instancer) else: point_instancer = self._single_agent_instance(self.agents_pos, self.nagents, self.agent_instance_path_bob, self.instancer_paths[0]) self.point_instancer_sets.append(point_instancer) def _single_agent_instance(self, agent_pos, nagents, agent_instance_path, instance_path): stage = omni.usd.get_context().get_stage() point_instancer = UsdGeom.PointInstancer.Get(stage, instance_path) if not point_instancer: point_instancer = UsdGeom.PointInstancer(stage.DefinePrim(instance_path, "PointInstancer")) point_instancer.CreatePrototypesRel().SetTargets([agent_instance_path]) self.proto_indices_attr = point_instancer.CreateProtoIndicesAttr() self.proto_indices_attr.Set([0] * nagents) ## max radius is scale of 1 agent_scales = self.agents_radi/self.radius_max self.agent_instancer_scales = [(x,x,x) for x in agent_scales] # change to numpy # Set scale point_instancer.GetScalesAttr().Set(self.agent_instancer_scales) point_instancer.GetPositionsAttr().Set(agent_pos) # Set orientation rot = Gf.Rotation() rot.SetRotateInto(self.instance_forward_vec, self.instance_forward_vec) self.agent_headings = [Gf.Quath(rot.GetQuat()) for x in range(nagents)] point_instancer.GetOrientationsAttr().Set(self.agent_headings) return point_instancer def set_instance_agents(self): # update the points # self.point_instancer.CreatePrototypesRel().SetTargets([self.agent_instance_path]) # self.proto_indices_attr = self.point_instancer.CreateProtoIndicesAttr() # self.proto_indices_attr.Set([0] * self.nagents) for idx, point_instancer in enumerate(self.point_instancer_sets): if len(self.point_instancer_sets) == 1: agents_pos = self.agents_pos else: _slice = int(self.nagents/2) if idx == 0: # Positions for this instance agents_pos = self.agents_pos[:_slice] else: # Positions for this instance agents_pos = self.agents_pos[_slice:] # Set position point_instancer.GetPositionsAttr().Set(agents_pos) if not self.use_heading: continue self.set_heading() def set_heading(self): for idx, point_instancer in enumerate(self.point_instancer_sets): if len(self.point_instancer_sets) == 1: agents_vel = self.agents_vel nagents = self.nagents else: _slice = int(self.nagents/2) nagents = _slice if idx == 0: # Velocities for this instance agents_vel = self.agents_vel[:_slice] else: # Velocities for this instance agents_vel = self.agents_vel[_slice:] # Create array of agent headings based on velocity normalize_vel = agents_vel rot = Gf.Rotation() self.agent_headings = [] cur_orient = point_instancer.GetOrientationsAttr().Get() for i in range(0, nagents): if np.sqrt(normalize_vel[i].dot(normalize_vel[i])) < self.vel_epsilon: tovec = cur_orient[i] self.agent_headings.append(cur_orient[i]) else: tovec = Gf.Vec3d(tuple(normalize_vel[i])) rot.SetRotateInto(self.instance_forward_vec, tovec) self.agent_headings.append(Gf.Quath(rot.GetQuat())) # Set orientation point_instancer.GetOrientationsAttr().Set(self.agent_headings) return #### Change colors stage = omni.usd.get_context().get_stage() # get path of material mat_path = '/CrowdBob/Looks/Linen_Blue' linen_mat = Sdf.Path(f'/World/Scope{mat_path}') mat_prim = stage.GetPrimAtPath(linen_mat) # print(mat_prim) # shader_path = '/Shader.inputs:diffuse_tint' # tint_shader = f'/World{mat_path}{shader_path}' shader = omni.usd.get_shader_from_material(mat_prim) # print(shader) #inp = shader.GetInput('diffuse_tint').Get() inp = shader.GetInput('diffuse_tint').Set((0.5,0.5,1.0)) class WarpCrowd(Simulator): '''A class to manage the warp-based version of crowd simulation ''' def __init__(self, world=None): super().__init__(world) self.device = 'cuda:0' # generate n number of agents self.nagents = 9 # set radius self.radius = 0.7 self.radius_min = 0.5 self.radius_max = 1.0 self.hash_radius = 0.7 # Radius to use for hashgrid # set mass self.mass = 20 # set pereption radius self.perception_radius = 6 # self.dt = 1.0/30.0 self.goal = [0.0,0.0,0.0] self.generation_origin = [10,10.0,0.0] self.inv_up = wp.vec3(1.0,1.0,1.0) # z-up self.inv_up[self.world_up] = 0.0 self.on_gpu = True def demo_agents(self, s=1.6, m=50, n=50): o = self.generation_origin # Initialize agents in a grid for testing self.agents_pos = np.asarray([ np.array([(s/2) + (x * s) +(o[0]/2) , (s/2) + (y * s) +(o[1]/2), 0 ], dtype=np.double) for x in range(m) for y in range(n) ]) self.nagents = len(self.agents_pos) self.configure_params() def configure_params(self): '''Convert all parameters to warp ''' self.agents_pos = np.asarray(self.agents_pos) # self.agents_pos = np.asarray([np.array([0,0,0], dtype=float) for x in range(self.nagents)]) self.agents_vel = np.asarray([np.array([0,0,0], dtype=float) for x in range(self.nagents)]) # # Set a quath for heading # rot = Gf.Rotation() # rot.SetRotateInto(self.instance_forward_vec, self.instance_forward_vec) # from, to # _hquat = Gf.Quath(rot.GetQuat()) # # Get rotation between agent forward direction self.agents_hdir = np.asarray([np.array([0,0,0,1], dtype=float) for x in range(self.nagents)]) self.force_list = np.asarray([np.array([0,0,0], dtype=float) for x in range(self.nagents)]) self.agents_radi = np.random.uniform(self.radius_min, self.radius_max, self.nagents) self.agents_mass = [self.mass for x in range(self.nagents)] self.agents_percept = np.asarray([self.perception_radius for x in range(self.nagents)]) self.agents_goal = np.asarray([np.array(self.goal, dtype=float) for x in range(self.nagents)]) self.agent_force_wp = wp.zeros(shape=self.nagents,device=self.device, dtype=wp.vec3) self.agents_pos_wp = wp.array(self.agents_pos, device=self.device, dtype=wp.vec3) self.agents_vel_wp = wp.array(self.agents_vel, device=self.device, dtype=wp.vec3) self.agents_hdir_wp = wp.array(self.agents_hdir, device=self.device, dtype=wp.vec4) self.agents_goal_wp = wp.array(self.agents_goal, device=self.device, dtype=wp.vec3) self.agents_radi_wp = wp.array(self.agents_radi, device=self.device, dtype=float) self.agents_mass_wp = wp.array(self.agents_mass, device=self.device, dtype=float) self.agents_percept_wp = wp.array(self.agents_percept, device=self.device, dtype=float) self.xnew_wp = wp.zeros_like(wp.array(self.agents_pos, device=self.device, dtype=wp.vec3)) self.vnew_wp = wp.zeros_like(wp.array(self.agents_pos, device=self.device, dtype=wp.vec3)) self.hdir_wp = wp.zeros_like(wp.array(self.agents_hdir, device=self.device, dtype=wp.vec4)) def config_hasgrid(self, nagents=None): '''Create a hash grid based on the number of agents Currently assumes z up Parameters ---------- nagents : int, optional _description_, by default None ''' if nagents is None: nagents = self.nagents self.grid = wp.HashGrid(dim_x=200, dim_y=200, dim_z=1, device=self.device) # self.grid = wp.HashGrid(dim_x=nagents, dim_y=nagents, dim_z=1, device=self.device) def config_mesh(self, points, faces): '''Create a warp mesh object from points and faces Parameters ---------- points : List[[x,y,z]] A list of floating point xyz vertices of a mesh faces : List[int] A list of integers corresponding to vertices. Must be triangle-based ''' # fake some points and faces if empty list was passed if len(points) == 0: points = [(0,0,0), (0,0,0), (0,0,0)] faces = [[1, 2, 3]] # print(points) # print(faces) # Init mesh for environment collision self.mesh = wp.Mesh( points=wp.array(points, dtype=wp.vec3, device=self.device), indices=wp.array(faces, dtype=int ,device=self.device) ) def update_goals(self, new_goal): if len(new_goal) == 1: self.goals = np.asarray([new_goal for x in range(self.nagents)]) else: self.goals = new_goal self.agents_goal_wp = wp.array(self.goals, device=self.device, dtype=wp.vec3) def run(self): # Rebuild hashgrid given new positions self.grid.build(points=self.agents_pos_wp, radius=self.hash_radius) # launch kernel wp.launch(kernel=crowd_force.get_forces, dim=self.nagents, inputs=[self.agents_pos_wp, self.agents_vel_wp, self.agents_goal_wp, self.agents_radi_wp, self.agents_mass_wp, self._dt, self.agents_percept_wp, self.grid.id, self.mesh.id, self.inv_up], outputs=[self.agent_force_wp], device=self.device ) self.force_list = self.agent_force_wp.numpy() self.step_processing() self.agents_pos_wp = wp.array(self.agents_pos, device=self.device, dtype=wp.vec3) self.agents_vel_wp = wp.array(self.agents_vel, device=self.device, dtype=wp.vec3) return self.agent_force_wp def internal_integration(self): # Given the forces, integrate for pos and vel wp.launch(kernel=crowd_force.integrate, dim=self.nagents, inputs=[self.agents_pos_wp, self.agents_vel_wp, self.agent_force_wp, self._dt], outputs=[self.xnew_wp, self.vnew_wp], device=self.device ) self.agents_pos_wp = self.xnew_wp self.agents_vel_wp = self.vnew_wp self.agents_pos = self.agents_pos_wp.numpy() self.agents_vel = self.agents_vel_wp.numpy() def set_heading(self): up = wp.vec3(0.0,1.0,0.0) forward = wp.vec3(1.0,0.0,0.0) wp.launch(kernel=crowd_force.heading, dim=self.nagents, inputs=[self.agents_vel_wp, up, forward], outputs=[self.hdir_wp], device=self.device ) self.agents_hdir_wp = self.hdir_wp self.agents_hdir = self.agents_hdir_wp.numpy() for idx, point_instancer in enumerate(self.point_instancer_sets): if len(self.point_instancer_sets) == 1: agent_headings = self.agents_hdir else: _slice = int(self.nagents/2) if idx == 0: agent_headings = self.agents_hdir[:_slice] else: agent_headings = self.agents_hdir[_slice:] # Set orientation point_instancer.GetOrientationsAttr().Set(agent_headings)
23,588
Python
37.231767
143
0.558632
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/usd_utils.py
import numpy as np from pxr import UsdGeom, Gf, Usd import omni def get_mesh(usd_stage, objs): points, faces = [],[] for obj in objs: f_offset = len(points) # f, p = convert_to_mesh(obj)#usd_stage.GetPrimAtPath(obj)) f, p = meshconvert(obj)#usd_stage.GetPrimAtPath(obj)) points.extend(p) faces.extend(f+f_offset) return points, faces def get_all_stage_mesh(stage, start_prim): found_meshes = [] # Traverse the scene graph and print the paths of prims, including instance proxies for x in Usd.PrimRange(start_prim, Usd.TraverseInstanceProxies()): if x.IsA(UsdGeom.Mesh): found_meshes.append(x) points, faces = get_mesh(stage, found_meshes) return points, faces def convert_to_mesh(prim): ''' convert a prim to BVH ''' # Get mesh name (prim name) m = UsdGeom.Mesh(prim) # Get verts and triangles tris = m.GetFaceVertexIndicesAttr().Get() tris_cnt = m.GetFaceVertexCountsAttr().Get() verts = m.GetPointsAttr().Get() tri_list = np.array(tris) vert_list = np.array(verts) xform = UsdGeom.Xformable(prim) time = Usd.TimeCode.Default() # The time at which we compute the bounding box world_transform: Gf.Matrix4d = xform.ComputeLocalToWorldTransform(time) translation: Gf.Vec3d = world_transform.ExtractTranslation() rotation: Gf.Rotation = world_transform.ExtractRotationMatrix() # rotation: Gf.Rotation = world_transform.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix())) rotation = rotation.GetOrthonormalized() # New vertices vert_list = np.dot((vert_list * scale ), rotation) + translation # vert_scaled = vert_list # vert_list[:,0] *= scale[0] # vert_list[:,1] *= scale[1] # vert_list[:,2] *= scale[2] # vert_rotated = np.dot(vert_scaled, rotation) # Rotate points # vert_translated = vert_rotated + translation # vert_list = vert_translated # Check if the face counts are 4, if so, reshape and turn to triangles if tris_cnt[0] == 4: quad_list = tri_list.reshape(-1,4) tri_list = quad_to_tri(quad_list) tri_list = tri_list.flatten() return tri_list, vert_list def quad_to_tri(a): idx = np.flatnonzero(a[:,-1] == 0) out0 = np.empty((a.shape[0],2,3),dtype=a.dtype) out0[:,0,1:] = a[:,1:-1] out0[:,1,1:] = a[:,2:] out0[...,0] = a[:,0,None] out0.shape = (-1,3) mask = np.ones(out0.shape[0],dtype=bool) mask[idx*2+1] = 0 return out0[mask] def selected_as_mesh(): # Get the current active selection of the stage stage = omni.usd.get_context().get_stage() # Get the selections from the stage _usd_context = omni.usd.get_context() _selection = _usd_context.get_selection() selected_paths = _selection.get_selected_prim_paths() # Expects a list, so take first selection prims = [stage.GetPrimAtPath(x) for x in selected_paths] points, faces = get_mesh(stage, selected_paths) return points, faces def children_as_mesh(stage, parent_prim): children = parent_prim.GetAllChildren() children = [child.GetPrimPath() for child in children] points, faces = get_mesh(stage, children) return points, faces def meshconvert(prim): # Create an XformCache object to efficiently compute world transforms xform_cache = UsdGeom.XformCache() # Get the mesh schema mesh = UsdGeom.Mesh(prim) # Get verts and triangles tris = mesh.GetFaceVertexIndicesAttr().Get() if not tris: return [], [] tris_cnt = mesh.GetFaceVertexCountsAttr().Get() # Get the vertices in local space points_attr = mesh.GetPointsAttr() local_points = points_attr.Get() # Convert the VtVec3fArray to a NumPy array points_np = np.array(local_points, dtype=np.float64) # Add a fourth component (with value 1.0) to make the points homogeneous num_points = len(local_points) ones = np.ones((num_points, 1), dtype=np.float64) points_np = np.hstack((points_np, ones)) # Compute the world transform for this prim world_transform = xform_cache.GetLocalToWorldTransform(prim) # Convert the GfMatrix to a NumPy array matrix_np = np.array(world_transform, dtype=np.float64).reshape((4, 4)) # Transform all vertices to world space using matrix multiplication world_points = np.dot(points_np, matrix_np) tri_list = convert_to_triangle_mesh(tris, tris_cnt) tri_list = tri_list.flatten() world_points = world_points[:,:3] return tri_list, world_points def convert_to_triangle_mesh(FaceVertexIndices, FaceVertexCounts): """ Convert a list of vertices and a list of faces into a triangle mesh. A list of triangle faces, where each face is a list of indices of the vertices that form the face. """ # Parse the face vertex indices into individual face lists based on the face vertex counts. faces = [] start = 0 for count in FaceVertexCounts: end = start + count face = FaceVertexIndices[start:end] faces.append(face) start = end # Convert all faces to triangles triangle_faces = [] for face in faces: if len(face) < 3: newface = [] # Invalid face elif len(face) == 3: newface = [face] # Already a triangle else: # Fan triangulation: pick the first vertex and connect it to all other vertices v0 = face[0] newface = [[v0, face[i], face[i + 1]] for i in range(1, len(face) - 1)] triangle_faces.extend(newface) return np.array(triangle_faces) # from pxr import UsdGeom, Sdf, Usd # import os # def add_ext_reference(prim: Usd.Prim, ref_asset_path: str, ref_target_path: Sdf.Path) -> None: # references: Usd.References = prim.GetReferences() # references.AddReference( # assetPath=ref_asset_path, # primPath=ref_target_path # OPTIONAL: Reference a specific target prim. Otherwise, uses the referenced layer's defaultPrim. # ) # class makescope: # def __init__(self): # self.stage = omni.usd.get_context().get_stage() # scope = UsdGeom.Scope.Define(self.stage, Sdf.Path('/World/Scope')) # ref_prim = UsdGeom.Xform.Define(self.stage, Sdf.Path('/World/Scope/CrowdJane')).GetPrim() # dir_path = os.path.join('G:/ProjectRepos/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/data/', 'CrowdBob.usda') # add_ext_reference(ref_prim, dir_path, Sdf.Path("<Default Prim>")) # ms = makescope()
6,666
Python
30.154205
132
0.645665
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/extension.py
import numpy as np import omni.ext import omni.ui as ui import omni.usd from omni.physx import get_physx_interface try: from omni.usd import get_world_transform_matrix except: from omni.usd.utils import get_world_transform_matrix from . import window from . import simulator from .env import Environment from . import usd_utils class SFsim(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query # additional information, like where this extension is located on filesystem. def on_startup(self, ext_id): print("[siborg.simulate.crowd] Social Forces Sim startup") self.goal_prim_path = '/World/CrowdGoals' self.obstacle_prim_path = '/World/Obstacles' self.grid_size = 3 self.rigid_flag = False self.pam_flag = False self.gpu_flag = False self.instancer_flag = False self.jane_flag = False self.heading_flag = False self.init_scene() self.show() self.goal_prim_dict = {} # {Prim path, subscriber} self._on_update_sub = None def show(self): self._window = ui.Window("Social Forces Demo Settings", width=500, height=250) gui_window = window.make_window_elements(self, self._window, self.Sim) def init_goal_prim(self, prim_path): omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', prim_path=prim_path, attributes={}, select_new_prim=True) def modify_goals(self, _new_goals): if len(_new_goals) == 0: return if self.Sim.nagents == 0: return # Assign goals based on number of goals available if len(_new_goals)>self.Sim.nagents: _new_goals = _new_goals[self.Sim.nagents:] # Get strides self.Sim.goals = np.asarray(self.Sim.goals, dtype=object) goal_cast = np.array_split(self.Sim.goals, len(_new_goals)) # Reassign the split arrays their new goals for idx in range(len(goal_cast)): goal_cast[idx][:] = _new_goals[idx] # Reshape into xyz vector goal_cast = np.vstack(goal_cast) goal_cast = np.asarray(goal_cast, dtype=np.float) # Update the simulations goals self.Sim.update_goals(goal_cast) def init_scene(self): self.World = Environment() if self.gpu_flag: self.Sim = simulator.WarpCrowd() else: self.Sim = simulator.Simulator() # Create the goal hierarchy self.init_goal_prim(self.goal_prim_path) self.init_goal_prim(self.obstacle_prim_path) def _on_update_event(self, dt): # Check the Goals xform path and see if there are any changes needed to the goal watchers self.stage = omni.usd.get_context().get_stage() parent_prim = self.stage.GetPrimAtPath(self.goal_prim_path) children = parent_prim.GetAllChildren() # Check if any children are gone from our dict, if so, unsubscribe their watcher dead_kids = [kid for kid in self.goal_prim_dict.keys() if kid not in children] for kid in dead_kids: try: self.goal_prim_dict[kid].unsubscribe() except: self.goal_prim_dict[kid] = None self.goal_prim_dict.pop(kid) # Check if there are any new children not in our dict, if so, add them as a goal and update watcher babies = [child for child in children if child not in self.goal_prim_dict.keys()] for baby in babies: self.goal_prim_dict[baby] = None # Update the goals new_goals = [] for x in self.goal_prim_dict.keys(): _prim = x try: t = omni.usd.get_world_transform_matrix(_prim).ExtractTranslation() except: t = omni.usd.utils.get_world_transform_matrix(_prim).ExtractTranslation() new_goals.append(t) if len(new_goals) == 0: return self.modify_goals(new_goals) def assign_meshes(self): self.stage = omni.usd.get_context().get_stage() # Use the meshes that are parent_prim = self.stage.GetPrimAtPath(self.obstacle_prim_path) # points, faces = usd_utils.children_as_mesh(self.stage, parent_prim) points, faces = usd_utils.get_all_stage_mesh(self.stage,parent_prim) self.Sim.config_mesh(points, faces) def api_example(self): self.Sim._unregister() if self.gpu_flag: self.Sim = simulator.WarpCrowd(self.World) self.Sim.config_hasgrid() self.assign_meshes() else: self.Sim = simulator.Simulator(self.World) self.demo_api_call(self.Sim) def demo_api_call(self, Sim): # Use the builtin function for demo agents Sim.rigidbody = self.rigid_flag # Set origin for spawning agents self.stage = omni.usd.get_context().get_stage() parent_prim = self.stage.GetPrimAtPath('/World/GenerationOrigin') Sim.generation_origin = [0,0,0] if parent_prim: Sim.generation_origin = get_world_transform_matrix(parent_prim).ExtractTranslation() Sim.generation_origin[2] = Sim.generation_origin[1] Sim.init_demo_agents(m=self.grid_size,n=self.grid_size,s=1.6) if self.pam_flag: Sim.use_pam = True if self.gpu_flag: Sim.configure_params() if not Sim.rigidbody: if self.jane_flag: # TODO make this work for all sim types Sim.add_jane = True else: Sim.add_jane = False if self.instancer_flag: Sim.point_instancer_sets = [] Sim.use_instancer = True if self.heading_flag: Sim.use_heading = True Sim.create_instance_agents() # Create a usdgeom point instance for easy visualization Sim.set_instance_agents() # update the usdgeom points for visualization else: Sim.use_instancer = False Sim.create_geompoints() # Create a usdgeom point instance for easy visualization Sim.set_geompoints() # update the usdgeom points for visualization # tell simulator to update positions after each run Sim.update_agents_sim = True # tell simulator to handle the update visualization Sim.update_viz = True # Register the simulation to updates, and the Sim will handle it from here Sim.register_simulation() if not self._on_update_sub: self._on_update_sub = get_physx_interface().subscribe_physics_step_events(self._on_update_event) def on_shutdown(self): print("[siborg.simulate.crowd] Crowd Sim shutdown") try: self.Sim._unregister() except: pass try: self._goal_subscriber.unsubscribe() except: self._goal_subscriber = None try: self._on_update_sub.unsubscribe() except: self._on_update_sub = None self.Sim._simulation_event = None self._window = None self.Sim = None
7,277
Python
35.39
108
0.601896
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/crowds.py
import numpy as np from siborg.simulate.crowd.agent import Agent class CrowdConfig: def __init__(self): self._goal = [0,0,0] self.goals = None self.agent_bodies = None self.nagents = 1 # set pereption radius self.perception_radius = 1.5 # set radius self.radius = .5 # set mass self.mass = 2 # Will use a physics scene self.rigidbody = False # Assume z-up world self.world_up = 2 def create_agents(self, num=None, goals=None, pos=None): '''Creates a set of agents and goals Uses the class instance defaults for radius, mass, perception, etc. Parameters ---------- num : int, optional number of agents to create (if not defined in init), by default None goals : ndarray([x,y,z]), optional either 1 or size equal to number of agents, by default None pos : ndarray([x,y,z]), optional must be same size as number of agents (otherwise will set all to origin, which is bad), because they will explode, by default None ''' # generate n number of agents if num: self.nagents = num # Check we can assign goals to agents if not goals: goals = [self._goal] if len(goals) != 1: if len(goals) != self.nagents: raise ValueError('If goals is not 1, must be same size as number of agents') elif len(goals) == 1: self.goals = np.asarray([goals[0] for x in range(self.nagents)], dtype=np.double) else: self.goals = goals # Set the agent positions if pos is not None: self.agents_pos = np.asarray(pos, dtype=np.double) else: self.agents_pos = np.asarray([np.array(0,0,0, dtype=np.double) for x in range(self.nagents)]) # only create an agent instance if user wants physics-based spheres if self.rigidbody: self.agent_bodies = [Agent() for x in range(self.nagents)] # move agents to their positions for i in range(len(self.agent_bodies)): x,y,z = self.agents_pos[i] self.agent_bodies[i].translate(x,y,z) else: self.agent_bodies = [None for x in range(self.nagents)] # set initial velocities to 0 self.agents_vel = np.asarray([np.array([0,0,0], dtype=np.double) for x in range(self.nagents)]) self.set_radius() self.set_mass() self.set_perception_radius() def set_radius(self,v=None): '''sets agents radius Parameters ---------- v : List[float], float, optional set the radius of the agents, if None, all agents get same radius, by default None ''' if v: if type(v) is float: self.agents_radi = np.asarray([v for x in range(self.nagents)]) elif len(v) != self.nagents: raise ValueError('Radius array must be same size as number of agents') else: self.agents_radi = v else: self.agents_radi = np.asarray([self.radius for x in range(self.nagents)]) def set_mass(self,v=None): '''sets agents mass Parameters ---------- v : List[float], optional set the mass of the agents, if None, all agents get same mass, by default None Raises ------ ValueError if size of mass array does not match number of agents ''' if v: if type(v) is float: self.agents_mass = np.asarray([v for x in range(self.nagents)]) elif len(v) != self.nagents: raise ValueError('mass array must be same size as number of agents') else: self.agents_mass = v else: self.agents_mass = np.asarray([self.mass for x in range(self.nagents)]) def set_perception_radius(self, v=None): '''sets agents perception radius Parameters ---------- v : List[float], optional set the percept radius of the agents, if None, all agents get same raidus, by default None Raises ------ ValueError if size of perception array does not match number of agents ''' if v: if type(v) is float: self.agents_percept = np.asarray([v for x in range(self.nagents)]) elif len(v) != self.nagents: raise ValueError('perception radius array must be same size as number of agents') else: self.agents_percept = v else: self.agents_percept = np.asarray([self.perception_radius for x in range(self.nagents)]) def init_demo_agents(self, m=5, n=5, s=1, o=[0,0,0]): '''Create a set of demo agents Parameters ---------- m : int, optional number of agents in row, by default 5 n : int, optional number of agents in col, by default 5 s : int, optional spacing between agents, by default 1 ''' o = self.generation_origin # Initialize agents in a grid for testing self.agents_pos = np.asarray([ np.array([(s/2) + (x * s) +(o[0]/2) , (s/2) + (y * s) +(o[1]/2), 0], dtype=np.double) for x in range(m) for y in range(n) ]) # # Initialize agents in a grid for testing # self.agents_pos = np.asarray([ # np.array([(s/2) + (x * s), (s/2) + (y * s), 0], dtype=np.double) # for x in range(m) # for y in range(n) # ]) self.agents_pos[:, [2, self.world_up]] = self.agents_pos[:, [self.world_up, 2]] self.nagents = len(self.agents_pos) #### if self.rigidbody: self.agent_bodies = [Agent() for x in range(self.nagents)] for i in range(len(self.agent_bodies)): x,y,z = self.agents_pos[i] self.agent_bodies[i].translate(x,y,z) else: self.agent_bodies = [None for x in range(self.nagents)] self.goals = np.asarray([self._goal for x in range(self.nagents)], dtype=np.double) self.agents_vel = np.asarray([np.array([0,0,0],dtype=np.double) for x in range(self.nagents)]) self.set_radius() self.set_mass() self.set_perception_radius()
6,938
Python
34.584615
105
0.511098
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/env.py
import omni import omni.kit.commands from pxr import Usd, Gf from pxr import UsdGeom from pxr import UsdPhysics, PhysxSchema class Environment: def __init__(self): print('Initializing Environment') self._stage = omni.usd.get_context().get_stage() self.set_scene(self._stage) def set_scene(self, stage): print(f'Setting up {stage}') self._stage = stage self.defaultPrimPath = str(self._stage.GetDefaultPrim().GetPath()) # Physics scene # UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) UsdGeom.SetStageMetersPerUnit(stage, 1.0) self.scene = UsdPhysics.Scene.Define(stage, self.defaultPrimPath + "/physicsScene") stage_axis = UsdGeom.GetStageUpAxis(stage) gravity_dir = Gf.Vec3f(0.0, 0.0, 0) if stage_axis is 'X': gravity_dir[0] = -1.0 if stage_axis is 'Y': gravity_dir[1] = -1.0 if stage_axis is 'Z': gravity_dir[2] = -1.0 self.scene.CreateGravityDirectionAttr().Set(gravity_dir) self.scene.CreateGravityMagnitudeAttr().Set(9.81) physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(self.scene.GetPrim()) physxSceneAPI.CreateEnableCCDAttr().Set(True) # Check if there is a physics groundplane in the scene plane_path = self.defaultPrimPath+"/GroundPlane" if self._stage.GetPrimAtPath(plane_path).IsValid(): pass else: # If not, make one omni.kit.commands.execute('AddGroundPlaneCommand', stage=self._stage, planePath='/GroundPlane', axis=UsdGeom.GetStageUpAxis(stage), size=1.0, position=Gf.Vec3f(0.0, 0.0, 0.0), color=Gf.Vec3f(0.5, 0.5, 0.5))
1,923
Python
34.629629
91
0.566823
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/agent.py
import omni from omni.physx.scripts import physicsUtils from pxr import Gf, UsdPhysics, PhysxSchema, UsdGeom, UsdShade import usdrt class Agent: def __init__(self): stage = omni.usd.get_context().get_stage() # Create a sphere representing the agent self.skin_mesh , self.skinMeshPath = self.sphere(stage) # Set a rigid body material and collider self.set_material(stage, self.skinMeshPath) # Add a translation operator and set it to zero position # Since we changed to create this object with an xform, don't need to add, just get it. # self.translateOp = self.skin_mesh.AddTranslateOp() self.translateOp = UsdGeom.XformOp(self.skin_mesh.GetPrim().GetAttribute("xformOp:translate")) self.translateOp.Set(Gf.Vec3f(0.0, 0.0, 0.0)) def sphere(self, stage): # Create sphere representing agent _, skinMeshPath = omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type="Sphere", prim_path='/World/Agents/Sphere', prepend_default_prim=True) skin_mesh = UsdGeom.Mesh.Get(stage, skinMeshPath) prim = skin_mesh.GetPrim() # setup physics - rigid body self.rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(prim) linVelocity = Gf.Vec3f(0.0, 0.0, 0.0) angularVelocity = Gf.Vec3f(0.0, 0.0, 0.0) # apply initial velocities self.rigidBodyAPI.CreateVelocityAttr().Set(linVelocity) self.rigidBodyAPI.CreateAngularVelocityAttr().Set(angularVelocity) self.massAPI = UsdPhysics.MassAPI.Apply(prim) self.massAPI.CreateMassAttr(2) self.massAPI.CreateCenterOfMassAttr().Set(Gf.Vec3f(0.0, 0.0, 0.0)) # Add a force attribute # shuttleForcePath = skinMeshPath + "/shuttleForce" # xform = UsdGeom.Xform.Define(stage, shuttleForcePath) # self.forceApi = PhysxSchema.PhysxForceAPI.Apply(xform.GetPrim()) # # self.forceApi = PhysxSchema.PhysxForceAPI.Apply(prim) # self.forceAttr = self.forceApi.GetForceAttr() self.usdrt_stage = usdrt.Usd.Stage.Attach(omni.usd.get_context().get_stage_id()) prim = self.usdrt_stage.GetPrimAtPath(skinMeshPath) self.world_force_attr = prim.CreateAttribute("_worldForce", usdrt.Sdf.ValueTypeNames.Float3, True) return skin_mesh, skinMeshPath def translate(self, x=0, y=0, z=0): self.translateOp.Set(self.translateOp.Get() + Gf.Vec3d( x, y, z)) @property def position(self): return self.translateOp.Get() @property def velocity(self): return self.rigidBodyAPI.GetVelocityAttr().Get() def set_material(self, stage, skinMeshPath): defaultPrimPath = str(stage.GetDefaultPrim().GetPath()) # Floor Material path = defaultPrimPath + "/rigidMaterial" prim_path = stage.GetPrimAtPath(skinMeshPath) # Set it as a rigid body rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(prim_path) # Add a collider (defaults to mesh triangulation) UsdPhysics.CollisionAPI.Apply(prim_path) # Apply a specific mass parameter UsdPhysics.MassAPI.Apply(prim_path) #Get the rigidbody parameter to set values on physxRbAPI = PhysxSchema.PhysxRigidBodyAPI.Apply(prim_path) #Enable CCD for this object physxRbAPI.CreateEnableCCDAttr().Set(True) # Create a (separate) physics material that gets added to the object path = defaultPrimPath + "/highdensitymaterial" UsdShade.Material.Define(stage, path) material = UsdPhysics.MaterialAPI.Apply(stage.GetPrimAtPath(path)) material.CreateStaticFrictionAttr().Set(0) material.CreateDynamicFrictionAttr().Set(0) material.CreateRestitutionAttr().Set(.2) material.CreateDensityAttr().Set(0.01) # Add material physicsUtils.add_physics_material_to_prim(stage, prim_path, path)
4,141
Python
38.075471
107
0.642357
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/window.py
from .models.socialforces import Parameters import omni.ui as ui combo_sub = None def make_window_elements(self, _window, Sim): with _window.frame: with ui.VStack(): with ui.HStack(): ui.Label('Max Speed') max_speed = ui.FloatField(height=20) max_speed.model.add_value_changed_fn(lambda m : setattr(Parameters, 'max_speed', m.get_value_as_float())) max_speed.model.set_value(Parameters.max_speed) with ui.HStack(): ui.Label('Desired Speed') v_desired = ui.FloatField(height=20) v_desired.model.add_value_changed_fn(lambda m : setattr(Parameters, 'v_desired', m.get_value_as_float())) v_desired.model.set_value(Parameters.v_desired) with ui.HStack(): ui.Label('A') A = ui.FloatField(height=20) A.model.add_value_changed_fn(lambda m : setattr(Parameters, 'A', m.get_value_as_float())) A.model.set_value(Parameters.A) with ui.HStack(): ui.Label('B') B = ui.FloatField(height=20) B.model.add_value_changed_fn(lambda m : setattr(Parameters, 'B', m.get_value_as_float())) B.model.set_value(Parameters.B) with ui.HStack(): ui.Label('kn') kn = ui.FloatField(height=20) kn.model.add_value_changed_fn(lambda m : setattr(Parameters, 'kn', m.get_value_as_float())) kn.model.set_value(Parameters.kn) with ui.HStack(): ui.Label('kt') kt = ui.FloatField(height=20) kt.model.add_value_changed_fn(lambda m : setattr(Parameters, 'kt', m.get_value_as_float())) kt.model.set_value(Parameters.kt) with ui.HStack(): ui.Label('Agent grid (nxn)') agent_grid = ui.IntField(height=20) agent_grid.model.add_value_changed_fn(lambda m : setattr(self, 'grid_size', m.get_value_as_int())) agent_grid.model.set_value(3) # with ui.HStack(): # ui.Label('Agent Mass') # kt = ui.FloatField(height=20) # kt.model.add_value_changed_fn(lambda m : setattr(Sim, 'mass', m.get_value_as_float())) # kt.model.set_value(Sim.mass) # with ui.HStack(): # ui.Label('Agent Radius') # kt = ui.FloatField(height=20) # kt.model.add_value_changed_fn(lambda m : Sim.set_radius(m.get_value_as_float())) # kt.model.set_value(Sim.radius) # with ui.HStack(): # ui.Label('Agent Perception Radius') # kt = ui.FloatField(height=20) # kt.model.add_value_changed_fn(lambda m : setattr(Sim, 'perception_radius', m.get_value_as_float())) # kt.model.set_value(Sim.perception_radius) # with ui.HStack(height=20): # ui.Button("Gen Agents", clicked_fn=Sim.create_agents) # nagents = ui.IntField(height=5) # nagents.model.set_value(Sim.nagents) # nagents.model.add_value_changed_fn(lambda m : setattr(Sim, 'nagents', m.get_value_as_int())) with ui.HStack(height=20): ui.Label('GPU', width=20) WarpModel = ui.CheckBox(width=30) WarpModel.model.add_value_changed_fn(lambda m : setattr(self, 'gpu_flag', m.get_value_as_bool())) WarpModel.model.set_value(True) ui.Label('Use Instances', width=20) SFModel = ui.CheckBox(width=30) SFModel.model.add_value_changed_fn(lambda m : setattr(self, 'instancer_flag', m.get_value_as_bool())) SFModel.model.set_value(True) ui.Label('Add Jane', width=5) RigidBody = ui.CheckBox(width=30) RigidBody.model.add_value_changed_fn(lambda m : setattr(self, 'jane_flag', m.get_value_as_bool())) RigidBody.model.set_value(False) ui.Label('Use Direction', width=5) RigidBody = ui.CheckBox(width=30) RigidBody.model.add_value_changed_fn(lambda m : setattr(self, 'heading_flag', m.get_value_as_bool())) RigidBody.model.set_value(True) ui.Label('Rigid Body', width=5) RigidBody = ui.CheckBox(width=30) RigidBody.model.add_value_changed_fn(lambda m : setattr(self, 'rigid_flag', m.get_value_as_bool())) RigidBody.model.set_value(False) ui.Label('PAM', width=20) SFModel = ui.CheckBox(width=30) SFModel.model.add_value_changed_fn(lambda m : setattr(self, 'pam_flag', m.get_value_as_bool())) SFModel.model.set_value(False) # options = ["GeomPoints", "RigidBody"] # combo_model: ui.AbstractItemModel = ui.ComboBox(0, *options).model # def combo_changed(item_model: ui.AbstractItemModel, item: ui.AbstractItem): # value_model = item_model.get_item_value_model(item) # current_index = value_model.as_int # option = options[current_index] # print(f"Selected '{option}' at index {current_index}.") # combo_sub = combo_model.subscribe_item_changed_fn(combo_changed) # def clicked(): # value_model = combo_model.get_item_value_model() # current_index = value_model.as_int # option = options[current_index] # print(f"Button Clicked! Selected '{option}' at index {current_index}.") # self.api_example(current_index) # ui.Button("Set Selected Meshes", width=5, clicked_fn=self.assign_meshes) ui.Button("Start Demo", width=5, clicked_fn=self.api_example) with ui.HStack(height=10): pass
6,133
Python
45.1203
121
0.536768
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex4.py
'''_summary_ ''' from siborg.simulate.crowd.simulator import Simulator def example_4(): # Example of using API Sim = Simulator() Sim.rigidbody = True # use rigid bodies Sim.init_demo_agents(m=3, n=5, s=1.1) # Register the simulation to updates, and the Sim will handle it from here Sim.register_simulation() # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # tell simulator to handle the update visualization Sim.update_viz = True example_4()
558
Python
26.949999
92
0.691756
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex3.py
'''_summary_ ''' import time from omni.physx import get_physx_interface from siborg.simulate.crowd.simulator import Simulator Sim = Simulator() start_time = time.time() _simulation_event = None def example_3(): # Example of using API # Use a builtin helper function to generate a grid of agents Sim.init_demo_agents(m=3, n=5, s=1.1) Sim.create_geompoints() # Create a usdgeom point instance for easy visualization Sim.set_geompoints() # update the usdgeom points for visualization # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # don't have the simulator update the geompoints, we do it ourselves Sim.update_viz = False # Register to our own physx update sim_subscriber() def sim_subscriber(): # This would need to get cleaned up _simulation_event = get_physx_interface().subscribe_physics_step_events(_on_update) def _on_update(dt): # Run one step of simulation # don't need to use forces since we told simulator to update forces = Sim.run() Sim.set_geompoints() # update the usdgeom points for visualization # For this demo we will unsubscribe after a few seconds if time.time() - start_time > 100 : print('ending') _simulation_event.unsubscribe() example_3()
1,338
Python
28.755555
92
0.701046
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex2.py
'''Example for Simulator handling update and using GeomPoints. Uses a helper function for initializing agents ''' from siborg.simulate.crowd.simulator import Simulator def example_2(): Sim = Simulator() # Use a builtin helper function to generate a grid of agents Sim.init_demo_agents(m=3,n=5,s=1.1) Sim.create_geompoints() # Create a usdgeom point instance for easy visualization # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # don't have the simulator update the geompoints, we do it ourselves Sim.update_viz = True Sim.register_simulation() example_2()
669
Python
32.499998
92
0.730942
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/examples/ex1.py
'''Example for Simulator handling update and using GeomPoints ''' from siborg.simulate.crowd.simulator import Simulator import numpy as np from math import sqrt def example_1(): # Example of using API Sim = Simulator() nagents = 10 # Some trickery to make a grid of agents and get the cloest number of agents to an even grid pos = np.asarray([ np.array([(1/2) + (x), (1/2) + (y), 0], dtype=np.double) for x in range(int(sqrt(nagents))) for y in range(int(sqrt(nagents))) ]) pos[:, [2, Sim.world_up]] = pos[:, [Sim.world_up, 2]] nagents = len(pos) Sim.create_agents(num=nagents, goals=[[10,10,0]], pos=pos) # initialize a set of agents Sim.create_geompoints() # Create a usdgeom point instance for easy visualization # tell simulator to update positions after each run, if not need to call Sim.integrate() Sim.update_agents_sim = True # don't have the simulator update the geompoints, we do it ourselves Sim.update_viz = True Sim.register_simulation() example_1()
1,119
Python
35.129031
96
0.626452
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/models/pam.py
''' Python implementation of the Predictive Avoidance Model (PAM) from A Predictive Collision Avoidance Model for Pedestrian Simulation, I. Karamouzas, P. Heil, P. van Beek, M. H. Overmars Motion in Games (MIG 2009), Lecture Notes in Computer Science (LNCS), Vol. 5884, 2009 ''' from dataclasses import dataclass import numpy as np from scipy.spatial import distance @dataclass class Parameters: # The agents field of view field_of_view = 200.0 # The agents radius ? Used here in this implementation or in sim? agent_radius = 0.5 # Minimum agent distance min_agent_dist = 0.1 # the mid distance parameters in peicewise personal space function predictive force dist dmid = 4.0 # KSI ksi = 0.5 # Nearest Neighbour distance ? Used here in this implementation or in sim? neighbor_dist = 10.0 # Maximum neighbours to consider ? Used here in this implementation or in sim? max_neighbors = 3 # Maximum acceleration ? Used here in this implementation or in sim/physics? max_accel = 20.0 # Maximum speed max_speed = 7 # Preferred Speed preferred_vel = 2.5 # Goal acquired radius goal_radius = 1.0 # Time Horizon time_horizon = 4.0 # Agent Distance agent_dist = 0.1 # Wall Distance wall_dist = 0.1 # Wall Steepnes wall_steepness = 2.0 # Agent Strength agent_strength = 1.0 # wFactor, factor to progressively scale down forces in when in a non-collision state w_factor = 0.8 # Noise flag (should noise be added to the movement action) noise = False force_clamp = 40.0 # *private* Ideal wall distance _ideal_wall_dist = agent_radius + wall_dist # *private* Squared ideal wall distance _SAFE = _ideal_wall_dist * _ideal_wall_dist # *private* Agent Personal space _agent_personal_space = agent_radius + min_agent_dist # *private* the min distance parameters in peicewise personal space function _dmin = agent_radius + _agent_personal_space # *private* the max distance parameters in peicewise personal space function _dmax = time_horizon * max_speed # *private* FOV cosine _cosFOV = np.cos((0.5 * np.pi * field_of_view) / 180.0) def ray_intersects_disc(pi, pj, v, r): # calc ray disc est. time to collision t = 0.0 w = pj - pi a = np.dot(v, v) b = np.dot(w, v) c = np.dot(w, w) - (r * r) discr = (b * b) - (a * c) if discr > 0.0: t = (b - np.sqrt(discr)) / a if t < 0.0: t = 999999.0 else: t = 999999.0 return t def mag(v): # calc magnitude of vector v_mag = np.sqrt(v.dot(v)) return v_mag def norm(v): # normalize a vector v_norm = np.array([0, 0, 0], dtype='float64') magnitude = mag(v) if magnitude > 0.0: v_norm = v / magnitude return v_norm def get_neighbors(cur, agents, pn_r): dist = distance.cdist([cur], agents) pn = dist < pn_r # Index to remove is when its zero pn_self = dist == 0 pn_self = np.nonzero(pn_self) pn[pn_self] = False pn = np.nonzero(pn) return pn def wall_force(obstacles, rr_i, closest_point, SAFE, add_force): for i in range(len(obstacles)): # Step 1: get closest point on obstacle to agent # [[ Need python code for this in simulation ]] n_w = rr_i - closest_point d_w = mag(n_w) * mag(n_w) if (d_w < SAFE): d_w = np.sqrt(d_w) if (d_w > 0): n_w /= d_w if ((d_w - Parameters.agent_radius) < 0.001): dist_min_radius = 0.001 else: d_w - Parameters.agent_radius obstacle_force = (Parameters._ideal_wall_dist - d_w) / np.pow(dist_min_radius, Parameters.wall_steepness) * n_w add_force(obstacle_force) def calc_goal_force(goal, rr_i, vv_i): # Preferred velocity is preferred speed in direction of goal preferred_vel = Parameters.preferred_vel * norm(goal - rr_i) # Goal force, is always added goal_force = (preferred_vel - vv_i) / Parameters.ksi return goal_force def collision_param(rr_i, vv_i, desired_vel, pn_rr, pn_vv, pn_r): # Keep track of if we ever enter a collision state agent_collision = False t_pairs = [] # Handle agents tc values for predictive forces among neighbours for j, rr_j in enumerate(pn_rr): # Get position and velocity of neighbor agent vv_j = pn_vv[j] # Get radii of neighbor agent rj = pn_r[j] combined_radius = Parameters._agent_personal_space + rj w = rr_j - rr_i if (mag(w) < combined_radius): agent_collision = True t_pairs.append((0.0, j)) else: rel_dir = norm(w) if np.dot(rel_dir, norm(vv_i)) < Parameters._cosFOV: continue tc = ray_intersects_disc(rr_i, rr_j, desired_vel - vv_j, combined_radius) if tc < Parameters.time_horizon: if len(t_pairs) < Parameters.max_neighbors: t_pairs.append((tc, j)) elif tc < t_pairs[0][0]: t_pairs.pop() t_pairs.append((tc, j)) return t_pairs, agent_collision def predictive_force(rr_i, desired_vel, desired_speed, pn_rr, pn_vv, pn_r, vv_i): # Handle predictive forces// Predictive forces # Setup collision parameters t_pairs, agent_collision = collision_param(rr_i, vv_i, desired_vel, pn_rr, pn_vv, pn_r) # This will be all the other forces, added in a particular way steering_force = np.array([0, 0, 0], dtype='float64') # will store a list of tuples, each tuple is (tc, agent) force_count = 0 for t_pair in t_pairs: # Nice variables from the t_pair tuples t = t_pair[0] agent_idx = t_pair[1] force_dir = rr_i + (desired_vel * t) - pn_rr[agent_idx] - (pn_vv[agent_idx] * t) force_dist = mag(force_dir) if force_dist > 0: force_dir /= force_dist collision_dist = np.maximum(force_dist - Parameters.agent_radius - pn_r[agent_idx], 0.0) #D = input to evasive force magnitude piecewise function D = np.maximum( (desired_speed * t) + collision_dist, 0.001) force_mag = 0.0 if D < Parameters._dmin: force_mag = Parameters.agent_strength * Parameters._dmin / D elif D < Parameters.dmid: force_mag = Parameters.agent_strength elif D < Parameters._dmax: force_mag = Parameters.agent_strength * (Parameters._dmax - D) / (Parameters._dmax - Parameters.dmid) else: continue force_mag *= np.power( (1.0 if agent_collision else Parameters.w_factor), force_count) force_count += 1 steering_force = force_mag * force_dir return steering_force def add_noise(steering_force): angle = np.random.uniform(0.0, 1.0) * 2.0 * np.pi dist = np.random.uniform(0.0, 1.0) * 0.001 steering_force += dist * np.array([np.cos(angle),np.sin(angle),0], dtype='float64') return steering_force def compute_force(rr_i, ri, vv_i, mass, goal, pn_rr, pn_vv, pn_r, dt): # Get the goal force goal_force = calc_goal_force(goal, rr_i, vv_i) # Desired values if all was going well in an empty world desired_vel = vv_i + goal_force * dt desired_speed = mag(desired_vel) # Get obstacle (wall) forces obstacle_force = np.array([0, 0, 0], dtype='float64') #@TODO # obstacle_force = wall_force() # Get predictive steering forces steering_force = predictive_force(rr_i, desired_vel, desired_speed, pn_rr, pn_vv, pn_r, vv_i) # Add noise for reducing deadlocks adding naturalness if Parameters.noise: steering_force = add_noise(steering_force) # Clamp driving force if mag(steering_force) > Parameters.force_clamp: steering_force = norm(steering_force) * Parameters.force_clamp return goal_force + obstacle_force + steering_force
8,170
Python
32.080972
123
0.599143
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/models/socialforces.py
from dataclasses import dataclass import numpy as np from scipy.spatial import distance # zero_vec = np.array([0,0,0], dtype='float64') @dataclass class Parameters: # names from https://www.sciencedirect.com/science/article/pii/S0378437120306853 Tau = 0.5 #(s) A = 2000.0 B = 0.08 kn = 1.2 * 100_000 # Kgs^-2 kt = 2.4 * 100_000 # Kg m^-1 s^-1 max_speed = 10 v_desired = 3.5 def calc_wall_force(): # TODO add wall and geometry recognition force = np.array([0,0,0], dtype='float64') return force def calc_agent_force(rr_i, ri, vv_i, pn_rr, pn_vv, pn_r): # Sum the forces of neighboring agents force = np.array([0,0,0], dtype='float64') # Set the total force of the other agents to zero ff_ij = np.array([0,0,0], dtype='float64') rr_j =np.array([0,0,0], dtype='float64') # Iterate through the neighbors and sum (f_ij) for j, rr_j in enumerate(pn_rr): # Get position and velocity of neighbor agent vv_j = pn_vv[j] # Get radii of neighbor agent rj = pn_r[j] # Pass agent position to AgentForce calculation ff_ij = neighbor_force(rr_i, ri, vv_i, rr_j, rj, vv_j) # Sum Forces force += ff_ij return force def neighbor_force(rr_i, ri, vv_i, rr_j, rj, vv_j): # Calculate the force exerted by another agent # Take in this agent (i) and a neighbors (j) position and radius # Sum of radii rij = ri + rj # distance between center of mass d_ij = mag(rr_i - rr_j) # "n_ij is the normalized vector points from pedestrian j to i" n_ij = norm(rr_i - rr_j) # Normalized vector pointing from j to i # t_ij "Vector of tangential relative velocity pointing from i to j." # A sliding force is applied on agent i in this direction to reduce the relative velocity. t_ij = np.cross(vv_j - vv_i, [0,0,1] ) dv_ji = np.dot(vv_j - vv_i, t_ij) # Calculate f_ij force = repulsion(rij, d_ij, n_ij) + proximity(rij, d_ij, n_ij) + sliding(rij, d_ij, dv_ji, t_ij) return force def calc_goal_force(goal, pos, vel, mass, v_desired, dt): ee_i = norm(goal - pos) force = mass * ( ( (v_desired * ee_i) - vel ) / Parameters.Tau ) return force def G(r_ij, d_ij): # g(x) is a function that returns zero if pedestrians touch # otherwise is equal to the argument x if (d_ij > r_ij): return 0.0 return r_ij - d_ij; def repulsion(r_ij, d_ij, n_ij): force = Parameters.A * np.exp( (r_ij - d_ij) / Parameters.B) * n_ij return force def proximity(r_ij, d_ij, n_ij): force = Parameters.kn * G(r_ij, d_ij) * n_ij return force def sliding(r_ij, d_ij, dv_ji, t_ij): force = Parameters.kt * G(r_ij, d_ij) * (dv_ji * t_ij) return force def mag(v): # calc magnitude of vector v_mag = np.sqrt(v.dot(v)) return v_mag def norm(v): # normalize a vector v_norm = v / mag(v) return v_norm def get_neighbors(cur, agents, pn_r): dist = distance.cdist([cur], agents) pn = dist < pn_r # Index to remove is when its zero pn_self = dist == 0 pn_self = np.nonzero(pn_self) pn[pn_self] = False pn = np.nonzero(pn) return pn def compute_force(rr_i, ri, vv_i, mass, goal, pn_rr, pn_vv, pn_r, dt): # Get the force for this agent to the goal goal = calc_goal_force(goal, rr_i, vv_i, mass, Parameters.v_desired, dt) agent = calc_agent_force(rr_i, ri, vv_i, pn_rr, pn_vv, pn_r) wall = calc_wall_force() force = goal + agent + wall force = norm(force) * min(mag(force), Parameters.max_speed) return force
3,633
Python
26.323308
102
0.603909
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/models/socialforces_warp.py
import warp as wp Tau = wp.constant(0.5) # s (acceleration) A = wp.constant(2000.0) # N B = wp.constant(0.08) # m kn = wp.constant(1.2 * 100000) # kg/s^-2 kt = wp.constant(2.4 * 100000) # kg/m^-1 s^-2 max_speed = wp.constant(10.0) # m/s v_desired = wp.constant(2.5) # m/s @wp.kernel def get_forces(positions: wp.array(dtype=wp.vec3), velocities: wp.array(dtype=wp.vec3), goals: wp.array(dtype=wp.vec3), radius: wp.array(dtype=float), mass: wp.array(dtype=float), dt: float, percept : wp.array(dtype=float), grid : wp.uint64, mesh: wp.uint64, inv_up: wp.vec3, forces: wp.array(dtype=wp.vec3), ): # thread index tid = wp.tid() cur_pos = positions[tid] cur_rad = radius[tid] cur_vel = velocities[tid] cur_mass = mass[tid] goal = goals[tid] pn = percept[tid] _force = compute_force(cur_pos, cur_rad, cur_vel, cur_mass, goal, positions, velocities, radius, dt, pn, grid, mesh) # Clear any vertical forces with Element-wise mul _force = wp.cw_mul(_force, inv_up) # compute distance of each point from origin forces[tid] = _force @wp.kernel def integrate(x : wp.array(dtype=wp.vec3), v : wp.array(dtype=wp.vec3), f : wp.array(dtype=wp.vec3), dt: float, xnew: wp.array(dtype=wp.vec3), vnew: wp.array(dtype=wp.vec3), ): tid = wp.tid() x0 = x[tid] v0 = v[tid] f0 = f[tid] v1 = v0 + (f0*1.0) * dt x1 = x0 + v1 * dt xnew[tid] = x1 vnew[tid] = v1 @wp.kernel def heading(v : wp.array(dtype=wp.vec3), up : wp.vec3, forward : wp.vec3, hdir: wp.array(dtype=wp.vec4), ): tid = wp.tid() v0 = v[tid] vnorm = wp.normalize(v0) hdir[tid] = velocity_to_quaternion(up, forward, vnorm) @wp.func def velocity_to_quaternion(up : wp.vec3, forward : wp.vec3, velocity: wp.vec3): # Construct a quaternion that rotates the agent's forward direction to align with the velocity vector if wp.length(forward) > 0: forward = wp.normalize(forward) if wp.length(velocity) > 0: velocity = wp.normalize(velocity) else: velocity = forward dot = wp.dot(forward, velocity) # Clip the dot product to avoid numerical instability if dot == 1.0: # If the forward and velocity vectors are already aligned, return the identity quaternion return wp.vec4(0.0, 0.0, 0.0, 1.0) else: axis = wp.cross(forward, velocity) axis = up * wp.sign(wp.dot(axis, up)) # Project the axis onto the up plane if wp.length(axis) > 0.0: axis = wp.normalize(axis) # Normalize the axis of rotation else:axis = up # Use a default axis of rotation if the iwput is a zero vector angle = wp.acos(dot) # Calculate the angle of rotation with clipping qw = wp.cos(angle/2.0) # Calculate the scalar component of the quaternion qx = wp.sin(angle/2.0) * axis[0] # Calculate the vector component of the quaternion qy = wp.sin(angle/2.0) * axis[1] # Calculate the vector component of the quaternion qz = wp.sin(angle/2.0) * axis[2] # Calculate the vector component of the quaternion return wp.vec4(qx, qy, qz, qw) @wp.func def calc_goal_force(goal: wp.vec3, pos: wp.vec3, vel: wp.vec3, mass: float, v_desired: float, dt: float): ee_i = wp.normalize(goal - pos) force = mass * ( ( (v_desired * ee_i) - vel ) / (Tau) ) return force @wp.func def calc_wall_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, mesh: wp.uint64): ''' rr_i : position ri : radius vv_i : velocity Computes: (A * exp[(ri-diw)/B] + kn*g(ri-diw))*niw - kt * g(ri-diw)(vi * tiw)tiw ''' face_index = int(0) face_u = float(0.0) face_v = float(0.0) sign = float(0.0) force = wp.vec3(0.0,0.0,0.0) # Define the up direction up_dir = wp.vec3(0.0, 0.0, 1.0) max_dist = float(ri * 5.0) has_point = wp.mesh_query_point(mesh, rr_i, max_dist, sign, face_index, face_u, face_v) if (not has_point): return wp.vec3(0.0, 0.0, 0.0) p = wp.mesh_eval_position(mesh, face_index, face_u, face_v) # d_iw = distance to wall W d_iw = wp.length(p - rr_i) # vector of the wall to the agent nn_iw = wp.normalize(rr_i - p) # perpendicular vector of the agent-wall (tangent force) tt_iw = wp.cross(up_dir, nn_iw) if wp.dot(vv_i, tt_iw) < 0.0: tt_iw = -1.0 * tt_iw # Compute force # f_iW = { A * exp[(ri-diw)/B] + kn*g(ri-diw) } * niw # - kt * g(ri-diw)(vi * tiw)tiw f_rep = ( A * wp.exp((ri-d_iw)/B) + kn * G(ri, d_iw) ) * nn_iw f_tan = kt * G(ri,d_iw) * wp.dot(vv_i, tt_iw) * tt_iw force = f_rep - f_tan return force @wp.func def calc_agent_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, pn_rr: wp.array(dtype=wp.vec3), pn_vv: wp.array(dtype=wp.vec3), pn_r: wp.array(dtype=float), pn: float, grid : wp.uint64, ): '''Sum the forces of neighboring agents''' # Set the total force of the other agents to zero force = wp.vec3(0.0, 0.0, 0.0) ff_ij = wp.vec3(0.0, 0.0, 0.0) rr_j = wp.vec3(0.0, 0.0, 0.0) # create grid query around point query = wp.hash_grid_query(grid, rr_i, pn) index = int(0) # Iterate through the neighbors and sum (f_ij) while(wp.hash_grid_query_next(query, index)): j = index neighbor = pn_rr[j] # compute distance to neighbor point dist = wp.length(rr_i-neighbor) if (dist <= pn): # Get position and velocity of neighbor agent rr_j = pn_rr[j] vv_j = pn_vv[j] # Get radii of neighbor agent rj = pn_r[j] # Pass agent position to AgentForce calculation ff_ij = neighbor_force(rr_i, ri, vv_i, rr_j, rj, vv_j) # Sum Forces force += ff_ij return force @wp.func def neighbor_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, rr_j: wp.vec3, rj: float, vv_j: wp.vec3): '''Calculate the force exerted by another agent. Take in this agent (i) and a neighbors (j) position and radius''' # Sum of radii rij = ri + rj # distance between center of mass d_ij = wp.length(rr_i - rr_j) # "n_ij is the normalized vector points from pedestrian j to i" n_ij = wp.normalize(rr_i - rr_j) # Normalized vector pointing from j to i # t_ij "Vector of tangential relative velocity pointing from i to j." # A sliding force is applied on agent i in this direction to reduce the relative velocity. t_ij = vv_j - vv_i dv_ji = wp.dot(vv_j - vv_i, t_ij) # Calculate f_ij force = repulsion(rij, d_ij, n_ij) + proximity(rij, d_ij, n_ij) + sliding(rij, d_ij, dv_ji, t_ij) return force @wp.func def G(r_ij: float, d_ij: float ): # g(x) is a function that returns zero if pedestrians touch # otherwise is equal to the argument x if (d_ij > r_ij): return 0.0 return r_ij - d_ij @wp.func def repulsion(r_ij: float, d_ij: float, n_ij: wp.vec3): force = A * wp.exp( (r_ij - d_ij) / B) * n_ij return force @wp.func def proximity(r_ij: float, d_ij: float, n_ij: wp.vec3): force = (kn * G(r_ij, d_ij)) * n_ij # body force return force @wp.func def sliding(r_ij: float, d_ij: float, dv_ji: float, t_ij: wp.vec3): force = kt * G(r_ij, d_ij) * (dv_ji * t_ij) return force @wp.func def compute_force(rr_i: wp.vec3, ri: float, vv_i: wp.vec3, mass:float, goal:wp.vec3, pn_rr: wp.array(dtype=wp.vec3), pn_vv: wp.array(dtype=wp.vec3), pn_r: wp.array(dtype=float), dt: float, pn: float, grid : wp.uint64, mesh: wp.uint64 ): ''' rr_i : position ri : radius vv_i : velocity pn_rr : List[perceived neighbor positions] pn_vv : List[perceived neighbor velocities] pn_r : List[perceived neighbor radius] ''' # Get the force for this agent to the goal goal = calc_goal_force(goal, rr_i, vv_i, mass, v_desired, dt) agent = calc_agent_force(rr_i, ri, vv_i, pn_rr, pn_vv, pn_r, pn, grid) wall = calc_wall_force(rr_i, ri, vv_i, mesh) # Sum of forces force = goal + agent + wall force = wp.normalize(force) * wp.min(wp.length(force), max_speed) return force
9,633
Python
29.200627
105
0.508876
cadop/crowds/exts/siborg.simulate.crowd/siborg/simulate/crowd/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
cadop/crowds/exts/siborg.simulate.crowd/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.0.3-alpha" # The title and description fields are primarily for displaying extension info in UI title = "Crowd Simulation" description="An implementation of the Social Forces crowd simulation (it may or may not be correct). There is currently no environment detection. The current implementation is in PhysX. We plan to support more methods in the future, as well as more crowd simulators. Contributions are welcome." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Create" # Keywords for the extension keywords = ["kit", "example", "crowds", "simulation"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import siborg.simulate.crowd". [[python.module]] name = "siborg.simulate.crowd" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ] [python.pipapi] use_online_index = true requirements = ["scipy"]
1,357
TOML
29.177777
295
0.744289
cadop/crowds/exts/siborg.simulate.crowd/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
cadop/arduverse/puppet_handle_1.py
from omni.kit.scripting import BehaviorScript import socket import numpy as np import math from pxr import Gf import numpy as np import math class Puppet2(BehaviorScript): def on_init(self): print(f"{__class__.__name__}.on_init()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8881 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) print("Waiting for data...") def on_destroy(self): print(f"{__class__.__name__}.on_destroy()->{self.prim_path}") self.sock = None rot = [0, 0, 0] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def on_play(self): print(f"{__class__.__name__}.on_play()->{self.prim_path}") # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT = 8881 # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((UDP_IP, UDP_PORT)) self.sock.setblocking(0) # Time interval between sensor readings in seconds self.dt = 0.02 def on_pause(self): print(f"{__class__.__name__}.on_pause()->{self.prim_path}") def on_stop(self): print(f"{__class__.__name__}.on_stop()->{self.prim_path}") self.on_destroy() def on_update(self, current_time: float, delta_time: float): self.get_data() def get_data(self): # # Receive data from the Arduino data = self.clear_socket_buffer() if data is None: return # Decode the data and split it into Pitch and Roll data = data.decode() device, pitch, roll, yaw = data.split(",") x,y,z = float(roll), float(yaw), 180-float(pitch) rot = [x, y, z] self.prim.GetAttribute('xformOp:rotateXYZ').Set(Gf.Vec3d(rot)) def clear_socket_buffer(self): # Function to clear the socket's buffer latest_data = None while True: try: # Try to read data from the socket in a non-blocking way latest_data, addr = self.sock.recvfrom(1024) except BlockingIOError: # No more data to read (buffer is empty) return latest_data
2,384
Python
30.8
72
0.575084
cadop/arduverse/README.md
# arduverse Project files and source code for making a real-time streaming from arduino to omniverse Clone/download the repo. You should be able to just open the usda file in *PuppetScene* folder. To use: - Upload the *UDP_FilteredAngle.ino* file to an arduino (RP2040 is what I used). - Make sure to change the wifi network credentials to your own - Try to run the *udp.py* file to make sure the arduino is connecting and sending data - If the udp to python connection is working, you should be able to get the scene running. - To use the base file, in omniverse create a python behavior script on any xform, and attach the script (e.g. *puppet_handle_1.py*) Open an issue if you have problems. Also if you want to contribute go for it. ![Featured Puppet Image](https://github.com/cadop/arduverse/blob/main/FeaturedImg.png?raw=true)
842
Markdown
51.687497
132
0.764846
cadop/arduverse/udp.py
import socket # Set up the server address and port UDP_IP = "0.0.0.0" UDP_PORT1 = 8881 UDP_PORT2 = 8882 # Create a UDP socket sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock1.bind((UDP_IP, UDP_PORT1)) sock2.bind((UDP_IP, UDP_PORT2)) sock1.setblocking(0) sock2.setblocking(0) print("Waiting for data...") while True: # Receive data from the Arduino try: data, addr = sock1.recvfrom(1024) print("Received message 1:", data.decode()) except: pass try: data, addr = sock2.recvfrom(1024) print("Received message 2:", data.decode()) except: pass
667
Python
22.857142
56
0.668666
jshrake-nvidia/kit-cv-video-example/README.md
# kit-cv-video-example Example Omniverse Kit extension that demonstrates how to stream video (webcam, RTSP, mp4, mov, ) to a dynamic texture using [OpenCV VideoCapture](https://docs.opencv.org/3.4/dd/d43/tutorial_py_video_display.html) and [omni.ui.DynamicTextureProvider](https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#byteimageprovider). ![demo](./images/demo.gif) For a basic example of how to use `omni.ui.DynamicTextureProvider`, please see <https://github.com/jshrake-nvidia/kit-dynamic-texture-example>. **WARNING**: This is a prototype and is not necessarily ready for production use. The performance of this example may not meet your performance requirements and is not optimized. This example is a temporary solution until a more mature and optimized streaming solution becomes available in the platform. This example currently only scales to a very limited number of low resolution streams. ## Getting Started - Requires Kit 104.1 >= - Tested in Create 2022.3.1, 2022.3.3 ``` ./link_app.bat --app create ./app/omni.create.bat --/rtx/ecoMode/enabled=false --ext-folder exts --enable omni.cv-video.example ``` Make sure that eco mode is disabled under Render Settings > Raytracing. From the extension UI window, update the URI and click the Create button. A plane prim will be created at (0, 0, 0) with an OmniPBR material containing a dynamic video stream for the albedo texture. The extension should support whatever the OpenCV VideoCapture API supports. Here are a few URIs you can use to test: - Your own web camera: `0` - HLS: `https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8` - RTSP: `rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4`
1,730
Markdown
54.838708
390
0.773988
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Omni RTSP Dyanmic Texture Example" description = "An example that demonstrates how to stream RTSP feeds using OpenCV and omni.ui.DynamicTextureProvider" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.pipapi" = {} "omni.warp" = {} [python.pipapi] requirements = [ "opencv-python" ] use_online_index = true [[python.module]] name = "omni.cv-video.example" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,245
TOML
23.431372
117
0.728514
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/omni/cv-video/example/extension.py
""" Omniverse Kit example extension that demonstrates how to stream video (such as RTSP) to a dynamic texture using [OpenCV VideoCapture](https://docs.opencv.org/3.4/dd/d43/tutorial_py_video_display.html) and [omni.ui.DynamicTextureProvider](https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#byteimageprovider). TODO: - [x] Investigate how to perform the color space conversion and texture updates in a separate thread - [ ] Investigate how to avoid the color space conversion and instead use the native format of the frame provided by OpenCV """ import asyncio import threading import time from typing import List import carb import carb.profiler import cv2 as cv import numpy as np import omni.ext import omni.kit.app import omni.ui from pxr import Kind, Sdf, Usd, UsdGeom, UsdShade DEFAULT_STREAM_URI = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4" #DEFAULT_STREAM_URI = "C:/Users/jshrake/Downloads/1080p.mp4" def create_textured_plane_prim( stage: Usd.Stage, prim_path: str, texture_name: str, width: float, height: float ) -> Usd.Prim: """ Creates a plane prim and an OmniPBR material with a dynamic texture for the albedo map """ hw = width / 2 hh = height / 2 # This code is mostly copy pasted from https://graphics.pixar.com/usd/release/tut_simple_shading.html billboard: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, f"{prim_path}/Mesh") billboard.CreatePointsAttr([(-hw, -hh, 0), (hw, -hh, 0), (hw, hh, 0), (-hw, hh, 0)]) billboard.CreateFaceVertexCountsAttr([4]) billboard.CreateFaceVertexIndicesAttr([0, 1, 2, 3]) billboard.CreateExtentAttr([(-430, -145, 0), (430, 145, 0)]) texCoords = UsdGeom.PrimvarsAPI(billboard).CreatePrimvar( "st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying ) texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)]) material_path = f"{prim_path}/Material" material: UsdShade.Material = UsdShade.Material.Define(stage, material_path) shader: UsdShade.Shader = UsdShade.Shader.Define(stage, f"{material_path}/Shader") shader.SetSourceAsset("OmniPBR.mdl", "mdl") shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") shader.CreateIdAttr("OmniPBR") shader.CreateInput("diffuse_texture", Sdf.ValueTypeNames.Asset).Set(f"dynamic://{texture_name}") material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") billboard.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(billboard).Bind(material) return billboard class OpenCvVideoStream: """ A small abstraction around OpenCV VideoCapture and omni.ui.DynamicTextureProvider, making a one-to-one mapping between the two Resources: - https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html - https://docs.opencv.org/3.4/dd/d43/tutorial_py_video_display.html - https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#omni.ui.ByteImageProvider.set_bytes_data_from_gpu """ def __init__(self, name: str, stream_uri: str): self.name = name self.uri = stream_uri self.texture_array = None try: # Attempt to treat the uri as an int # https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html#a5d5f5dacb77bbebdcbfb341e3d4355c1 stream_uri_as_int = int(stream_uri) self._video_capture = cv.VideoCapture(stream_uri_as_int) except: # Otherwise treat the uri as a str self._video_capture = cv.VideoCapture(stream_uri) self.fps: float = self._video_capture.get(cv.CAP_PROP_FPS) self.width: int = self._video_capture.get(cv.CAP_PROP_FRAME_WIDTH) self.height: int = self._video_capture.get(cv.CAP_PROP_FRAME_HEIGHT) self._dynamic_texture = omni.ui.DynamicTextureProvider(name) self._last_read = time.time() self.is_ok = self._video_capture.isOpened() # If this FPS is 0, set it to something sensible if self.fps == 0: self.fps = 24 @carb.profiler.profile def update_texture(self): # Rate limit frame reads to the underlying FPS of the capture stream now = time.time() time_delta = now - self._last_read if time_delta < 1.0 / self.fps: return self._last_read = now # Read the frame carb.profiler.begin(0, "read") ret, frame = self._video_capture.read() carb.profiler.end(0) # The video may be at the end, loop by setting the frame position back to 0 if not ret: self._video_capture.set(cv.CAP_PROP_POS_FRAMES, 0) self._last_read = time.time() return # By default, OpenCV converts the frame to BGR # We need to convert the frame to a texture format suitable for RTX # In this case, we convert to BGRA, but the full list of texture formats can be found at # # kit\source\extensions\omni.gpu_foundation\bindings\python\omni.gpu_foundation_factory\GpuFoundationFactoryBindingsPython.cpp frame: np.ndarray carb.profiler.begin(0, "color space conversion") frame = cv.cvtColor(frame, cv.COLOR_BGR2RGBA) carb.profiler.end(0) height, width, channels = frame.shape carb.profiler.begin(0, "set_bytes_data") self._dynamic_texture.set_data_array(frame, [width, height, channels]) carb.profiler.end(0) class OmniRtspExample(omni.ext.IExt): def on_startup(self, ext_id): # stream = omni.kit.app.get_app().get_update_event_stream() # self._sub = stream.create_subscription_to_pop(self._update_streams, name="update") self._streams: List[OpenCvVideoStream] = [] self._stream_threads: List[threading.Thread] = [] self._stream_uri_model = omni.ui.SimpleStringModel(DEFAULT_STREAM_URI) self._window = omni.ui.Window("OpenCV Video Streaming Example", width=800, height=200) with self._window.frame: with omni.ui.VStack(): omni.ui.StringField(model=self._stream_uri_model) omni.ui.Button("Create", clicked_fn=self._on_click_create) @carb.profiler.profile def _update_stream(self, i): async def loop(): while self._running: await asyncio.sleep(0.001) self._streams[i].update_texture() asyncio.run(loop()) def _on_click_create(self): name = f"Video{len(self._streams)}" image_name = name usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() prim_path = f"/World/{name}" # If the prim already exists, remove it so we can create it again try: stage.RemovePrim(prim_path) self._streams = [stream for stream in self._streams if stream.name != image_name] except: pass # Create the stream stream_uri = self._stream_uri_model.get_value_as_string() video_stream = OpenCvVideoStream(image_name, stream_uri) if not video_stream.is_ok: carb.log_error(f"Error opening stream: {stream_uri}") return self._streams.append(video_stream) carb.log_info(f"Creating video steam {stream_uri} {video_stream.width}x{video_stream.height}") # Create the mesh + material + shader model_root = UsdGeom.Xform.Define(stage, prim_path) Usd.ModelAPI(model_root).SetKind(Kind.Tokens.component) create_textured_plane_prim(stage, prim_path, image_name, video_stream.width, video_stream.height) # Clear the string model # self._stream_uri_model.set_value("") # Create the thread to pump the video stream self._running = True i = len(self._streams) - 1 thread = threading.Thread(target=self._update_stream, args=(i, )) thread.daemon = True thread.start() self._stream_threads.append(thread) def on_shutdown(self): # self._sub.unsubscribe() self._running = False for thread in self._stream_threads: thread.join() self._stream_threads = [] self._streams = []
8,262
Python
43.187166
201
0.657105
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/omni/cv-video/example/__init__.py
# TODO: Work around OM-108110 # by explicitly adding the python3.dll directory to the DLL search path list. # cv2.dll fails to load because it can't load the python3.dll dependency try: import os import pathlib import sys # The python3.dll lives in the python directory adjacent to the kit executable # Get the path to the current kit process exe_path = sys.executable exe_dir = pathlib.Path(exe_path).parent python_dir = exe_dir / "python" print(f"Adding {python_dir} to DLL search path list") os.add_dll_directory(python_dir) except Exception as e: print(f"Error adding python directory to DLL search path list {e}") from .extension import *
690
Python
33.549998
82
0.718841
jshrake-nvidia/kit-cv-video-example/exts/omni.cv-video.example/docs/README.md
# Simple UI Extension Template The simplest python extension example. Use it as a starting point for your extensions.
119
Markdown
28.999993
86
0.806723
jshrake-nvidia/kit-dynamic-texture-example/README.md
# Dynamic Texture Provider Example Demonstrates how to programmatically generate a textured quad using the [omni.ui.DynamicTextureProvider](https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html) API. Tested against Create 2022.3.1. ```console .\link_app.bat --path C:\Users\jshrake\AppData\Local\ov\pkg\prod-create-2022.3.1 .\app\omni.create.bat --ext-folder exts --enable omni.dynamic_texture_example ``` ![demo](./demo.gif) ## *Omniverse Kit* Extensions Project Template This project is a template for developing extensions for *Omniverse Kit*. # Getting Started ## Install Omniverse and some Apps 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ## Add a new extension to your *Omniverse App* 1. Fork and clone this repo, for example in `C:\projects\kit-extension-template` 2. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts` ![Extension Manager Window](/images/add-ext-search-path.png) 5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Few tips * Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`. * Most important thing extension has is a config file: `extension.toml`, take a peek. ## Next Steps: Alternative way to add a new extension To get a better understanding and learn a few other things, we recommend following next steps: 1. Remove search path added in the previous section. 1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience. 2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section). 3. Run this app with `exts` folder added as an extensions search path and new extension enabled: ```bash > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > app\omni.code.bat -h ``` 4. After the *App* started you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. 5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*: ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world ``` It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From here you can enable more extensions from the UI. ### Few tips * In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies. * Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html # Running Tests To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html). # Linking with an *Omniverse* app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app create ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Adding a new extension Adding a new extension is as simple as copying and renaming existing one: 1. copy `exts/omni.hello.world` to `exts/[new extension name]` 2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]` 3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load: ```toml [[python.module]] name = "[new python module]" ``` No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
7,339
Markdown
46.662337
318
0.751329
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Dynamic Texture Example" description = "Demonstrates how to programmatically generate a textured quad using the omni.ui.DynamicTextureProvider API" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.pipapi" = {} [python.pipapi] requirements = [ "pillow" ] use_online_index = true # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.dynamic_texture_example" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,329
TOML
25.078431
122
0.738901
jshrake-nvidia/kit-dynamic-texture-example/exts/omni.dynamic_texture_example/omni/dynamic_texture_example/extension.py
''' Demonstrates how to programmatically generate a textured quad using the omni.ui.DynamicTextureProvider API. This is contrived example that reads the image from the local filesystem (cat.jpg). You can imagine sourcing the image bytes from a network request instead. Resources: - https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html - See the full list of omni.ui.TextureFormat variants at .\app\kit\extscore\omni.gpu_foundation\omni\gpu_foundation_factory\_gpu_foundation_factory.pyi TODO(jshrake): - [ ] Currently the dynamic texture name only works with the OmniPBR.mdl material. Need to understand why it doesn't work with other materials, such as UsdPreviewSurface. - [ ] Test instantiating and using the DynamicTextureProvider in a separate thread ''' from typing import Tuple, Union import pathlib import omni import omni.ui as ui from PIL import Image from pxr import Kind, Sdf, Usd, UsdGeom, UsdShade def create_textured_plane_prim(stage: Usd.Stage, prim_path: str, texture_name: str) -> Usd.Prim: # This code is mostly copy pasted from https://graphics.pixar.com/usd/release/tut_simple_shading.html billboard: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, f"{prim_path}/Mesh") billboard.CreatePointsAttr([(-430, -145, 0), (430, -145, 0), (430, 145, 0), (-430, 145, 0)]) billboard.CreateFaceVertexCountsAttr([4]) billboard.CreateFaceVertexIndicesAttr([0,1,2,3]) billboard.CreateExtentAttr([(-430, -145, 0), (430, 145, 0)]) texCoords = UsdGeom.PrimvarsAPI(billboard).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying) texCoords.Set([(0, 0), (1, 0), (1,1), (0, 1)]) material_path = f"{prim_path}/Material" material = UsdShade.Material.Define(stage, material_path) shader: UsdShade.Shader = UsdShade.Shader.Define(stage, f"{material_path}/Shader") shader.SetSourceAsset("OmniPBR.mdl", "mdl") shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") shader.CreateIdAttr("OmniPBR") shader.CreateInput("diffuse_texture", Sdf.ValueTypeNames.Asset).Set(f"dynamic://{texture_name}") material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") billboard.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(billboard).Bind(material) return billboard def create_dynamic_texture(texture_name: str, bytes: bytes, resolution: Tuple[int, int], format: ui.TextureFormat) -> ui.DynamicTextureProvider: # See https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.ByteImageProvider.html#omni.ui.ByteImageProvider.set_bytes_data_from_gpu bytes_list = list(bytes) dtp = ui.DynamicTextureProvider(texture_name) dtp.set_bytes_data(bytes_list, list(resolution), format) return dtp class DynamicTextureProviderExample(omni.ext.IExt): def on_startup(self, ext_id): self._texture: Union[None, ui.DynamicTextureProvider] = None self._window = ui.Window("Create Dynamic Texture Provider Example", width=300, height=300) with self._window.frame: ui.Button("Create", clicked_fn=self._on_click_create) def _on_click_create(self): usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() name = f"TexturePlane" image_name = name prim_path = f"/World/{name}" # If the prim already exists, remove it so we can create it again try: stage.RemovePrim(prim_path) self._texture = None except: pass # Create the prim root model_root = UsdGeom.Xform.Define(stage, prim_path) Usd.ModelAPI(model_root).SetKind(Kind.Tokens.component) # Create the mesh + material + shader create_textured_plane_prim(stage, prim_path, image_name) # Open the adjacent cat.jpg file and create the texture dir = pathlib.Path(__file__).parent.resolve() image_path = dir.joinpath("cat.jpg") image: Image.Image = Image.open(image_path, mode='r') # Ensure the image format is RGBA image = image.convert('RGBA') image_bytes = image.tobytes() image_resolution = (image.width, image.height) image_format = ui.TextureFormat.RGBA8_UNORM self._texture = create_dynamic_texture(image_name, image_bytes, image_resolution, image_format) def on_shutdown(self): self._texture = None
4,533
Python
48.282608
156
0.692698
renanmb/Omniverse_legged_robotics/README.md
The idea of this repo is to start converting open source models of robots into Omniverse Isaac-Sim friendly format. # URDF Descriptions The URDFs found in this repository have been forked/modified/linked from the following projects: ## Quadrupeds - [kodlab_gazebo - Ghost Robotics](https://github.com/KodlabPenn/kodlab_gazebo) - [ANYbotics](https://github.com/ANYbotics) - [ANYbotics' ANYmal B](https://github.com/ANYbotics/anymal_b_simple_description) - [ANYbotics' ANYmal B - Modified for CHAMP](https://github.com/chvmp/anymal_b_simple_description) - [ANYbotics' ANYmal C](https://github.com/ANYbotics/anymal_c_simple_description) - [ANYbotics' ANYmal B - Modified for CHAMP](https://github.com/chvmp/anymal_c_simple_description) - Boston Dynamic's Little Dog - [Boston Dynamic's Little Dog - by RobotLocomotion](https://github.com/RobotLocomotion/LittleDog) - [Boston Dynamic's Little Dog - Modified for CHAMP](https://github.com/chvmp/littledog_description) - Boston Dynamic's Spot - [Boston Dynamic's Spot - by heuristicus](https://github.com/heuristicus/spot_ros) - [Boston Dynamic's Spot - Modified for CHAMP](https://github.com/chvmp/spot_ros) - [Dream Walker](https://github.com/Ohaginia/dream_walker) - [MIT Mini Cheetah - Original](https://github.com/HitSZwang/mini-cheetah-gazebo-urdf) - [MIT Mini Cheetah - Modified for CHAMP](https://github.com/chvmp/mini-cheetah-gazebo-urdf) - [OpenDog V2 - Original](https://github.com/XRobots/openDogV2) - [OpenDog V2 - Modified for CHAMP](https://github.com/chvmp/opendog_description) - Open Quadruped - [Open Quadruped](https://github.com/moribots/spot_mini_mini) - [SpotMicroAI - Gitlab](https://gitlab.com/custom_robots/spotmicroai) - [Spot Micro](https://github.com/chvmp/spotmicro_description) - [Unitree Robotics All](https://github.com/unitreerobotics/unitree_ros) - [Unitree Robotics All - Modified for CHAMP](https://github.com/chvmp/unitree_ros) - [Unitree Robotics' A1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/a1_description) - [Unitree Robotics' AliengoZ1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/aliengoZ1_description) - [Unitree Robotics'Aliengo](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/aliengo_description) - [Unitree Robotics' B1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/b1_description) - [Unitree Robotics' Go1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/go1_description) - [Unitree Robotics' Laikago](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/laikago_description) - [Unitree Robotics' Z1](https://github.com/unitreerobotics/unitree_ros/tree/master/robots/z1_description) - [Stochlab's Stochlite](https://stochlab.github.io/) - [Stochlab's Stochlite - Modified by aditya-shirwatkar](https://github.com/aditya-shirwatkar/stochlite_description) - Mini Pupper - [MangDang's Mini Pupper](https://github.com/mangdangroboticsclub/QuadrupedRobot) - [simplified robot description of the MangDang's Mini Pupper](https://github.com/nisshan-x/mini_pupper_description) - [Stanford pupper - Original](https://stanfordstudentrobotics.org/pupper) - [Stanford pupper - Modified by Chandykunju Alex](https://github.com/chandyalex/stanford_pupper_description.git) ## Bipedal - [Agility Robotics' Cassie - UMich-BipedLab](https://github.com/UMich-BipedLab/cassie_description) - [Agility Robotics' Digit - DigitRobot.jl](https://github.com/adubredu/DigitRobot.jl) - [NJIT - TOCABI](https://github.com/cadop/tocabi) ## Manipulation - [GoogleAI ROBEL D'Kitty](https://github.com/google-research/robel-scenes) - [GoogleAI ROBEL D'Kitty - Modified for CHAMP](https://github.com/chvmp/dkitty_description) - [The Shadow Robot Company](https://github.com/shadow-robot) - [Shadow Hand - archived](https://github.com/AndrejOrsula/shadow_hand_ign) # ## Cassie_description This repository contains the .urdf model of the CASSIE robot from Agility Robotics. It also includes a way to visualize the robot using ROS and rviz. https://github.com/UMich-BipedLab/cassie_description ## a1 robot simulation - Python version This repository contains all the files and code needed to simulate the a1 quadrupedal robot using Gazebo and ROS. The software runs on ROS noetic and Ubuntu 20.04. https://github.com/lnotspotl/a1_sim_py ## Here are the ROS simulation packages for Unitree robots https://github.com/unitreerobotics/unitree_ros ## Zoo from CHAMP This repository contains configuration packages of various quadrupedal robots generated by CHAMP's setup assistant. The URDFs found in this repository have been forked/modified/linked from the following projects: https://github.com/chvmp/robots
4,799
Markdown
66.605633
163
0.761617
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/z1_description/config/robot_control.yaml
z1_gazebo: # Publish all joint states ----------------------------------- joint_state_controller: type: joint_state_controller/JointStateController publish_rate: 1000 Joint01_controller: type: unitree_legged_control/UnitreeJointController joint: joint1 pid: {p: 300.0, i: 0.0, d: 5.0} Joint02_controller: type: unitree_legged_control/UnitreeJointController joint: joint2 pid: {p: 300.0, i: 0.0, d: 5.0} Joint03_controller: type: unitree_legged_control/UnitreeJointController joint: joint3 pid: {p: 300.0, i: 0.0, d: 5.0} Joint04_controller: type: unitree_legged_control/UnitreeJointController joint: joint4 pid: {p: 300.0, i: 0.0, d: 5.0} Joint05_controller: type: unitree_legged_control/UnitreeJointController joint: joint5 pid: {p: 300.0, i: 0.0, d: 5.0} Joint06_controller: type: unitree_legged_control/UnitreeJointController joint: joint6 pid: {p: 300.0, i: 0.0, d: 5.0} gripper_controller: type: unitree_legged_control/UnitreeJointController joint: jointGripper pid: {p: 300.0, i: 0.0, d: 5.0}
1,227
YAML
29.699999
66
0.594947
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/laikago_description/config/robot_control.yaml
laikago_gazebo: # Publish all joint states ----------------------------------- joint_state_controller: type: joint_state_controller/JointStateController publish_rate: 1000 # FL Controllers --------------------------------------- FL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # FR Controllers --------------------------------------- FR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: FR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} FR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: FR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} FR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: FR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RL Controllers --------------------------------------- RL_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RL_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RL_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RL_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RL_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RL_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0} # RR Controllers --------------------------------------- RR_hip_controller: type: unitree_legged_control/UnitreeJointController joint: RR_hip_joint pid: {p: 100.0, i: 0.0, d: 5.0} RR_thigh_controller: type: unitree_legged_control/UnitreeJointController joint: RR_thigh_joint pid: {p: 300.0, i: 0.0, d: 8.0} RR_calf_controller: type: unitree_legged_control/UnitreeJointController joint: RR_calf_joint pid: {p: 300.0, i: 0.0, d: 8.0}
2,291
YAML
31.28169
66
0.553907
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/README.md
# Introduction Here are the ROS simulation packages for Unitree robots, You can load robots and joint controllers in Gazebo, so you can perform low-level control (control the torque, position and angular velocity) of the robot joints. Please be aware that the Gazebo simulation cannot do high-level control, namely walking. Aside from these simulation functions, you can also control your real robots in ROS with the [unitree_ros_to_real](https://github.com/unitreerobotics/unitree_ros_to_real) packages. For real robots, you can do high-level and low-level control using our ROS packages. ## Packages: Robot description: `go1_description`, `a1_description`, `aliengo_description`, `laikago_description` Robot and joints controller: `unitree_controller` Simulation related: `unitree_gazebo`, `unitree_legged_control` # Dependencies * [ROS](https://www.ros.org/) Melodic or ROS Kinetic (has not been tested) * [Gazebo8](http://gazebosim.org/) * [unitree_legged_msgs](https://github.com/unitreerobotics/unitree_ros_to_real): `unitree_legged_msgs` is a package under [unitree_ros_to_real](https://github.com/unitreerobotics/unitree_ros_to_real). # Build <!-- If you would like to fully compile the `unitree_ros`, please run the following command to install relative packages. --> For ROS Melodic: ``` sudo apt-get install ros-melodic-controller-interface ros-melodic-gazebo-ros-control ros-melodic-joint-state-controller ros-melodic-effort-controllers ros-melodic-joint-trajectory-controller ``` For ROS Kinetic: ``` sudo apt-get install ros-kinetic-controller-manager ros-kinetic-ros-control ros-kinetic-ros-controllers ros-kinetic-joint-state-controller ros-kinetic-effort-controllers ros-kinetic-velocity-controllers ros-kinetic-position-controllers ros-kinetic-robot-controllers ros-kinetic-robot-state-publisher ros-kinetic-gazebo8-ros ros-kinetic-gazebo8-ros-control ros-kinetic-gazebo8-ros-pkgs ros-kinetic-gazebo8-ros-dev ``` And open the file `unitree_gazebo/worlds/stairs.world`. At the end of the file: ``` <include> <uri>model:///home/unitree/catkin_ws/src/unitree_ros/unitree_gazebo/worlds/building_editor_models/stairs</uri> </include> ``` Please change the path of `building_editor_models/stairs` to the real path on your PC. Then you can use catkin_make to build: ``` cd ~/catkin_ws catkin_make ``` If you face a dependency problem, you can just run `catkin_make` again. # Detail of Packages ## unitree_legged_control: It contains the joints controllers for Gazebo simulation, which allows users to control joints with position, velocity and torque. Refer to "[unitree_ros/unitree_controller/src/servo.cpp](https://github.com/unitreerobotics/unitree_ros/blob/master/unitree_controller/src/servo.cpp)" for joint control examples in different modes. ## The description of robots: Namely the description of Go1, A1, Aliengo and Laikago. Each package includes mesh, urdf and xacro files of robot. Take Laikago for example, you can check the model in Rviz by: ``` roslaunch laikago_description laikago_rviz.launch ``` ## unitree_gazebo & unitree_controller: You can launch the Gazebo simulation with the following command: ``` roslaunch unitree_gazebo normal.launch rname:=a1 wname:=stairs ``` Where the `rname` means robot name, which can be `laikago`, `aliengo`, `a1` or `go1`. The `wname` means world name, which can be `earth`, `space` or `stairs`. And the default value of `rname` is `laikago`, while the default value of `wname` is `earth`. In Gazebo, the robot should be lying on the ground with joints not activated. ### Stand controller After launching the gazebo simulation, you can start to control the robot: ``` rosrun unitree_controller unitree_servo ``` And you can add external disturbances, like a push or a kick: ``` rosrun unitree_controller unitree_external_force ``` ### Position and pose publisher Here we demonstrated how to control the position and pose of robot without a controller, which should be useful in SLAM or visual development. Then run the position and pose publisher in another terminal: ``` rosrun unitree_controller unitree_move_kinetic ``` The robot will turn around the origin, which is the movement under the world coordinate frame. And inside of the source file [move_publisher.cpp](https://github.com/unitreerobotics/unitree_ros/blob/master/unitree_controller/src/move_publisher.cpp), we also provide the method to move using the robot coordinate frame. You can change the value of `def_frame` to `coord::ROBOT` and run the catkin_make again, then the `unitree_move_publisher` will move robot under its own coordinate frame.
4,596
Markdown
57.935897
574
0.779373
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_gazebo/plugin/foot_contact_plugin.cc
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include <string> #include <gazebo/common/Events.hh> #include <ros/ros.h> #include <ros/advertise_options.h> #include <gazebo/gazebo.hh> #include <gazebo/sensors/sensors.hh> #include <geometry_msgs/WrenchStamped.h> namespace gazebo { class UnitreeFootContactPlugin : public SensorPlugin { public: UnitreeFootContactPlugin() : SensorPlugin(){} ~UnitreeFootContactPlugin(){} void Load(sensors::SensorPtr _sensor, sdf::ElementPtr _sdf) { this->parentSensor = std::dynamic_pointer_cast<sensors::ContactSensor>(_sensor); // Make sure the parent sensor is valid. if (!this->parentSensor){ gzerr << "UnitreeFootContactPlugin requires a ContactSensor.\n"; return; } this->contact_namespace = "contact/"; this->rosnode = new ros::NodeHandle(this->contact_namespace); // add "visual" is for the same name of draw node this->force_pub = this->rosnode->advertise<geometry_msgs::WrenchStamped>("/visual/"+_sensor->Name()+"/the_force", 100); // Connect to the sensor update event. this->update_connection = this->parentSensor->ConnectUpdated(std::bind(&UnitreeFootContactPlugin::OnUpdate, this)); this->parentSensor->SetActive(true); // Make sure the parent sensor is active. count = 0; Fx = 0; Fy = 0; Fz = 0; ROS_INFO("Load %s plugin.", _sensor->Name().c_str()); } private: void OnUpdate() { msgs::Contacts contacts; contacts = this->parentSensor->Contacts(); count = contacts.contact_size(); // std::cout << count <<"\n"; for (unsigned int i = 0; i < count; ++i){ if(contacts.contact(i).position_size() != 1){ ROS_ERROR("Contact count isn't correct!!!!"); } for (unsigned int j = 0; j < contacts.contact(i).position_size(); ++j){ // std::cout << i <<" "<< contacts.contact(i).position_size() <<" Force:" // << contacts.contact(i).wrench(j).body_1_wrench().force().x() << " " // << contacts.contact(i).wrench(j).body_1_wrench().force().y() << " " // << contacts.contact(i).wrench(j).body_1_wrench().force().z() << "\n"; Fx += contacts.contact(i).wrench(0).body_1_wrench().force().x(); // Notice: the force is in local coordinate, not in world or base coordnate. Fy += contacts.contact(i).wrench(0).body_1_wrench().force().y(); Fz += contacts.contact(i).wrench(0).body_1_wrench().force().z(); } } if(count != 0){ force.wrench.force.x = Fx/double(count); force.wrench.force.y = Fy/double(count); force.wrench.force.z = Fz/double(count); count = 0; Fx = 0; Fy = 0; Fz = 0; } else{ force.wrench.force.x = 0; force.wrench.force.y = 0; force.wrench.force.z = 0; } this->force_pub.publish(force); } private: ros::NodeHandle* rosnode; ros::Publisher force_pub; event::ConnectionPtr update_connection; std::string contact_namespace; sensors::ContactSensorPtr parentSensor; geometry_msgs::WrenchStamped force; int count = 0; double Fx=0, Fy=0, Fz=0; }; GZ_REGISTER_SENSOR_PLUGIN(UnitreeFootContactPlugin) }
4,092
C++
42.542553
161
0.503666
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_gazebo/plugin/draw_force_plugin.cc
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include <ignition/math/Color.hh> #include <gazebo/common/Events.hh> #include <gazebo/msgs/msgs.hh> #include <gazebo/transport/Node.hh> #include <gazebo/common/Plugin.hh> #include <ros/ros.h> #include "gazebo/rendering/DynamicLines.hh" #include "gazebo/rendering/RenderTypes.hh" #include "gazebo/rendering/Visual.hh" #include "gazebo/rendering/Scene.hh" #include <ros/ros.h> #include <boost/bind.hpp> #include <geometry_msgs/WrenchStamped.h> namespace gazebo { class UnitreeDrawForcePlugin : public VisualPlugin { public: UnitreeDrawForcePlugin():line(NULL){} ~UnitreeDrawForcePlugin(){ this->visual->DeleteDynamicLine(this->line); } void Load(rendering::VisualPtr _parent, sdf::ElementPtr _sdf ) { this->visual = _parent; this->visual_namespace = "visual/"; if (!_sdf->HasElement("topicName")){ ROS_INFO("Force draw plugin missing <topicName>, defaults to /default_force_draw"); this->topic_name = "/default_force_draw"; } else{ this->topic_name = _sdf->Get<std::string>("topicName"); } if (!ros::isInitialized()){ int argc = 0; char** argv = NULL; ros::init(argc,argv,"gazebo_visual",ros::init_options::NoSigintHandler|ros::init_options::AnonymousName); } this->line = this->visual->CreateDynamicLine(rendering::RENDERING_LINE_STRIP); this->line->AddPoint(ignition::math::Vector3d(0, 0, 0), common::Color(0, 1, 0, 1.0)); this->line->AddPoint(ignition::math::Vector3d(1, 1, 1), common::Color(0, 1, 0, 1.0)); this->line->setMaterial("Gazebo/Purple"); this->line->setVisibilityFlags(GZ_VISIBILITY_GUI); this->visual->SetVisible(true); this->rosnode = new ros::NodeHandle(this->visual_namespace); this->force_sub = this->rosnode->subscribe(this->topic_name+"/"+"the_force", 30, &UnitreeDrawForcePlugin::GetForceCallback, this); this->update_connection = event::Events::ConnectPreRender(boost::bind(&UnitreeDrawForcePlugin::OnUpdate, this)); ROS_INFO("Load %s Draw Force plugin.", this->topic_name.c_str()); } void OnUpdate() { this->line->SetPoint(1, ignition::math::Vector3d(Fx, Fy, Fz)); } void GetForceCallback(const geometry_msgs::WrenchStamped & msg) { Fx = msg.wrench.force.x/20.0; Fy = msg.wrench.force.y/20.0; Fz = msg.wrench.force.z/20.0; // Fx = msg.wrench.force.x; // Fy = msg.wrench.force.y; // Fz = msg.wrench.force.z; } private: ros::NodeHandle* rosnode; std::string topic_name; rendering::VisualPtr visual; rendering::DynamicLines *line; std::string visual_namespace; ros::Subscriber force_sub; double Fx=0, Fy=0, Fz=0; event::ConnectionPtr update_connection; }; GZ_REGISTER_VISUAL_PLUGIN(UnitreeDrawForcePlugin) }
3,448
C++
39.104651
142
0.571056
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/move_publisher.cpp
#include <ros/ros.h> #include <gazebo_msgs/ModelState.h> #include <gazebo_msgs/SetModelState.h> #include <string> #include <stdio.h> #include <tf/transform_datatypes.h> // #include <std_msgs/Float64.h> #include <math.h> #include <iostream> int main(int argc, char **argv) { enum coord { WORLD, ROBOT }; coord def_frame = coord::WORLD; ros::init(argc, argv, "move_publisher"); ros::NodeHandle nh; ros::Publisher move_publisher = nh.advertise<gazebo_msgs::ModelState>("/gazebo/set_model_state", 1000); gazebo_msgs::ModelState model_state_pub; std::string robot_name; ros::param::get("/robot_name", robot_name); std::cout << "robot_name: " << robot_name << std::endl; model_state_pub.model_name = robot_name + "_gazebo"; ros::Rate loop_rate(1000); if(def_frame == coord::WORLD) { model_state_pub.pose.position.x = 0.0; model_state_pub.pose.position.y = 0.0; model_state_pub.pose.position.z = 0.5; model_state_pub.pose.orientation.x = 0.0; model_state_pub.pose.orientation.y = 0.0; model_state_pub.pose.orientation.z = 0.0; model_state_pub.pose.orientation.w = 1.0; model_state_pub.reference_frame = "world"; long long time_ms = 0; //time, ms const double period = 5000; //ms const double radius = 1.5; //m tf::Quaternion q; while(ros::ok()) { model_state_pub.pose.position.x = radius * sin(2*M_PI*(double)time_ms/period); model_state_pub.pose.position.y = radius * cos(2*M_PI*(double)time_ms/period); model_state_pub.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, - 2*M_PI*(double)time_ms/period); move_publisher.publish(model_state_pub); loop_rate.sleep(); time_ms += 1; } } else if(def_frame == coord::ROBOT) { model_state_pub.twist.linear.x= 0.02; //0.02: 2cm/sec model_state_pub.twist.linear.y= 0.0; model_state_pub.twist.linear.z= 0.08; model_state_pub.twist.angular.x= 0.0; model_state_pub.twist.angular.y= 0.0; model_state_pub.twist.angular.z= 0.0; model_state_pub.reference_frame = "base"; while(ros::ok()) { move_publisher.publish(model_state_pub); loop_rate.sleep(); } } }
2,425
C++
29.325
126
0.585567
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/external_force.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include <ros/ros.h> #include <geometry_msgs/Wrench.h> #include <signal.h> #include <termios.h> #include <stdio.h> #define KEYCODE_UP 0x41 #define KEYCODE_DOWN 0x42 #define KEYCODE_LEFT 0x44 #define KEYCODE_RIGHT 0x43 #define KEYCODE_SPACE 0x20 int mode = 1; // pulsed mode or continuous mode class teleForceCmd { public: teleForceCmd(); void keyLoop(); void pubForce(double x, double y, double z); private: double Fx, Fy, Fz; ros::NodeHandle n; ros::Publisher force_pub; geometry_msgs::Wrench Force; }; teleForceCmd::teleForceCmd() { Fx = 0; Fy = 0; Fz = 0; force_pub = n.advertise<geometry_msgs::Wrench>("/apply_force/trunk", 20); sleep(1); pubForce(Fx, Fy, Fz); } int kfd = 0; struct termios cooked, raw; void quit(int sig) { tcsetattr(kfd, TCSANOW, &cooked); ros::shutdown(); exit(0); } int main(int argc, char** argv) { ros::init(argc, argv, "external_force"); teleForceCmd remote; signal(SIGINT,quit); remote.keyLoop(); return(0); } void teleForceCmd::pubForce(double x, double y, double z) { Force.force.x = Fx; Force.force.y = Fy; Force.force.z = Fz; force_pub.publish(Force); ros::spinOnce(); } void teleForceCmd::keyLoop() { char c; bool dirty=false; // get the console in raw mode tcgetattr(kfd, &cooked); 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("Reading from keyboard"); puts("---------------------------"); puts("Use 'Space' to change mode, default is Pulsed mode:"); puts("Use 'Up/Down/Left/Right' to change direction"); for(;;){ // get the next event from the keyboard if(read(kfd, &c, 1) < 0){ perror("read():"); exit(-1); } ROS_DEBUG("value: 0x%02X\n", c); switch(c){ case KEYCODE_UP: if(mode > 0) { Fx = 60; } else { Fx += 16; if(Fx > 220) Fx = 220; if(Fx < -220) Fx = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_DOWN: if(mode > 0) { Fx = -60; } else { Fx -= 16; if(Fx > 220) Fx = 220; if(Fx < -220) Fx = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_LEFT: if(mode > 0) { Fy = 30; } else { Fy += 8; if(Fy > 220) Fy = 220; if(Fy < -220) Fy = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_RIGHT: if(mode > 0) { Fy = -30; } else { Fy -= 8; if(Fy > 220) Fy = 220; if(Fy < -220) Fy = -220; } ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; case KEYCODE_SPACE: mode = mode*(-1); if(mode > 0){ ROS_INFO("Change to Pulsed mode."); } else { ROS_INFO("Change to Continuous mode."); } Fx = 0; Fy = 0; Fz = 0; ROS_INFO("Fx:%3d Fy:%3d Fz:%3d", (int)Fx, (int)Fy, (int)Fz); dirty = true; break; } if(dirty == true){ pubForce(Fx, Fy, Fz); if(mode > 0){ usleep(100000); // 100 ms Fx = 0; Fy = 0; Fz = 0; pubForce(Fx, Fy, Fz); } dirty=false; } } return; }
4,382
C++
25.245509
77
0.446143
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/body.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include "body.h" namespace unitree_model { ros::Publisher servo_pub[12]; unitree_legged_msgs::LowCmd lowCmd; unitree_legged_msgs::LowState lowState; // These parameters are only for reference. // Actual patameters need to be debugged if you want to run on real robot. void paramInit() { for(int i=0; i<4; i++){ lowCmd.motorCmd[i*3+0].mode = 0x0A; lowCmd.motorCmd[i*3+0].Kp = 70; lowCmd.motorCmd[i*3+0].dq = 0; lowCmd.motorCmd[i*3+0].Kd = 3; lowCmd.motorCmd[i*3+0].tau = 0; lowCmd.motorCmd[i*3+1].mode = 0x0A; lowCmd.motorCmd[i*3+1].Kp = 180; lowCmd.motorCmd[i*3+1].dq = 0; lowCmd.motorCmd[i*3+1].Kd = 8; lowCmd.motorCmd[i*3+1].tau = 0; lowCmd.motorCmd[i*3+2].mode = 0x0A; lowCmd.motorCmd[i*3+2].Kp = 300; lowCmd.motorCmd[i*3+2].dq = 0; lowCmd.motorCmd[i*3+2].Kd = 15; lowCmd.motorCmd[i*3+2].tau = 0; } for(int i=0; i<12; i++){ lowCmd.motorCmd[i].q = lowState.motorState[i].q; } } void stand() { double pos[12] = {0.0, 0.67, -1.3, -0.0, 0.67, -1.3, 0.0, 0.67, -1.3, -0.0, 0.67, -1.3}; moveAllPosition(pos, 2*1000); } void motion_init() { paramInit(); stand(); } void sendServoCmd() { for(int m=0; m<12; m++){ servo_pub[m].publish(lowCmd.motorCmd[m]); } ros::spinOnce(); usleep(1000); } void moveAllPosition(double* targetPos, double duration) { double pos[12] ,lastPos[12], percent; for(int j=0; j<12; j++) lastPos[j] = lowState.motorState[j].q; for(int i=1; i<=duration; i++){ if(!ros::ok()) break; percent = (double)i/duration; for(int j=0; j<12; j++){ lowCmd.motorCmd[j].q = lastPos[j]*(1-percent) + targetPos[j]*percent; } sendServoCmd(); } } }
2,130
C++
26.320512
82
0.532394
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/src/servo.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #include "ros/ros.h" #include <stdio.h> #include <stdlib.h> #include "unitree_legged_msgs/LowCmd.h" #include "unitree_legged_msgs/LowState.h" #include "unitree_legged_msgs/MotorCmd.h" #include "unitree_legged_msgs/MotorState.h" #include <geometry_msgs/WrenchStamped.h> #include <sensor_msgs/Imu.h> #include <std_msgs/Bool.h> #include <vector> #include <string> #include <math.h> #include <nav_msgs/Odometry.h> #include "body.h" using namespace std; using namespace unitree_model; bool start_up = true; class multiThread { public: multiThread(string rname){ robot_name = rname; imu_sub = nm.subscribe("/trunk_imu", 1, &multiThread::imuCallback, this); footForce_sub[0] = nm.subscribe("/visual/FR_foot_contact/the_force", 1, &multiThread::FRfootCallback, this); footForce_sub[1] = nm.subscribe("/visual/FL_foot_contact/the_force", 1, &multiThread::FLfootCallback, this); footForce_sub[2] = nm.subscribe("/visual/RR_foot_contact/the_force", 1, &multiThread::RRfootCallback, this); footForce_sub[3] = nm.subscribe("/visual/RL_foot_contact/the_force", 1, &multiThread::RLfootCallback, this); servo_sub[0] = nm.subscribe("/" + robot_name + "_gazebo/FR_hip_controller/state", 1, &multiThread::FRhipCallback, this); servo_sub[1] = nm.subscribe("/" + robot_name + "_gazebo/FR_thigh_controller/state", 1, &multiThread::FRthighCallback, this); servo_sub[2] = nm.subscribe("/" + robot_name + "_gazebo/FR_calf_controller/state", 1, &multiThread::FRcalfCallback, this); servo_sub[3] = nm.subscribe("/" + robot_name + "_gazebo/FL_hip_controller/state", 1, &multiThread::FLhipCallback, this); servo_sub[4] = nm.subscribe("/" + robot_name + "_gazebo/FL_thigh_controller/state", 1, &multiThread::FLthighCallback, this); servo_sub[5] = nm.subscribe("/" + robot_name + "_gazebo/FL_calf_controller/state", 1, &multiThread::FLcalfCallback, this); servo_sub[6] = nm.subscribe("/" + robot_name + "_gazebo/RR_hip_controller/state", 1, &multiThread::RRhipCallback, this); servo_sub[7] = nm.subscribe("/" + robot_name + "_gazebo/RR_thigh_controller/state", 1, &multiThread::RRthighCallback, this); servo_sub[8] = nm.subscribe("/" + robot_name + "_gazebo/RR_calf_controller/state", 1, &multiThread::RRcalfCallback, this); servo_sub[9] = nm.subscribe("/" + robot_name + "_gazebo/RL_hip_controller/state", 1, &multiThread::RLhipCallback, this); servo_sub[10] = nm.subscribe("/" + robot_name + "_gazebo/RL_thigh_controller/state", 1, &multiThread::RLthighCallback, this); servo_sub[11] = nm.subscribe("/" + robot_name + "_gazebo/RL_calf_controller/state", 1, &multiThread::RLcalfCallback, this); } void imuCallback(const sensor_msgs::Imu & msg) { lowState.imu.quaternion[0] = msg.orientation.w; lowState.imu.quaternion[1] = msg.orientation.x; lowState.imu.quaternion[2] = msg.orientation.y; lowState.imu.quaternion[3] = msg.orientation.z; lowState.imu.gyroscope[0] = msg.angular_velocity.x; lowState.imu.gyroscope[1] = msg.angular_velocity.y; lowState.imu.gyroscope[2] = msg.angular_velocity.z; lowState.imu.accelerometer[0] = msg.linear_acceleration.x; lowState.imu.accelerometer[1] = msg.linear_acceleration.y; lowState.imu.accelerometer[2] = msg.linear_acceleration.z; } void FRhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[0].mode = msg.mode; lowState.motorState[0].q = msg.q; lowState.motorState[0].dq = msg.dq; lowState.motorState[0].tauEst = msg.tauEst; } void FRthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[1].mode = msg.mode; lowState.motorState[1].q = msg.q; lowState.motorState[1].dq = msg.dq; lowState.motorState[1].tauEst = msg.tauEst; } void FRcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[2].mode = msg.mode; lowState.motorState[2].q = msg.q; lowState.motorState[2].dq = msg.dq; lowState.motorState[2].tauEst = msg.tauEst; } void FLhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[3].mode = msg.mode; lowState.motorState[3].q = msg.q; lowState.motorState[3].dq = msg.dq; lowState.motorState[3].tauEst = msg.tauEst; } void FLthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[4].mode = msg.mode; lowState.motorState[4].q = msg.q; lowState.motorState[4].dq = msg.dq; lowState.motorState[4].tauEst = msg.tauEst; } void FLcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[5].mode = msg.mode; lowState.motorState[5].q = msg.q; lowState.motorState[5].dq = msg.dq; lowState.motorState[5].tauEst = msg.tauEst; } void RRhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[6].mode = msg.mode; lowState.motorState[6].q = msg.q; lowState.motorState[6].dq = msg.dq; lowState.motorState[6].tauEst = msg.tauEst; } void RRthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[7].mode = msg.mode; lowState.motorState[7].q = msg.q; lowState.motorState[7].dq = msg.dq; lowState.motorState[7].tauEst = msg.tauEst; } void RRcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[8].mode = msg.mode; lowState.motorState[8].q = msg.q; lowState.motorState[8].dq = msg.dq; lowState.motorState[8].tauEst = msg.tauEst; } void RLhipCallback(const unitree_legged_msgs::MotorState& msg) { start_up = false; lowState.motorState[9].mode = msg.mode; lowState.motorState[9].q = msg.q; lowState.motorState[9].dq = msg.dq; lowState.motorState[9].tauEst = msg.tauEst; } void RLthighCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[10].mode = msg.mode; lowState.motorState[10].q = msg.q; lowState.motorState[10].dq = msg.dq; lowState.motorState[10].tauEst = msg.tauEst; } void RLcalfCallback(const unitree_legged_msgs::MotorState& msg) { lowState.motorState[11].mode = msg.mode; lowState.motorState[11].q = msg.q; lowState.motorState[11].dq = msg.dq; lowState.motorState[11].tauEst = msg.tauEst; } void FRfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[0].x = msg.wrench.force.x; lowState.eeForce[0].y = msg.wrench.force.y; lowState.eeForce[0].z = msg.wrench.force.z; lowState.footForce[0] = msg.wrench.force.z; } void FLfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[1].x = msg.wrench.force.x; lowState.eeForce[1].y = msg.wrench.force.y; lowState.eeForce[1].z = msg.wrench.force.z; lowState.footForce[1] = msg.wrench.force.z; } void RRfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[2].x = msg.wrench.force.x; lowState.eeForce[2].y = msg.wrench.force.y; lowState.eeForce[2].z = msg.wrench.force.z; lowState.footForce[2] = msg.wrench.force.z; } void RLfootCallback(const geometry_msgs::WrenchStamped& msg) { lowState.eeForce[3].x = msg.wrench.force.x; lowState.eeForce[3].y = msg.wrench.force.y; lowState.eeForce[3].z = msg.wrench.force.z; lowState.footForce[3] = msg.wrench.force.z; } private: ros::NodeHandle nm; ros::Subscriber servo_sub[12], footForce_sub[4], imu_sub; string robot_name; }; int main(int argc, char **argv) { ros::init(argc, argv, "unitree_gazebo_servo"); string robot_name; ros::param::get("/robot_name", robot_name); cout << "robot_name: " << robot_name << endl; multiThread listen_publish_obj(robot_name); ros::AsyncSpinner spinner(1); // one threads spinner.start(); usleep(300000); // must wait 300ms, to get first state ros::NodeHandle n; ros::Publisher lowState_pub; //for rviz visualization // ros::Rate loop_rate(1000); // the following nodes have been initialized by "gazebo.launch" lowState_pub = n.advertise<unitree_legged_msgs::LowState>("/" + robot_name + "_gazebo/lowState/state", 1); servo_pub[0] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FR_hip_controller/command", 1); servo_pub[1] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FR_thigh_controller/command", 1); servo_pub[2] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FR_calf_controller/command", 1); servo_pub[3] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FL_hip_controller/command", 1); servo_pub[4] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FL_thigh_controller/command", 1); servo_pub[5] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/FL_calf_controller/command", 1); servo_pub[6] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RR_hip_controller/command", 1); servo_pub[7] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RR_thigh_controller/command", 1); servo_pub[8] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RR_calf_controller/command", 1); servo_pub[9] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RL_hip_controller/command", 1); servo_pub[10] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RL_thigh_controller/command", 1); servo_pub[11] = n.advertise<unitree_legged_msgs::MotorCmd>("/" + robot_name + "_gazebo/RL_calf_controller/command", 1); motion_init(); while (ros::ok()){ /* control logic */ lowState_pub.publish(lowState); sendServoCmd(); } return 0; }
10,620
C++
41.654618
133
0.638606
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_controller/include/body.h
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #ifndef __BODY_H__ #define __BODY_H__ #include "ros/ros.h" #include "unitree_legged_msgs/LowCmd.h" #include "unitree_legged_msgs/LowState.h" #include "unitree_legged_msgs/HighState.h" #define PosStopF (2.146E+9f) #define VelStopF (16000.f) namespace unitree_model { extern ros::Publisher servo_pub[12]; extern ros::Publisher highState_pub; extern unitree_legged_msgs::LowCmd lowCmd; extern unitree_legged_msgs::LowState lowState; void stand(); void motion_init(); void sendServoCmd(); void moveAllPosition(double* jointPositions, double duration); } #endif
855
C
27.533332
73
0.626901
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/unitree_controller_plugins.xml
<library path="lib/libunitree_legged_control"> <class name="unitree_legged_control/UnitreeJointController" type="unitree_legged_control::UnitreeJointController" base_class_type="controller_interface::ControllerBase"/> <description> The unitree joint controller. </description> </library>
354
XML
38.44444
75
0.661017
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/src/joint_controller.cpp
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ // #include "unitree_legged_control/joint_controller.h" #include "joint_controller.h" #include <pluginlib/class_list_macros.h> // #define rqtTune // use rqt or not namespace unitree_legged_control { UnitreeJointController::UnitreeJointController(){ memset(&lastCmd, 0, sizeof(unitree_legged_msgs::MotorCmd)); memset(&lastState, 0, sizeof(unitree_legged_msgs::MotorState)); memset(&servoCmd, 0, sizeof(ServoCmd)); } UnitreeJointController::~UnitreeJointController(){ sub_ft.shutdown(); sub_cmd.shutdown(); } void UnitreeJointController::setTorqueCB(const geometry_msgs::WrenchStampedConstPtr& msg) { if(isHip) sensor_torque = msg->wrench.torque.x; else sensor_torque = msg->wrench.torque.y; // printf("sensor torque%f\n", sensor_torque); } void UnitreeJointController::setCommandCB(const unitree_legged_msgs::MotorCmdConstPtr& msg) { lastCmd.mode = msg->mode; lastCmd.q = msg->q; lastCmd.Kp = msg->Kp; lastCmd.dq = msg->dq; lastCmd.Kd = msg->Kd; lastCmd.tau = msg->tau; // the writeFromNonRT can be used in RT, if you have the guarantee that // * no non-rt thread is calling the same function (we're not subscribing to ros callbacks) // * there is only one single rt thread command.writeFromNonRT(lastCmd); } // Controller initialization in non-realtime bool UnitreeJointController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { isHip = false; isThigh = false; isCalf = false; // rqtTune = false; sensor_torque = 0; name_space = n.getNamespace(); if (!n.getParam("joint", joint_name)){ ROS_ERROR("No joint given in namespace: '%s')", n.getNamespace().c_str()); return false; } // load pid param from ymal only if rqt need // if(rqtTune) { #ifdef rqtTune // Load PID Controller using gains set on parameter server if (!pid_controller_.init(ros::NodeHandle(n, "pid"))) return false; #endif // } urdf::Model urdf; // Get URDF info about joint if (!urdf.initParamWithNodeHandle("robot_description", n)){ ROS_ERROR("Failed to parse urdf file"); return false; } joint_urdf = urdf.getJoint(joint_name); if (!joint_urdf){ ROS_ERROR("Could not find joint '%s' in urdf", joint_name.c_str()); return false; } if(joint_name == "FR_hip_joint" || joint_name == "FL_hip_joint" || joint_name == "RR_hip_joint" || joint_name == "RL_hip_joint"){ isHip = true; } if(joint_name == "FR_calf_joint" || joint_name == "FL_calf_joint" || joint_name == "RR_calf_joint" || joint_name == "RL_calf_joint"){ isCalf = true; } joint = robot->getHandle(joint_name); // Start command subscriber sub_ft = n.subscribe(name_space + "/" +"joint_wrench", 1, &UnitreeJointController::setTorqueCB, this); sub_cmd = n.subscribe("command", 20, &UnitreeJointController::setCommandCB, this); // pub_state = n.advertise<unitree_legged_msgs::MotorState>(name_space + "/state", 20); // Start realtime state publisher controller_state_publisher_.reset( new realtime_tools::RealtimePublisher<unitree_legged_msgs::MotorState>(n, name_space + "/state", 1)); return true; } void UnitreeJointController::setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min, const bool &antiwindup) { pid_controller_.setGains(p,i,d,i_max,i_min,antiwindup); } void UnitreeJointController::getGains(double &p, double &i, double &d, double &i_max, double &i_min, bool &antiwindup) { pid_controller_.getGains(p,i,d,i_max,i_min,antiwindup); } void UnitreeJointController::getGains(double &p, double &i, double &d, double &i_max, double &i_min) { bool dummy; pid_controller_.getGains(p,i,d,i_max,i_min,dummy); } // Controller startup in realtime void UnitreeJointController::starting(const ros::Time& time) { // lastCmd.Kp = 0; // lastCmd.Kd = 0; double init_pos = joint.getPosition(); lastCmd.q = init_pos; lastState.q = init_pos; lastCmd.dq = 0; lastState.dq = 0; lastCmd.tau = 0; lastState.tauEst = 0; command.initRT(lastCmd); pid_controller_.reset(); } // Controller update loop in realtime void UnitreeJointController::update(const ros::Time& time, const ros::Duration& period) { double currentPos, currentVel, calcTorque; lastCmd = *(command.readFromRT()); // set command data if(lastCmd.mode == PMSM) { servoCmd.pos = lastCmd.q; positionLimits(servoCmd.pos); servoCmd.posStiffness = lastCmd.Kp; if(fabs(lastCmd.q - PosStopF) < 0.00001){ servoCmd.posStiffness = 0; } servoCmd.vel = lastCmd.dq; velocityLimits(servoCmd.vel); servoCmd.velStiffness = lastCmd.Kd; if(fabs(lastCmd.dq - VelStopF) < 0.00001){ servoCmd.velStiffness = 0; } servoCmd.torque = lastCmd.tau; effortLimits(servoCmd.torque); } if(lastCmd.mode == BRAKE) { servoCmd.posStiffness = 0; servoCmd.vel = 0; servoCmd.velStiffness = 20; servoCmd.torque = 0; effortLimits(servoCmd.torque); } // } else { // servoCmd.posStiffness = 0; // servoCmd.velStiffness = 5; // servoCmd.torque = 0; // } // rqt set P D gains // if(rqtTune) { #ifdef rqtTune double i, i_max, i_min; getGains(servoCmd.posStiffness,i,servoCmd.velStiffness,i_max,i_min); #endif // } currentPos = joint.getPosition(); currentVel = computeVel(currentPos, (double)lastState.q, (double)lastState.dq, period.toSec()); calcTorque = computeTorque(currentPos, currentVel, servoCmd); effortLimits(calcTorque); joint.setCommand(calcTorque); lastState.q = currentPos; lastState.dq = currentVel; // lastState.tauEst = calcTorque; // lastState.tauEst = sensor_torque; lastState.tauEst = joint.getEffort(); // pub_state.publish(lastState); // publish state if (controller_state_publisher_ && controller_state_publisher_->trylock()) { controller_state_publisher_->msg_.q = lastState.q; controller_state_publisher_->msg_.dq = lastState.dq; controller_state_publisher_->msg_.tauEst = lastState.tauEst; controller_state_publisher_->unlockAndPublish(); } // printf("sensor torque%f\n", sensor_torque); // if(joint_name == "wrist1_joint") printf("wrist1 setp:%f getp:%f t:%f\n", servoCmd.pos, currentPos, calcTorque); } // Controller stopping in realtime void UnitreeJointController::stopping(){} void UnitreeJointController::positionLimits(double &position) { if (joint_urdf->type == urdf::Joint::REVOLUTE || joint_urdf->type == urdf::Joint::PRISMATIC) clamp(position, joint_urdf->limits->lower, joint_urdf->limits->upper); } void UnitreeJointController::velocityLimits(double &velocity) { if (joint_urdf->type == urdf::Joint::REVOLUTE || joint_urdf->type == urdf::Joint::PRISMATIC) clamp(velocity, -joint_urdf->limits->velocity, joint_urdf->limits->velocity); } void UnitreeJointController::effortLimits(double &effort) { if (joint_urdf->type == urdf::Joint::REVOLUTE || joint_urdf->type == urdf::Joint::PRISMATIC) clamp(effort, -joint_urdf->limits->effort, joint_urdf->limits->effort); } } // namespace // Register controller to pluginlib PLUGINLIB_EXPORT_CLASS(unitree_legged_control::UnitreeJointController, controller_interface::ControllerBase);
8,576
C++
36.291304
158
0.592001
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/include/unitree_joint_control_tool.h
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ // #ifndef _UNITREE_JOINT_CONTROL_TOOL_H_ // #define _UNITREE_JOINT_CONTROL_TOOL_H_ #ifndef _LAIKAGO_CONTROL_TOOL_H_ #define _LAIKAGO_CONTROL_TOOL_H_ #include <stdio.h> #include <stdint.h> #include <algorithm> #include <math.h> #define posStopF (2.146E+9f) // stop position control mode #define velStopF (16000.0f) // stop velocity control mode typedef struct { uint8_t mode; double pos; double posStiffness; double vel; double velStiffness; double torque; } ServoCmd; double clamp(double&, double, double); // eg. clamp(1.5, -1, 1) = 1 double computeVel(double current_position, double last_position, double last_velocity, double duration); // get current velocity double computeTorque(double current_position, double current_velocity, ServoCmd&); // get torque #endif
1,099
C
31.35294
129
0.627843
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/unitree_legged_control/include/joint_controller.h
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #ifndef _UNITREE_ROS_JOINT_CONTROLLER_H_ #define _UNITREE_ROS_JOINT_CONTROLLER_H_ #include <ros/node_handle.h> #include <urdf/model.h> #include <control_toolbox/pid.h> #include <boost/scoped_ptr.hpp> #include <boost/thread/condition.hpp> #include <realtime_tools/realtime_publisher.h> #include <hardware_interface/joint_command_interface.h> #include <controller_interface/controller.h> #include <std_msgs/Float64.h> #include <realtime_tools/realtime_buffer.h> #include <controller_interface/controller.h> #include <hardware_interface/joint_command_interface.h> #include "unitree_legged_msgs/MotorCmd.h" #include "unitree_legged_msgs/MotorState.h" #include <geometry_msgs/WrenchStamped.h> #include "unitree_joint_control_tool.h" #define PMSM (0x0A) #define BRAKE (0x00) #define PosStopF (2.146E+9f) #define VelStopF (16000.0f) namespace unitree_legged_control { class UnitreeJointController: public controller_interface::Controller<hardware_interface::EffortJointInterface> { private: hardware_interface::JointHandle joint; ros::Subscriber sub_cmd, sub_ft; // ros::Publisher pub_state; control_toolbox::Pid pid_controller_; boost::scoped_ptr<realtime_tools::RealtimePublisher<unitree_legged_msgs::MotorState> > controller_state_publisher_ ; public: // bool start_up; std::string name_space; std::string joint_name; float sensor_torque; bool isHip, isThigh, isCalf, rqtTune; urdf::JointConstSharedPtr joint_urdf; realtime_tools::RealtimeBuffer<unitree_legged_msgs::MotorCmd> command; unitree_legged_msgs::MotorCmd lastCmd; unitree_legged_msgs::MotorState lastState; ServoCmd servoCmd; UnitreeJointController(); ~UnitreeJointController(); virtual bool init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n); virtual void starting(const ros::Time& time); virtual void update(const ros::Time& time, const ros::Duration& period); virtual void stopping(); void setTorqueCB(const geometry_msgs::WrenchStampedConstPtr& msg); void setCommandCB(const unitree_legged_msgs::MotorCmdConstPtr& msg); void positionLimits(double &position); void velocityLimits(double &velocity); void effortLimits(double &effort); void setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min, const bool &antiwindup = false); void getGains(double &p, double &i, double &d, double &i_max, double &i_min, bool &antiwindup); void getGains(double &p, double &i, double &d, double &i_max, double &i_min); }; } #endif
2,999
C
39.54054
147
0.674558
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/opendog_description-CHAMP/README.md
URDF and Gazebo model of [Jame's Bruton's](https://www.youtube.com/user/jamesbruton) [OpenDog V2](https://github.com/XRobots/openDogV2) project.
146
Markdown
72.499964
145
0.760274
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/README.md
# openDogV2: CAD and Code that relates to this YouTube series: https://www.youtube.com/playlist?list=PLpwJoq86vov9CcmrLGyM2XyyYDAYG0-Iu Release 1: created at the end of part 6 of the YouTube series. Please note the issues stated at the end of this video. Release 2: created at the end of part 7 of the YouTube series. Please note the issues stated during this video. Note that the remote is unchanged since release 1. Relase 3: created for part 8 of the YouTube series. Includes the modified knee motor pulley, Python and Arduino code for the deep learning model. # Related Community Projects: OpenDog URDF/config for CHAMP: https://github.com/chvmp/opendog_description 'openDog 2.1' with higher belt reductions and cooling fans: https://github.com/J-DIndustries/openDog-V2.1
789
Markdown
42.888887
162
0.784537
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/Release02/Code/openDogV2_R2/MPU6050_6Axis_MotionApps20.h
// I2Cdev library collection - MPU6050 I2C device class, 6-axis MotionApps 2.0 implementation // Based on InvenSense MPU-6050 register map document rev. 2.0, 5/19/2011 (RM-MPU-6000A-00) // 5/20/2013 by Jeff Rowberg <jeff@rowberg.net> // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib // // Changelog: // ... - ongoing debug release /* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2012 Jeff Rowberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================== */ #ifndef _MPU6050_6AXIS_MOTIONAPPS20_H_ #define _MPU6050_6AXIS_MOTIONAPPS20_H_ #include "I2Cdev.h" #include "helper_3dmath.h" // MotionApps 2.0 DMP implementation, built using the MPU-6050EVB evaluation board #define MPU6050_INCLUDE_DMP_MOTIONAPPS20 #include "MPU6050.h" // Tom Carpenter's conditional PROGMEM code // http://forum.arduino.cc/index.php?topic=129407.0 #ifndef __arm__ #include <avr/pgmspace.h> #else // Teensy 3.0 library conditional PROGMEM code from Paul Stoffregen #ifndef __PGMSPACE_H_ #define __PGMSPACE_H_ 1 #include <inttypes.h> #define PROGMEM #define PGM_P const char * #define PSTR(str) (str) #define F(x) x typedef void prog_void; typedef char prog_char; typedef unsigned char prog_uchar; typedef int8_t prog_int8_t; typedef uint8_t prog_uint8_t; typedef int16_t prog_int16_t; typedef uint16_t prog_uint16_t; typedef int32_t prog_int32_t; typedef uint32_t prog_uint32_t; #define strcpy_P(dest, src) strcpy((dest), (src)) #define strcat_P(dest, src) strcat((dest), (src)) #define strcmp_P(a, b) strcmp((a), (b)) #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) #define pgm_read_word(addr) (*(const unsigned short *)(addr)) #define pgm_read_dword(addr) (*(const unsigned long *)(addr)) #define pgm_read_float(addr) (*(const float *)(addr)) #define pgm_read_byte_near(addr) pgm_read_byte(addr) #define pgm_read_word_near(addr) pgm_read_word(addr) #define pgm_read_dword_near(addr) pgm_read_dword(addr) #define pgm_read_float_near(addr) pgm_read_float(addr) #define pgm_read_byte_far(addr) pgm_read_byte(addr) #define pgm_read_word_far(addr) pgm_read_word(addr) #define pgm_read_dword_far(addr) pgm_read_dword(addr) #define pgm_read_float_far(addr) pgm_read_float(addr) #endif #endif /* Source is from the InvenSense MotionApps v2 demo code. Original source is * unavailable, unless you happen to be amazing as decompiling binary by * hand (in which case, please contact me, and I'm totally serious). * * Also, I'd like to offer many, many thanks to Noah Zerkin for all of the * DMP reverse-engineering he did to help make this bit of wizardry * possible. */ // NOTE! Enabling DEBUG adds about 3.3kB to the flash program size. // Debug output is now working even on ATMega328P MCUs (e.g. Arduino Uno) // after moving string constants to flash memory storage using the F() // compiler macro (Arduino IDE 1.0+ required). //#define DEBUG #ifdef DEBUG #define DEBUG_PRINT(x) Serial.print(x) #define DEBUG_PRINTF(x, y) Serial.print(x, y) #define DEBUG_PRINTLN(x) Serial.println(x) #define DEBUG_PRINTLNF(x, y) Serial.println(x, y) #else #define DEBUG_PRINT(x) #define DEBUG_PRINTF(x, y) #define DEBUG_PRINTLN(x) #define DEBUG_PRINTLNF(x, y) #endif #define MPU6050_DMP_CODE_SIZE 1929 // dmpMemory[] #define MPU6050_DMP_CONFIG_SIZE 192 // dmpConfig[] #define MPU6050_DMP_UPDATES_SIZE 47 // dmpUpdates[] /* ================================================================================================ * | Default MotionApps v2.0 42-byte FIFO packet structure: | | | | [QUAT W][ ][QUAT X][ ][QUAT Y][ ][QUAT Z][ ][GYRO X][ ][GYRO Y][ ] | | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | | | | [GYRO Z][ ][ACC X ][ ][ACC Y ][ ][ACC Z ][ ][ ] | | 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | * ================================================================================================ */ // this block of memory gets written to the MPU on start-up, and it seems // to be volatile memory, so it has to be done each time (it only takes ~1 // second though) const unsigned char dmpMemory[MPU6050_DMP_CODE_SIZE] PROGMEM = { // bank 0, 256 bytes 0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82, 0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC, 0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4, 0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10, // bank 1, 256 bytes 0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8, 0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C, 0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0, // bank 2, 256 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bank 3, 256 bytes 0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F, 0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2, 0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF, 0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C, 0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1, 0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01, 0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80, 0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80, 0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E, 0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9, 0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0, 0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86, 0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1, 0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86, // bank 4, 256 bytes 0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA, 0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C, 0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8, 0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3, 0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84, 0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5, 0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3, 0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1, 0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5, 0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A, 0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8, 0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87, // bank 5, 256 bytes 0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8, 0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68, 0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D, 0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94, 0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56, 0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA, 0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A, 0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60, 0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97, 0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04, 0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78, 0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79, 0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68, 0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68, // bank 6, 256 bytes 0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04, 0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66, 0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31, 0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60, 0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76, 0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56, 0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD, 0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91, 0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE, 0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9, 0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD, 0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E, 0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8, 0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89, 0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79, // bank 7, 138 bytes (remainder) 0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA, 0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB, 0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3, 0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3, 0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC, 0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF }; // thanks to Noah Zerkin for piecing this stuff together! const unsigned char dmpConfig[MPU6050_DMP_CONFIG_SIZE] PROGMEM = { // BANK OFFSET LENGTH [DATA] 0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration 0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration 0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration 0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration 0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration 0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration 0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration 0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration 0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01 0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02 0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10 0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11 0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12 0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20 0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21 0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22 0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors 0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion 0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update 0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone // SPECIAL 0x01 = enable interrupts 0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION 0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt 0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion 0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer 0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro 0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo 0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo 0x02, 0x16, 0x02, 0x00, 0x09 // D_0_22 inv_set_fifo_rate // This very last 0x01 WAS a 0x09, which drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz, // 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very noisy data. // DMP output frequency is calculated easily using this equation: (200Hz / (1 + value)) // It is important to make sure the host processor can keep up with reading and processing // the FIFO output at the desired rate. Handling FIFO overflow cleanly is also a good idea. }; const unsigned char dmpUpdates[MPU6050_DMP_UPDATES_SIZE] PROGMEM = { 0x01, 0xB2, 0x02, 0xFF, 0xFF, 0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35, 0x01, 0x6A, 0x02, 0x06, 0x00, 0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00, 0x01, 0x62, 0x02, 0x00, 0x00, 0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00 }; uint8_t MPU6050::dmpInitialize() { // reset device DEBUG_PRINTLN(F("\n\nResetting MPU6050...")); reset(); delay(30); // wait after reset // enable sleep mode and wake cycle /*Serial.println(F("Enabling sleep mode...")); setSleepEnabled(true); Serial.println(F("Enabling wake cycle...")); setWakeCycleEnabled(true);*/ // disable sleep mode DEBUG_PRINTLN(F("Disabling sleep mode...")); setSleepEnabled(false); // get MPU hardware revision DEBUG_PRINTLN(F("Selecting user bank 16...")); setMemoryBank(0x10, true, true); DEBUG_PRINTLN(F("Selecting memory byte 6...")); setMemoryStartAddress(0x06); DEBUG_PRINTLN(F("Checking hardware revision...")); uint8_t hwRevision = readMemoryByte(); DEBUG_PRINT(F("Revision @ user[16][6] = ")); DEBUG_PRINTLNF(hwRevision, HEX); DEBUG_PRINTLN(F("Resetting memory bank selection to 0...")); setMemoryBank(0, false, false); // check OTP bank valid DEBUG_PRINTLN(F("Reading OTP bank valid flag...")); uint8_t otpValid = getOTPBankValid(); DEBUG_PRINT(F("OTP bank is ")); DEBUG_PRINTLN(otpValid ? F("valid!") : F("invalid!")); // get X/Y/Z gyro offsets DEBUG_PRINTLN(F("Reading gyro offset TC values...")); int8_t xgOffsetTC = getXGyroOffsetTC(); int8_t ygOffsetTC = getYGyroOffsetTC(); int8_t zgOffsetTC = getZGyroOffsetTC(); DEBUG_PRINT(F("X gyro offset = ")); DEBUG_PRINTLN(xgOffset); DEBUG_PRINT(F("Y gyro offset = ")); DEBUG_PRINTLN(ygOffset); DEBUG_PRINT(F("Z gyro offset = ")); DEBUG_PRINTLN(zgOffset); // setup weird slave stuff (?) DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F...")); setSlaveAddress(0, 0x7F); DEBUG_PRINTLN(F("Disabling I2C Master mode...")); setI2CMasterModeEnabled(false); DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)...")); setSlaveAddress(0, 0x68); DEBUG_PRINTLN(F("Resetting I2C Master control...")); resetI2CMaster(); delay(20); // load DMP code into memory banks DEBUG_PRINT(F("Writing DMP code to MPU memory banks (")); DEBUG_PRINT(MPU6050_DMP_CODE_SIZE); DEBUG_PRINTLN(F(" bytes)")); if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) { DEBUG_PRINTLN(F("Success! DMP code written and verified.")); // write DMP configuration DEBUG_PRINT(F("Writing DMP configuration to MPU memory banks (")); DEBUG_PRINT(MPU6050_DMP_CONFIG_SIZE); DEBUG_PRINTLN(F(" bytes in config def)")); if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) { DEBUG_PRINTLN(F("Success! DMP configuration written and verified.")); DEBUG_PRINTLN(F("Setting clock source to Z Gyro...")); setClockSource(MPU6050_CLOCK_PLL_ZGYRO); DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled...")); setIntEnabled(0x12); DEBUG_PRINTLN(F("Setting sample rate to 200Hz...")); setRate(4); // 1khz / (1 + 4) = 200 Hz DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]...")); setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L); DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz...")); setDLPFMode(MPU6050_DLPF_BW_42); DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec...")); setFullScaleGyroRange(MPU6050_GYRO_FS_2000); DEBUG_PRINTLN(F("Setting DMP configuration bytes (function unknown)...")); setDMPConfig1(0x03); setDMPConfig2(0x00); DEBUG_PRINTLN(F("Clearing OTP Bank flag...")); setOTPBankValid(false); DEBUG_PRINTLN(F("Setting X/Y/Z gyro offset TCs to previous values...")); setXGyroOffsetTC(xgOffsetTC); setYGyroOffsetTC(ygOffsetTC); setZGyroOffsetTC(zgOffsetTC); //DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero...")); //setXGyroOffset(0); //setYGyroOffset(0); //setZGyroOffset(0); DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)...")); uint8_t dmpUpdate[16], j; uint16_t pos = 0; for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)...")); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); DEBUG_PRINTLN(F("Resetting FIFO...")); resetFIFO(); DEBUG_PRINTLN(F("Reading FIFO count...")); uint16_t fifoCount = getFIFOCount(); uint8_t fifoBuffer[128]; DEBUG_PRINT(F("Current FIFO count=")); DEBUG_PRINTLN(fifoCount); getFIFOBytes(fifoBuffer, fifoCount); DEBUG_PRINTLN(F("Setting motion detection threshold to 2...")); setMotionDetectionThreshold(2); DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156...")); setZeroMotionDetectionThreshold(156); DEBUG_PRINTLN(F("Setting motion detection duration to 80...")); setMotionDetectionDuration(80); DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0...")); setZeroMotionDetectionDuration(0); DEBUG_PRINTLN(F("Resetting FIFO...")); resetFIFO(); DEBUG_PRINTLN(F("Enabling FIFO...")); setFIFOEnabled(true); DEBUG_PRINTLN(F("Enabling DMP...")); setDMPEnabled(true); DEBUG_PRINTLN(F("Resetting DMP...")); resetDMP(); DEBUG_PRINTLN(F("Writing final memory update 3/7 (function unknown)...")); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); DEBUG_PRINTLN(F("Writing final memory update 4/7 (function unknown)...")); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); DEBUG_PRINTLN(F("Writing final memory update 5/7 (function unknown)...")); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); DEBUG_PRINTLN(F("Waiting for FIFO count > 2...")); while ((fifoCount = getFIFOCount()) < 3); DEBUG_PRINT(F("Current FIFO count=")); DEBUG_PRINTLN(fifoCount); DEBUG_PRINTLN(F("Reading FIFO data...")); getFIFOBytes(fifoBuffer, fifoCount); DEBUG_PRINTLN(F("Reading interrupt status...")); uint8_t mpuIntStatus = getIntStatus(); DEBUG_PRINT(F("Current interrupt status=")); DEBUG_PRINTLNF(mpuIntStatus, HEX); DEBUG_PRINTLN(F("Reading final memory update 6/7 (function unknown)...")); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); DEBUG_PRINTLN(F("Waiting for FIFO count > 2...")); while ((fifoCount = getFIFOCount()) < 3); DEBUG_PRINT(F("Current FIFO count=")); DEBUG_PRINTLN(fifoCount); DEBUG_PRINTLN(F("Reading FIFO data...")); getFIFOBytes(fifoBuffer, fifoCount); DEBUG_PRINTLN(F("Reading interrupt status...")); mpuIntStatus = getIntStatus(); DEBUG_PRINT(F("Current interrupt status=")); DEBUG_PRINTLNF(mpuIntStatus, HEX); DEBUG_PRINTLN(F("Writing final memory update 7/7 (function unknown)...")); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); DEBUG_PRINTLN(F("DMP is good to go! Finally.")); DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)...")); setDMPEnabled(false); DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer...")); dmpPacketSize = 42; /*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) { return 3; // TODO: proper error code for no memory }*/ DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time...")); resetFIFO(); getIntStatus(); } else { DEBUG_PRINTLN(F("ERROR! DMP configuration verification failed.")); return 2; // configuration block loading failed } } else { DEBUG_PRINTLN(F("ERROR! DMP code verification failed.")); return 1; // main binary block loading failed } return 0; // success } bool MPU6050::dmpPacketAvailable() { return getFIFOCount() >= dmpGetFIFOPacketSize(); } // uint8_t MPU6050::dmpSetFIFORate(uint8_t fifoRate); // uint8_t MPU6050::dmpGetFIFORate(); // uint8_t MPU6050::dmpGetSampleStepSizeMS(); // uint8_t MPU6050::dmpGetSampleFrequency(); // int32_t MPU6050::dmpDecodeTemperature(int8_t tempReg); //uint8_t MPU6050::dmpRegisterFIFORateProcess(inv_obj_func func, int16_t priority); //uint8_t MPU6050::dmpUnregisterFIFORateProcess(inv_obj_func func); //uint8_t MPU6050::dmpRunFIFORateProcesses(); // uint8_t MPU6050::dmpSendQuaternion(uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendGyro(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendLinearAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendLinearAccelInWorld(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendControlData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendSensorData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendExternalSensorData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendGravity(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendPacketNumber(uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendQuantizedAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendEIS(uint_fast16_t elements, uint_fast16_t accuracy); uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[28] << 24) + (packet[29] << 16) + (packet[30] << 8) + packet[31]); data[1] = ((packet[32] << 24) + (packet[33] << 16) + (packet[34] << 8) + packet[35]); data[2] = ((packet[36] << 24) + (packet[37] << 16) + (packet[38] << 8) + packet[39]); return 0; } uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = (packet[28] << 8) + packet[29]; data[1] = (packet[32] << 8) + packet[33]; data[2] = (packet[36] << 8) + packet[37]; return 0; } uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; v -> x = (packet[28] << 8) + packet[29]; v -> y = (packet[32] << 8) + packet[33]; v -> z = (packet[36] << 8) + packet[37]; return 0; } uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[0] << 24) + (packet[1] << 16) + (packet[2] << 8) + packet[3]); data[1] = ((packet[4] << 24) + (packet[5] << 16) + (packet[6] << 8) + packet[7]); data[2] = ((packet[8] << 24) + (packet[9] << 16) + (packet[10] << 8) + packet[11]); data[3] = ((packet[12] << 24) + (packet[13] << 16) + (packet[14] << 8) + packet[15]); return 0; } uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[0] << 8) + packet[1]); data[1] = ((packet[4] << 8) + packet[5]); data[2] = ((packet[8] << 8) + packet[9]); data[3] = ((packet[12] << 8) + packet[13]); return 0; } uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) int16_t qI[4]; uint8_t status = dmpGetQuaternion(qI, packet); if (status == 0) { q -> w = (float)qI[0] / 16384.0f; q -> x = (float)qI[1] / 16384.0f; q -> y = (float)qI[2] / 16384.0f; q -> z = (float)qI[3] / 16384.0f; return 0; } return status; // int16 return value, indicates error if this line is reached } // uint8_t MPU6050::dmpGet6AxisQuaternion(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetRelativeQuaternion(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[16] << 24) + (packet[17] << 16) + (packet[18] << 8) + packet[19]); data[1] = ((packet[20] << 24) + (packet[21] << 16) + (packet[22] << 8) + packet[23]); data[2] = ((packet[24] << 24) + (packet[25] << 16) + (packet[26] << 8) + packet[27]); return 0; } uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = (packet[16] << 8) + packet[17]; data[1] = (packet[20] << 8) + packet[21]; data[2] = (packet[24] << 8) + packet[25]; return 0; } uint8_t MPU6050::dmpGetGyro(VectorInt16 *v, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; v -> x = (packet[16] << 8) + packet[17]; v -> y = (packet[20] << 8) + packet[21]; v -> z = (packet[24] << 8) + packet[25]; return 0; } // uint8_t MPU6050::dmpSetLinearAccelFilterCoefficient(float coef); // uint8_t MPU6050::dmpGetLinearAccel(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) { // get rid of the gravity component (+1g = +8192 in standard DMP FIFO packet, sensitivity is 2g) v -> x = vRaw -> x - gravity -> x*8192; v -> y = vRaw -> y - gravity -> y*8192; v -> z = vRaw -> z - gravity -> z*8192; return 0; } // uint8_t MPU6050::dmpGetLinearAccelInWorld(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) { // rotate measured 3D acceleration vector into original state // frame of reference based on orientation quaternion memcpy(v, vReal, sizeof(VectorInt16)); v -> rotate(q); return 0; } // uint8_t MPU6050::dmpGetGyroAndAccelSensor(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetGyroSensor(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetControlData(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetTemperature(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetGravity(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) { v -> x = 2 * (q -> x*q -> z - q -> w*q -> y); v -> y = 2 * (q -> w*q -> x + q -> y*q -> z); v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z; return 0; } // uint8_t MPU6050::dmpGetUnquantizedAccel(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetQuantizedAccel(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetExternalSensorData(long *data, int size, const uint8_t* packet); // uint8_t MPU6050::dmpGetEIS(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) { data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // psi data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y); // theta data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1); // phi return 0; } uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) { // yaw: (about Z axis) data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // pitch: (nose up/down, about Y axis) data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z)); // roll: (tilt left/right, about X axis) data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z)); return 0; } // uint8_t MPU6050::dmpGetAccelFloat(float *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetQuaternionFloat(float *data, const uint8_t* packet); uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) { /*for (uint8_t k = 0; k < dmpPacketSize; k++) { if (dmpData[k] < 0x10) Serial.print("0"); Serial.print(dmpData[k], HEX); Serial.print(" "); } Serial.print("\n");*/ //Serial.println((uint16_t)dmpPacketBuffer); return 0; } uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) { uint8_t status; uint8_t buf[dmpPacketSize]; for (uint8_t i = 0; i < numPackets; i++) { // read packet from FIFO getFIFOBytes(buf, dmpPacketSize); // process packet if ((status = dmpProcessFIFOPacket(buf)) > 0) return status; // increment external process count variable, if supplied if (processed != 0) *processed++; } return 0; } // uint8_t MPU6050::dmpSetFIFOProcessedCallback(void (*func) (void)); // uint8_t MPU6050::dmpInitFIFOParam(); // uint8_t MPU6050::dmpCloseFIFO(); // uint8_t MPU6050::dmpSetGyroDataSource(uint_fast8_t source); // uint8_t MPU6050::dmpDecodeQuantizedAccel(); // uint32_t MPU6050::dmpGetGyroSumOfSquare(); // uint32_t MPU6050::dmpGetAccelSumOfSquare(); // void MPU6050::dmpOverrideQuaternion(long *q); uint16_t MPU6050::dmpGetFIFOPacketSize() { return dmpPacketSize; } #endif /* _MPU6050_6AXIS_MOTIONAPPS20_H_ */
41,027
C
53.704
114
0.617106
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/Release03/code/Python/camera100.py
import RPi.GPIO as GPIO import jetson.inference import jetson.utils import time import argparse import sys # parse the command line parser = argparse.ArgumentParser(description="Locate objects in a live camera stream using an object detection DNN.", formatter_class=argparse.RawTextHelpFormatter, epilog=jetson.inference.detectNet.Usage() + jetson.utils.videoSource.Usage() + jetson.utils.videoOutput.Usage() + jetson.utils.logUsage()) parser.add_argument("input_URI", type=str, default="", nargs='?', help="URI of the input stream") parser.add_argument("output_URI", type=str, default="", nargs='?', help="URI of the output stream") parser.add_argument("--network", type=str, default="ssd-mobilenet-v2", help="pre-trained model to load (see below for options)") parser.add_argument("--overlay", type=str, default="box,labels,conf", help="detection overlay flags (e.g. --overlay=box,labels,conf)\nvalid combinations are: 'box', 'labels', 'conf', 'none'") parser.add_argument("--threshold", type=float, default=0.5, help="minimum detection threshold to use") is_headless = ["--headless"] if sys.argv[0].find('console.py') != -1 else [""] try: opt = parser.parse_known_args()[0] except: print("") parser.print_help() sys.exit(0) # load the object detection network net = jetson.inference.detectNet(opt.network, sys.argv, opt.threshold) # create video sources & outputs input = jetson.utils.videoSource(opt.input_URI, argv=sys.argv) output = jetson.utils.videoOutput(opt.output_URI, argv=sys.argv+is_headless) #setup GPIO pins GPIO.setmode(GPIO.BCM) #RaspPi pin numbering GPIO.setup(18, GPIO.OUT, initial=GPIO.HIGH) GPIO.output(18, GPIO.HIGH) GPIO.setup(17, GPIO.OUT, initial=GPIO.HIGH) GPIO.output(17, GPIO.HIGH) GPIO.setup(16, GPIO.OUT, initial=GPIO.HIGH) GPIO.output(16, GPIO.HIGH) GPIO.setup(20, GPIO.OUT, initial=GPIO.HIGH) GPIO.output(20, GPIO.HIGH) GPIO.setup(21, GPIO.OUT, initial=GPIO.HIGH) GPIO.output(21, GPIO.HIGH) def back(): GPIO.output(18, GPIO.LOW) GPIO.output(17, GPIO.HIGH) GPIO.output(16, GPIO.HIGH) GPIO.output(20, GPIO.HIGH) GPIO.output(21, GPIO.HIGH) print("back") def forward(): GPIO.output(18, GPIO.HIGH) GPIO.output(17, GPIO.LOW) GPIO.output(16, GPIO.HIGH) GPIO.output(20, GPIO.HIGH) GPIO.output(21, GPIO.HIGH) print("forward") def left(): GPIO.output(18, GPIO.HIGH) GPIO.output(17, GPIO.HIGH) GPIO.output(16, GPIO.LOW) GPIO.output(20, GPIO.HIGH) GPIO.output(21, GPIO.HIGH) print("left") def right(): GPIO.output(18, GPIO.HIGH) GPIO.output(17, GPIO.HIGH) GPIO.output(16, GPIO.HIGH) GPIO.output(20, GPIO.LOW) GPIO.output(21, GPIO.HIGH) print("right") def up(): GPIO.output(18, GPIO.HIGH) GPIO.output(17, GPIO.HIGH) GPIO.output(16, GPIO.HIGH) GPIO.output(20, GPIO.HIGH) GPIO.output(21, GPIO.LOW) print("up") def nothing(): GPIO.output(18, GPIO.HIGH) GPIO.output(17, GPIO.HIGH) GPIO.output(16, GPIO.HIGH) GPIO.output(20, GPIO.HIGH) GPIO.output(21, GPIO.HIGH) print("nothing") # declare variables as global and that global index global width global location global confidence index = 0 width = 0 location = 0 condifence = 0; # process frames until the user exits while True: # capture the next image img = input.Capture() # detect objects in the image (with overlay) detections = net.Detect(img, overlay=opt.overlay) # print the detections #print("detected {:d} objects in image".format(len(detections))) # check for detections, otherwise nothing if(len(detections) > 0): print("object detected") for detection in detections: index = detections[0].ClassID confidence = (detections[0].Confidence) width = (detections[0].Width) location = (detections[0].Center[0]) # print index of item, width and horizonal location print(index) print(width) print(location) print(confidence) # look for detections if (index == 1 and confidence > 0.9): back() elif (index == 2 and confidence > 0.7): forward() elif (index == 3 and confidence > 0.7): left() elif (index == 4 and confidence > 0.7): right() elif (index == 5 and confidence > 0.7): up() else: nothing() # nothing is detected # render the image output.Render(img) # update the title bar output.SetStatus("{:s} | Network {:.0f} FPS".format(opt.network, net.GetNetworkFPS())) # print out performance info #net.PrintProfilerTimes() # exit on input/output EOS if not input.IsStreaming() or not output.IsStreaming(): break
4,525
Python
24.570621
192
0.698122
renanmb/Omniverse_legged_robotics/URDF-Descriptions/cassie_description-UMich-BipedLab/README.md
# cassie_description This repository contains the .urdf model of the CASSIE robot from Agility Robotics. It also includes a a way to visualize the robot using ROS and rviz. Installation to view .urdf using rviz ===================================== - Download and install ROS by following the instructions at http://wiki.ros.org/indigo/Installation/Ubuntu. - Create a folder for the catkin workspace ``` mkdir ~/catkin_ws cd ~/catkin_ws mkdir src cd src catkin_init_workspace ``` - Clone the repository to get the cassie_description package ``` git clone https://github.com/UMich-BipedLab/cassie_description.git ``` - Build the package ``` cd ../ catkin_make source devel/setup.bash ``` - Launch rviz to visualize the .urdf file ``` roslaunch cassie_description display.launch ```
790
Markdown
22.264705
107
0.720253
renanmb/Omniverse_legged_robotics/URDF-Descriptions/cassie_description-UMich-BipedLab/config/dependent_joints.yaml
dependent_joints: knee_to_shin_left: {parent: knee_joint_left, factor: -1 } ankle_joint_left: {parent: knee_joint_left, factor: 0 } knee_to_shin_right: {parent: knee_joint_right, factor: 0 } ankle_joint_right: {parent: knee_joint_right, factor: -1 } zeros: knee_to_shin_left: 0 ankle_joint_left: 0.226893 knee_to_shin_right: 0 ankle_joint_right: 0.226893
374
YAML
30.249997
60
0.68984
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/calibrate_servos.py
from pupper.HardwareInterface import HardwareInterface from pupper.Config import PWMParams, ServoParams import numpy as np import re def get_motor_name(i, j): motor_type = {0: "abduction", 1: "inner", 2: "outer"} # Top # Bottom leg_pos = {0: "front-right", 1: "front-left", 2: "back-right", 3: "back-left"} final_name = motor_type[i] + " " + leg_pos[j] return final_name def get_motor_setpoint(i, j): data = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [45, 45, 45, 45]]) return data[i, j] def degrees_to_radians(input_array): """Converts degrees to radians. Parameters ---------- input_array : Numpy array or float Degrees Returns ------- Numpy array or float Radians """ return input_array * np.pi / 180.0 def radians_to_degrees(input_array): """Converts degrees to radians. Parameters ---------- input_array : Numpy array or float Radians Returns ------- Numpy array or float Degrees """ return input_array * 180.0 / np.pi def step_until(hardware_interface, axis, leg, set_point): """Returns the angle offset needed to correct a given link by asking the user for input. Returns ------- Float Angle offset needed to correct the link. """ found_position = False set_names = ["horizontal", "horizontal", "vertical"] offset = 0 while not found_position: move_input = str( input("Enter 'a' or 'b' to move the link until it is **" + set_names[axis] + "**. Enter 'd' when done. Input: " ) ) if move_input == "a": offset += 1.0 hardware_interface.set_actuator_position( degrees_to_radians(set_point + offset), axis, leg, ) elif move_input == "b": offset -= 1.0 hardware_interface.set_actuator_position( degrees_to_radians(set_point + offset), axis, leg, ) elif move_input == "d": found_position = True print("Offset: ", offset) return offset def calibrate_angle_offset(hardware_interface): """Calibrate the angle offset for the twelve motors on the robot. Note that servo_params is modified in-place. Parameters ---------- servo_params : ServoParams Servo parameters. This variable is updated in-place. pi_board : Pi RaspberryPi object. pwm_params : PWMParams PWMParams object. """ # Found K value of (11.4) print("The scaling constant for your servo represents how much you have to increase\nthe pwm pulse width (in microseconds) to rotate the servo output 1 degree.") print("This value is currently set to: {:.3f}".format(degrees_to_radians(hardware_interface.servo_params.micros_per_rad))) print("For newer CLS6336 and CLS6327 servos the value should be 11.333.") ks = input("Press <Enter> to keep the current value, or enter a new value: ") if ks != '': k = float(ks) hardware_interface.servo_params.micros_per_rad = k * 180 / np.pi hardware_interface.servo_params.neutral_angle_degrees = np.zeros((3, 4)) for leg_index in range(4): for axis in range(3): # Loop until we're satisfied with the calibration completed = False while not completed: motor_name = get_motor_name(axis, leg_index) print("\n\nCalibrating the **" + motor_name + " motor **") set_point = get_motor_setpoint(axis, leg_index) # Zero out the neutral angle hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = 0 # Move servo to set_point angle hardware_interface.set_actuator_position( degrees_to_radians(set_point), axis, leg_index, ) # Adjust the angle using keyboard input until it matches the reference angle offset = step_until( hardware_interface, axis, leg_index, set_point ) print("Final offset: ", offset) # The upper leg link has a different equation because we're calibrating to make it horizontal, not vertical if axis == 1: hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = set_point - offset else: hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = -(set_point + offset) print("Calibrated neutral angle: ", hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index]) # Send the servo command using the new beta value and check that it's ok hardware_interface.set_actuator_position( degrees_to_radians([0, 45, -45][axis]), axis, leg_index, ) okay = "" prompt = "The leg should be at exactly **" + ["horizontal", "45 degrees", "45 degrees"][axis] + "**. Are you satisfied? Enter 'yes' or 'no': " while okay not in ["y", "n", "yes", "no"]: okay = str( input(prompt) ) completed = okay == "y" or okay == "yes" def overwrite_ServoCalibration_file(servo_params): preamble = """# WARNING: This file is machine generated. Edit at your own risk. import numpy as np """ # Format array object string for np.array p1 = re.compile("([0-9]\.) ( *)") # pattern to replace the space that follows each number with a comma partially_formatted_matrix = p1.sub(r"\1,\2", str(servo_params.neutral_angle_degrees)) p2 = re.compile("(\]\n)") # pattern to add a comma at the end of the first two lines formatted_matrix_with_required_commas = p2.sub("],\n", partially_formatted_matrix) # Overwrite pupper/ServoCalibration.py file with modified values with open("pupper/ServoCalibration.py", "w") as f: print(preamble, file = f) print("MICROS_PER_RAD = {:.3f} * 180.0 / np.pi".format(degrees_to_radians(servo_params.micros_per_rad)), file = f) print("NEUTRAL_ANGLE_DEGREES = np.array(", file = f) print(formatted_matrix_with_required_commas, file = f) print(")", file = f) def main(): """Main program """ hardware_interface = HardwareInterface() calibrate_angle_offset(hardware_interface) overwrite_ServoCalibration_file(hardware_interface.servo_params) print("\n\n CALIBRATION COMPLETE!\n") print("Calibrated neutral angles:") print(hardware_interface.servo_params.neutral_angle_degrees) main()
6,862
Python
34.376288
165
0.581609
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/run_robot.py
import numpy as np import time from src.IMU import IMU from src.Controller import Controller from src.JoystickInterface import JoystickInterface from src.State import State from pupper.HardwareInterface import HardwareInterface from pupper.Config import Configuration from pupper.Kinematics import four_legs_inverse_kinematics def main(use_imu=False): """Main program """ # Create config config = Configuration() hardware_interface = HardwareInterface() # Create imu handle if use_imu: imu = IMU(port="/dev/ttyACM0") imu.flush_buffer() # Create controller and user input handles controller = Controller( config, four_legs_inverse_kinematics, ) state = State() print("Creating joystick listener...") joystick_interface = JoystickInterface(config) print("Done.") last_loop = time.time() print("Summary of gait parameters:") print("overlap time: ", config.overlap_time) print("swing time: ", config.swing_time) print("z clearance: ", config.z_clearance) print("x shift: ", config.x_shift) # Wait until the activate button has been pressed while True: print("Waiting for L1 to activate robot.") while True: command = joystick_interface.get_command(state) joystick_interface.set_color(config.ps4_deactivated_color) if command.activate_event == 1: break time.sleep(0.1) print("Robot activated.") joystick_interface.set_color(config.ps4_color) while True: now = time.time() if now - last_loop < config.dt: continue last_loop = time.time() # Parse the udp joystick commands and then update the robot controller's parameters command = joystick_interface.get_command(state) if command.activate_event == 1: print("Deactivating Robot") break # Read imu data. Orientation will be None if no data was available quat_orientation = ( imu.read_orientation() if use_imu else np.array([1, 0, 0, 0]) ) state.quat_orientation = quat_orientation # Step the controller forward by dt controller.run(state, command) # Update the pwm widths going to the servos hardware_interface.set_actuator_postions(state.joint_angles) main()
2,473
Python
29.925
95
0.627982
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Gaits.py
class GaitController: def __init__(self, config): self.config = config def phase_index(self, ticks): """Calculates which part of the gait cycle the robot should be in given the time in ticks. Parameters ---------- ticks : int Number of timesteps since the program started gaitparams : GaitParams GaitParams object Returns ------- Int The index of the gait phase that the robot should be in. """ phase_time = ticks % self.config.phase_length phase_sum = 0 for i in range(self.config.num_phases): phase_sum += self.config.phase_ticks[i] if phase_time < phase_sum: return i assert False def subphase_ticks(self, ticks): """Calculates the number of ticks (timesteps) since the start of the current phase. Parameters ---------- ticks : Int Number of timesteps since the program started gaitparams : GaitParams GaitParams object Returns ------- Int Number of ticks since the start of the current phase. """ phase_time = ticks % self.config.phase_length phase_sum = 0 subphase_ticks = 0 for i in range(self.config.num_phases): phase_sum += self.config.phase_ticks[i] if phase_time < phase_sum: subphase_ticks = phase_time - phase_sum + self.config.phase_ticks[i] return subphase_ticks assert False def contacts(self, ticks): """Calculates which feet should be in contact at the given number of ticks Parameters ---------- ticks : Int Number of timesteps since the program started. gaitparams : GaitParams GaitParams object Returns ------- numpy array (4,) Numpy vector with 0 indicating flight and 1 indicating stance. """ return self.config.contact_phases[:, self.phase_index(ticks)]
2,154
Python
28.930555
98
0.545032
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Command.py
import numpy as np class Command: """Stores movement command """ def __init__(self): self.horizontal_velocity = np.array([0, 0]) self.yaw_rate = 0.0 self.height = -0.16 self.pitch = 0.0 self.roll = 0.0 self.activation = 0 self.hop_event = False self.trot_event = False self.activate_event = False
392
Python
20.833332
51
0.533163
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/SwingLegController.py
import numpy as np from transforms3d.euler import euler2mat class SwingController: def __init__(self, config): self.config = config def raibert_touchdown_location( self, leg_index, command ): delta_p_2d = ( self.config.alpha * self.config.stance_ticks * self.config.dt * command.horizontal_velocity ) delta_p = np.array([delta_p_2d[0], delta_p_2d[1], 0]) theta = ( self.config.beta * self.config.stance_ticks * self.config.dt * command.yaw_rate ) R = euler2mat(0, 0, theta) return R @ self.config.default_stance[:, leg_index] + delta_p def swing_height(self, swing_phase, triangular=True): if triangular: if swing_phase < 0.5: swing_height_ = swing_phase / 0.5 * self.config.z_clearance else: swing_height_ = self.config.z_clearance * (1 - (swing_phase - 0.5) / 0.5) return swing_height_ def next_foot_location( self, swing_prop, leg_index, state, command, ): assert swing_prop >= 0 and swing_prop <= 1 foot_location = state.foot_locations[:, leg_index] swing_height_ = self.swing_height(swing_prop) touchdown_location = self.raibert_touchdown_location(leg_index, command) time_left = self.config.dt * self.config.swing_ticks * (1.0 - swing_prop) v = (touchdown_location - foot_location) / time_left * np.array([1, 1, 0]) delta_foot_location = v * self.config.dt z_vector = np.array([0, 0, swing_height_ + command.height]) return foot_location * np.array([1, 1, 0]) + z_vector + delta_foot_location
1,781
Python
32.622641
89
0.563167
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/State.py
import numpy as np from enum import Enum class State: def __init__(self): self.horizontal_velocity = np.array([0.0, 0.0]) self.yaw_rate = 0.0 self.height = -0.16 self.pitch = 0.0 self.roll = 0.0 self.activation = 0 self.behavior_state = BehaviorState.REST self.ticks = 0 self.foot_locations = np.zeros((3, 4)) self.joint_angles = np.zeros((3, 4)) self.behavior_state = BehaviorState.REST class BehaviorState(Enum): DEACTIVATED = -1 REST = 0 TROT = 1 HOP = 2 FINISHHOP = 3
589
Python
20.851851
55
0.568761
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/StanceController.py
import numpy as np from transforms3d.euler import euler2mat class StanceController: def __init__(self, config): self.config = config def position_delta(self, leg_index, state, command): """Calculate the difference between the next desired body location and the current body location Parameters ---------- z_measured : float Z coordinate of the feet relative to the body. stance_params : StanceParams Stance parameters object. movement_reference : MovementReference Movement reference object. gait_params : GaitParams Gait parameters object. Returns ------- (Numpy array (3), Numpy array (3, 3)) (Position increment, rotation matrix increment) """ z = state.foot_locations[2, leg_index] v_xy = np.array( [ -command.horizontal_velocity[0], -command.horizontal_velocity[1], 1.0 / self.config.z_time_constant * (state.height - z), ] ) delta_p = v_xy * self.config.dt delta_R = euler2mat(0, 0, -command.yaw_rate * self.config.dt) return (delta_p, delta_R) # TODO: put current foot location into state def next_foot_location(self, leg_index, state, command): foot_location = state.foot_locations[:, leg_index] (delta_p, delta_R) = self.position_delta(leg_index, state, command) incremented_location = delta_R @ foot_location + delta_p return incremented_location
1,628
Python
32.244897
104
0.57801
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/IMU.py
import serial import numpy as np import time class IMU: def __init__(self, port, baudrate=500000): self.serial_handle = serial.Serial( port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0, ) self.last_quat = np.array([1, 0, 0, 0]) self.start_time = time.time() def flush_buffer(self): self.serial_handle.reset_input_buffer() def read_orientation(self): """Reads quaternion measurements from the Teensy until none are left. Returns the last read quaternion. Parameters ---------- serial_handle : Serial object Handle to the pyserial Serial object Returns ------- np array (4,) If there was quaternion data to read on the serial port returns the quaternion as a numpy array, otherwise returns the last read quaternion. """ while True: x = self.serial_handle.readline().decode("utf").strip() if x is "" or x is None: return self.last_quat else: parsed = x.split(",") if len(parsed) == 4: self.last_quat = np.array(parsed, dtype=np.float64) else: print("Did not receive 4-vector from imu")
1,440
Python
30.326086
152
0.543056
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Tests.py
# using LinearAlgebra # using Profile # using StaticArrays # using Plots # using BenchmarkTools # include("Kinematics.jl") # include("PupperConfig.jl") # include("Gait.jl") # include("StanceController.jl") # include("SwingLegController.jl") # include("Types.jl") # include("Controller.jl") import numpy as np import matplotlib.pyplot as plt from Kinematics import leg_explicit_inverse_kinematics from PupperConfig import * from Gaits import * from StanceController import position_delta, stance_foot_location from SwingLegController import * from Types import MovementReference, GaitParams, StanceParams, SwingParams from Controller import * # function round_(a, dec) # return map(x -> round(x, digits=dec), a) # end # function testInverseKinematicsExplicit!() # println("\n-------------- Testing Inverse Kinematics -----------") # config = PupperConfig() # println("\nTesting Inverse Kinematics") # function testHelper(r, alpha_true, i; do_assert=true) # eps = 1e-6 # @time α = leg_explicitinversekinematics_prismatic(r, i, config) # println("Leg ", i, ": r: ", r, " -> α: ", α) # if do_assert # @assert norm(α - alpha_true) < eps # end # end # c = config.LEG_L/sqrt(2) # offset = config.ABDUCTION_OFFSET # testHelper(SVector(0, offset, -0.125), SVector(0, 0, 0), 2) # testHelper(SVector(c, offset, -c), SVector(0, -pi/4, 0), 2) # testHelper(SVector(-c, offset, -c), SVector(0, pi/4, 0), 2) # testHelper(SVector(0, c, -c), missing, 2, do_assert=false) # testHelper(SVector(-c, -offset, -c), [0, pi/4, 0], 1) # testHelper(SVector(config.LEG_L * sqrt(3)/2, offset, -config.LEG_L / 2), SVector(0, -pi/3, 0), 2) # end def test_inverse_kinematics_linkage(): print("\n-------------- Testing Five-bar Linkage Inverse Kinematics -----------") config = PupperConfig() print("\nTesting Inverse Kinematics") def testHelper(r, alpha_true, i, do_assert=True): eps = 1e-6 alpha = leg_explicit_inverse_kinematics(r, i, config) print("Leg ", i, ": r: ", r, " -> α: ", alpha) if do_assert: assert np.linalg.norm(alpha - alpha_true) < eps c = config.LEG_L / (2 ** 0.5) offset = config.ABDUCTION_OFFSET testHelper(np.array([0, offset, -0.125]), None, 1, do_assert=False) testHelper(np.array([c, offset, -c]), None, 1, do_assert=False) testHelper(np.array([-c, offset, -c]), None, 1, do_assert=False) testHelper(np.array([0, c, -c]), None, 1, do_assert=False) testHelper(np.array([-c, -offset, -c]), None, 0, do_assert=False) testHelper( np.array([config.LEG_L * (3 ** 0.5) / 2, offset, -config.LEG_L / 2]), None, 1, do_assert=False, ) # function testForwardKinematics!() # println("\n-------------- Testing Forward Kinematics -----------") # config = PupperConfig() # println("\nTesting Forward Kinematics") # function testHelper(alpha, r_true, i; do_assert=true) # eps = 1e-6 # r = zeros(3) # println("Vectors") # a = [alpha.data...] # @time legForwardKinematics!(r, a, i, config) # println("SVectors") # @time r = legForwardKinematics(alpha, i, config) # println("Leg ", i, ": α: ", alpha, " -> r: ", r) # if do_assert # @assert norm(r_true - r) < eps # end # end # l = config.LEG_L # offset = config.ABDUCTION_OFFSET # testHelper(SVector{3}([0.0, 0.0, 0.0]), SVector{3}([0, offset, -l]), 2) # testHelper(SVector{3}([0.0, pi/4, 0.0]), missing, 2, do_assert=false) # # testHelper([0.0, 0.0, 0.0], [0, offset, -l], 2) # # testHelper([0.0, pi/4, 0.0], missing, 2, do_assert=false) # end # function testForwardInverseAgreeance() # println("\n-------------- Testing Forward/Inverse Consistency -----------") # config = PupperConfig() # println("\nTest forward/inverse consistency") # eps = 1e-6 # for i in 1:10 # alpha = SVector(rand()-0.5, rand()-0.5, (rand()-0.5)*0.05) # leg = rand(1:4) # @time r = legForwardKinematics(alpha, leg, config) # # @code_warntype legForwardKinematics!(r, alpha, leg, config) # @time alpha_prime = leg_explicitinversekinematics_prismatic(r, leg, config) # # @code_warntype inverseKinematicsExplicit!(alpha_prime, r, leg, config) # println("Leg ", leg, ": α: ", round_(alpha, 3), " -> r_body_foot: ", round_(r, 3), " -> α': ", round_(alpha_prime, 3)) # @assert norm(alpha_prime - alpha) < eps # end # end # function testAllInverseKinematics() # println("\n-------------- Testing Four Leg Inverse Kinematics -----------") # function helper(r_body, alpha_true; do_assert=true) # println("Timing for fourlegs_inversekinematics") # config = PupperConfig() # @time alpha = fourlegs_inversekinematics(SMatrix(r_body), config) # @code_warntype fourlegs_inversekinematics(SMatrix(r_body), config) # println("r: ", r_body, " -> α: ", alpha) # if do_assert # @assert norm(alpha - alpha_true) < 1e-10 # end # end # config = PupperConfig() # f = config.LEG_FB # l = config.LEG_LR # s = -0.125 # o = config.ABDUCTION_OFFSET # r_body = MMatrix{3,4}(zeros(3,4)) # r_body[:,1] = [f, -l-o, s] # r_body[:,2] = [f, l+o, s] # r_body[:,3] = [-f, -l-o, s] # r_body[:,4] = [-f, l+o, s] # helper(r_body, zeros(3,4)) # helper(SMatrix{3,4}(zeros(3,4)), missing, do_assert=false) # end # function testKinematics() # testInverseKinematicsExplicit!() # testForwardKinematics!() # testForwardInverseAgreeance() # testAllInverseKinematics() # end # function testGait() # println("\n-------------- Testing Gait -----------") # p = GaitParams() # # println("Gait params=",p) # t = 680 # println("Timing for phaseindex") # @time ph = phaseindex(t, p) # # @code_warntype phaseindex(t, p) # println("t=",t," phase=",ph) # @assert ph == 4 # @assert phaseindex(0, p) == 1 # println("Timing for contacts") # @time c = contacts(t, p) # # @code_warntype contacts(t, p) # @assert typeof(c) == SArray{Tuple{4},Int64,1,4} # println("t=", t, " contacts=", c) # end def test_stance_controller(): print("\n-------------- Testing Stance Controller -----------") stanceparams = StanceParams() gaitparams = GaitParams() zmeas = -0.20 mvref = MovementReference() dp, dR = position_delta(zmeas, stanceparams, mvref, gaitparams) assert np.linalg.norm(dR - np.eye(3)) < 1e-10 assert np.linalg.norm(dp - np.array([0, 0, gaitparams.dt * 0.04])) < 1e-10 zmeas = -0.18 mvref = MovementReference() mvref.v_xy_ref = np.array([1.0, 0.0]) mvref.z_ref = -0.18 dp, dR = position_delta(zmeas, stanceparams, mvref, gaitparams) zmeas = -0.20 mvref = MovementReference() mvref.wz_ref = 1.0 mvref.z_ref = -0.20 dp, dR = position_delta(zmeas, stanceparams, mvref, gaitparams) assert np.linalg.norm(dp - np.array([0, 0, 0])) < 1e-10 assert np.linalg.norm(dR[0, 1] - (gaitparams.dt)) < 1e-6 stancefootloc = np.zeros(3) sloc = stance_foot_location(stancefootloc, stanceparams, gaitparams, mvref) # function typeswinglegcontroller() # println("\n--------------- Code warn type for raibert_tdlocation[s] ----------") # swp = SwingParams() # stp = StanceParams() # gp = GaitParams() # mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18) # raibert_tdlocations(swp, stp, gp, mvref) # mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18) # raibert_tdlocation(1, swp, stp, gp, mvref) # end # function TestSwingLegController() # println("\n-------------- Testing Swing Leg Controller -----------") # swp = SwingParams() # stp = StanceParams() # gp = GaitParams() # p = ControllerParams() # println("Timing for swingheight:") # @time z = swingheight(0.5, swp) # println("z clearance at t=1/2swingtime =>",z) # @assert abs(z - swp.zclearance) < 1e-10 # println("Timing for swingheight:") # @time z = swingheight(0, swp) # println("Z clearance at t=0 =>",z) # @assert abs(z) < 1e-10 # mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18) # println("Timing for raibert tdlocation*s*:") # @time l = raibert_tdlocations(swp, stp, gp, mvref) # target = stp.defaultstance .+ [gp.stanceticks*gp.dt*0.5*1, 0, 0] # println("Touchdown locations =>", l, " <?=> ", target) # @assert norm(l - target) <= 1e-10 # mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18) # println("Timing for raibert tdlocation:") # @time l = raibert_tdlocation(1, swp, stp, gp, mvref) # fcurrent = SMatrix{3, 4, Float64}(stp.defaultstance) # mvref = MovementReference() # tswing = 0.125 # println("Timing for swingfootlocation*s* increment") # @time l = swingfootlocations(tswing, fcurrent, swp, stp, gp, mvref) # println(l) # fcurrent = SVector{3, Float64}(0.0, 0.0, 0.0) # println("Timing for swingfootlocation") # @time swingfootlocation(tswing, fcurrent, 1, swp, stp, gp, mvref) # typeswinglegcontroller() # return nothing # end def test_run(): print("Run timing") foot_loc_history, joint_angle_history = run() plt.subplot(211) x = plt.plot(foot_loc_history[0, :, :].T, label="x") y = plt.plot(foot_loc_history[1, :, :].T, label="y") z = plt.plot(foot_loc_history[2, :, :].T, label="z") plt.subplot(212) alpha = plt.plot(joint_angle_history[0, :, :].T, label="alpha") beta = plt.plot(joint_angle_history[1, :, :].T, label="beta") gamma = plt.plot(joint_angle_history[2, :, :].T, label="gamma") plt.show() # plot(x, β, y, α, z, γ, layout=(3,2), legend=false)) # function teststep() # swingparams = SwingParams() # stanceparams = StanceParams() # gaitparams = GaitParams() # mvref = MovementReference(vxyref=SVector{2}(0.2, 0.0), wzref=0.0) # conparams = ControllerParams() # robotconfig = PupperConfig() # footlocations::SMatrix{3, 4, Float64, 12} = stanceparams.defaultstance .+ SVector{3, Float64}(0, 0, mvref.zref) # ticks = 1 # println("Timing for step!") # @btime step($ticks, $footlocations, $swingparams, $stanceparams, $gaitparams, $mvref, $conparams) # @code_warntype step(ticks, footlocations, swingparams, stanceparams, gaitparams, mvref, conparams) # end # # testGait() # # testKinematics() # # TestStanceController() # # testStaticArrays() # # TestSwingLegController() # test_inversekinematics_linkage() # # teststep() # # testrun() test_inverse_kinematics_linkage() test_stance_controller() test_run()
10,778
Python
33.548077
128
0.59705
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/JoystickInterface.py
import UDPComms import numpy as np import time from src.State import BehaviorState, State from src.Command import Command from src.Utilities import deadband, clipped_first_order_filter class JoystickInterface: def __init__( self, config, udp_port=8830, udp_publisher_port = 8840, ): self.config = config self.previous_gait_toggle = 0 self.previous_state = BehaviorState.REST self.previous_hop_toggle = 0 self.previous_activate_toggle = 0 self.message_rate = 50 self.udp_handle = UDPComms.Subscriber(udp_port, timeout=0.3) self.udp_publisher = UDPComms.Publisher(udp_publisher_port) def get_command(self, state, do_print=False): try: msg = self.udp_handle.get() command = Command() ####### Handle discrete commands ######## # Check if requesting a state transition to trotting, or from trotting to resting gait_toggle = msg["R1"] command.trot_event = (gait_toggle == 1 and self.previous_gait_toggle == 0) # Check if requesting a state transition to hopping, from trotting or resting hop_toggle = msg["x"] command.hop_event = (hop_toggle == 1 and self.previous_hop_toggle == 0) activate_toggle = msg["L1"] command.activate_event = (activate_toggle == 1 and self.previous_activate_toggle == 0) # Update previous values for toggles and state self.previous_gait_toggle = gait_toggle self.previous_hop_toggle = hop_toggle self.previous_activate_toggle = activate_toggle ####### Handle continuous commands ######## x_vel = msg["ly"] * self.config.max_x_velocity y_vel = msg["lx"] * -self.config.max_y_velocity command.horizontal_velocity = np.array([x_vel, y_vel]) command.yaw_rate = msg["rx"] * -self.config.max_yaw_rate message_rate = msg["message_rate"] message_dt = 1.0 / message_rate pitch = msg["ry"] * self.config.max_pitch deadbanded_pitch = deadband( pitch, self.config.pitch_deadband ) pitch_rate = clipped_first_order_filter( state.pitch, deadbanded_pitch, self.config.max_pitch_rate, self.config.pitch_time_constant, ) command.pitch = state.pitch + message_dt * pitch_rate height_movement = msg["dpady"] command.height = state.height - message_dt * self.config.z_speed * height_movement roll_movement = - msg["dpadx"] command.roll = state.roll + message_dt * self.config.roll_speed * roll_movement return command except UDPComms.timeout: if do_print: print("UDP Timed out") return Command() def set_color(self, color): joystick_msg = {"ps4_color": color} self.udp_publisher.send(joystick_msg)
3,099
Python
36.349397
98
0.575992
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Utilities.py
import numpy as np def deadband(value, band_radius): return max(value - band_radius, 0) + min(value + band_radius, 0) def clipped_first_order_filter(input, target, max_rate, tau): rate = (target - input) / tau return np.clip(rate, -max_rate, max_rate)
268
Python
23.454543
68
0.671642
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Controller.py
from src.Gaits import GaitController from src.StanceController import StanceController from src.SwingLegController import SwingController from src.Utilities import clipped_first_order_filter from src.State import BehaviorState, State import numpy as np from transforms3d.euler import euler2mat, quat2euler from transforms3d.quaternions import qconjugate, quat2axangle from transforms3d.axangles import axangle2mat class Controller: """Controller and planner object """ def __init__( self, config, inverse_kinematics, ): self.config = config self.smoothed_yaw = 0.0 # for REST mode only self.inverse_kinematics = inverse_kinematics self.contact_modes = np.zeros(4) self.gait_controller = GaitController(self.config) self.swing_controller = SwingController(self.config) self.stance_controller = StanceController(self.config) self.hop_transition_mapping = {BehaviorState.REST: BehaviorState.HOP, BehaviorState.HOP: BehaviorState.FINISHHOP, BehaviorState.FINISHHOP: BehaviorState.REST, BehaviorState.TROT: BehaviorState.HOP} self.trot_transition_mapping = {BehaviorState.REST: BehaviorState.TROT, BehaviorState.TROT: BehaviorState.REST, BehaviorState.HOP: BehaviorState.TROT, BehaviorState.FINISHHOP: BehaviorState.TROT} self.activate_transition_mapping = {BehaviorState.DEACTIVATED: BehaviorState.REST, BehaviorState.REST: BehaviorState.DEACTIVATED} def step_gait(self, state, command): """Calculate the desired foot locations for the next timestep Returns ------- Numpy array (3, 4) Matrix of new foot locations. """ contact_modes = self.gait_controller.contacts(state.ticks) new_foot_locations = np.zeros((3, 4)) for leg_index in range(4): contact_mode = contact_modes[leg_index] foot_location = state.foot_locations[:, leg_index] if contact_mode == 1: new_location = self.stance_controller.next_foot_location(leg_index, state, command) else: swing_proportion = ( self.gait_controller.subphase_ticks(state.ticks) / self.config.swing_ticks ) new_location = self.swing_controller.next_foot_location( swing_proportion, leg_index, state, command ) new_foot_locations[:, leg_index] = new_location return new_foot_locations, contact_modes def run(self, state, command): """Steps the controller forward one timestep Parameters ---------- controller : Controller Robot controller object. """ ########## Update operating state based on command ###### if command.activate_event: state.behavior_state = self.activate_transition_mapping[state.behavior_state] elif command.trot_event: state.behavior_state = self.trot_transition_mapping[state.behavior_state] elif command.hop_event: state.behavior_state = self.hop_transition_mapping[state.behavior_state] if state.behavior_state == BehaviorState.TROT: state.foot_locations, contact_modes = self.step_gait( state, command, ) # Apply the desired body rotation rotated_foot_locations = ( euler2mat( command.roll, command.pitch, 0.0 ) @ state.foot_locations ) # Construct foot rotation matrix to compensate for body tilt (roll, pitch, yaw) = quat2euler(state.quat_orientation) correction_factor = 0.8 max_tilt = 0.4 roll_compensation = correction_factor * np.clip(roll, -max_tilt, max_tilt) pitch_compensation = correction_factor * np.clip(pitch, -max_tilt, max_tilt) rmat = euler2mat(roll_compensation, pitch_compensation, 0) rotated_foot_locations = rmat.T @ rotated_foot_locations state.joint_angles = self.inverse_kinematics( rotated_foot_locations, self.config ) elif state.behavior_state == BehaviorState.HOP: state.foot_locations = ( self.config.default_stance + np.array([0, 0, -0.09])[:, np.newaxis] ) state.joint_angles = self.inverse_kinematics( state.foot_locations, self.config ) elif state.behavior_state == BehaviorState.FINISHHOP: state.foot_locations = ( self.config.default_stance + np.array([0, 0, -0.22])[:, np.newaxis] ) state.joint_angles = self.inverse_kinematics( state.foot_locations, self.config ) elif state.behavior_state == BehaviorState.REST: yaw_proportion = command.yaw_rate / self.config.max_yaw_rate self.smoothed_yaw += ( self.config.dt * clipped_first_order_filter( self.smoothed_yaw, yaw_proportion * -self.config.max_stance_yaw, self.config.max_stance_yaw_rate, self.config.yaw_time_constant, ) ) # Set the foot locations to the default stance plus the standard height state.foot_locations = ( self.config.default_stance + np.array([0, 0, command.height])[:, np.newaxis] ) # Apply the desired body rotation rotated_foot_locations = ( euler2mat( command.roll, command.pitch, self.smoothed_yaw, ) @ state.foot_locations ) state.joint_angles = self.inverse_kinematics( rotated_foot_locations, self.config ) state.ticks += 1 state.pitch = command.pitch state.roll = command.roll state.height = command.height def set_pose_to_default(self): state.foot_locations = ( self.config.default_stance + np.array([0, 0, self.config.default_z_ref])[:, np.newaxis] ) state.joint_angles = controller.inverse_kinematics( state.foot_locations, self.config )
6,547
Python
37.292397
205
0.583168
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/ServoCalibration.py
# WARNING: This file is machine generated. Edit at your own risk. import numpy as np MICROS_PER_RAD = 11.333 * 180.0 / np.pi NEUTRAL_ANGLE_DEGREES = np.array( [[ 0., 0., 0., 0.], [ 45., 45., 45., 45.], [-45.,-45.,-45.,-45.]] )
236
Python
18.749998
65
0.576271
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/HardwareInterface.py
import pigpio from pupper.Config import ServoParams, PWMParams class HardwareInterface: def __init__(self): self.pi = pigpio.pi() self.pwm_params = PWMParams() self.servo_params = ServoParams() initialize_pwm(self.pi, self.pwm_params) def set_actuator_postions(self, joint_angles): send_servo_commands(self.pi, self.pwm_params, self.servo_params, joint_angles) def set_actuator_position(self, joint_angle, axis, leg): send_servo_command(self.pi, self.pwm_params, self.servo_params, joint_angle, axis, leg) def pwm_to_duty_cycle(pulsewidth_micros, pwm_params): """Converts a pwm signal (measured in microseconds) to a corresponding duty cycle on the gpio pwm pin Parameters ---------- pulsewidth_micros : float Width of the pwm signal in microseconds pwm_params : PWMParams PWMParams object Returns ------- float PWM duty cycle corresponding to the pulse width """ return int(pulsewidth_micros / 1e6 * pwm_params.freq * pwm_params.range) def angle_to_pwm(angle, servo_params, axis_index, leg_index): """Converts a desired servo angle into the corresponding PWM command Parameters ---------- angle : float Desired servo angle, relative to the vertical (z) axis servo_params : ServoParams ServoParams object axis_index : int Specifies which joint of leg to control. 0 is abduction servo, 1 is inner hip servo, 2 is outer hip servo. leg_index : int Specifies which leg to control. 0 is front-right, 1 is front-left, 2 is back-right, 3 is back-left. Returns ------- float PWM width in microseconds """ angle_deviation = ( angle - servo_params.neutral_angles[axis_index, leg_index] ) * servo_params.servo_multipliers[axis_index, leg_index] pulse_width_micros = ( servo_params.neutral_position_pwm + servo_params.micros_per_rad * angle_deviation ) return pulse_width_micros def angle_to_duty_cycle(angle, pwm_params, servo_params, axis_index, leg_index): return pwm_to_duty_cycle( angle_to_pwm(angle, servo_params, axis_index, leg_index), pwm_params ) def initialize_pwm(pi, pwm_params): for leg_index in range(4): for axis_index in range(3): pi.set_PWM_frequency( pwm_params.pins[axis_index, leg_index], pwm_params.freq ) pi.set_PWM_range(pwm_params.pins[axis_index, leg_index], pwm_params.range) def send_servo_commands(pi, pwm_params, servo_params, joint_angles): for leg_index in range(4): for axis_index in range(3): duty_cycle = angle_to_duty_cycle( joint_angles[axis_index, leg_index], pwm_params, servo_params, axis_index, leg_index, ) pi.set_PWM_dutycycle(pwm_params.pins[axis_index, leg_index], duty_cycle) def send_servo_command(pi, pwm_params, servo_params, joint_angle, axis, leg): duty_cycle = angle_to_duty_cycle(joint_angle, pwm_params, servo_params, axis, leg) pi.set_PWM_dutycycle(pwm_params.pins[axis, leg], duty_cycle) def deactivate_servos(pi, pwm_params): for leg_index in range(4): for axis_index in range(3): pi.set_PWM_dutycycle(pwm_params.pins[axis_index, leg_index], 0)
3,408
Python
32.097087
114
0.639085
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/Kinematics.py
import numpy as np from transforms3d.euler import euler2mat def leg_explicit_inverse_kinematics(r_body_foot, leg_index, config): """Find the joint angles corresponding to the given body-relative foot position for a given leg and configuration Parameters ---------- r_body_foot : [type] [description] leg_index : [type] [description] config : [type] [description] Returns ------- numpy array (3) Array of corresponding joint angles. """ (x, y, z) = r_body_foot # Distance from the leg origin to the foot, projected into the y-z plane R_body_foot_yz = (y ** 2 + z ** 2) ** 0.5 # Distance from the leg's forward/back point of rotation to the foot R_hip_foot_yz = (R_body_foot_yz ** 2 - config.ABDUCTION_OFFSET ** 2) ** 0.5 # Interior angle of the right triangle formed in the y-z plane by the leg that is coincident to the ab/adduction axis # For feet 2 (front left) and 4 (back left), the abduction offset is positive, for the right feet, the abduction offset is negative. arccos_argument = config.ABDUCTION_OFFSETS[leg_index] / R_body_foot_yz arccos_argument = np.clip(arccos_argument, -0.99, 0.99) phi = np.arccos(arccos_argument) # Angle of the y-z projection of the hip-to-foot vector, relative to the positive y-axis hip_foot_angle = np.arctan2(z, y) # Ab/adduction angle, relative to the positive y-axis abduction_angle = phi + hip_foot_angle # theta: Angle between the tilted negative z-axis and the hip-to-foot vector theta = np.arctan2(-x, R_hip_foot_yz) # Distance between the hip and foot R_hip_foot = (R_hip_foot_yz ** 2 + x ** 2) ** 0.5 # Angle between the line going from hip to foot and the link L1 arccos_argument = (config.LEG_L1 ** 2 + R_hip_foot ** 2 - config.LEG_L2 ** 2) / ( 2 * config.LEG_L1 * R_hip_foot ) arccos_argument = np.clip(arccos_argument, -0.99, 0.99) trident = np.arccos(arccos_argument) # Angle of the first link relative to the tilted negative z axis hip_angle = theta + trident # Angle between the leg links L1 and L2 arccos_argument = (config.LEG_L1 ** 2 + config.LEG_L2 ** 2 - R_hip_foot ** 2) / ( 2 * config.LEG_L1 * config.LEG_L2 ) arccos_argument = np.clip(arccos_argument, -0.99, 0.99) beta = np.arccos(arccos_argument) # Angle of the second link relative to the tilted negative z axis knee_angle = hip_angle - (np.pi - beta) return np.array([abduction_angle, hip_angle, knee_angle]) def four_legs_inverse_kinematics(r_body_foot, config): """Find the joint angles for all twelve DOF correspoinding to the given matrix of body-relative foot positions. Parameters ---------- r_body_foot : numpy array (3,4) Matrix of the body-frame foot positions. Each column corresponds to a separate foot. config : Config object Object of robot configuration parameters. Returns ------- numpy array (3,4) Matrix of corresponding joint angles. """ alpha = np.zeros((3, 4)) for i in range(4): body_offset = config.LEG_ORIGINS[:, i] alpha[:, i] = leg_explicit_inverse_kinematics( r_body_foot[:, i] - body_offset, i, config ) return alpha
3,324
Python
34.752688
136
0.639892
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/HardwareConfig.py
""" Per-robot configuration file that is particular to each individual robot, not just the type of robot. """ PS4_COLOR = {"red": 0, "blue": 0, "green": 255} PS4_DEACTIVATED_COLOR = {"red": 0, "blue": 0, "green": 50}
217
Python
35.333327
101
0.658986
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/Config.py
import numpy as np from pupper.ServoCalibration import MICROS_PER_RAD, NEUTRAL_ANGLE_DEGREES from pupper.HardwareConfig import PS4_COLOR, PS4_DEACTIVATED_COLOR from enum import Enum # TODO: put these somewhere else class PWMParams: def __init__(self): self.pins = np.array([[2, 14, 18, 23], [3, 15, 27, 24], [4, 17, 22, 25]]) self.range = 4000 self.freq = 250 class ServoParams: def __init__(self): self.neutral_position_pwm = 1500 # Middle position self.micros_per_rad = MICROS_PER_RAD # Must be calibrated # The neutral angle of the joint relative to the modeled zero-angle in degrees, for each joint self.neutral_angle_degrees = NEUTRAL_ANGLE_DEGREES self.servo_multipliers = np.array( [[1, 1, 1, 1], [-1, 1, -1, 1], [1, -1, 1, -1]] ) @property def neutral_angles(self): return self.neutral_angle_degrees * np.pi / 180.0 # Convert to radians class Configuration: def __init__(self): ################# CONTROLLER BASE COLOR ############## self.ps4_color = PS4_COLOR self.ps4_deactivated_color = PS4_DEACTIVATED_COLOR #################### COMMANDS #################### self.max_x_velocity = 0.4 self.max_y_velocity = 0.3 self.max_yaw_rate = 2.0 self.max_pitch = 30.0 * np.pi / 180.0 #################### MOVEMENT PARAMS #################### self.z_time_constant = 0.02 self.z_speed = 0.03 # maximum speed [m/s] self.pitch_deadband = 0.02 self.pitch_time_constant = 0.25 self.max_pitch_rate = 0.15 self.roll_speed = 0.16 # maximum roll rate [rad/s] self.yaw_time_constant = 0.3 self.max_stance_yaw = 1.2 self.max_stance_yaw_rate = 2.0 #################### STANCE #################### self.delta_x = 0.1 self.delta_y = 0.09 self.x_shift = 0.0 self.default_z_ref = -0.16 #################### SWING ###################### self.z_coeffs = None self.z_clearance = 0.07 self.alpha = ( 0.5 # Ratio between touchdown distance and total horizontal stance movement ) self.beta = ( 0.5 # Ratio between touchdown distance and total horizontal stance movement ) #################### GAIT ####################### self.dt = 0.01 self.num_phases = 4 self.contact_phases = np.array( [[1, 1, 1, 0], [1, 0, 1, 1], [1, 0, 1, 1], [1, 1, 1, 0]] ) self.overlap_time = ( 0.10 # duration of the phase where all four feet are on the ground ) self.swing_time = ( 0.15 # duration of the phase when only two feet are on the ground ) ######################## GEOMETRY ###################### self.LEG_FB = 0.10 # front-back distance from center line to leg axis self.LEG_LR = 0.04 # left-right distance from center line to leg plane self.LEG_L2 = 0.115 self.LEG_L1 = 0.1235 self.ABDUCTION_OFFSET = 0.03 # distance from abduction axis to leg self.FOOT_RADIUS = 0.01 self.HIP_L = 0.0394 self.HIP_W = 0.0744 self.HIP_T = 0.0214 self.HIP_OFFSET = 0.0132 self.L = 0.276 self.W = 0.100 self.T = 0.050 self.LEG_ORIGINS = np.array( [ [self.LEG_FB, self.LEG_FB, -self.LEG_FB, -self.LEG_FB], [-self.LEG_LR, self.LEG_LR, -self.LEG_LR, self.LEG_LR], [0, 0, 0, 0], ] ) self.ABDUCTION_OFFSETS = np.array( [ -self.ABDUCTION_OFFSET, self.ABDUCTION_OFFSET, -self.ABDUCTION_OFFSET, self.ABDUCTION_OFFSET, ] ) ################### INERTIAL #################### self.FRAME_MASS = 0.560 # kg self.MODULE_MASS = 0.080 # kg self.LEG_MASS = 0.030 # kg self.MASS = self.FRAME_MASS + (self.MODULE_MASS + self.LEG_MASS) * 4 # Compensation factor of 3 because the inertia measurement was just # of the carbon fiber and plastic parts of the frame and did not # include the hip servos and electronics self.FRAME_INERTIA = tuple( map(lambda x: 3.0 * x, (1.844e-4, 1.254e-3, 1.337e-3)) ) self.MODULE_INERTIA = (3.698e-5, 7.127e-6, 4.075e-5) leg_z = 1e-6 leg_mass = 0.010 leg_x = 1 / 12 * self.LEG_L1 ** 2 * leg_mass leg_y = leg_x self.LEG_INERTIA = (leg_x, leg_y, leg_z) @property def default_stance(self): return np.array( [ [ self.delta_x + self.x_shift, self.delta_x + self.x_shift, -self.delta_x + self.x_shift, -self.delta_x + self.x_shift, ], [-self.delta_y, self.delta_y, -self.delta_y, self.delta_y], [0, 0, 0, 0], ] ) ################## SWING ########################### @property def z_clearance(self): return self.__z_clearance @z_clearance.setter def z_clearance(self, z): self.__z_clearance = z # b_z = np.array([0, 0, 0, 0, self.__z_clearance]) # A_z = np.array( # [ # [0, 0, 0, 0, 1], # [1, 1, 1, 1, 1], # [0, 0, 0, 1, 0], # [4, 3, 2, 1, 0], # [0.5 ** 4, 0.5 ** 3, 0.5 ** 2, 0.5 ** 1, 0.5 ** 0], # ] # ) # self.z_coeffs = solve(A_z, b_z) ########################### GAIT #################### @property def overlap_ticks(self): return int(self.overlap_time / self.dt) @property def swing_ticks(self): return int(self.swing_time / self.dt) @property def stance_ticks(self): return 2 * self.overlap_ticks + self.swing_ticks @property def phase_ticks(self): return np.array( [self.overlap_ticks, self.swing_ticks, self.overlap_ticks, self.swing_ticks] ) @property def phase_length(self): return 2 * self.overlap_ticks + 2 * self.swing_ticks class SimulationConfig: def __init__(self): self.XML_IN = "pupper.xml" self.XML_OUT = "pupper_out.xml" self.START_HEIGHT = 0.3 self.MU = 1.5 # coeff friction self.DT = 0.001 # seconds between simulation steps self.JOINT_SOLREF = "0.001 1" # time constant and damping ratio for joints self.JOINT_SOLIMP = "0.9 0.95 0.001" # joint constraint parameters self.GEOM_SOLREF = "0.01 1" # time constant and damping ratio for geom contacts self.GEOM_SOLIMP = "0.9 0.95 0.001" # geometry contact parameters # Joint params G = 220 # Servo gear ratio m_rotor = 0.016 # Servo rotor mass r_rotor = 0.005 # Rotor radius self.ARMATURE = G ** 2 * m_rotor * r_rotor ** 2 # Inertia of rotational joints # print("Servo armature", self.ARMATURE) NATURAL_DAMPING = 1.0 # Damping resulting from friction ELECTRICAL_DAMPING = 0.049 # Damping resulting from back-EMF self.REV_DAMPING = ( NATURAL_DAMPING + ELECTRICAL_DAMPING ) # Damping torque on the revolute joints # Servo params self.SERVO_REV_KP = 300 # Position gain [Nm/rad] # Force limits self.MAX_JOINT_TORQUE = 3.0 self.REVOLUTE_RANGE = 1.57
7,666
Python
32.480349
102
0.501435
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/HardwareInterface.py
import odrive from odrive.enums import * from woofer.Config import RobotConfig from woofer.HardwareConfig import ( ODRIVE_SERIAL_NUMBERS, ACTUATOR_DIRECTIONS, ANGLE_OFFSETS, map_actuators_to_axes, ) import time import threading import numpy as np class HardwareInterface: def __init__(self): self.config = RobotConfig() assert len(ODRIVE_SERIAL_NUMBERS) == self.config.NUM_ODRIVES self.odrives = [None for _ in range(self.config.NUM_ODRIVES)] threads = [] for i in range(self.config.NUM_ODRIVES): t = threading.Thread(target=find_odrive, args=(i, self.odrives)) threads.append(t) t.start() for t in threads: t.join() input("Press enter to calibrate odrives...") calibrate_odrives(self.odrives) set_position_control(self.odrives) self.axes = assign_axes(self.odrives) def set_actuator_postions(self, joint_angles): set_all_odrive_positions(self.axes, joint_angles, self.config) def deactivate_actuators(self): set_odrives_idle(self.odrives) def find_odrive(i, odrives): o = odrive.find_any(serial_number=ODRIVE_SERIAL_NUMBERS[i]) print("Found odrive: ", i) odrives[i] = o def calibrate_odrives(odrives): for odrv in odrives: odrv.axis0.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE odrv.axis1.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE for odrv in odrives: while ( odrv.axis0.current_state != AXIS_STATE_IDLE or odrv.axis1.current_state != AXIS_STATE_IDLE ): time.sleep(0.1) # busy waiting - not ideal def set_position_control(odrives): for odrv in odrives: for axis in [odrv.axis0, odrv.axis1]: axis.controller.config.pos_gain = 60 axis.controller.config.vel_gain = 0.002 axis.controller.config.vel_limit_tolerance = 0 axis.controller.config.vel_integrator_gain = 0 axis.motor.config.current_lim = 15 print("Updated gains") odrv.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL odrv.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL def set_odrives_idle(odrives): for odrv in odrives: odrv.axis0.requested_state = AXIS_STATE_IDLE odrv.axis1.requested_state = AXIS_STATE_IDLE def assign_axes(odrives): return map_actuators_to_axes(odrives) def set_all_odrive_positions(axes, joint_angles, config): for i in range(joint_angles.shape[0]): for j in range(joint_angles.shape[1]): axes[i][j].controller.pos_setpoint = actuator_angle_to_odrive( joint_angles, i, j, config ) def radians_to_encoder_count(angle, config): return (angle / (2 * np.pi)) * config.ENCODER_CPR * config.MOTOR_REDUCTION def actuator_angle_to_odrive(joint_angles, i, j, config): offset_angle = joint_angles[i][j] + ANGLE_OFFSETS[i][j] odrive_radians = offset_angle * ACTUATOR_DIRECTIONS[i][j] return radians_to_encoder_count(odrive_radians, config)
3,118
Python
30.82653
78
0.652341
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/Kinematics.py
import numpy as np def leg_forward_kinematics(alpha, leg_index, config): """Find the body-centric coordinates of a given foot given the joint angles. Parameters ---------- alpha : Numpy array (3) Joint angles ordered as (abduction, hip, knee) leg_index : int Leg index. config : Config object Robot parameters object Returns ------- Numpy array (3) Body-centric coordinates of the specified foot """ pass def leg_explicit_inverse_kinematics(r_body_foot, leg_index, config): """Find the joint angles corresponding to the given body-relative foot position for a given leg and configuration Parameters ---------- r_body_foot : [type] [description] leg_index : [type] [description] config : [type] [description] Returns ------- numpy array (3) Array of corresponding joint angles. """ (x, y, z) = r_body_foot # Distance from the leg origin to the foot, projected into the y-z plane R_body_foot_yz = (y ** 2 + z ** 2) ** 0.5 # Distance from the leg's forward/back point of rotation to the foot R_hip_foot_yz = (R_body_foot_yz ** 2 - config.ABDUCTION_OFFSET ** 2) ** 0.5 # Interior angle of the right triangle formed in the y-z plane by the leg that is coincident to the ab/adduction axis # For feet 2 (front left) and 4 (back left), the abduction offset is positive, for the right feet, the abduction offset is negative. cos_param = config.ABDUCTION_OFFSETS[leg_index] / R_body_foot_yz if abs(cos_param) > 0.9: print("Clipping 1st cos param") cos_param = np.clip(cos_param, -0.9, 0.9) phi = np.arccos(cos_param) # Angle of the y-z projection of the hip-to-foot vector, relative to the positive y-axis hip_foot_angle = np.arctan2(z, y) # Ab/adduction angle, relative to the positive y-axis abduction_angle = phi + hip_foot_angle # theta: Angle between the tilted negative z-axis and the hip-to-foot vector theta = np.arctan2(-x, R_hip_foot_yz) # Distance between the hip and foot R_hip_foot = (R_hip_foot_yz ** 2 + x ** 2) ** 0.5 # Using law of cosines to determine the angle between upper leg links cos_param = (config.UPPER_LEG ** 2 + R_hip_foot ** 2 - config.LOWER_LEG ** 2) / (2.0*config.UPPER_LEG*R_hip_foot) # Ensure that the leg isn't over or under extending cos_param = np.clip(cos_param, -0.9, 0.9) if abs(cos_param) > 0.9: print("Clipping 2nd cos param") # gamma: Angle between upper leg links and the center of the leg gamma = np.arccos(cos_param) return np.array([abduction_angle, theta - gamma, theta + gamma]) def four_legs_inverse_kinematics(r_body_foot, config): """Find the joint angles for all twelve DOF correspoinding to the given matrix of body-relative foot positions. Parameters ---------- r_body_foot : numpy array (3,4) Matrix of the body-frame foot positions. Each column corresponds to a separate foot. config : Config object Object of robot configuration parameters. Returns ------- numpy array (3,4) Matrix of corresponding joint angles. """ alpha = np.zeros((3, 4)) for i in range(4): body_offset = config.LEG_ORIGINS[:, i] alpha[:, i] = leg_explicit_inverse_kinematics( r_body_foot[:, i] - body_offset, i, config ) return alpha
3,449
Python
34.204081
136
0.636416
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/HardwareConfig.py
""" Per-robot configuration file that is particular to each individual robot, not just the type of robot. """ import numpy as np ODRIVE_SERIAL_NUMBERS = [ "2065339F304B", "208F3384304B", "365833753037", "207E35753748", "208F3385304B", "208E3387304B", ] ACTUATOR_DIRECTIONS = np.array([[1, 1, -1, -1], [-1, -1, -1, -1], [1, 1, 1, 1]]) ANGLE_OFFSETS = np.array( [ [0, 0, 0, 0], [np.pi / 2, np.pi / 2, np.pi / 2, np.pi / 2], [-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2], ] ) def map_actuators_to_axes(odrives): axes = [[None for _ in range(4)] for _ in range(3)] axes[0][0] = odrives[1].axis1 axes[1][0] = odrives[0].axis0 axes[2][0] = odrives[0].axis1 axes[0][1] = odrives[1].axis0 axes[1][1] = odrives[2].axis1 axes[2][1] = odrives[2].axis0 axes[0][2] = odrives[4].axis1 axes[1][2] = odrives[5].axis0 axes[2][2] = odrives[5].axis1 axes[0][3] = odrives[4].axis0 axes[1][3] = odrives[3].axis1 axes[2][3] = odrives[3].axis0 return axes
1,057
Python
22.511111
101
0.553453
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/Config.py
import numpy as np from scipy.linalg import solve class BehaviorState(Enum): REST = 0 TROT = 1 HOP = 2 FINISHHOP = 3 class UserInputParams: def __init__(self): self.max_x_velocity = 0.5 self.max_y_velocity = 0.24 self.max_yaw_rate = 0.2 self.max_pitch = 30.0 * np.pi / 180.0 class MovementReference: """Stores movement reference """ def __init__(self): self.v_xy_ref = np.array([0, 0]) self.wz_ref = 0.0 self.z_ref = -0.265 self.pitch = 0.0 self.roll = 0.0 class SwingParams: """Swing Parameters """ def __init__(self): self.z_coeffs = None self.z_clearance = 0.05 self.alpha = ( 0.5 ) # Ratio between touchdown distance and total horizontal stance movement self.beta = ( 0.5 ) # Ratio between touchdown distance and total horizontal stance movement @property def z_clearance(self): return self.__z_clearance @z_clearance.setter def z_clearance(self, z): self.__z_clearance = z b_z = np.array([0, 0, 0, 0, self.__z_clearance]) A_z = np.array( [ [0, 0, 0, 0, 1], [1, 1, 1, 1, 1], [0, 0, 0, 1, 0], [4, 3, 2, 1, 0], [0.5 ** 4, 0.5 ** 3, 0.5 ** 2, 0.5 ** 1, 0.5 ** 0], ] ) self.z_coeffs = solve(A_z, b_z) class StanceParams: """Stance parameters """ def __init__(self): self.z_time_constant = 0.02 self.z_speed = 0.03 # maximum speed [m/s] self.pitch_deadband = 0.02 self.pitch_time_constant = 0.25 self.max_pitch_rate = 0.15 self.roll_speed = 0.16 # maximum roll rate [rad/s] self.delta_x = 0.23 self.delta_y = 0.173 self.x_shift = -0.01 @property def default_stance(self): return np.array( [ [ self.delta_x + self.x_shift, self.delta_x + self.x_shift, -self.delta_x + self.x_shift, -self.delta_x + self.x_shift, ], [-self.delta_y, self.delta_y, -self.delta_y, self.delta_y], [0, 0, 0, 0], ] ) class GaitParams: """Gait Parameters """ def __init__(self): self.dt = 0.01 self.num_phases = 4 self.contact_phases = np.array( [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] ) self.overlap_time = ( 0.5 # duration of the phase where all four feet are on the ground ) self.swing_time = ( 0.5 # duration of the phase when only two feet are on the ground ) @property def overlap_ticks(self): return int(self.overlap_time / self.dt) @property def swing_ticks(self): return int(self.swing_time / self.dt) @property def stance_ticks(self): return 2 * self.overlap_ticks + self.swing_ticks @property def phase_times(self): return np.array( [self.overlap_ticks, self.swing_ticks, self.overlap_ticks, self.swing_ticks] ) @property def phase_length(self): return 2 * self.overlap_ticks + 2 * self.swing_ticks class RobotConfig: """Woofer hardware parameters """ def __init__(self): # Robot geometry self.LEG_FB = 0.23 # front-back distance from center line to leg axis self.LEG_LR = 0.109 # left-right distance from center line to leg plane self.ABDUCTION_OFFSET = 0.064 # distance from abduction axis to leg self.FOOT_RADIUS = 0.02 self.UPPER_LEG = 0.18 self.LOWER_LEG = 0.32 # Update hip geometry self.HIP_L = 0.0394 self.HIP_W = 0.0744 self.HIP_T = 0.0214 self.HIP_OFFSET = 0.0132 self.L = 0.66 self.W = 0.176 self.T = 0.092 self.LEG_ORIGINS = np.array( [ [self.LEG_FB, self.LEG_FB, -self.LEG_FB, -self.LEG_FB], [-self.LEG_LR, self.LEG_LR, -self.LEG_LR, self.LEG_LR], [0, 0, 0, 0], ] ) self.ABDUCTION_OFFSETS = np.array( [ -self.ABDUCTION_OFFSET, self.ABDUCTION_OFFSET, -self.ABDUCTION_OFFSET, self.ABDUCTION_OFFSET, ] ) self.START_HEIGHT = 0.3 # Robot inertia params self.FRAME_MASS = 3.0 # kg self.MODULE_MASS = 1.033 # kg self.LEG_MASS = 0.15 # kg self.MASS = self.FRAME_MASS + (self.MODULE_MASS + self.LEG_MASS) * 4 # Compensation factor of 3 because the inertia measurement was just # of the carbon fiber and plastic parts of the frame and did not # include the hip servos and electronics self.FRAME_INERTIA = tuple( map(lambda x: 3.0 * x, (1.844e-4, 1.254e-3, 1.337e-3)) ) self.MODULE_INERTIA = (3.698e-5, 7.127e-6, 4.075e-5) leg_z = 1e-6 leg_mass = 0.010 leg_x = 1 / 12 * self.LOWER_LEG ** 2 * leg_mass leg_y = leg_x self.LEG_INERTIA = (leg_x, leg_y, leg_z) # Joint params G = 220 # Servo gear ratio m_rotor = 0.016 # Servo rotor mass r_rotor = 0.005 # Rotor radius self.ARMATURE = G ** 2 * m_rotor * r_rotor ** 2 # Inertia of rotational joints # print("Servo armature", self.ARMATURE) NATURAL_DAMPING = 1.0 # Damping resulting from friction ELECTRICAL_DAMPING = 0.049 # Damping resulting from back-EMF self.REV_DAMPING = ( NATURAL_DAMPING + ELECTRICAL_DAMPING ) # Damping torque on the revolute joints # Force limits self.MAX_JOINT_TORQUE = 12.0 self.REVOLUTE_RANGE = 3 self.NUM_ODRIVES = 6 self.ENCODER_CPR = 2000 self.MOTOR_REDUCTION = 4 class EnvironmentConfig: """Environmental parameters """ def __init__(self): self.MU = 1.5 # coeff friction self.DT = 0.001 # seconds between simulation steps class SolverConfig: """MuJoCo solver parameters """ def __init__(self): self.JOINT_SOLREF = "0.001 1" # time constant and damping ratio for joints self.JOINT_SOLIMP = "0.9 0.95 0.001" # joint constraint parameters self.GEOM_SOLREF = "0.01 1" # time constant and damping ratio for geom contacts self.GEOM_SOLIMP = "0.9 0.95 0.001" # geometry contact parameters
6,661
Python
26.643153
88
0.523945
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/mini_pupper_simplified/README.md
# Mini Pupper Robot Description (URDF) ## Overview This package contains a simplified robot description (URDF) of the [Mini Pupper](https://www.kickstarter.com/projects/336477435/mini-pupper-open-sourceros-robot-dog-kit) developed by [MangDang](https://twitter.com/LeggedRobot). STL filesare forked from [mayataka/mini_pupper_trajopt](https://github.com/mayataka/mini_pupper_trajopt). ## License This software is released under a [BSD 3-Clause license](LICENSE). ## Usage See [CHAMP](https://github.com/chvmp/champ)
523
Markdown
31.749998
227
0.768642
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/rover.py
#!/usr/bin/env python3 import sys import argparse import json import time import select import pexpect import UDPComms import msgpack def peek_func(port): sub = UDPComms.Subscriber(port, timeout = 10) while 1: try: data = sub.recv() print( json.dumps(data) ) except UDPComms.timeout: exit() def poke_func(port, rate): pub = UDPComms.Publisher(port) data = None while 1: if select.select([sys.stdin], [], [], 0)[0]: line = sys.stdin.readline() # detailed behaviour # reading from file: -ignores empty lines -repeats last line forever # reading from terminal: -repeats last command if line.rstrip(): data = line.rstrip() elif len(line) == 0: # exit() #uncomment to quit on end of file pass else: continue if data != None: pub.send( json.loads(data) ) time.sleep( rate/1000 ) def call_func(command, ssh = True): child = pexpect.spawn(command) if ssh: i = 1 while i == 1: try: i = child.expect(['password:', 'Are you sure you want to continue connecting', 'Welcome'], timeout=20) except pexpect.EOF: print("Can't connect to device") exit() except pexpect.TIMEOUT: print("Interaction with device failed") exit() if i == 1: child.sendline('yes') if i == 0: child.sendline('raspberry') else: try: child.expect('robot:', timeout=1) child.sendline('hello') except pexpect.TIMEOUT: pass child.interact() if __name__ == '__main__': parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='subparser') peek = subparsers.add_parser("peek") peek.add_argument('port', help="UDP port to subscribe to", type=int) poke = subparsers.add_parser("poke") poke.add_argument('port', help="UDP port to publish the data to", type=int) poke.add_argument('rate', help="how often to republish (ms)", type=float) peek = subparsers.add_parser("discover") commands = ['status', 'log', 'start', 'stop', 'restart', 'enable', 'disable'] for command in commands: status = subparsers.add_parser(command) status.add_argument('host', help="Which device to look for this program on") status.add_argument('unit', help="The unit whose status we want to know", nargs='?', default=None) connect = subparsers.add_parser('connect') connect.add_argument('host', help="Which device to log into") args = parser.parse_args() if args.subparser == 'peek': peek_func(args.port) elif args.subparser == 'poke': poke_func(args.port, args.rate) elif args.subparser == 'connect': call_func("ssh pi@"+args.host+".local") elif args.subparser == 'discover': call_func("nmap -sP 10.0.0.0/24", ssh=False) elif args.subparser in commands: if args.unit is None: args.unit = args.host if args.host == 'local': prefix = "" ssh = False else: prefix = "ssh pi@"+args.host+".local " ssh = True if args.subparser == 'status': call_func(prefix + "sudo systemctl status "+args.unit, ssh) elif args.subparser == 'log': call_func(prefix + "sudo journalctl -f -u "+args.unit, ssh) elif args.subparser == 'start': call_func(prefix + "sudo systemctl start "+args.unit, ssh) elif args.subparser == 'stop': call_func(prefix + "sudo systemctl stop "+args.unit, ssh) elif args.subparser == 'restart': call_func(prefix + "sudo systemctl restart "+args.unit, ssh) elif args.subparser == 'enable': call_func(prefix + "sudo systemctl enable "+args.unit, ssh) elif args.subparser == 'disable': call_func(prefix + "sudo systemctl disable "+args.unit, ssh) else: parser.print_help()
4,329
Python
30.838235
84
0.546778
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/__init__.py
from .UDPComms import Publisher from .UDPComms import Subscriber from .UDPComms import timeout
95
Python
22.999994
32
0.842105
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/setup.py
#!/usr/bin/env python from distutils.core import setup setup(name='UDPComms', version='1.1dev', py_modules=['UDPComms'], description='Simple library for sending messages over UDP', author='Michal Adamkiewicz', author_email='mikadam@stanford.edu', url='https://github.com/stanfordroboticsclub/UDP-Comms', )
349
Python
25.923075
65
0.673352
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/UDPComms.py
import socket import struct from collections import namedtuple from time import monotonic import msgpack import time timeout = socket.timeout MAX_SIZE = 65507 class Publisher: def __init__(self, port_tx,port): """ Create a Publisher Object Arguments: port -- the port to publish the messages on """ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.des_address = ("127.0.0.1",port_tx) self.sock.bind(("127.0.0.1", port)) self.sock.settimeout(0.2) def send(self, obj): """ Publish a message. The obj can be any nesting of standard python types """ msg = msgpack.dumps(obj, use_bin_type=False) assert len(msg) < MAX_SIZE, "Encoded message too big!" self.sock.sendto(msg,self.des_address) def __del__(self): self.sock.close() class Subscriber: def __init__(self, port_rx, timeout=0.2): """ Create a Subscriber Object Arguments: port -- the port to listen to messages on timeout -- how long to wait before a message is considered out of date """ self.max_size = MAX_SIZE self.timeout = timeout self.last_data = None self.last_time = float('-inf') self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.settimeout(timeout) self.sock.bind(("127.0.0.1", port_rx)) def recv(self): """ Receive a single message from the socket buffer. It blocks for up to timeout seconds. If no message is received before timeout it raises a UDPComms.timeout exception""" try: self.last_data, address = self.sock.recvfrom(3) except BlockingIOError: raise socket.timeout("no messages in buffer and called with timeout = 0") print(self.last_data) self.last_time = monotonic() return msgpack.loads(self.last_data, raw=False) def get(self): """ Returns the latest message it can without blocking. If the latest massage is older then timeout seconds it raises a UDPComms.timeout exception""" try: self.sock.settimeout(0) while True: self.last_data, address = self.sock.recvfrom(self.max_size) self.last_time = monotonic() except socket.error: pass finally: self.sock.settimeout(self.timeout) current_time = monotonic() if (current_time - self.last_time) < self.timeout: return msgpack.loads(self.last_data, raw=False) else: raise socket.timeout("timeout=" + str(self.timeout) + \ ", last message time=" + str(self.last_time) + \ ", current time=" + str(current_time)) def get_list(self): """ Returns list of messages, in the order they were received""" msg_bufer = [] try: self.sock.settimeout(0) while True: self.last_data, address = self.sock.recvfrom(self.max_size) self.last_time = monotonic() msg = msgpack.loads(self.last_data, raw=False) msg_bufer.append(msg) except socket.error: pass finally: self.sock.settimeout(self.timeout) return msg_bufer def __del__(self): self.sock.close() class Subscriber: def __init__(self, port, timeout=0.2): """ Create a Subscriber Object Arguments: port -- the port to listen to messages on timeout -- how long to wait before a message is considered out of date """ self.max_size = MAX_SIZE self.port = port self.timeout = timeout self.last_data = None self.last_time = float('-inf') self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) self.sock.settimeout(timeout) self.sock.bind(("", port)) def recv(self): """ Receive a single message from the socket buffer. It blocks for up to timeout seconds. If no message is received before timeout it raises a UDPComms.timeout exception""" try: self.last_data, address = self.sock.recvfrom(self.max_size) except BlockingIOError: raise socket.timeout("no messages in buffer and called with timeout = 0") self.last_time = monotonic() return msgpack.loads(self.last_data, raw=False) def get(self): """ Returns the latest message it can without blocking. If the latest massage is older then timeout seconds it raises a UDPComms.timeout exception""" try: self.sock.settimeout(0) while True: self.last_data, address = self.sock.recvfrom(self.max_size) self.last_time = monotonic() except socket.error: pass finally: self.sock.settimeout(self.timeout) current_time = monotonic() if (current_time - self.last_time) < self.timeout: return msgpack.loads(self.last_data, raw=False) else: raise socket.timeout("timeout=" + str(self.timeout) + \ ", last message time=" + str(self.last_time) + \ ", current time=" + str(current_time)) def get_list(self): """ Returns list of messages, in the order they were received""" msg_bufer = [] try: self.sock.settimeout(0) while True: self.last_data, address = self.sock.recvfrom(self.max_size) self.last_time = monotonic() msg = msgpack.loads(self.last_data, raw=False) msg_bufer.append(msg) except socket.error: pass finally: self.sock.settimeout(self.timeout) return msg_bufer def __del__(self): self.sock.close() if __name__ == "__main__": msg = 'very important data' a = Publisher(1000) a.send( {"text": "magic", "number":5.5, "bool":False} )
6,463
Python
33.021052
97
0.573727
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/README.md
# UDPComms This is a simple library to enable communication between different processes (potentially on different machines) over a network using UDP. It's goals a simplicity and easy of understanding and reliability. It works for devices on the `10.0.0.X` subnet although this can easiliy be changed. Currently it works in python 2 and 3 but it should be relatively simple to extend it to other languages such as C (to run on embeded devices) or Julia (to interface with faster solvers). This new verison of the library automatically determines the type of the message and trasmits it along with it, so the subscribers can decode it correctly. While faster to prototype with then systems with explicit type declaration (such as ROS) its easy to shoot yourself in the foot if types are mismatched between publisher and subscriber. ### To Send Messages ``` >>> from UDPComms import Publisher >>> a = Publisher(5500) >>> a.send({"name":"Bob", "age": 20, "height": 180.5, "mass": 70.1}) ``` ### To Receive Messages #### recv Method Note: before using the `Subsciber.recv()` method read about the `Subsciber.get()` and understand the difference between them. The `Subsciber.recv()` method will pull a message from the socket buffer and it won't necessary be the most recent message. If you are calling it too slowly and there is a lot of messages you will be getting old messages. The `Subsciber.recv()` can also block for up to `timeout` seconds messing up timing. ``` >>> from UDPComms import Subscriber >>> a = Subscriber(5500) >>> message = a.recv() >>> message['age'] 20 >>> message['height'] 180.5 >>> message['name'] "Bob" >>> message {"name":"Bob", "age": 20, "height": 180.5, "mass": 70.1} ``` #### get Method The preferred way of accessing messages is the `Subsciber.get()` method (as opposed to the `recv()` method). It is guaranteed to be nonblocking so it can be used in places without messing with timing. It checks for any new messages and returns the newest one. If the newest message is older then `timeout` seconds it raises the `UDPComms.timeout` exception. **This is an important safety feature!** Make sure to catch the timeout using `try: ... except UDPComms.timeout: ...` and put the robot in a safe configuration (e.g. turn off motors, when the joystick stop sending messages) Note that if you call `.get` immediately after creating a subscriber it is possible its hasn't received any messages yet and it will timeout. In general it is better to have a short timeout and gracefully catch timeouts then to have long timeouts ``` >>> from UDPComms import Subscriber, timout >>> a = Subscriber(5500) >>> while 1: >>> try: >>> message = a.get() >>> print("got", message) >>> except timeout: >>> print("safing robot") ``` #### get_list Method Although UDPComms isn't ideal for commands that need to be processed in order (as the underlying UDP protocol has no guarantees of deliverry) it can be used as such in a pinch. The `Subsciber.get_list()` method will return all the messages we haven't seen yet in a list ``` >>> from UDPComms import Subscriber, timout >>> a = Subscriber(5500) >>> messages = a.get_list() >>> for message in messages: >>> print("got", message) ``` ### Publisher Arguments - `port` The port the messages will be sent on. If you are part of Stanford Student Robotics make sure there isn't any port conflicts by checking the `UDP Ports` sheet of the [CS Comms System](https://docs.google.com/spreadsheets/d/1pqduUwYa1_sWiObJDrvCCz4Al3pl588ytE4u-Dwa6Pw/edit?usp=sharing) document. If you are not I recommend keep track of your port numbers somewhere. It's possible that in the future UDPComms will have a system of naming (with a string) as opposed to numbering publishers. - `ip` By default UDPComms sends to the `10.0.0.X` subnet, but can be changed to a different ip using this argument. Set to localhost (`127.0.0.1`) for development on the same computer. ### Subscriber Arguments - `port` The port the subscriber will be listen on. - `timeout` If the `recv()` method don't get a message in `timeout` seconds it throws a `UDPComms.timeout` exception ### Rover The library also comes with the `rover` command that can be used to interact with the messages manually. | Command | Descripion | |---------|------------| | `rover peek port` | print messages sent on port `port` | | `rover poke port rate` | send messages to `port` once every `rate` milliseconds. Type message in json format and press return | There are more commands used for starting and stoping services described in [this repo](https://github.com/stanfordroboticsclub/RPI-Setup/blob/master/README.md) ### To Install ``` $git clone https://github.com/stanfordroboticsclub/UDPComms.git $sudo bash UDPComms/install.sh ``` ### To Update ``` $cd UDPComms $git pull $sudo bash install.sh ``` ### Developing without hardware Because this library expects you to be connected to the robot (`10.0.0.X`) network you won't be able to send messages between two programs on your computer without any other hardware connected. You can get around this by forcing your (unused) ethernet interface to get an ip on the rover network without anything being connected to it. On my computer you can do this using this command: `sudo ifconfig en1 10.0.0.52 netmask 255.255.255.0` Note that the exact command depends which interface on your computer is unused and what ip you want. So only use this if you know what you are doing. If you have internet access a slightly cleaner way to do it is to setup [RemoteVPN](https://github.com/stanfordroboticsclub/RemoteVPN) on your development computer and simply connect to a development network (given if you are the only computer there) ### Known issues: - Macs have issues sending large messages. They are fine receiving them. I think it is related to [this issue](https://github.com/BanTheRewind/Cinder-Asio/issues/9). I wonder does it work on Linux by chance (as the packets happen to be in order) but so far we didn't have issues. - Messages over the size of one MTU (typically 1500 bytes) will be split up into multiple frames which reduces their chance of getting to their destination on wireless networks.
6,216
Markdown
50.380165
489
0.742117
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Doc/guide/software_installation.rst
===================== Software Installation ===================== .. contents:: :depth: 4 Setting up your Raspberry Pi ------------------------------ * Raspberry Pi 4(2GB DDR for normal use, 4GB DDR for install and debug by self) * SD Card (32GB recommended) * Raspberry Pi 4 power supply (USB-C, 5V, >=3A) * Ethernet cable Preparing the Pi's SD card ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From your desktop / laptop: 1. Put the SD card into your desktop / laptop. ############################################### 2. Download this version of Ubuntu 21.10 ################################################################# Download Ubuntu21.10 server version 64bit image(NOT including desktop). Use `this version <https://drive.google.com/file/d/1JVtjFTKE6FloG3giyMN_VuS0dKt4n2xq/view?usp=sharing>`_ so everyone is using the same version. Unzip and extract the file. You can also check the version from `ubuntu offical website. <https://ubuntu.com/download/raspberry-pi>`_ 3. Use `etcher <https://www.balena.io/etcher/>`_ to flash the card. ########################################################################################## * For quick start, you can also download the `pre-installed image <https://drive.google.com/drive/folders/12FDFbZzO61Euh8pJI9oCxN-eLVm5zjyi?usp=sharing>`_ , (username: ubuntu , password: mangdang ) flash it into the card, then skip all the following steps and start to calibarte the Pupper Mini. * If you are using the recommended etcher, this is the start-up menu. Select ubuntu-21.10-preinstalled-server-arm64+raspi.img (file inside zip )and the SD card. .. image:: ../_static/flash1.png :align: center * Image of SD card being flashed. .. image:: ../_static/flash2.png :align: center * Done! .. image:: ../_static/flash3.png :align: center Enabling Basic Functionality ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Turn on your Raspberry Pi. ################################################################################################### Remove SD card from computer and put it into your Raspberry Pi. Connect the IO board to the Pi, Connect battery power from IO board power interface, Connect keyboard, and mouse to the Pi as well. Connect the Pi to a displayer by HDMI line. Switch power on/off button to set up the Pi. Follow the prompts to change the password((The default password is ``mangdang``)), and then install desktop. Before installation, please make sure that raspberry pi is plugged into the network cable to access the Internet. After installing the desktop, you only need to reboot it one time. The system will enter the desktop system by default. Run ``$sudo apt install ubuntu-desktop`` .. image:: ../_static/installDesktop.jpg :align: center 2. Initial Ubuntu server ######################################################## * The install time depends on your network speed, probably dozens of minutes. Input "Y" to continue, and then input "startx" to boot up desktop at first time. .. image:: ../_static/installDesktop2.jpg :align: center Reboot it only at first time, and then check the IP address, you can connect it later by SSH. .. image:: ../_static/bootupDesktop4.jpg :align: center 2. SSH into the pi from your computer and install the robot program. ###################################### Run ``ssh ubuntu@IP address`` (The default password is ``mangdang``) .. image:: ../_static/ssh.png :align: center Make ``Robotics`` folder and download the source code. Run ``git clone -b MiniPupper_V2 https://github.com/mangdangroboticsclub/QuadrupedRobot.git`` .. image:: ../_static/gitclonesourcecode.png :align: center Install requirements (on the Pi). Run ``sudo bash Legacy/pre_install.sh``, the pre-install time depends on your network speed, maybe dezons of minutes, or several hours. .. image:: ../_static/preInstall.png :align: center Insall the pupper robot program. * ``cd QuadrupedRobot`` * ``sudo bash install.sh`` .. image:: ../_static/preInstall.png :align: center 3. Power-cycle the robot ############################# Unplug the battery, wait about 30 seconds, and then plug it back in. 4. Verify everything is working ############################### #. If you just powered on the Pi, wait about 30 seconds until the green light stops blinking. #. SSH into the robot * Run ``ssh pi@10.0.0.xx (where xx is the IP address you chose for the robot)`` #. Check the status for the joystick service * Run ``sudo systemctl status joystick`` * If you haven't yet connected the PS4 controller, it should say something like :: pi@pupper(rw):~/StanfordQuadruped$ sudo systemctl status joystick ● joystick.service - Pupper Joystick service Loaded: loaded (/home/pi/PupperCommand/joystick.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-03-01 06:57:20 GMT; 1s ago Main PID: 5692 (python3) Tasks: 3 (limit: 4035) Memory: 7.1M CGroup: /system.slice/joystick.service ├─5692 /usr/bin/python3 /home/pi/PupperCommand/joystick.py └─5708 hcitool scan --flush Mar 01 06:57:20 pupper systemd[1]: Started Pupper Joystick service. Mar 01 06:57:21 pupper python3[5692]: [info][controller 1] Created devices /dev/input/js0 (joystick) /dev/input/event0 (evdev) Mar 01 06:57:21 pupper python3[5692]: [info][bluetooth] Scanning for devices #. Connect the PS4 controller to the Pi by putting it pairing mode. * To put it into pairing mode, hold the share button and circular Playstation button at the same time until it starts making quick double flashes. * If it starts making slow single flashes, hold the Playstation button down until it stops blinking and try again. #. Once the controller is connected, check the status again * Run ``sudo systemctl status joystick`` * It should now look something like:: pi@pupper(rw):~/StanfordQuadruped$ sudo systemctl status joystick ● joystick.service - Pupper Joystick service Loaded: loaded (/home/pi/PupperCommand/joystick.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-03-01 06:57:20 GMT; 55s ago Main PID: 5692 (python3) Tasks: 2 (limit: 4035) Memory: 7.3M CGroup: /system.slice/joystick.service └─5692 /usr/bin/python3 /home/pi/PupperCommand/joystick.py Mar 01 06:57:20 pupper systemd[1]: Started Pupper Joystick service. Mar 01 06:57:21 pupper python3[5692]: [info][controller 1] Created devices /dev/input/js0 (joystick) /dev/input/event0 (evdev) Mar 01 06:57:21 pupper python3[5692]: [info][bluetooth] Scanning for devices Mar 01 06:58:12 pupper python3[5692]: [info][bluetooth] Found device A0:AB:51:33:B5:A0 Mar 01 06:58:13 pupper python3[5692]: [info][controller 1] Connected to Bluetooth Controller (A0:AB:51:33:B5:A0) Mar 01 06:58:14 pupper python3[5692]: running Mar 01 06:58:14 pupper python3[5692]: [info][controller 1] Battery: 50% * If the pi can't find the joystick after a minute or two, it's possible that the pi's bluetooth controller was never turned on. Run ``sudo hciconfig hci0 up`` to turn the radio on. Then restart the pi. #. Check the status of the robot service * Run ``sudo systemctl status robot`` * The output varies depending on the order of you running various programs, but just check that it doesn't have any red text saying that it failed. * If it did fail, usually this fixes it: ``sudo systemctl restart robot`` 7. Done! ######### Continue to Calibration.
7,709
reStructuredText
40.675675
297
0.652354
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Example/display/demo.py
import os import sys from PIL import Image sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot") sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs]) from Mangdang.LCD.ST7789 import ST7789 def main(): """ The demo for picture show """ # init st7789 device disp = ST7789() disp.begin() disp.clear() # show exaple picture image=Image.open("./dog.png") image.resize((320,240)) disp.display(image) main()
527
Python
20.119999
129
0.671727
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/PWMController/pwm-pca9685.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for PCA9685 16-channel 12-bit PWM LED controller * * Copyright (C) 2013 Steffen Trumtrar <s.trumtrar@pengutronix.de> * Copyright (C) 2015 Clemens Gruber <clemens.gruber@pqgruber.com> * * based on the pwm-twl-led.c driver */ #include <linux/acpi.h> #include <linux/gpio/driver.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/platform_device.h> #include <linux/property.h> #include <linux/pwm.h> #include <linux/regmap.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/pm_runtime.h> #include <linux/bitmap.h> /* * Because the PCA9685 has only one prescaler per chip, only the first channel * that is enabled is allowed to change the prescale register. * PWM channels requested afterwards must use a period that results in the same * prescale setting as the one set by the first requested channel. * GPIOs do not count as enabled PWMs as they are not using the prescaler. */ #define PCA9685_MODE1 0x00 #define PCA9685_MODE2 0x01 #define PCA9685_SUBADDR1 0x02 #define PCA9685_SUBADDR2 0x03 #define PCA9685_SUBADDR3 0x04 #define PCA9685_ALLCALLADDR 0x05 #define PCA9685_LEDX_ON_L 0x06 #define PCA9685_LEDX_ON_H 0x07 #define PCA9685_LEDX_OFF_L 0x08 #define PCA9685_LEDX_OFF_H 0x09 #define PCA9685_ALL_LED_ON_L 0xFA #define PCA9685_ALL_LED_ON_H 0xFB #define PCA9685_ALL_LED_OFF_L 0xFC #define PCA9685_ALL_LED_OFF_H 0xFD #define PCA9685_PRESCALE 0xFE #define PCA9685_PRESCALE_MIN 0x03 /* => max. frequency of 1526 Hz */ #define PCA9685_PRESCALE_MAX 0xFF /* => min. frequency of 24 Hz */ #define PCA9685_COUNTER_RANGE 4096 #define PCA9685_OSC_CLOCK_MHZ 25 /* Internal oscillator with 25 MHz */ #define PCA9685_NUMREGS 0xFF #define PCA9685_MAXCHAN 0x10 #define LED_FULL BIT(4) #define MODE1_ALLCALL BIT(0) #define MODE1_SUB3 BIT(1) #define MODE1_SUB2 BIT(2) #define MODE1_SUB1 BIT(3) #define MODE1_SLEEP BIT(4) #define MODE2_INVRT BIT(4) #define MODE2_OUTDRV BIT(2) #define LED_N_ON_H(N) (PCA9685_LEDX_ON_H + (4 * (N))) #define LED_N_ON_L(N) (PCA9685_LEDX_ON_L + (4 * (N))) #define LED_N_OFF_H(N) (PCA9685_LEDX_OFF_H + (4 * (N))) #define LED_N_OFF_L(N) (PCA9685_LEDX_OFF_L + (4 * (N))) #define REG_ON_H(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_ON_H : LED_N_ON_H((C))) #define REG_ON_L(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_ON_L : LED_N_ON_L((C))) #define REG_OFF_H(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_OFF_H : LED_N_OFF_H((C))) #define REG_OFF_L(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_OFF_L : LED_N_OFF_L((C))) struct pca9685 { struct pwm_chip chip; struct regmap *regmap; struct mutex lock; DECLARE_BITMAP(pwms_enabled, PCA9685_MAXCHAN + 1); #if IS_ENABLED(CONFIG_GPIOLIB) struct gpio_chip gpio; DECLARE_BITMAP(pwms_inuse, PCA9685_MAXCHAN + 1); #endif }; static inline struct pca9685 *to_pca(struct pwm_chip *chip) { return container_of(chip, struct pca9685, chip); } /* This function is supposed to be called with the lock mutex held */ static bool pca9685_prescaler_can_change(struct pca9685 *pca, int channel) { /* No PWM enabled: Change allowed */ if (bitmap_empty(pca->pwms_enabled, PCA9685_MAXCHAN + 1)) return true; /* More than one PWM enabled: Change not allowed */ if (bitmap_weight(pca->pwms_enabled, PCA9685_MAXCHAN + 1) > 1) return false; /* * Only one PWM enabled: Change allowed if the PWM about to * be changed is the one that is already enabled */ return test_bit(channel, pca->pwms_enabled); } /* Helper function to set the duty cycle ratio to duty/4096 (e.g. duty=2048 -> 50%) */ static void pca9685_pwm_set_duty(struct pca9685 *pca, int channel, unsigned int duty) { if (duty == 0) { /* Set the full OFF bit, which has the highest precedence */ regmap_write(pca->regmap, REG_OFF_H(channel), LED_FULL); } else if (duty >= PCA9685_COUNTER_RANGE) { /* Set the full ON bit and clear the full OFF bit */ regmap_write(pca->regmap, REG_ON_H(channel), LED_FULL); regmap_write(pca->regmap, REG_OFF_H(channel), 0); } else { /* Set OFF time (clears the full OFF bit) */ regmap_write(pca->regmap, REG_OFF_L(channel), duty & 0xff); regmap_write(pca->regmap, REG_OFF_H(channel), (duty >> 8) & 0xf); /* Clear the full ON bit */ regmap_write(pca->regmap, REG_ON_H(channel), 0); } } static unsigned int pca9685_pwm_get_duty(struct pca9685 *pca, int channel) { unsigned int off_h = 0, val = 0; if (WARN_ON(channel >= PCA9685_MAXCHAN)) { /* HW does not support reading state of "all LEDs" channel */ return 0; } regmap_read(pca->regmap, LED_N_OFF_H(channel), &off_h); if (off_h & LED_FULL) { /* Full OFF bit is set */ return 0; } regmap_read(pca->regmap, LED_N_ON_H(channel), &val); if (val & LED_FULL) { /* Full ON bit is set */ return PCA9685_COUNTER_RANGE; } if (regmap_read(pca->regmap, LED_N_OFF_L(channel), &val)) { /* Reset val to 0 in case reading LED_N_OFF_L failed */ val = 0; } return ((off_h & 0xf) << 8) | (val & 0xff); } #if IS_ENABLED(CONFIG_GPIOLIB) static bool pca9685_pwm_test_and_set_inuse(struct pca9685 *pca, int pwm_idx) { bool is_inuse; mutex_lock(&pca->lock); if (pwm_idx >= PCA9685_MAXCHAN) { /* * "All LEDs" channel: * pretend already in use if any of the PWMs are requested */ if (!bitmap_empty(pca->pwms_inuse, PCA9685_MAXCHAN)) { is_inuse = true; goto out; } } else { /* * Regular channel: * pretend already in use if the "all LEDs" channel is requested */ if (test_bit(PCA9685_MAXCHAN, pca->pwms_inuse)) { is_inuse = true; goto out; } } is_inuse = test_and_set_bit(pwm_idx, pca->pwms_inuse); out: mutex_unlock(&pca->lock); return is_inuse; } static void pca9685_pwm_clear_inuse(struct pca9685 *pca, int pwm_idx) { mutex_lock(&pca->lock); clear_bit(pwm_idx, pca->pwms_inuse); mutex_unlock(&pca->lock); } static int pca9685_pwm_gpio_request(struct gpio_chip *gpio, unsigned int offset) { struct pca9685 *pca = gpiochip_get_data(gpio); if (pca9685_pwm_test_and_set_inuse(pca, offset)) return -EBUSY; pm_runtime_get_sync(pca->chip.dev); return 0; } static int pca9685_pwm_gpio_get(struct gpio_chip *gpio, unsigned int offset) { struct pca9685 *pca = gpiochip_get_data(gpio); return pca9685_pwm_get_duty(pca, offset) != 0; } static void pca9685_pwm_gpio_set(struct gpio_chip *gpio, unsigned int offset, int value) { struct pca9685 *pca = gpiochip_get_data(gpio); pca9685_pwm_set_duty(pca, offset, value ? PCA9685_COUNTER_RANGE : 0); } static void pca9685_pwm_gpio_free(struct gpio_chip *gpio, unsigned int offset) { struct pca9685 *pca = gpiochip_get_data(gpio); pca9685_pwm_set_duty(pca, offset, 0); pm_runtime_put(pca->chip.dev); pca9685_pwm_clear_inuse(pca, offset); } static int pca9685_pwm_gpio_get_direction(struct gpio_chip *chip, unsigned int offset) { /* Always out */ return GPIO_LINE_DIRECTION_OUT; } static int pca9685_pwm_gpio_direction_input(struct gpio_chip *gpio, unsigned int offset) { return -EINVAL; } static int pca9685_pwm_gpio_direction_output(struct gpio_chip *gpio, unsigned int offset, int value) { pca9685_pwm_gpio_set(gpio, offset, value); return 0; } /* * The PCA9685 has a bit for turning the PWM output full off or on. Some * boards like Intel Galileo actually uses these as normal GPIOs so we * expose a GPIO chip here which can exclusively take over the underlying * PWM channel. */ static int pca9685_pwm_gpio_probe(struct pca9685 *pca) { struct device *dev = pca->chip.dev; pca->gpio.label = dev_name(dev); pca->gpio.parent = dev; pca->gpio.request = pca9685_pwm_gpio_request; pca->gpio.free = pca9685_pwm_gpio_free; pca->gpio.get_direction = pca9685_pwm_gpio_get_direction; pca->gpio.direction_input = pca9685_pwm_gpio_direction_input; pca->gpio.direction_output = pca9685_pwm_gpio_direction_output; pca->gpio.get = pca9685_pwm_gpio_get; pca->gpio.set = pca9685_pwm_gpio_set; pca->gpio.base = -1; pca->gpio.ngpio = PCA9685_MAXCHAN; pca->gpio.can_sleep = true; return devm_gpiochip_add_data(dev, &pca->gpio, pca); } #else static inline bool pca9685_pwm_test_and_set_inuse(struct pca9685 *pca, int pwm_idx) { return false; } static inline void pca9685_pwm_clear_inuse(struct pca9685 *pca, int pwm_idx) { } static inline int pca9685_pwm_gpio_probe(struct pca9685 *pca) { return 0; } #endif static void pca9685_set_sleep_mode(struct pca9685 *pca, bool enable) { regmap_update_bits(pca->regmap, PCA9685_MODE1, MODE1_SLEEP, enable ? MODE1_SLEEP : 0); if (!enable) { /* Wait 500us for the oscillator to be back up */ udelay(500); } } static int __pca9685_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm, const struct pwm_state *state) { struct pca9685 *pca = to_pca(chip); unsigned long long duty, prescale; unsigned int val = 0; if (state->polarity != PWM_POLARITY_NORMAL) return -EINVAL; prescale = DIV_ROUND_CLOSEST_ULL(PCA9685_OSC_CLOCK_MHZ * state->period, PCA9685_COUNTER_RANGE * 1000) - 1; if (prescale < PCA9685_PRESCALE_MIN || prescale > PCA9685_PRESCALE_MAX) { dev_err(chip->dev, "pwm not changed: period out of bounds!\n"); return -EINVAL; } if (!state->enabled) { pca9685_pwm_set_duty(pca, pwm->hwpwm, 0); return 0; } regmap_read(pca->regmap, PCA9685_PRESCALE, &val); if (prescale != val) { if (!pca9685_prescaler_can_change(pca, pwm->hwpwm)) { dev_err(chip->dev, "pwm not changed: periods of enabled pwms must match!\n"); return -EBUSY; } /* * Putting the chip briefly into SLEEP mode * at this point won't interfere with the * pm_runtime framework, because the pm_runtime * state is guaranteed active here. */ /* Put chip into sleep mode */ pca9685_set_sleep_mode(pca, true); /* Change the chip-wide output frequency */ regmap_write(pca->regmap, PCA9685_PRESCALE, prescale); /* Wake the chip up */ pca9685_set_sleep_mode(pca, false); } duty = PCA9685_COUNTER_RANGE * state->duty_cycle; duty = DIV_ROUND_UP_ULL(duty, state->period); pca9685_pwm_set_duty(pca, pwm->hwpwm, duty); return 0; } static int pca9685_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm, const struct pwm_state *state) { struct pca9685 *pca = to_pca(chip); int ret; mutex_lock(&pca->lock); ret = __pca9685_pwm_apply(chip, pwm, state); if (ret == 0) { if (state->enabled) set_bit(pwm->hwpwm, pca->pwms_enabled); else clear_bit(pwm->hwpwm, pca->pwms_enabled); } mutex_unlock(&pca->lock); return ret; } static void pca9685_pwm_get_state(struct pwm_chip *chip, struct pwm_device *pwm, struct pwm_state *state) { struct pca9685 *pca = to_pca(chip); unsigned long long duty; unsigned int val = 0; /* Calculate (chip-wide) period from prescale value */ regmap_read(pca->regmap, PCA9685_PRESCALE, &val); /* * PCA9685_OSC_CLOCK_MHZ is 25, i.e. an integer divider of 1000. * The following calculation is therefore only a multiplication * and we are not losing precision. */ state->period = (PCA9685_COUNTER_RANGE * 1000 / PCA9685_OSC_CLOCK_MHZ) * (val + 1); /* The (per-channel) polarity is fixed */ state->polarity = PWM_POLARITY_NORMAL; if (pwm->hwpwm >= PCA9685_MAXCHAN) { /* * The "all LEDs" channel does not support HW readout * Return 0 and disabled for backwards compatibility */ state->duty_cycle = 0; state->enabled = false; return; } state->enabled = true; duty = pca9685_pwm_get_duty(pca, pwm->hwpwm); state->duty_cycle = DIV_ROUND_DOWN_ULL(duty * state->period, PCA9685_COUNTER_RANGE); } static int pca9685_pwm_request(struct pwm_chip *chip, struct pwm_device *pwm) { struct pca9685 *pca = to_pca(chip); if (pca9685_pwm_test_and_set_inuse(pca, pwm->hwpwm)) return -EBUSY; if (pwm->hwpwm < PCA9685_MAXCHAN) { /* PWMs - except the "all LEDs" channel - default to enabled */ mutex_lock(&pca->lock); set_bit(pwm->hwpwm, pca->pwms_enabled); mutex_unlock(&pca->lock); } pm_runtime_get_sync(chip->dev); return 0; } static void pca9685_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm) { struct pca9685 *pca = to_pca(chip); mutex_lock(&pca->lock); pca9685_pwm_set_duty(pca, pwm->hwpwm, 0); clear_bit(pwm->hwpwm, pca->pwms_enabled); mutex_unlock(&pca->lock); pm_runtime_put(chip->dev); pca9685_pwm_clear_inuse(pca, pwm->hwpwm); } static const struct pwm_ops pca9685_pwm_ops = { .apply = pca9685_pwm_apply, .get_state = pca9685_pwm_get_state, .request = pca9685_pwm_request, .free = pca9685_pwm_free, .owner = THIS_MODULE, }; static const struct regmap_config pca9685_regmap_i2c_config = { .reg_bits = 8, .val_bits = 8, .max_register = PCA9685_NUMREGS, .cache_type = REGCACHE_NONE, }; static int pca9685_pwm_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct pca9685 *pca; unsigned int reg; int ret; pca = devm_kzalloc(&client->dev, sizeof(*pca), GFP_KERNEL); if (!pca) return -ENOMEM; pca->regmap = devm_regmap_init_i2c(client, &pca9685_regmap_i2c_config); if (IS_ERR(pca->regmap)) { ret = PTR_ERR(pca->regmap); dev_err(&client->dev, "Failed to initialize register map: %d\n", ret); return ret; } i2c_set_clientdata(client, pca); mutex_init(&pca->lock); regmap_read(pca->regmap, PCA9685_MODE2, &reg); if (device_property_read_bool(&client->dev, "invert")) reg |= MODE2_INVRT; else reg &= ~MODE2_INVRT; if (device_property_read_bool(&client->dev, "open-drain")) reg &= ~MODE2_OUTDRV; else reg |= MODE2_OUTDRV; regmap_write(pca->regmap, PCA9685_MODE2, reg); /* Disable all LED ALLCALL and SUBx addresses to avoid bus collisions */ regmap_read(pca->regmap, PCA9685_MODE1, &reg); reg &= ~(MODE1_ALLCALL | MODE1_SUB1 | MODE1_SUB2 | MODE1_SUB3); regmap_write(pca->regmap, PCA9685_MODE1, reg); /* Reset OFF registers to POR default */ regmap_write(pca->regmap, PCA9685_ALL_LED_OFF_L, LED_FULL); regmap_write(pca->regmap, PCA9685_ALL_LED_OFF_H, LED_FULL); pca->chip.ops = &pca9685_pwm_ops; /* Add an extra channel for ALL_LED */ pca->chip.npwm = PCA9685_MAXCHAN + 1; pca->chip.dev = &client->dev; ret = pwmchip_add(&pca->chip); if (ret < 0) return ret; ret = pca9685_pwm_gpio_probe(pca); if (ret < 0) { pwmchip_remove(&pca->chip); return ret; } pm_runtime_enable(&client->dev); if (pm_runtime_enabled(&client->dev)) { /* * Although the chip comes out of power-up in the sleep state, * we force it to sleep in case it was woken up before */ pca9685_set_sleep_mode(pca, true); pm_runtime_set_suspended(&client->dev); } else { /* Wake the chip up if runtime PM is disabled */ pca9685_set_sleep_mode(pca, false); } return 0; } static int pca9685_pwm_remove(struct i2c_client *client) { struct pca9685 *pca = i2c_get_clientdata(client); int ret; //ret = pwmchip_remove(&pca->chip); pwmchip_remove(&pca->chip); //if (ret) // return ret; if (!pm_runtime_enabled(&client->dev)) { /* Put chip in sleep state if runtime PM is disabled */ pca9685_set_sleep_mode(pca, true); } pm_runtime_disable(&client->dev); return 0; } static int __maybe_unused pca9685_pwm_runtime_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct pca9685 *pca = i2c_get_clientdata(client); pca9685_set_sleep_mode(pca, true); return 0; } static int __maybe_unused pca9685_pwm_runtime_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct pca9685 *pca = i2c_get_clientdata(client); pca9685_set_sleep_mode(pca, false); return 0; } static const struct i2c_device_id pca9685_id[] = { { "pca9685", 0 }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(i2c, pca9685_id); #ifdef CONFIG_ACPI static const struct acpi_device_id pca9685_acpi_ids[] = { { "INT3492", 0 }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(acpi, pca9685_acpi_ids); #endif #ifdef CONFIG_OF static const struct of_device_id pca9685_dt_ids[] = { { .compatible = "nxp,pca9685-pwm", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, pca9685_dt_ids); #endif static const struct dev_pm_ops pca9685_pwm_pm = { SET_RUNTIME_PM_OPS(pca9685_pwm_runtime_suspend, pca9685_pwm_runtime_resume, NULL) }; static struct i2c_driver pca9685_i2c_driver = { .driver = { .name = "pca9685-pwm", .acpi_match_table = ACPI_PTR(pca9685_acpi_ids), .of_match_table = of_match_ptr(pca9685_dt_ids), .pm = &pca9685_pwm_pm, }, .probe = pca9685_pwm_probe, .remove = pca9685_pwm_remove, .id_table = pca9685_id, }; module_i2c_driver(pca9685_i2c_driver); MODULE_AUTHOR("Steffen Trumtrar <s.trumtrar@pengutronix.de>"); MODULE_DESCRIPTION("PWM driver for PCA9685"); MODULE_LICENSE("GPL");
16,597
C
25.901134
88
0.685124
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/EEPROM/at24.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * at24.c - handle most I2C EEPROMs * * Copyright (C) 2005-2007 David Brownell * Copyright (C) 2008 Wolfram Sang, Pengutronix */ #include <linux/acpi.h> #include <linux/bitops.h> #include <linux/capability.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/nvmem-provider.h> #include <linux/of_device.h> #include <linux/pm_runtime.h> #include <linux/property.h> #include <linux/regmap.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> /* Address pointer is 16 bit. */ #define AT24_FLAG_ADDR16 BIT(7) /* sysfs-entry will be read-only. */ #define AT24_FLAG_READONLY BIT(6) /* sysfs-entry will be world-readable. */ #define AT24_FLAG_IRUGO BIT(5) /* Take always 8 addresses (24c00). */ #define AT24_FLAG_TAKE8ADDR BIT(4) /* Factory-programmed serial number. */ #define AT24_FLAG_SERIAL BIT(3) /* Factory-programmed mac address. */ #define AT24_FLAG_MAC BIT(2) /* Does not auto-rollover reads to the next slave address. */ #define AT24_FLAG_NO_RDROL BIT(1) /* * I2C EEPROMs from most vendors are inexpensive and mostly interchangeable. * Differences between different vendor product lines (like Atmel AT24C or * MicroChip 24LC, etc) won't much matter for typical read/write access. * There are also I2C RAM chips, likewise interchangeable. One example * would be the PCF8570, which acts like a 24c02 EEPROM (256 bytes). * * However, misconfiguration can lose data. "Set 16-bit memory address" * to a part with 8-bit addressing will overwrite data. Writing with too * big a page size also loses data. And it's not safe to assume that the * conventional addresses 0x50..0x57 only hold eeproms; a PCF8563 RTC * uses 0x51, for just one example. * * Accordingly, explicit board-specific configuration data should be used * in almost all cases. (One partial exception is an SMBus used to access * "SPD" data for DRAM sticks. Those only use 24c02 EEPROMs.) * * So this driver uses "new style" I2C driver binding, expecting to be * told what devices exist. That may be in arch/X/mach-Y/board-Z.c or * similar kernel-resident tables; or, configuration data coming from * a bootloader. * * Other than binding model, current differences from "eeprom" driver are * that this one handles write access and isn't restricted to 24c02 devices. * It also handles larger devices (32 kbit and up) with two-byte addresses, * which won't work on pure SMBus systems. */ struct at24_client { struct i2c_client *client; struct regmap *regmap; }; struct at24_data { /* * Lock protects against activities from other Linux tasks, * but not from changes by other I2C masters. */ struct mutex lock; unsigned int write_max; unsigned int num_addresses; unsigned int offset_adj; u32 byte_len; u16 page_size; u8 flags; struct nvmem_device *nvmem; struct regulator *vcc_reg; void (*read_post)(unsigned int off, char *buf, size_t count); /* * Some chips tie up multiple I2C addresses; dummy devices reserve * them for us, and we'll use them with SMBus calls. */ struct at24_client client[]; }; /* * This parameter is to help this driver avoid blocking other drivers out * of I2C for potentially troublesome amounts of time. With a 100 kHz I2C * clock, one 256 byte read takes about 1/43 second which is excessive; * but the 1/170 second it takes at 400 kHz may be quite reasonable; and * at 1 MHz (Fm+) a 1/430 second delay could easily be invisible. * * This value is forced to be a power of two so that writes align on pages. */ static unsigned int at24_io_limit = 128; module_param_named(io_limit, at24_io_limit, uint, 0); MODULE_PARM_DESC(at24_io_limit, "Maximum bytes per I/O (default 128)"); /* * Specs often allow 5 msec for a page write, sometimes 20 msec; * it's important to recover from write timeouts. */ static unsigned int at24_write_timeout = 25; module_param_named(write_timeout, at24_write_timeout, uint, 0); MODULE_PARM_DESC(at24_write_timeout, "Time (in ms) to try writes (default 25)"); struct at24_chip_data { u32 byte_len; u8 flags; void (*read_post)(unsigned int off, char *buf, size_t count); }; #define AT24_CHIP_DATA(_name, _len, _flags) \ static const struct at24_chip_data _name = { \ .byte_len = _len, .flags = _flags, \ } #define AT24_CHIP_DATA_CB(_name, _len, _flags, _read_post) \ static const struct at24_chip_data _name = { \ .byte_len = _len, .flags = _flags, \ .read_post = _read_post, \ } static void at24_read_post_vaio(unsigned int off, char *buf, size_t count) { int i; if (capable(CAP_SYS_ADMIN)) return; /* * Hide VAIO private settings to regular users: * - BIOS passwords: bytes 0x00 to 0x0f * - UUID: bytes 0x10 to 0x1f * - Serial number: 0xc0 to 0xdf */ for (i = 0; i < count; i++) { if ((off + i <= 0x1f) || (off + i >= 0xc0 && off + i <= 0xdf)) buf[i] = 0; } } /* needs 8 addresses as A0-A2 are ignored */ AT24_CHIP_DATA(at24_data_24c00, 128 / 8, AT24_FLAG_TAKE8ADDR); /* old variants can't be handled with this generic entry! */ AT24_CHIP_DATA(at24_data_24c01, 1024 / 8, 0); AT24_CHIP_DATA(at24_data_24cs01, 16, AT24_FLAG_SERIAL | AT24_FLAG_READONLY); AT24_CHIP_DATA(at24_data_24c02, 2048 / 8, 0); AT24_CHIP_DATA(at24_data_24cs02, 16, AT24_FLAG_SERIAL | AT24_FLAG_READONLY); AT24_CHIP_DATA(at24_data_24mac402, 48 / 8, AT24_FLAG_MAC | AT24_FLAG_READONLY); AT24_CHIP_DATA(at24_data_24mac602, 64 / 8, AT24_FLAG_MAC | AT24_FLAG_READONLY); /* spd is a 24c02 in memory DIMMs */ AT24_CHIP_DATA(at24_data_spd, 2048 / 8, AT24_FLAG_READONLY | AT24_FLAG_IRUGO); /* 24c02_vaio is a 24c02 on some Sony laptops */ AT24_CHIP_DATA_CB(at24_data_24c02_vaio, 2048 / 8, AT24_FLAG_READONLY | AT24_FLAG_IRUGO, at24_read_post_vaio); AT24_CHIP_DATA(at24_data_24c04, 4096 / 8, 0); AT24_CHIP_DATA(at24_data_24cs04, 16, AT24_FLAG_SERIAL | AT24_FLAG_READONLY); /* 24rf08 quirk is handled at i2c-core */ AT24_CHIP_DATA(at24_data_24c08, 8192 / 8, 0); AT24_CHIP_DATA(at24_data_24cs08, 16, AT24_FLAG_SERIAL | AT24_FLAG_READONLY); AT24_CHIP_DATA(at24_data_24c16, 16384 / 8, 0); AT24_CHIP_DATA(at24_data_24cs16, 16, AT24_FLAG_SERIAL | AT24_FLAG_READONLY); AT24_CHIP_DATA(at24_data_24c32, 32768 / 8, AT24_FLAG_ADDR16); AT24_CHIP_DATA(at24_data_24cs32, 16, AT24_FLAG_ADDR16 | AT24_FLAG_SERIAL | AT24_FLAG_READONLY); AT24_CHIP_DATA(at24_data_24c64, 65536 / 8, AT24_FLAG_ADDR16); AT24_CHIP_DATA(at24_data_24cs64, 16, AT24_FLAG_ADDR16 | AT24_FLAG_SERIAL | AT24_FLAG_READONLY); AT24_CHIP_DATA(at24_data_24c128, 131072 / 8, AT24_FLAG_ADDR16); AT24_CHIP_DATA(at24_data_24c256, 262144 / 8, AT24_FLAG_ADDR16); AT24_CHIP_DATA(at24_data_24c512, 524288 / 8, AT24_FLAG_ADDR16); AT24_CHIP_DATA(at24_data_24c1024, 1048576 / 8, AT24_FLAG_ADDR16); AT24_CHIP_DATA(at24_data_24c2048, 2097152 / 8, AT24_FLAG_ADDR16); /* identical to 24c08 ? */ AT24_CHIP_DATA(at24_data_INT3499, 8192 / 8, 0); static const struct i2c_device_id at24_ids[] = { { "24c00", (kernel_ulong_t)&at24_data_24c00 }, { "24c01", (kernel_ulong_t)&at24_data_24c01 }, { "24cs01", (kernel_ulong_t)&at24_data_24cs01 }, { "24c02", (kernel_ulong_t)&at24_data_24c02 }, { "24cs02", (kernel_ulong_t)&at24_data_24cs02 }, { "24mac402", (kernel_ulong_t)&at24_data_24mac402 }, { "24mac602", (kernel_ulong_t)&at24_data_24mac602 }, { "spd", (kernel_ulong_t)&at24_data_spd }, { "24c02-vaio", (kernel_ulong_t)&at24_data_24c02_vaio }, { "24c04", (kernel_ulong_t)&at24_data_24c04 }, { "24cs04", (kernel_ulong_t)&at24_data_24cs04 }, { "24c08", (kernel_ulong_t)&at24_data_24c08 }, { "24cs08", (kernel_ulong_t)&at24_data_24cs08 }, { "24c16", (kernel_ulong_t)&at24_data_24c16 }, { "24cs16", (kernel_ulong_t)&at24_data_24cs16 }, { "24c32", (kernel_ulong_t)&at24_data_24c32 }, { "24cs32", (kernel_ulong_t)&at24_data_24cs32 }, { "24c64", (kernel_ulong_t)&at24_data_24c64 }, { "24cs64", (kernel_ulong_t)&at24_data_24cs64 }, { "24c128", (kernel_ulong_t)&at24_data_24c128 }, { "24c256", (kernel_ulong_t)&at24_data_24c256 }, { "24c512", (kernel_ulong_t)&at24_data_24c512 }, { "24c1024", (kernel_ulong_t)&at24_data_24c1024 }, { "24c2048", (kernel_ulong_t)&at24_data_24c2048 }, { "at24", 0 }, { /* END OF LIST */ } }; MODULE_DEVICE_TABLE(i2c, at24_ids); static const struct of_device_id at24_of_match[] = { { .compatible = "atmel,24c00", .data = &at24_data_24c00 }, { .compatible = "atmel,24c01", .data = &at24_data_24c01 }, { .compatible = "atmel,24cs01", .data = &at24_data_24cs01 }, { .compatible = "atmel,24c02", .data = &at24_data_24c02 }, { .compatible = "atmel,24cs02", .data = &at24_data_24cs02 }, { .compatible = "atmel,24mac402", .data = &at24_data_24mac402 }, { .compatible = "atmel,24mac602", .data = &at24_data_24mac602 }, { .compatible = "atmel,spd", .data = &at24_data_spd }, { .compatible = "atmel,24c04", .data = &at24_data_24c04 }, { .compatible = "atmel,24cs04", .data = &at24_data_24cs04 }, { .compatible = "atmel,24c08", .data = &at24_data_24c08 }, { .compatible = "atmel,24cs08", .data = &at24_data_24cs08 }, { .compatible = "atmel,24c16", .data = &at24_data_24c16 }, { .compatible = "atmel,24cs16", .data = &at24_data_24cs16 }, { .compatible = "atmel,24c32", .data = &at24_data_24c32 }, { .compatible = "atmel,24cs32", .data = &at24_data_24cs32 }, { .compatible = "atmel,24c64", .data = &at24_data_24c64 }, { .compatible = "atmel,24cs64", .data = &at24_data_24cs64 }, { .compatible = "atmel,24c128", .data = &at24_data_24c128 }, { .compatible = "atmel,24c256", .data = &at24_data_24c256 }, { .compatible = "atmel,24c512", .data = &at24_data_24c512 }, { .compatible = "atmel,24c1024", .data = &at24_data_24c1024 }, { .compatible = "atmel,24c2048", .data = &at24_data_24c2048 }, { /* END OF LIST */ }, }; MODULE_DEVICE_TABLE(of, at24_of_match); static const struct acpi_device_id __maybe_unused at24_acpi_ids[] = { { "INT3499", (kernel_ulong_t)&at24_data_INT3499 }, { "TPF0001", (kernel_ulong_t)&at24_data_24c1024 }, { /* END OF LIST */ } }; MODULE_DEVICE_TABLE(acpi, at24_acpi_ids); /* * This routine supports chips which consume multiple I2C addresses. It * computes the addressing information to be used for a given r/w request. * Assumes that sanity checks for offset happened at sysfs-layer. * * Slave address and byte offset derive from the offset. Always * set the byte address; on a multi-master board, another master * may have changed the chip's "current" address pointer. */ static struct at24_client *at24_translate_offset(struct at24_data *at24, unsigned int *offset) { unsigned int i; if (at24->flags & AT24_FLAG_ADDR16) { i = *offset >> 16; *offset &= 0xffff; } else { i = *offset >> 8; *offset &= 0xff; } return &at24->client[i]; } static struct device *at24_base_client_dev(struct at24_data *at24) { return &at24->client[0].client->dev; } static size_t at24_adjust_read_count(struct at24_data *at24, unsigned int offset, size_t count) { unsigned int bits; size_t remainder; /* * In case of multi-address chips that don't rollover reads to * the next slave address: truncate the count to the slave boundary, * so that the read never straddles slaves. */ if (at24->flags & AT24_FLAG_NO_RDROL) { bits = (at24->flags & AT24_FLAG_ADDR16) ? 16 : 8; remainder = BIT(bits) - offset; if (count > remainder) count = remainder; } if (count > at24_io_limit) count = at24_io_limit; return count; } static ssize_t at24_regmap_read(struct at24_data *at24, char *buf, unsigned int offset, size_t count) { unsigned long timeout, read_time; struct at24_client *at24_client; struct i2c_client *client; struct regmap *regmap; int ret; at24_client = at24_translate_offset(at24, &offset); regmap = at24_client->regmap; client = at24_client->client; count = at24_adjust_read_count(at24, offset, count); /* adjust offset for mac and serial read ops */ offset += at24->offset_adj; timeout = jiffies + msecs_to_jiffies(at24_write_timeout); do { /* * The timestamp shall be taken before the actual operation * to avoid a premature timeout in case of high CPU load. */ read_time = jiffies; ret = regmap_bulk_read(regmap, offset, buf, count); dev_dbg(&client->dev, "read %zu@%d --> %d (%ld)\n", count, offset, ret, jiffies); if (!ret) return count; usleep_range(1000, 1500); } while (time_before(read_time, timeout)); return -ETIMEDOUT; } /* * Note that if the hardware write-protect pin is pulled high, the whole * chip is normally write protected. But there are plenty of product * variants here, including OTP fuses and partial chip protect. * * We only use page mode writes; the alternative is sloooow. These routines * write at most one page. */ static size_t at24_adjust_write_count(struct at24_data *at24, unsigned int offset, size_t count) { unsigned int next_page; /* write_max is at most a page */ if (count > at24->write_max) count = at24->write_max; /* Never roll over backwards, to the start of this page */ next_page = roundup(offset + 1, at24->page_size); if (offset + count > next_page) count = next_page - offset; return count; } static ssize_t at24_regmap_write(struct at24_data *at24, const char *buf, unsigned int offset, size_t count) { unsigned long timeout, write_time; struct at24_client *at24_client; struct i2c_client *client; struct regmap *regmap; int ret; at24_client = at24_translate_offset(at24, &offset); regmap = at24_client->regmap; client = at24_client->client; count = at24_adjust_write_count(at24, offset, count); timeout = jiffies + msecs_to_jiffies(at24_write_timeout); do { /* * The timestamp shall be taken before the actual operation * to avoid a premature timeout in case of high CPU load. */ write_time = jiffies; ret = regmap_bulk_write(regmap, offset, buf, count); dev_dbg(&client->dev, "write %zu@%d --> %d (%ld)\n", count, offset, ret, jiffies); if (!ret) return count; usleep_range(1000, 1500); } while (time_before(write_time, timeout)); return -ETIMEDOUT; } static int at24_read(void *priv, unsigned int off, void *val, size_t count) { struct at24_data *at24; struct device *dev; char *buf = val; int i, ret; at24 = priv; dev = at24_base_client_dev(at24); if (unlikely(!count)) return count; if (off + count > at24->byte_len) return -EINVAL; ret = pm_runtime_get_sync(dev); if (ret < 0) { pm_runtime_put_noidle(dev); return ret; } /* * Read data from chip, protecting against concurrent updates * from this host, but not from other I2C masters. */ mutex_lock(&at24->lock); for (i = 0; count; i += ret, count -= ret) { ret = at24_regmap_read(at24, buf + i, off + i, count); if (ret < 0) { mutex_unlock(&at24->lock); pm_runtime_put(dev); return ret; } } mutex_unlock(&at24->lock); pm_runtime_put(dev); if (unlikely(at24->read_post)) at24->read_post(off, buf, i); return 0; } static int at24_write(void *priv, unsigned int off, void *val, size_t count) { struct at24_data *at24; struct device *dev; char *buf = val; int ret; at24 = priv; dev = at24_base_client_dev(at24); if (unlikely(!count)) return -EINVAL; if (off + count > at24->byte_len) return -EINVAL; ret = pm_runtime_get_sync(dev); if (ret < 0) { pm_runtime_put_noidle(dev); return ret; } /* * Write data to chip, protecting against concurrent updates * from this host, but not from other I2C masters. */ mutex_lock(&at24->lock); while (count) { ret = at24_regmap_write(at24, buf, off, count); if (ret < 0) { mutex_unlock(&at24->lock); pm_runtime_put(dev); return ret; } buf += ret; off += ret; count -= ret; } mutex_unlock(&at24->lock); pm_runtime_put(dev); return 0; } static const struct at24_chip_data *at24_get_chip_data(struct device *dev) { struct device_node *of_node = dev->of_node; const struct at24_chip_data *cdata; const struct i2c_device_id *id; id = i2c_match_id(at24_ids, to_i2c_client(dev)); /* * The I2C core allows OF nodes compatibles to match against the * I2C device ID table as a fallback, so check not only if an OF * node is present but also if it matches an OF device ID entry. */ if (of_node && of_match_device(at24_of_match, dev)) cdata = of_device_get_match_data(dev); else if (id) cdata = (void *)id->driver_data; else cdata = acpi_device_get_match_data(dev); if (!cdata) return ERR_PTR(-ENODEV); return cdata; } static int at24_make_dummy_client(struct at24_data *at24, unsigned int index, struct regmap_config *regmap_config) { struct i2c_client *base_client, *dummy_client; struct regmap *regmap; struct device *dev; base_client = at24->client[0].client; dev = &base_client->dev; dummy_client = devm_i2c_new_dummy_device(dev, base_client->adapter, base_client->addr + index); if (IS_ERR(dummy_client)) return PTR_ERR(dummy_client); regmap = devm_regmap_init_i2c(dummy_client, regmap_config); if (IS_ERR(regmap)) return PTR_ERR(regmap); at24->client[index].client = dummy_client; at24->client[index].regmap = regmap; return 0; } static unsigned int at24_get_offset_adj(u8 flags, unsigned int byte_len) { if (flags & AT24_FLAG_MAC) { /* EUI-48 starts from 0x9a, EUI-64 from 0x98 */ return 0xa0 - byte_len; } else if (flags & AT24_FLAG_SERIAL && flags & AT24_FLAG_ADDR16) { /* * For 16 bit address pointers, the word address must contain * a '10' sequence in bits 11 and 10 regardless of the * intended position of the address pointer. */ return 0x0800; } else if (flags & AT24_FLAG_SERIAL) { /* * Otherwise the word address must begin with a '10' sequence, * regardless of the intended address. */ return 0x0080; } else { return 0; } } static int at24_probe(struct i2c_client *client) { struct regmap_config regmap_config = { }; struct nvmem_config nvmem_config = { }; u32 byte_len, page_size, flags, addrw; const struct at24_chip_data *cdata; struct device *dev = &client->dev; bool i2c_fn_i2c, i2c_fn_block; unsigned int i, num_addresses; struct at24_data *at24; struct regmap *regmap; bool writable; u8 test_byte; int err; i2c_fn_i2c = i2c_check_functionality(client->adapter, I2C_FUNC_I2C); i2c_fn_block = i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WRITE_I2C_BLOCK); cdata = at24_get_chip_data(dev); if (IS_ERR(cdata)) return PTR_ERR(cdata); err = device_property_read_u32(dev, "pagesize", &page_size); if (err) /* * This is slow, but we can't know all eeproms, so we better * play safe. Specifying custom eeprom-types via device tree * or properties is recommended anyhow. */ page_size = 1; flags = cdata->flags; if (device_property_present(dev, "read-only")) flags |= AT24_FLAG_READONLY; if (device_property_present(dev, "no-read-rollover")) flags |= AT24_FLAG_NO_RDROL; err = device_property_read_u32(dev, "address-width", &addrw); if (!err) { switch (addrw) { case 8: if (flags & AT24_FLAG_ADDR16) dev_warn(dev, "Override address width to be 8, while default is 16\n"); flags &= ~AT24_FLAG_ADDR16; break; case 16: flags |= AT24_FLAG_ADDR16; break; default: dev_warn(dev, "Bad \"address-width\" property: %u\n", addrw); } } err = device_property_read_u32(dev, "size", &byte_len); if (err) byte_len = cdata->byte_len; if (!i2c_fn_i2c && !i2c_fn_block) page_size = 1; if (!page_size) { dev_err(dev, "page_size must not be 0!\n"); return -EINVAL; } if (!is_power_of_2(page_size)) dev_warn(dev, "page_size looks suspicious (no power of 2)!\n"); err = device_property_read_u32(dev, "num-addresses", &num_addresses); if (err) { if (flags & AT24_FLAG_TAKE8ADDR) num_addresses = 8; else num_addresses = DIV_ROUND_UP(byte_len, (flags & AT24_FLAG_ADDR16) ? 65536 : 256); } if ((flags & AT24_FLAG_SERIAL) && (flags & AT24_FLAG_MAC)) { dev_err(dev, "invalid device data - cannot have both AT24_FLAG_SERIAL & AT24_FLAG_MAC."); return -EINVAL; } regmap_config.val_bits = 8; regmap_config.reg_bits = (flags & AT24_FLAG_ADDR16) ? 16 : 8; regmap_config.disable_locking = true; regmap = devm_regmap_init_i2c(client, &regmap_config); if (IS_ERR(regmap)) return PTR_ERR(regmap); at24 = devm_kzalloc(dev, struct_size(at24, client, num_addresses), GFP_KERNEL); if (!at24) return -ENOMEM; mutex_init(&at24->lock); at24->byte_len = byte_len; at24->page_size = page_size; at24->flags = flags; at24->read_post = cdata->read_post; at24->num_addresses = num_addresses; at24->offset_adj = at24_get_offset_adj(flags, byte_len); at24->client[0].client = client; at24->client[0].regmap = regmap; at24->vcc_reg = devm_regulator_get(dev, "vcc"); if (IS_ERR(at24->vcc_reg)) return PTR_ERR(at24->vcc_reg); writable = !(flags & AT24_FLAG_READONLY); if (writable) { at24->write_max = min_t(unsigned int, page_size, at24_io_limit); if (!i2c_fn_i2c && at24->write_max > I2C_SMBUS_BLOCK_MAX) at24->write_max = I2C_SMBUS_BLOCK_MAX; } /* use dummy devices for multiple-address chips */ for (i = 1; i < num_addresses; i++) { err = at24_make_dummy_client(at24, i, &regmap_config); if (err) return err; } /* * We initialize nvmem_config.id to NVMEM_DEVID_AUTO even if the * label property is set as some platform can have multiple eeproms * with same label and we can not register each of those with same * label. Failing to register those eeproms trigger cascade failure * on such platform. */ nvmem_config.id = NVMEM_DEVID_AUTO; if (device_property_present(dev, "label")) { err = device_property_read_string(dev, "label", &nvmem_config.name); if (err) return err; } else { nvmem_config.name = dev_name(dev); } nvmem_config.type = NVMEM_TYPE_EEPROM; nvmem_config.dev = dev; nvmem_config.read_only = !writable; nvmem_config.root_only = !(flags & AT24_FLAG_IRUGO); nvmem_config.owner = THIS_MODULE; nvmem_config.compat = true; nvmem_config.base_dev = dev; nvmem_config.reg_read = at24_read; nvmem_config.reg_write = at24_write; nvmem_config.priv = at24; nvmem_config.stride = 1; nvmem_config.word_size = 1; nvmem_config.size = byte_len; i2c_set_clientdata(client, at24); err = regulator_enable(at24->vcc_reg); if (err) { dev_err(dev, "Failed to enable vcc regulator\n"); return err; } /* enable runtime pm */ pm_runtime_set_active(dev); pm_runtime_enable(dev); at24->nvmem = devm_nvmem_register(dev, &nvmem_config); if (IS_ERR(at24->nvmem)) { pm_runtime_disable(dev); if (!pm_runtime_status_suspended(dev)) regulator_disable(at24->vcc_reg); return PTR_ERR(at24->nvmem); } /* * Perform a one-byte test read to verify that the * chip is functional. */ err = at24_read(at24, 0, &test_byte, 1); if (err) { pm_runtime_disable(dev); if (!pm_runtime_status_suspended(dev)) regulator_disable(at24->vcc_reg); return -ENODEV; } pm_runtime_idle(dev); if (writable) dev_info(dev, "%u byte %s EEPROM, writable, %u bytes/write\n", byte_len, client->name, at24->write_max); else dev_info(dev, "%u byte %s EEPROM, read-only\n", byte_len, client->name); return 0; } static int at24_remove(struct i2c_client *client) { struct at24_data *at24 = i2c_get_clientdata(client); pm_runtime_disable(&client->dev); if (!pm_runtime_status_suspended(&client->dev)) regulator_disable(at24->vcc_reg); pm_runtime_set_suspended(&client->dev); return 0; } static int __maybe_unused at24_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct at24_data *at24 = i2c_get_clientdata(client); return regulator_disable(at24->vcc_reg); } static int __maybe_unused at24_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct at24_data *at24 = i2c_get_clientdata(client); return regulator_enable(at24->vcc_reg); } static const struct dev_pm_ops at24_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume) SET_RUNTIME_PM_OPS(at24_suspend, at24_resume, NULL) }; static struct i2c_driver at24_driver = { .driver = { .name = "at24", .pm = &at24_pm_ops, .of_match_table = at24_of_match, .acpi_match_table = ACPI_PTR(at24_acpi_ids), }, .probe_new = at24_probe, .remove = at24_remove, .id_table = at24_ids, }; static int __init at24_init(void) { if (!at24_io_limit) { pr_err("at24: at24_io_limit must not be 0!\n"); return -EINVAL; } at24_io_limit = rounddown_pow_of_two(at24_io_limit); return i2c_add_driver(&at24_driver); } module_init(at24_init); static void __exit at24_exit(void) { i2c_del_driver(&at24_driver); } module_exit(at24_exit); MODULE_DESCRIPTION("Driver for most I2C EEPROMs"); MODULE_AUTHOR("David Brownell and Wolfram Sang"); MODULE_LICENSE("GPL");
24,923
C
28.015134
80
0.676443
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/__init__.py
from __future__ import absolute_import from Mangdang.Adafruit_GPIO.GPIO import *
82
Python
19.749995
41
0.780488
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/Platform.py
# Copyright (c) 2014 Adafruit Industries # Author: Tony DiCola # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import platform import re # Platform identification constants. UNKNOWN = 0 RASPBERRY_PI = 1 BEAGLEBONE_BLACK = 2 MINNOWBOARD = 3 JETSON_NANO = 4 def platform_detect(): """Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.""" # Handle Raspberry Pi pi = pi_version() if pi is not None: return RASPBERRY_PI # Handle Beaglebone Black # TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading # the platform. plat = platform.platform() if plat.lower().find('armv7l-with-debian') > -1: return BEAGLEBONE_BLACK elif plat.lower().find('armv7l-with-ubuntu') > -1: return BEAGLEBONE_BLACK elif plat.lower().find('armv7l-with-glibc2.4') > -1: return BEAGLEBONE_BLACK elif plat.lower().find('tegra-aarch64-with-ubuntu') > -1: return JETSON_NANO # Handle Minnowboard # Assumption is that mraa is installed try: import mraa if mraa.getPlatformName()=='MinnowBoard MAX': return MINNOWBOARD except ImportError: pass # Couldn't figure out the platform, just return unknown. return UNKNOWN def pi_revision(): """Detect the revision number of a Raspberry Pi, useful for changing functionality like default I2C bus based on revision.""" # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History with open('/proc/cpuinfo', 'r') as infile: for line in infile: # Match a line of the form "Revision : 0002" while ignoring extra # info in front of the revsion (like 1000 when the Pi was over-volted). match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE) if match and match.group(1) in ['0000', '0002', '0003']: # Return revision 1 if revision ends with 0000, 0002 or 0003. return 1 elif match: # Assume revision 2 if revision ends with any other 4 chars. return 2 # Couldn't find the revision, throw an exception. raise RuntimeError('Could not determine Raspberry Pi revision.') def pi_version(): """Detect the version of the Raspberry Pi. Returns either 1, 2 or None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+), Raspberry Pi 2 (model B+), or not a Raspberry Pi. """ # Check /proc/cpuinfo for the Hardware field value. # 2708 is pi 1 # 2709 is pi 2 # 2835 is pi 3 on 4.9.x kernel # Anything else is not a pi. with open('/proc/cpuinfo', 'r') as infile: cpuinfo = infile.read() # Match a line like 'Hardware : BCM2709' match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo, flags=re.MULTILINE | re.IGNORECASE) if not match: # Couldn't find the hardware, assume it isn't a pi. return None if match.group(1) == 'BCM2708': # Pi 1 return 1 elif match.group(1) == 'BCM2709': # Pi 2 return 2 elif match.group(1) == 'BCM2835': # Pi 3 / Pi on 4.9.x kernel return 3 else: # Something else, not a pi. return None
4,413
Python
37.719298
94
0.65375
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/GPIO.py
# Copyright (c) 2014 Adafruit Industries # Author: Tony DiCola # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import Adafruit_GPIO.Platform as Platform OUT = 0 IN = 1 HIGH = True LOW = False RISING = 1 FALLING = 2 BOTH = 3 PUD_OFF = 0 PUD_DOWN = 1 PUD_UP = 2 class BaseGPIO(object): """Base class for implementing simple digital IO for a platform. Implementors are expected to subclass from this and provide an implementation of the setup, output, and input functions.""" def setup(self, pin, mode, pull_up_down=PUD_OFF): """Set the input or output mode for a specified pin. Mode should be either OUT or IN.""" raise NotImplementedError def output(self, pin, value): """Set the specified pin the provided high/low value. Value should be either HIGH/LOW or a boolean (true = high).""" raise NotImplementedError def input(self, pin): """Read the specified pin and return HIGH/true if the pin is pulled high, or LOW/false if pulled low.""" raise NotImplementedError def set_high(self, pin): """Set the specified pin HIGH.""" self.output(pin, HIGH) def set_low(self, pin): """Set the specified pin LOW.""" self.output(pin, LOW) def is_high(self, pin): """Return true if the specified pin is pulled high.""" return self.input(pin) == HIGH def is_low(self, pin): """Return true if the specified pin is pulled low.""" return self.input(pin) == LOW # Basic implementation of multiple pin methods just loops through pins and # processes each one individually. This is not optimal, but derived classes can # provide a more optimal implementation that deals with groups of pins # simultaneously. # See MCP230xx or PCF8574 classes for examples of optimized implementations. def output_pins(self, pins): """Set multiple pins high or low at once. Pins should be a dict of pin name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins will be set to the given values. """ # General implementation just loops through pins and writes them out # manually. This is not optimized, but subclasses can choose to implement # a more optimal batch output implementation. See the MCP230xx class for # example of optimized implementation. for pin, value in iter(pins.items()): self.output(pin, value) def setup_pins(self, pins): """Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin type (IN or OUT). """ # General implementation that can be optimized by derived classes. for pin, value in iter(pins.items()): self.setup(pin, value) def input_pins(self, pins): """Read multiple pins specified in the given list and return list of pin values GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low. """ # General implementation that can be optimized by derived classes. return [self.input(pin) for pin in pins] def add_event_detect(self, pin, edge): """Enable edge detection events for a particular GPIO channel. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ raise NotImplementedError def remove_event_detect(self, pin): """Remove edge detection for a particular GPIO channel. Pin should be type IN. """ raise NotImplementedError def add_event_callback(self, pin, callback): """Add a callback for an event already defined using add_event_detect(). Pin should be type IN. """ raise NotImplementedError def event_detected(self, pin): """Returns True if an edge has occured on a given GPIO. You need to enable edge detection using add_event_detect() first. Pin should be type IN. """ raise NotImplementedError def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH.""" raise NotImplementedError def cleanup(self, pin=None): """Clean up GPIO event detection for specific pin, or all pins if none is specified. """ raise NotImplementedError # helper functions useful to derived classes def _validate_pin(self, pin): # Raise an exception if pin is outside the range of allowed values. if pin < 0 or pin >= self.NUM_GPIO: raise ValueError('Invalid GPIO value, must be between 0 and {0}.'.format(self.NUM_GPIO)) def _bit2(self, src, bit, val): bit = 1 << bit return (src | bit) if val else (src & ~bit) class RPiGPIOAdapter(BaseGPIO): """GPIO implementation for the Raspberry Pi using the RPi.GPIO library.""" def __init__(self, rpi_gpio, mode=None): self.rpi_gpio = rpi_gpio # Suppress warnings about GPIO in use. rpi_gpio.setwarnings(False) # Setup board pin mode. if mode == rpi_gpio.BOARD or mode == rpi_gpio.BCM: rpi_gpio.setmode(mode) elif mode is not None: raise ValueError('Unexpected value for mode. Must be BOARD or BCM.') else: # Default to BCM numbering if not told otherwise. rpi_gpio.setmode(rpi_gpio.BCM) # Define mapping of Adafruit GPIO library constants to RPi.GPIO constants. self._dir_mapping = { OUT: rpi_gpio.OUT, IN: rpi_gpio.IN } self._pud_mapping = { PUD_OFF: rpi_gpio.PUD_OFF, PUD_DOWN: rpi_gpio.PUD_DOWN, PUD_UP: rpi_gpio.PUD_UP } self._edge_mapping = { RISING: rpi_gpio.RISING, FALLING: rpi_gpio.FALLING, BOTH: rpi_gpio.BOTH } def setup(self, pin, mode, pull_up_down=PUD_OFF): """Set the input or output mode for a specified pin. Mode should be either OUTPUT or INPUT. """ self.rpi_gpio.setup(pin, self._dir_mapping[mode], pull_up_down=self._pud_mapping[pull_up_down]) def output(self, pin, value): """Set the specified pin the provided high/low value. Value should be either HIGH/LOW or a boolean (true = high). """ self.rpi_gpio.output(pin, value) def input(self, pin): """Read the specified pin and return HIGH/true if the pin is pulled high, or LOW/false if pulled low. """ return self.rpi_gpio.input(pin) def input_pins(self, pins): """Read multiple pins specified in the given list and return list of pin values GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low. """ # maybe rpi has a mass read... it would be more efficient to use it if it exists return [self.rpi_gpio.input(pin) for pin in pins] def add_event_detect(self, pin, edge, callback=None, bouncetime=-1): """Enable edge detection events for a particular GPIO channel. Pin should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a function for the event. Bouncetime is switch bounce timeout in ms for callback """ kwargs = {} if callback: kwargs['callback']=callback if bouncetime > 0: kwargs['bouncetime']=bouncetime self.rpi_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs) def remove_event_detect(self, pin): """Remove edge detection for a particular GPIO channel. Pin should be type IN. """ self.rpi_gpio.remove_event_detect(pin) def add_event_callback(self, pin, callback): """Add a callback for an event already defined using add_event_detect(). Pin should be type IN. """ self.rpi_gpio.add_event_callback(pin, callback) def event_detected(self, pin): """Returns True if an edge has occured on a given GPIO. You need to enable edge detection using add_event_detect() first. Pin should be type IN. """ return self.rpi_gpio.event_detected(pin) def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.rpi_gpio.wait_for_edge(pin, self._edge_mapping[edge]) def cleanup(self, pin=None): """Clean up GPIO event detection for specific pin, or all pins if none is specified. """ if pin is None: self.rpi_gpio.cleanup() else: self.rpi_gpio.cleanup(pin) class AdafruitBBIOAdapter(BaseGPIO): """GPIO implementation for the Beaglebone Black using the Adafruit_BBIO library. """ def __init__(self, bbio_gpio): self.bbio_gpio = bbio_gpio # Define mapping of Adafruit GPIO library constants to RPi.GPIO constants. self._dir_mapping = { OUT: bbio_gpio.OUT, IN: bbio_gpio.IN } self._pud_mapping = { PUD_OFF: bbio_gpio.PUD_OFF, PUD_DOWN: bbio_gpio.PUD_DOWN, PUD_UP: bbio_gpio.PUD_UP } self._edge_mapping = { RISING: bbio_gpio.RISING, FALLING: bbio_gpio.FALLING, BOTH: bbio_gpio.BOTH } def setup(self, pin, mode, pull_up_down=PUD_OFF): """Set the input or output mode for a specified pin. Mode should be either OUTPUT or INPUT. """ self.bbio_gpio.setup(pin, self._dir_mapping[mode], pull_up_down=self._pud_mapping[pull_up_down]) def output(self, pin, value): """Set the specified pin the provided high/low value. Value should be either HIGH/LOW or a boolean (true = high). """ self.bbio_gpio.output(pin, value) def input(self, pin): """Read the specified pin and return HIGH/true if the pin is pulled high, or LOW/false if pulled low. """ return self.bbio_gpio.input(pin) def input_pins(self, pins): """Read multiple pins specified in the given list and return list of pin values GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low. """ # maybe bbb has a mass read... it would be more efficient to use it if it exists return [self.bbio_gpio.input(pin) for pin in pins] def add_event_detect(self, pin, edge, callback=None, bouncetime=-1): """Enable edge detection events for a particular GPIO channel. Pin should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a function for the event. Bouncetime is switch bounce timeout in ms for callback """ kwargs = {} if callback: kwargs['callback']=callback if bouncetime > 0: kwargs['bouncetime']=bouncetime self.bbio_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs) def remove_event_detect(self, pin): """Remove edge detection for a particular GPIO channel. Pin should be type IN. """ self.bbio_gpio.remove_event_detect(pin) def add_event_callback(self, pin, callback, bouncetime=-1): """Add a callback for an event already defined using add_event_detect(). Pin should be type IN. Bouncetime is switch bounce timeout in ms for callback """ kwargs = {} if bouncetime > 0: kwargs['bouncetime']=bouncetime self.bbio_gpio.add_event_callback(pin, callback, **kwargs) def event_detected(self, pin): """Returns True if an edge has occured on a given GPIO. You need to enable edge detection using add_event_detect() first. Pin should be type IN. """ return self.bbio_gpio.event_detected(pin) def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.bbio_gpio.wait_for_edge(pin, self._edge_mapping[edge]) def cleanup(self, pin=None): """Clean up GPIO event detection for specific pin, or all pins if none is specified. """ if pin is None: self.bbio_gpio.cleanup() else: self.bbio_gpio.cleanup(pin) class AdafruitMinnowAdapter(BaseGPIO): """GPIO implementation for the Minnowboard + MAX using the mraa library""" def __init__(self,mraa_gpio): self.mraa_gpio = mraa_gpio # Define mapping of Adafruit GPIO library constants to mraa constants self._dir_mapping = { OUT: self.mraa_gpio.DIR_OUT, IN: self.mraa_gpio.DIR_IN } self._pud_mapping = { PUD_OFF: self.mraa_gpio.MODE_STRONG, PUD_UP: self.mraa_gpio.MODE_HIZ, PUD_DOWN: self.mraa_gpio.MODE_PULLDOWN } self._edge_mapping = { RISING: self.mraa_gpio.EDGE_RISING, FALLING: self.mraa_gpio.EDGE_FALLING, BOTH: self.mraa_gpio.EDGE_BOTH } def setup(self,pin,mode): """Set the input or output mode for a specified pin. Mode should be either DIR_IN or DIR_OUT. """ self.mraa_gpio.Gpio.dir(self.mraa_gpio.Gpio(pin),self._dir_mapping[mode]) def output(self,pin,value): """Set the specified pin the provided high/low value. Value should be either 1 (ON or HIGH), or 0 (OFF or LOW) or a boolean. """ self.mraa_gpio.Gpio.write(self.mraa_gpio.Gpio(pin), value) def input(self,pin): """Read the specified pin and return HIGH/true if the pin is pulled high, or LOW/false if pulled low. """ return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin)) def add_event_detect(self, pin, edge, callback=None, bouncetime=-1): """Enable edge detection events for a particular GPIO channel. Pin should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a function for the event. Bouncetime is switch bounce timeout in ms for callback """ kwargs = {} if callback: kwargs['callback']=callback if bouncetime > 0: kwargs['bouncetime']=bouncetime self.mraa_gpio.Gpio.isr(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge], **kwargs) def remove_event_detect(self, pin): """Remove edge detection for a particular GPIO channel. Pin should be type IN. """ self.mraa_gpio.Gpio.isrExit(self.mraa_gpio.Gpio(pin)) def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.bbio_gpio.wait_for_edge(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge]) def get_platform_gpio(**keywords): """Attempt to return a GPIO instance for the platform which the code is being executed on. Currently supports only the Raspberry Pi using the RPi.GPIO library and Beaglebone Black using the Adafruit_BBIO library. Will throw an exception if a GPIO instance can't be created for the current platform. The returned GPIO object is an instance of BaseGPIO. """ plat = Platform.platform_detect() if plat == Platform.RASPBERRY_PI: import RPi.GPIO return RPiGPIOAdapter(RPi.GPIO, **keywords) elif plat == Platform.BEAGLEBONE_BLACK: import Adafruit_BBIO.GPIO return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords) elif plat == Platform.MINNOWBOARD: import mraa return AdafruitMinnowAdapter(mraa, **keywords) elif plat == Platform.JETSON_NANO: import Jetson.GPIO return RPiGPIOAdapter(Jetson.GPIO, **keywords) elif plat == Platform.UNKNOWN: raise RuntimeError('Could not determine platform.')
17,268
Python
39.160465
100
0.618253
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/SPI.py
# Copyright (c) 2014 Adafruit Industries # Author: Tony DiCola # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import operator import time import Mangdang.Adafruit_GPIO as GPIO MSBFIRST = 0 LSBFIRST = 1 class SpiDev(object): """Hardware-based SPI implementation using the spidev interface.""" def __init__(self, port, device, max_speed_hz=500000): """Initialize an SPI device using the SPIdev interface. Port and device identify the device, for example the device /dev/spidev1.0 would be port 1 and device 0. """ import spidev self._device = spidev.SpiDev() self._device.open(port, device) self._device.max_speed_hz=max_speed_hz # Default to mode 0, and make sure CS is active low. self._device.mode = 0 #self._device.cshigh = False def set_clock_hz(self, hz): """Set the speed of the SPI clock in hertz. Note that not all speeds are supported and a lower speed might be chosen by the hardware. """ self._device.max_speed_hz=hz def set_mode(self, mode): """Set SPI mode which controls clock polarity and phase. Should be a numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus """ if mode < 0 or mode > 3: raise ValueError('Mode must be a value 0, 1, 2, or 3.') self._device.mode = mode def set_bit_order(self, order): """Set order of bits to be read/written over serial lines. Should be either MSBFIRST for most-significant first, or LSBFIRST for least-signifcant first. """ if order == MSBFIRST: self._device.lsbfirst = False elif order == LSBFIRST: self._device.lsbfirst = True else: raise ValueError('Order must be MSBFIRST or LSBFIRST.') def close(self): """Close communication with the SPI device.""" self._device.close() def write(self, data): """Half-duplex SPI write. The specified array of bytes will be clocked out the MOSI line. """ self._device.writebytes(data) def read(self, length): """Half-duplex SPI read. The specified length of bytes will be clocked in the MISO line and returned as a bytearray object. """ return bytearray(self._device.readbytes(length)) def transfer(self, data): """Full-duplex SPI read and write. The specified array of bytes will be clocked out the MOSI line, while simultaneously bytes will be read from the MISO line. Read bytes will be returned as a bytearray object. """ return bytearray(self._device.xfer2(data)) class SpiDevMraa(object): """Hardware SPI implementation with the mraa library on Minnowboard""" def __init__(self, port, device, max_speed_hz=500000): import mraa self._device = mraa.Spi(0) self._device.mode(0) def set_clock_hz(self, hz): """Set the speed of the SPI clock in hertz. Note that not all speeds are supported and a lower speed might be chosen by the hardware. """ self._device.frequency(hz) def set_mode(self,mode): """Set SPI mode which controls clock polarity and phase. Should be a numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus """ if mode < 0 or mode > 3: raise ValueError('Mode must be a value 0, 1, 2, or 3.') self._device.mode(mode) def set_bit_order(self, order): """Set order of bits to be read/written over serial lines. Should be either MSBFIRST for most-significant first, or LSBFIRST for least-signifcant first. """ if order == MSBFIRST: self._device.lsbmode(False) elif order == LSBFIRST: self._device.lsbmode(True) else: raise ValueError('Order must be MSBFIRST or LSBFIRST.') def close(self): """Close communication with the SPI device.""" self._device.Spi() def write(self, data): """Half-duplex SPI write. The specified array of bytes will be clocked out the MOSI line. """ self._device.write(bytearray(data)) class BitBang(object): """Software-based implementation of the SPI protocol over GPIO pins.""" def __init__(self, gpio, sclk, mosi=None, miso=None, ss=None): """Initialize bit bang (or software) based SPI. Must provide a BaseGPIO class, the SPI clock, and optionally MOSI, MISO, and SS (slave select) pin numbers. If MOSI is set to None then writes will be disabled and fail with an error, likewise for MISO reads will be disabled. If SS is set to None then SS will not be asserted high/low by the library when transfering data. """ self._gpio = gpio self._sclk = sclk self._mosi = mosi self._miso = miso self._ss = ss # Set pins as outputs/inputs. gpio.setup(sclk, GPIO.OUT) if mosi is not None: gpio.setup(mosi, GPIO.OUT) if miso is not None: gpio.setup(miso, GPIO.IN) if ss is not None: gpio.setup(ss, GPIO.OUT) # Assert SS high to start with device communication off. gpio.set_high(ss) # Assume mode 0. self.set_mode(0) # Assume most significant bit first order. self.set_bit_order(MSBFIRST) def set_clock_hz(self, hz): """Set the speed of the SPI clock. This is unsupported with the bit bang SPI class and will be ignored. """ pass def set_mode(self, mode): """Set SPI mode which controls clock polarity and phase. Should be a numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus """ if mode < 0 or mode > 3: raise ValueError('Mode must be a value 0, 1, 2, or 3.') if mode & 0x02: # Clock is normally high in mode 2 and 3. self._clock_base = GPIO.HIGH else: # Clock is normally low in mode 0 and 1. self._clock_base = GPIO.LOW if mode & 0x01: # Read on trailing edge in mode 1 and 3. self._read_leading = False else: # Read on leading edge in mode 0 and 2. self._read_leading = True # Put clock into its base state. self._gpio.output(self._sclk, self._clock_base) def set_bit_order(self, order): """Set order of bits to be read/written over serial lines. Should be either MSBFIRST for most-significant first, or LSBFIRST for least-signifcant first. """ # Set self._mask to the bitmask which points at the appropriate bit to # read or write, and appropriate left/right shift operator function for # reading/writing. if order == MSBFIRST: self._mask = 0x80 self._write_shift = operator.lshift self._read_shift = operator.rshift elif order == LSBFIRST: self._mask = 0x01 self._write_shift = operator.rshift self._read_shift = operator.lshift else: raise ValueError('Order must be MSBFIRST or LSBFIRST.') def close(self): """Close the SPI connection. Unused in the bit bang implementation.""" pass def write(self, data, assert_ss=True, deassert_ss=True): """Half-duplex SPI write. If assert_ss is True, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line, and if deassert_ss is True the SS line be put back high. """ # Fail MOSI is not specified. if self._mosi is None: raise RuntimeError('Write attempted with no MOSI pin specified.') if assert_ss and self._ss is not None: self._gpio.set_low(self._ss) for byte in data: for i in range(8): # Write bit to MOSI. if self._write_shift(byte, i) & self._mask: self._gpio.set_high(self._mosi) else: self._gpio.set_low(self._mosi) # Flip clock off base. self._gpio.output(self._sclk, not self._clock_base) # Return clock to base. self._gpio.output(self._sclk, self._clock_base) if deassert_ss and self._ss is not None: self._gpio.set_high(self._ss) def read(self, length, assert_ss=True, deassert_ss=True): """Half-duplex SPI read. If assert_ss is true, the SS line will be asserted low, the specified length of bytes will be clocked in the MISO line, and if deassert_ss is true the SS line will be put back high. Bytes which are read will be returned as a bytearray object. """ if self._miso is None: raise RuntimeError('Read attempted with no MISO pin specified.') if assert_ss and self._ss is not None: self._gpio.set_low(self._ss) result = bytearray(length) for i in range(length): for j in range(8): # Flip clock off base. self._gpio.output(self._sclk, not self._clock_base) # Handle read on leading edge of clock. if self._read_leading: if self._gpio.is_high(self._miso): # Set bit to 1 at appropriate location. result[i] |= self._read_shift(self._mask, j) else: # Set bit to 0 at appropriate location. result[i] &= ~self._read_shift(self._mask, j) # Return clock to base. self._gpio.output(self._sclk, self._clock_base) # Handle read on trailing edge of clock. if not self._read_leading: if self._gpio.is_high(self._miso): # Set bit to 1 at appropriate location. result[i] |= self._read_shift(self._mask, j) else: # Set bit to 0 at appropriate location. result[i] &= ~self._read_shift(self._mask, j) if deassert_ss and self._ss is not None: self._gpio.set_high(self._ss) return result def transfer(self, data, assert_ss=True, deassert_ss=True): """Full-duplex SPI read and write. If assert_ss is true, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line while bytes will also be read from the MISO line, and if deassert_ss is true the SS line will be put back high. Bytes which are read will be returned as a bytearray object. """ if self._mosi is None: raise RuntimeError('Write attempted with no MOSI pin specified.') if self._miso is None: raise RuntimeError('Read attempted with no MISO pin specified.') if assert_ss and self._ss is not None: self._gpio.set_low(self._ss) result = bytearray(len(data)) for i in range(len(data)): for j in range(8): # Write bit to MOSI. if self._write_shift(data[i], j) & self._mask: self._gpio.set_high(self._mosi) else: self._gpio.set_low(self._mosi) # Flip clock off base. self._gpio.output(self._sclk, not self._clock_base) # Handle read on leading edge of clock. if self._read_leading: if self._gpio.is_high(self._miso): # Set bit to 1 at appropriate location. result[i] |= self._read_shift(self._mask, j) else: # Set bit to 0 at appropriate location. result[i] &= ~self._read_shift(self._mask, j) # Return clock to base. self._gpio.output(self._sclk, self._clock_base) # Handle read on trailing edge of clock. if not self._read_leading: if self._gpio.is_high(self._miso): # Set bit to 1 at appropriate location. result[i] |= self._read_shift(self._mask, j) else: # Set bit to 0 at appropriate location. result[i] &= ~self._read_shift(self._mask, j) if deassert_ss and self._ss is not None: self._gpio.set_high(self._ss) return result
13,970
Python
41.465045
81
0.585827
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/FuelGauge/max1720x_battery.c
/* * Maxim MAX17201/MAX17205 fuel gauge driver * * Author: Mahir Ozturk <mahir.ozturk@maximintegrated.com> * Copyright (C) 2019 Maxim Integrated * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This driver is based on max17042/40_battery.c */ #include <linux/delay.h> #include <linux/err.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/mod_devicetable.h> #include <linux/mutex.h> #include <linux/of.h> #include <linux/power_supply.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/regmap.h> #include <linux/slab.h> #define DRV_NAME "max1720x" /* CONFIG register bits */ #define MAX1720X_CONFIG_ALRT_EN (1 << 2) /* STATUS register bits */ #define MAX1720X_STATUS_BST (1 << 3) #define MAX1720X_STATUS_POR (1 << 1) /* STATUS interrupt status bits */ #define MAX1720X_STATUS_ALRT_CLR_MASK (0x88BB) #define MAX1720X_STATUS_SOC_MAX_ALRT (1 << 14) #define MAX1720X_STATUS_TEMP_MAX_ALRT (1 << 13) #define MAX1720X_STATUS_VOLT_MAX_ALRT (1 << 12) #define MAX1720X_STATUS_SOC_MIN_ALRT (1 << 10) #define MAX1720X_STATUS_TEMP_MIN_ALRT (1 << 9) #define MAX1720X_STATUS_VOLT_MIN_ALRT (1 << 8) #define MAX1720X_STATUS_CURR_MAX_ALRT (1 << 6) #define MAX1720X_STATUS_CURR_MIN_ALRT (1 << 2) /* ProtStatus register bits */ #define MAX1730X_PROTSTATUS_CHGWDT (1 << 15) #define MAX1730X_PROTSTATUS_TOOHOTC (1 << 14) #define MAX1730X_PROTSTATUS_FULL (1 << 13) #define MAX1730X_PROTSTATUS_TOOCOLDC (1 << 12) #define MAX1730X_PROTSTATUS_OVP (1 << 11) #define MAX1730X_PROTSTATUS_OCCP (1 << 10) #define MAX1730X_PROTSTATUS_QOVFLW (1 << 9) #define MAX1730X_PROTSTATUS_RESCFAULT (1 << 7) #define MAX1730X_PROTSTATUS_PERMFAIL (1 << 6) #define MAX1730X_PROTSTATUS_DIEHOT (1 << 5) #define MAX1730X_PROTSTATUS_TOOHOTD (1 << 4) #define MAX1730X_PROTSTATUS_UVP (1 << 3) #define MAX1730X_PROTSTATUS_ODCP (1 << 2) #define MAX1730X_PROTSTATUS_RESDFAULT (1 << 1) #define MAX1730X_PROTSTATUS_SHDN (1 << 0) #define MAX1720X_VMAX_TOLERANCE 50 /* 50 mV */ #define MODELGAUGE_DATA_I2C_ADDR 0x36 #define NONVOLATILE_DATA_I2C_ADDR 0x0B struct max1720x_platform_data { /* * rsense in miliOhms. * default 10 (if rsense = 0) as it is the recommended value by * the datasheet although it can be changed by board designers. */ unsigned int rsense; int volt_min; /* in mV */ int volt_max; /* in mV */ int temp_min; /* in DegreC */ int temp_max; /* in DegreeC */ int soc_max; /* in percent */ int soc_min; /* in percent */ int curr_max; /* in mA */ int curr_min; /* in mA */ }; struct max1720x_priv { struct i2c_client *client; struct device *dev; struct regmap *regmap; struct power_supply *battery; struct max1720x_platform_data *pdata; struct work_struct init_worker; struct attribute_group *attr_grp; const u8 *regs; u8 nvmem_high_addr; int cycles_reg_lsb_percent; int (*get_charging_status)(void); int (*get_battery_health)(struct max1720x_priv *priv, int *health); }; enum chip_id { ID_MAX1720X, ID_MAX1730X, }; enum register_ids { STATUS_REG = 0, VALRTTH_REG, TALRTTH_REG, SALRTTH_REG, ATRATE_REG, REPCAP_REG, REPSOC_REG, TEMP_REG, VCELL_REG, CURRENT_REG, AVGCURRENT_REG, TTE_REG , CYCLES_REG, DESIGNCAP_REG, AVGVCELL_REG, MAXMINVOLT_REG, CONFIG_REG, TTF_REG , VERSION_REG, FULLCAPREP_REG, VEMPTY_REG, QH_REG , IALRTTH_REG, PROTSTATUS_REG, ATTTE_REG, VFOCV_REG, }; static int max1720x_get_battery_health(struct max1720x_priv *priv, int *health); static int max1730x_get_battery_health(struct max1720x_priv *priv, int *health); static int (*get_battery_health_handlers[]) (struct max1720x_priv *priv, int *health) = { [ID_MAX1720X] = max1720x_get_battery_health, [ID_MAX1730X] = max1730x_get_battery_health, }; /* Register addresses */ static const u8 max1720x_regs[] = { [STATUS_REG] = 0x00, [VALRTTH_REG] = 0x01, [TALRTTH_REG] = 0x02, [SALRTTH_REG] = 0x03, [ATRATE_REG] = 0x04, [REPCAP_REG] = 0x05, [REPSOC_REG] = 0x06, [TEMP_REG] = 0x08, [VCELL_REG] = 0x09, [CURRENT_REG] = 0x0A, [AVGCURRENT_REG] = 0x0B, [TTE_REG] = 0x11, [CYCLES_REG] = 0x17, [DESIGNCAP_REG] = 0x18, [AVGVCELL_REG] = 0x19, [MAXMINVOLT_REG] = 0x1B, [CONFIG_REG] = 0x1D, [TTF_REG] = 0x20, [VERSION_REG] = 0x21, [FULLCAPREP_REG] = 0x35, [VEMPTY_REG] = 0x3A, [QH_REG] = 0x4D, [IALRTTH_REG] = 0xB4, [ATTTE_REG] = 0xDD, [VFOCV_REG] = 0xFB, }; static const u8 max1730x_regs[] = { [STATUS_REG] = 0x00, [VALRTTH_REG] = 0x01, [TALRTTH_REG] = 0x02, [SALRTTH_REG] = 0x03, [ATRATE_REG] = 0x04, [REPCAP_REG] = 0x05, [REPSOC_REG] = 0x06, [TEMP_REG] = 0x1B, [VCELL_REG] = 0x1A, [CURRENT_REG] = 0x1C, [AVGCURRENT_REG] = 0x1D, [TTE_REG] = 0x11, [CYCLES_REG] = 0x17, [DESIGNCAP_REG] = 0x18, [AVGVCELL_REG] = 0x19, [MAXMINVOLT_REG] = 0x08, [CONFIG_REG] = 0x1D, [TTF_REG] = 0x20, [VERSION_REG] = 0x21, [FULLCAPREP_REG] = 0x10, [VEMPTY_REG] = 0x3A, [QH_REG] = 0x4D, [IALRTTH_REG] = 0xAC, [PROTSTATUS_REG] = 0xD9, [ATTTE_REG] = 0xDD, [VFOCV_REG] = 0xFB, }; static const u8* chip_regs[] = { [ID_MAX1720X] = max1720x_regs, [ID_MAX1730X] = max1730x_regs, }; static const u8 nvmem_high_addrs[] = { [ID_MAX1720X] = 0xDF, [ID_MAX1730X] = 0xEF, }; static const int cycles_reg_lsb_percents[] = { [ID_MAX1720X] = 25, [ID_MAX1730X] = 16, }; static enum power_supply_property max1720x_battery_props[] = { POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_CYCLE_COUNT, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_AVG, POWER_SUPPLY_PROP_VOLTAGE_OCV, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN, POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CHARGE_NOW, POWER_SUPPLY_PROP_CHARGE_COUNTER, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_TEMP_ALERT_MIN, POWER_SUPPLY_PROP_TEMP_ALERT_MAX, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_AVG, POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG, POWER_SUPPLY_PROP_TIME_TO_FULL_AVG, }; static inline int max1720x_raw_voltage_to_uvolts(struct max1720x_priv *priv, int lsb) { return lsb * 10000 / 65536; /* 78.125uV per bit */ } static inline int max1720x_raw_current_to_uamps(struct max1720x_priv *priv, int curr) { return curr * 15625 / ((int)priv->pdata->rsense * 10); } static inline int max1720x_raw_capacity_to_uamph(struct max1720x_priv *priv, int cap) { return cap * 5000 / (int)priv->pdata->rsense; } static ssize_t max1720x_log_show(struct device *dev, struct device_attribute *attr, char *buf) { struct max1720x_priv *priv = dev_get_drvdata(dev); int rc = 0, reg = 0; u32 val = 0; for (reg = 0; reg < 0xE0; reg++) { regmap_read(priv->regmap, reg, &val); rc += (int)snprintf(buf+rc, PAGE_SIZE-rc, "0x%04X,", val); if (reg == 0x4F) reg += 0x60; if (reg == 0xBF) reg += 0x10; } rc += (int)snprintf(buf+rc, PAGE_SIZE-rc, "\n"); return rc; } static ssize_t max1720x_nvmem_show(struct device *dev, struct device_attribute *attr, char *buf) { struct max1720x_priv *priv = dev_get_drvdata(dev); int rc = 0, reg = 0; u32 val = 0; int ret; int i; /* * Device has a separate slave address for accessing non-volatile memory * region, so we are temporarily changing i2c client address. */ priv->client->addr = NONVOLATILE_DATA_I2C_ADDR; for (reg = 0x80; reg < priv->nvmem_high_addr; reg += 16) { rc += snprintf(buf+rc, PAGE_SIZE-rc, "Page %02Xh: ", (reg + 0x100) >> 4); for (i = 0; i < 16; i++) { ret = regmap_read(priv->regmap, reg + i, &val); if (ret) { dev_err(dev, "NV memory reading failed (%d)\n", ret); return 0; } rc += snprintf(buf+rc, PAGE_SIZE-rc, "0x%04X ", val); } rc += snprintf(buf+rc, PAGE_SIZE-rc, "\n"); } priv->client->addr = MODELGAUGE_DATA_I2C_ADDR; return rc; } static ssize_t max1720x_atrate_show(struct device *dev, struct device_attribute *attr, char *buf) { struct max1720x_priv *priv = dev_get_drvdata(dev); u32 val = 0; int ret; ret = regmap_read(priv->regmap, priv->regs[ATRATE_REG], &val); if (ret) { return 0; } return sprintf(buf, "%d", (short)val); } static ssize_t max1720x_atrate_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct max1720x_priv *priv = dev_get_drvdata(dev); s32 val = 0; int ret; if (kstrtos32(buf, 0, &val)) return -EINVAL; ret = regmap_write(priv->regmap, priv->regs[ATRATE_REG], val); if (ret < 0) return ret; return count; } static ssize_t max1720x_attte_show(struct device *dev, struct device_attribute *attr, char *buf) { struct max1720x_priv *priv = dev_get_drvdata(dev); u32 val = 0; int ret; ret = regmap_read(priv->regmap, priv->regs[ATTTE_REG], &val); if (ret) { return 0; } return sprintf(buf, "%d", (short)val); } static DEVICE_ATTR(log, S_IRUGO, max1720x_log_show, NULL); static DEVICE_ATTR(nvmem, S_IRUGO, max1720x_nvmem_show, NULL); static DEVICE_ATTR(atrate, S_IRUGO | S_IWUSR, max1720x_atrate_show, max1720x_atrate_store); static DEVICE_ATTR(attte, S_IRUGO, max1720x_attte_show, NULL); static struct attribute *max1720x_attr[] = { &dev_attr_log.attr, &dev_attr_nvmem.attr, &dev_attr_atrate.attr, &dev_attr_attte.attr, NULL }; static struct attribute_group max1720x_attr_group = { .attrs = max1720x_attr, }; static int max1720x_get_temperature(struct max1720x_priv *priv, int *temp) { int ret; u32 data; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[TEMP_REG], &data); if (ret < 0) return ret; *temp = sign_extend32(data, 15); /* The value is converted into centigrade scale */ /* Units of LSB = 1 / 256 degree Celsius */ *temp = (*temp * 10) >> 8; return 0; } static int max1720x_set_temp_lower_limit(struct max1720x_priv *priv, int temp) { int ret; u32 data; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[TALRTTH_REG], &data); if (ret < 0) return ret; /* Input in deci-centigrade, convert to centigrade */ temp /= 10; data &= 0xFF00; data |= (temp & 0xFF); ret = regmap_write(map, priv->regs[TALRTTH_REG], data); if (ret < 0) return ret; return 0; } static int max1720x_get_temperature_alert_min(struct max1720x_priv *priv, int *temp) { int ret; u32 data; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[TALRTTH_REG], &data); if (ret < 0) return ret; /* Convert 1DegreeC LSB to 0.1DegreeC LSB */ *temp = sign_extend32(data & 0xff, 7) * 10; return 0; } static int max1720x_set_temp_upper_limit(struct max1720x_priv *priv, int temp) { int ret; u32 data; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[TALRTTH_REG], &data); if (ret < 0) return ret; /* Input in deci-centigrade, convert to centigrade */ temp /= 10; data &= 0xFF; data |= ((temp << 8) & 0xFF00); ret = regmap_write(map, priv->regs[TALRTTH_REG], data); if (ret < 0) return ret; return 0; } static int max1720x_get_temperature_alert_max(struct max1720x_priv *priv, int *temp) { int ret; u32 data; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[TALRTTH_REG], &data); if (ret < 0) return ret; /* Convert 1DegreeC LSB to 0.1DegreeC LSB */ *temp = sign_extend32(data >> 8, 7) * 10; return 0; } static int max1720x_get_battery_health(struct max1720x_priv *priv, int *health) { int temp, vavg, vbatt, ret; u32 val; ret = regmap_read(priv->regmap, priv->regs[AVGVCELL_REG], &val); if (ret < 0) goto health_error; /* bits [0-3] unused */ vavg = max1720x_raw_voltage_to_uvolts(priv, val); /* Convert to millivolts */ vavg /= 1000; ret = regmap_read(priv->regmap, priv->regs[VCELL_REG], &val); if (ret < 0) goto health_error; /* bits [0-3] unused */ vbatt = max1720x_raw_voltage_to_uvolts(priv, val); /* Convert to millivolts */ vbatt /= 1000; if (vavg < priv->pdata->volt_min) { *health = POWER_SUPPLY_HEALTH_DEAD; goto out; } if (vbatt > priv->pdata->volt_max + MAX1720X_VMAX_TOLERANCE) { *health = POWER_SUPPLY_HEALTH_OVERVOLTAGE; goto out; } ret = max1720x_get_temperature(priv, &temp); if (ret < 0) goto health_error; if (temp <= priv->pdata->temp_min) { *health = POWER_SUPPLY_HEALTH_COLD; goto out; } if (temp >= priv->pdata->temp_max) { *health = POWER_SUPPLY_HEALTH_OVERHEAT; goto out; } *health = POWER_SUPPLY_HEALTH_GOOD; out: return 0; health_error: return ret; } static int max1730x_get_battery_health(struct max1720x_priv *priv, int *health) { int ret; u32 val; ret = regmap_read(priv->regmap, priv->regs[PROTSTATUS_REG], &val); if (ret < 0) return ret; if ((val & MAX1730X_PROTSTATUS_RESCFAULT) || (val & MAX1730X_PROTSTATUS_RESDFAULT)) { *health = POWER_SUPPLY_HEALTH_UNKNOWN; } else if ((val & MAX1730X_PROTSTATUS_TOOHOTC) || (val & MAX1730X_PROTSTATUS_TOOHOTD) || (val & MAX1730X_PROTSTATUS_DIEHOT)) { *health = POWER_SUPPLY_HEALTH_OVERHEAT; } else if ((val & MAX1730X_PROTSTATUS_UVP) || (val & MAX1730X_PROTSTATUS_PERMFAIL) || (val & MAX1730X_PROTSTATUS_SHDN)) { *health = POWER_SUPPLY_HEALTH_DEAD; } else if (val & MAX1730X_PROTSTATUS_TOOCOLDC) { *health = POWER_SUPPLY_HEALTH_COLD; } else if (val & MAX1730X_PROTSTATUS_OVP) { *health = POWER_SUPPLY_HEALTH_OVERVOLTAGE; } else if ((val & MAX1730X_PROTSTATUS_QOVFLW) || (val & MAX1730X_PROTSTATUS_OCCP) || (val & MAX1730X_PROTSTATUS_ODCP)) { *health = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; } else if (val & MAX1730X_PROTSTATUS_CHGWDT) { *health = POWER_SUPPLY_HEALTH_WATCHDOG_TIMER_EXPIRE; } else { *health = POWER_SUPPLY_HEALTH_GOOD; } return 0; } static int max1720x_get_min_capacity_alert_th(struct max1720x_priv *priv, unsigned int *th) { int ret; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[SALRTTH_REG], th); if (ret < 0) return ret; *th &= 0xFF; return 0; } static int max1720x_set_min_capacity_alert_th(struct max1720x_priv *priv, unsigned int th) { int ret; unsigned int data; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[SALRTTH_REG], &data); if (ret < 0) return ret; data &= 0xFF00; data |= (th & 0xFF); ret = regmap_write(map, priv->regs[SALRTTH_REG], data); if (ret < 0) return ret; return 0; } static int max1720x_get_max_capacity_alert_th(struct max1720x_priv *priv, unsigned int *th) { int ret; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[SALRTTH_REG], th); if (ret < 0) return ret; *th >>= 8; return 0; } static int max1720x_set_max_capacity_alert_th(struct max1720x_priv *priv, unsigned int th) { int ret; unsigned int data; struct regmap *map = priv->regmap; ret = regmap_read(map, priv->regs[SALRTTH_REG], &data); if (ret < 0) return ret; data &= 0xFF; data |= ((th & 0xFF) << 8); ret = regmap_write(map, priv->regs[SALRTTH_REG], data); if (ret < 0) return ret; return 0; } static int max1720x_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct max1720x_priv *priv = power_supply_get_drvdata(psy); struct regmap *regmap = priv->regmap; struct max1720x_platform_data *pdata = priv->pdata; unsigned int reg; int ret; switch (psp) { case POWER_SUPPLY_PROP_PRESENT: ret = regmap_read(regmap, priv->regs[STATUS_REG], &reg); if (ret < 0) return ret; if (reg & MAX1720X_STATUS_BST) val->intval = 0; else val->intval = 1; break; case POWER_SUPPLY_PROP_CYCLE_COUNT: ret = regmap_read(regmap, priv->regs[CYCLES_REG], &reg); if (ret < 0) return ret; val->intval = reg * 100 / priv->cycles_reg_lsb_percent; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: ret = regmap_read(regmap, priv->regs[MAXMINVOLT_REG], &reg); if (ret < 0) return ret; val->intval = reg >> 8; val->intval *= 20000; /* Units of LSB = 20mV */ break; case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN: ret = regmap_read(regmap, priv->regs[VEMPTY_REG], &reg); if (ret < 0) return ret; val->intval = reg >> 7; val->intval *= 10000; /* Units of LSB = 10mV */ break; case POWER_SUPPLY_PROP_STATUS: if (pdata && priv->get_charging_status) val->intval = priv->get_charging_status(); else val->intval = POWER_SUPPLY_STATUS_UNKNOWN; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = regmap_read(regmap, priv->regs[VCELL_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_voltage_to_uvolts(priv, reg); break; case POWER_SUPPLY_PROP_VOLTAGE_AVG: ret = regmap_read(regmap, priv->regs[AVGVCELL_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_voltage_to_uvolts(priv, reg); break; case POWER_SUPPLY_PROP_VOLTAGE_OCV: ret = regmap_read(regmap, priv->regs[VFOCV_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_voltage_to_uvolts(priv, reg); break; case POWER_SUPPLY_PROP_CAPACITY: ret = regmap_read(regmap, priv->regs[REPSOC_REG], &reg); if (ret < 0) return ret; val->intval = reg >> 8; /* RepSOC LSB: 1/256 % */ break; case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN: ret = max1720x_get_min_capacity_alert_th(priv, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX: ret = max1720x_get_max_capacity_alert_th(priv, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN: ret = regmap_read(regmap, priv->regs[DESIGNCAP_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_capacity_to_uamph(priv, reg); break; case POWER_SUPPLY_PROP_CHARGE_FULL: ret = regmap_read(regmap, priv->regs[FULLCAPREP_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_capacity_to_uamph(priv, reg); break; case POWER_SUPPLY_PROP_CHARGE_COUNTER: ret = regmap_read(regmap, priv->regs[QH_REG], &reg); if (ret < 0) return ret; /* This register is signed as oppose to other capacity type * registers. */ val->intval = max1720x_raw_capacity_to_uamph(priv, sign_extend32(reg, 15)); break; case POWER_SUPPLY_PROP_CHARGE_NOW: ret = regmap_read(regmap, priv->regs[REPCAP_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_capacity_to_uamph(priv, reg); break; case POWER_SUPPLY_PROP_TEMP: ret = max1720x_get_temperature(priv, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_TEMP_ALERT_MIN: ret = max1720x_get_temperature_alert_min(priv, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_TEMP_ALERT_MAX: ret = max1720x_get_temperature_alert_max(priv, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_HEALTH: if (priv->get_battery_health != 0) { ret = priv->get_battery_health(priv, &val->intval); if (ret < 0) return ret; } else { val->intval = POWER_SUPPLY_HEALTH_UNKNOWN; } break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = regmap_read(regmap, priv->regs[CURRENT_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_current_to_uamps(priv, sign_extend32(reg, 15)); break; case POWER_SUPPLY_PROP_CURRENT_AVG: ret = regmap_read(regmap, priv->regs[AVGCURRENT_REG], &reg); if (ret < 0) return ret; val->intval = max1720x_raw_current_to_uamps(priv, sign_extend32(reg, 15)); break; case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG: ret = regmap_read(regmap, priv->regs[TTE_REG], &reg); if (ret < 0) return ret; val->intval = (reg * 45) >> 3; /* TTE LSB: 5.625 sec */ break; case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG: ret = regmap_read(regmap, priv->regs[TTF_REG], &reg); if (ret < 0) return ret; val->intval = (reg * 45) >> 3; /* TTF LSB: 5.625 sec */ break; default: return -EINVAL; } return 0; } static int max1720x_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct max1720x_priv *priv = power_supply_get_drvdata(psy); int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_TEMP_ALERT_MIN: ret = max1720x_set_temp_lower_limit(priv, val->intval); if (ret < 0) dev_err(priv->dev, "temp alert min set fail:%d\n", ret); break; case POWER_SUPPLY_PROP_TEMP_ALERT_MAX: ret = max1720x_set_temp_upper_limit(priv, val->intval); if (ret < 0) dev_err(priv->dev, "temp alert max set fail:%d\n", ret); break; case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN: ret = max1720x_set_min_capacity_alert_th(priv, val->intval); if (ret < 0) dev_err(priv->dev, "capacity alert min set fail:%d\n", ret); break; case POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX: ret = max1720x_set_max_capacity_alert_th(priv, val->intval); if (ret < 0) dev_err(priv->dev, "capacity alert max set fail:%d\n", ret); break; default: return -EINVAL; } return ret; } static int max1720x_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { int ret; switch (psp) { case POWER_SUPPLY_PROP_TEMP_ALERT_MIN: case POWER_SUPPLY_PROP_TEMP_ALERT_MAX: case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN: case POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX: ret = 1; break; default: ret = 0; } return ret; } static irqreturn_t max1720x_irq_handler(int id, void *dev) { struct max1720x_priv *priv = dev; u32 val; /* Check alert type */ regmap_read(priv->regmap, priv->regs[STATUS_REG], &val); if (val & MAX1720X_STATUS_SOC_MAX_ALRT) dev_info(priv->dev, "Alert: SOC MAX!\n"); if (val & MAX1720X_STATUS_SOC_MIN_ALRT) dev_info(priv->dev, "Alert: SOC MIN!\n"); if (val & MAX1720X_STATUS_TEMP_MAX_ALRT) dev_info(priv->dev, "Alert: TEMP MAX!\n"); if (val & MAX1720X_STATUS_TEMP_MIN_ALRT) dev_info(priv->dev, "Alert: TEMP MIN!\n"); if (val & MAX1720X_STATUS_VOLT_MAX_ALRT) dev_info(priv->dev, "Alert: VOLT MAX!\n"); if (val & MAX1720X_STATUS_VOLT_MIN_ALRT) dev_info(priv->dev, "Alert: VOLT MIN!\n"); if (val & MAX1720X_STATUS_CURR_MAX_ALRT) dev_info(priv->dev, "Alert: CURR MAX!\n"); if (val & MAX1720X_STATUS_CURR_MIN_ALRT) dev_info(priv->dev, "Alert: CURR MIN!\n"); /* Clear alerts */ regmap_write(priv->regmap, priv->regs[STATUS_REG], val & MAX1720X_STATUS_ALRT_CLR_MASK); power_supply_changed(priv->battery); return IRQ_HANDLED; } static void max1720x_set_alert_thresholds(struct max1720x_priv *priv) { struct max1720x_platform_data *pdata = priv->pdata; struct regmap *regmap = priv->regmap; u32 val; /* Set VAlrtTh */ val = (pdata->volt_min / 20); val |= ((pdata->volt_max / 20) << 8); regmap_write(regmap, priv->regs[VALRTTH_REG], val); /* Set TAlrtTh */ val = pdata->temp_min & 0xFF; val |= ((pdata->temp_max & 0xFF) << 8); regmap_write(regmap, priv->regs[TALRTTH_REG], val); /* Set SAlrtTh */ val = pdata->soc_min; val |= (pdata->soc_max << 8); regmap_write(regmap, priv->regs[SALRTTH_REG], val); /* Set IAlrtTh */ val = (pdata->curr_min * pdata->rsense / 400) & 0xFF; val |= (((pdata->curr_max * pdata->rsense / 400) & 0xFF) << 8); regmap_write(regmap, priv->regs[IALRTTH_REG], val); } static int max1720x_init(struct max1720x_priv *priv) { struct regmap *regmap = priv->regmap; int ret; unsigned int reg; u32 fgrev; ret = regmap_read(regmap, priv->regs[VERSION_REG], &fgrev); if (ret < 0) return ret; dev_info(priv->dev, "IC Version: 0x%04x\n", fgrev); /* Optional step - alert threshold initialization */ max1720x_set_alert_thresholds(priv); /* Clear Status.POR */ ret = regmap_read(regmap, priv->regs[STATUS_REG], &reg); if (ret < 0) return ret; ret = regmap_write(regmap, priv->regs[STATUS_REG], reg & ~MAX1720X_STATUS_POR); if (ret < 0) return ret; return 0; } static void max1720x_init_worker(struct work_struct *work) { struct max1720x_priv *priv = container_of(work, struct max1720x_priv, init_worker); max1720x_init(priv); } static struct max1720x_platform_data *max1720x_parse_dt(struct device *dev) { struct device_node *np = dev->of_node; struct max1720x_platform_data *pdata; int ret; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return NULL; ret = of_property_read_u32(np, "talrt-min", &pdata->temp_min); if (ret) pdata->temp_min = -128; /* DegreeC */ /* Disable alert */ ret = of_property_read_u32(np, "talrt-max", &pdata->temp_max); if (ret) pdata->temp_max = 127; /* DegreeC */ /* Disable alert */ ret = of_property_read_u32(np, "valrt-min", &pdata->volt_min); if (ret) pdata->volt_min = 0; /* mV */ /* Disable alert */ ret = of_property_read_u32(np, "valrt-max", &pdata->volt_max); if (ret) pdata->volt_max = 5100; /* mV */ /* Disable alert */ ret = of_property_read_u32(np, "ialrt-min", &pdata->curr_min); if (ret) pdata->curr_min = -5120; /* mA */ /* Disable alert */ ret = of_property_read_u32(np, "ialrt-max", &pdata->curr_max); if (ret) pdata->curr_max = 5080; /* mA */ /* Disable alert */ ret = of_property_read_u32(np, "salrt-min", &pdata->soc_min); if (ret) pdata->soc_min = 0; /* Percent */ /* Disable alert */ ret = of_property_read_u32(np, "salrt-max", &pdata->soc_max); if (ret) pdata->soc_max = 255; /* Percent */ /* Disable alert */ ret = of_property_read_u32(np, "rsense", &pdata->rsense); if (ret) pdata->rsense = 10; return pdata; } static const struct regmap_config max1720x_regmap = { .reg_bits = 8, .val_bits = 16, .val_format_endian = REGMAP_ENDIAN_NATIVE, }; static const struct power_supply_desc max1720x_fg_desc = { .name = "max1720x_battery", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = max1720x_battery_props, .num_properties = ARRAY_SIZE(max1720x_battery_props), .get_property = max1720x_get_property, .set_property = max1720x_set_property, .property_is_writeable = max1720x_property_is_writeable, }; static int max1720x_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); struct max1720x_priv *priv; struct power_supply_config psy_cfg = {}; int ret; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) return -EIO; priv = devm_kzalloc(&client->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->regs = chip_regs[id->driver_data]; priv->nvmem_high_addr = nvmem_high_addrs[id->driver_data]; priv->cycles_reg_lsb_percent = cycles_reg_lsb_percents[id->driver_data]; priv->get_battery_health = get_battery_health_handlers[id->driver_data]; if (client->dev.of_node) priv->pdata = max1720x_parse_dt(&client->dev); else priv->pdata = client->dev.platform_data; priv->dev = &client->dev; i2c_set_clientdata(client, priv); priv->client = client; priv->regmap = devm_regmap_init_i2c(client, &max1720x_regmap); if (IS_ERR(priv->regmap)) return PTR_ERR(priv->regmap); INIT_WORK(&priv->init_worker, max1720x_init_worker); schedule_work(&priv->init_worker); psy_cfg.drv_data = priv; priv->battery = power_supply_register(&client->dev, &max1720x_fg_desc, &psy_cfg); if (IS_ERR(priv->battery)) { ret = PTR_ERR(priv->battery); dev_err(&client->dev, "failed to register battery: %d\n", ret); goto err_supply; } if (client->irq) { ret = devm_request_threaded_irq(priv->dev, client->irq, NULL, max1720x_irq_handler, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, priv->battery->desc->name, priv); if (ret) { dev_err(priv->dev, "Failed to request irq %d\n", client->irq); goto err_irq; } else { regmap_update_bits(priv->regmap, priv->regs[CONFIG_REG], MAX1720X_CONFIG_ALRT_EN, MAX1720X_CONFIG_ALRT_EN); } } /* Create max1720x sysfs attributes */ priv->attr_grp = &max1720x_attr_group; ret = sysfs_create_group(&priv->dev->kobj, priv->attr_grp); if (ret) { dev_err(priv->dev, "Failed to create attribute group [%d]\n", ret); priv->attr_grp = NULL; goto err_attr; } return 0; err_irq: power_supply_unregister(priv->battery); err_supply: cancel_work_sync(&priv->init_worker); err_attr: sysfs_remove_group(&priv->dev->kobj, priv->attr_grp); return ret; } static int max1720x_remove(struct i2c_client *client) { struct max1720x_priv *priv = i2c_get_clientdata(client); cancel_work_sync(&priv->init_worker); sysfs_remove_group(&priv->dev->kobj, priv->attr_grp); power_supply_unregister(priv->battery); return 0; } #ifdef CONFIG_PM_SLEEP static int max1720x_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); if (client->irq) { disable_irq(client->irq); enable_irq_wake(client->irq); } return 0; } static int max1720x_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); if (client->irq) { disable_irq_wake(client->irq); enable_irq(client->irq); } return 0; } static SIMPLE_DEV_PM_OPS(max1720x_pm_ops, max1720x_suspend, max1720x_resume); #define MAX1720X_PM_OPS (&max1720x_pm_ops) #else #define MAX1720X_PM_OPS NULL #endif /* CONFIG_PM_SLEEP */ #ifdef CONFIG_OF static const struct of_device_id max1720x_match[] = { { .compatible = "maxim,max17201", }, { .compatible = "maxim,max17205", }, { .compatible = "maxim,max17301", }, { .compatible = "maxim,max17302", }, { .compatible = "maxim,max17303", }, { }, }; MODULE_DEVICE_TABLE(of, max1720x_match); #endif static const struct i2c_device_id max1720x_id[] = { { "max17201", ID_MAX1720X }, { "max17205", ID_MAX1720X }, { "max17301", ID_MAX1730X }, { "max17302", ID_MAX1730X }, { "max17303", ID_MAX1730X }, { }, }; MODULE_DEVICE_TABLE(i2c, max1720x_id); static struct i2c_driver max1720x_i2c_driver = { .driver = { .name = DRV_NAME, .of_match_table = of_match_ptr(max1720x_match), .pm = MAX1720X_PM_OPS, }, .probe = max1720x_probe, .remove = max1720x_remove, .id_table = max1720x_id, }; module_i2c_driver(max1720x_i2c_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Mahir Ozturk <mahir.ozturk@maximintegrated.com>"); MODULE_DESCRIPTION("Maxim MAX17201/5 and MAX17301/2/3 Fuel Gauge driver");
30,367
C
23.912223
80
0.662331
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/LCD/ST7789.py
# ST7789 IPS LCD (320x240) driver import numbers import time import numpy as np import sys import os from PIL import Image from PIL import ImageDraw sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot") sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs]) import Mangdang.Adafruit_GPIO as GPIO import Mangdang.Adafruit_GPIO.SPI as SPI from Mangdang.LCD.gif import AnimatedGif SPI_CLOCK_HZ = 31200000 # 31.2 MHz # Constants for interacting with display registers. ST7789_TFTWIDTH = 320 ST7789_TFTHEIGHT = 240 ST7789_NOP = 0x00 ST7789_SWRESET = 0x01 ST7789_RDDID = 0x04 ST7789_RDDST = 0x09 ST7789_RDDPM = 0x0A ST7789_RDDMADCTL = 0x0B ST7789_RDDCOLMOD = 0x0C ST7789_RDDIM = 0x0D ST7789_RDDSM = 0x0E ST7789_RDDSDR = 0x0F ST7789_SLPIN = 0x10 ST7789_SLPOUT = 0x11 ST7789_PTLON = 0x12 ST7789_NORON = 0x13 ST7789_INVOFF = 0x20 ST7789_INVON = 0x21 ST7789_GAMSET = 0x26 ST7789_DISPOFF = 0x28 ST7789_DISPON = 0x29 ST7789_CASET = 0x2A ST7789_RASET = 0x2B ST7789_RAMWR = 0x2C ST7789_RAMRD = 0x2E ST7789_PTLAR = 0x30 ST7789_VSCRDEF = 0x33 ST7789_TEOFF = 0x34 ST7789_TEON = 0x35 ST7789_MADCTL = 0x36 ST7789_VSCRSADD = 0x37 ST7789_IDMOFF = 0x38 ST7789_IDMON = 0x39 ST7789_COLMOD = 0x3A ST7789_RAMWRC = 0x3C ST7789_RAMRDC = 0x3E ST7789_TESCAN = 0x44 ST7789_RDTESCAN = 0x45 ST7789_WRDISBV = 0x51 ST7789_RDDISBV = 0x52 ST7789_WRCTRLD = 0x53 ST7789_RDCTRLD = 0x54 ST7789_WRCACE = 0x55 ST7789_RDCABC = 0x56 ST7789_WRCABCMB = 0x5E ST7789_RDCABCMB = 0x5F ST7789_RDABCSDR = 0x68 ST7789_RDID1 = 0xDA ST7789_RDID2 = 0xDB ST7789_RDID3 = 0xDC ST7789_RAMCTRL = 0xB0 ST7789_RGBCTRL = 0xB1 ST7789_PORCTRL = 0xB2 ST7789_FRCTRL1 = 0xB3 ST7789_GCTRL = 0xB7 ST7789_DGMEN = 0xBA ST7789_VCOMS = 0xBB ST7789_LCMCTRL = 0xC0 ST7789_IDSET = 0xC1 ST7789_VDVVRHEN = 0xC2 ST7789_VRHS = 0xC3 ST7789_VDVSET = 0xC4 ST7789_VCMOFSET = 0xC5 ST7789_FRCTR2 = 0xC6 ST7789_CABCCTRL = 0xC7 ST7789_REGSEL1 = 0xC8 ST7789_REGSEL2 = 0xCA ST7789_PWMFRSEL = 0xCC ST7789_PWCTRL1 = 0xD0 ST7789_VAPVANEN = 0xD2 ST7789_CMD2EN = 0xDF5A6902 ST7789_PVGAMCTRL = 0xE0 ST7789_NVGAMCTRL = 0xE1 ST7789_DGMLUTR = 0xE2 ST7789_DGMLUTB = 0xE3 ST7789_GATECTRL = 0xE4 ST7789_PWCTRL2 = 0xE8 ST7789_EQCTRL = 0xE9 ST7789_PROMCTRL = 0xEC ST7789_PROMEN = 0xFA ST7789_NVMSET = 0xFC ST7789_PROMACT = 0xFE # Colours for convenience ST7789_BLACK = 0x0000 # 0b 00000 000000 00000 ST7789_BLUE = 0x001F # 0b 00000 000000 11111 ST7789_GREEN = 0x07E0 # 0b 00000 111111 00000 ST7789_RED = 0xF800 # 0b 11111 000000 00000 ST7789_CYAN = 0x07FF # 0b 00000 111111 11111 ST7789_MAGENTA = 0xF81F # 0b 11111 000000 11111 ST7789_YELLOW = 0xFFE0 # 0b 11111 111111 00000 ST7789_WHITE = 0xFFFF # 0b 11111 111111 11111 def color565(r, g, b): """Convert red, green, blue components to a 16-bit 565 RGB value. Components should be values 0 to 255. """ return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) def image_to_data(image): """Generator function to convert a PIL image to 16-bit 565 RGB bytes.""" # NumPy is much faster at doing this. NumPy code provided by: # Keith (https://www.blogger.com/profile/02555547344016007163) pb = np.array(image.convert('RGB')).astype('uint16') color = ((pb[:,:,0] & 0xF8) << 8) | ((pb[:,:,1] & 0xFC) << 3) | (pb[:,:,2] >> 3) return np.dstack(((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist() class ST7789(object): """Representation of an ST7789 IPS LCD.""" def __init__(self, rst, dc, led): """Create an instance of the display using SPI communication. Must provide the GPIO pin number for the D/C pin and the SPI driver. Can optionally provide the GPIO pin number for the reset pin as the rst parameter. """ SPI_PORT = 0 SPI_DEVICE = 0 SPI_MODE = 0b11 SPI_SPEED_HZ = 40000000 self._spi = SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=SPI_SPEED_HZ) self._rst = rst self._dc = dc self._led = led self._gpio = None self.width = ST7789_TFTWIDTH self.height = ST7789_TFTHEIGHT if self._gpio is None: self._gpio = GPIO.get_platform_gpio() # Set DC as output. self._gpio.setup(self._dc, GPIO.OUT) # Setup reset as output (if provided). if self._rst is not None: self._gpio.setup(self._rst, GPIO.OUT) # Turn on the backlight LED self._gpio.setup(self._led, GPIO.OUT) # Set SPI to mode 0, MSB first. self._spi.set_mode(SPI_MODE) self._spi.set_bit_order(SPI.MSBFIRST) self._spi.set_clock_hz(SPI_CLOCK_HZ) # Create an image buffer. self.buffer = Image.new('RGB', (self.width, self.height)) def send(self, data, is_data=True, chunk_size=4096): """Write a byte or array of bytes to the display. Is_data parameter controls if byte should be interpreted as display data (True) or command data (False). Chunk_size is an optional size of bytes to write in a single SPI transaction, with a default of 4096. """ # Set DC low for command, high for data. self._gpio.output(self._dc, is_data) # Convert scalar argument to list so either can be passed as parameter. if isinstance(data, numbers.Number): data = [data & 0xFF] # Write data a chunk at a time. for start in range(0, len(data), chunk_size): end = min(start+chunk_size, len(data)) self._spi.write(data[start:end]) def command(self, data): """Write a byte or array of bytes to the display as command data.""" self.send(data, False) def data(self, data): """Write a byte or array of bytes to the display as display data.""" self.send(data, True) def reset(self): """Reset the display, if reset pin is connected.""" if self._rst is not None: self._gpio.set_high(self._rst) time.sleep(0.100) self._gpio.set_low(self._rst) time.sleep(0.100) self._gpio.set_high(self._rst) time.sleep(0.100) def _init(self): # Initialize the display. Broken out as a separate function so it can # be overridden by other displays in the future. time.sleep(0.012) self.command(0x11) time.sleep(0.150) self.command(0x36) self.data(0xA0) self.data(0x00) self.command(0x3A) self.data(0x05) self.command(0xB2) self.data(0x0C) self.data(0x0C) self.data(0x00) self.data(0x33) self.data(0x33) self.command(0xB7) self.data(0x35) ## ---------------------------------ST7789S Power setting - ---------------------------- self.command(0xBB) self.data(0x29) # self.command(0xC0) # self.data(0x2C) self.command(0xC2) self.data(0x01) self.command(0xC3) self.data(0x19) self.command(0xC4) self.data(0x20) self.command(0xC5) self.data(0x1A) self.command(0xC6) self.data(0x1F) ## 0x0F:60Hz # self.command(0xCA) # self.data(0x0F) # # self.command(0xC8) # self.data(0x08) # # self.command(0x55) # self.data(0x90) self.command(0xD0) self.data(0xA4) self.data(0xA1) ## --------------------------------ST7789S gamma setting - ----------------------------- self.command(0xE0) self.data(0xD0) self.data(0x08) self.data(0x0E) self.data(0x09) self.data(0x09) self.data(0x05) self.data(0x31) self.data(0x33) self.data(0x48) self.data(0x17) self.data(0x14) self.data(0x15) self.data(0x31) self.data(0x34) self.command(0xE1) self.data(0xD0) self.data(0x08) self.data(0x0E) self.data(0x09) self.data(0x09) self.data(0x15) self.data(0x31) self.data(0x33) self.data(0x48) self.data(0x17) self.data(0x14) self.data(0x15) self.data(0x31) self.data(0x34) self.command(0x21) self.command(0x29) time.sleep(0.100) # 100 ms self._gpio.set_high(self._led) def begin(self): """Initialize the display. Should be called once before other calls that interact with the display are called. """ self.reset() self._init() def set_window(self, x0=0, y0=0, x1=None, y1=None): """Set the pixel address window for proceeding drawing commands. x0 and x1 should define the minimum and maximum x pixel bounds. y0 and y1 should define the minimum and maximum y pixel bound. If no parameters are specified the default will be to update the entire display from 0,0 to width-1,height-1. """ if x1 is None: x1 = self.width-1 if y1 is None: y1 = self.height-1 self.command(ST7789_CASET) # Column addr set self.data(x0 >> 8) self.data(x0) # XSTART self.data(x1 >> 8) self.data(x1) # XEND self.command(ST7789_RASET) # Row addr set self.data(y0 >> 8) self.data(y0) # YSTART self.data(y1 >> 8) self.data(y1) # YEND self.command(ST7789_RAMWR) # write to RAM #def display(self, image=None): def display(self, image=None, x0=0, y0=0, x1=None, y1=None): """Write the display buffer or provided image to the hardware. If no image parameter is provided the display buffer will be written to the hardware. If an image is provided, it should be RGB format and the same dimensions as the display hardware. """ # By default write the internal buffer to the display. if image is None: image = self.buffer # Set address bounds to entire display. #self.set_window() if x1 is None: x1 = self.width-1 if y1 is None: y1 = self.height-1 self.set_window(x0, y0, x1, y1) #image.thumbnail((x1-x0+1, y1-y0+1), Image.ANTIALIAS) # Convert image to array of 16bit 565 RGB data bytes. # Unfortunate that this copy has to occur, but the SPI byte writing # function needs to take an array of bytes and PIL doesn't natively # store images in 16-bit 565 RGB format. pixelbytes = list(image_to_data(image)) # Write data to hardware. self.data(pixelbytes) def clear(self, color=(0,0,0)): """Clear the image buffer to the specified RGB color (default black).""" width, height = self.buffer.size self.buffer.putdata([color]*(width*height)) def draw(self): """Return a PIL ImageDraw instance for 2D drawing on the image buffer.""" return ImageDraw.Draw(self.buffer)
11,573
Python
29.781915
129
0.584723
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/LCD/gif.py
import os import time from PIL import Image from PIL import ImageOps class Frame: def __init__(self, duration=0): self.duration = duration self.image = None class AnimatedGif: def __init__(self, display, width=None, height=None, folder=None): self._frame_count = 0 self._loop = 0 self._index = 0 self._duration = 0 self._gif_files = [] self._frames = [] self._gif_folder = folder if width is not None: self._width = width else: self._width = display.width if height is not None: self._height = height else: self._height = display.height self.display = display if folder is not None: self.load_files(folder) self.preload() def advance(self): self._index = (self._index + 1) % len(self._gif_files) def back(self): self._index = (self._index - 1 + len(self._gif_files)) % len(self._gif_files) def load_files(self, folder): gif_files = [f for f in os.listdir(folder) if f.endswith(".gif")] for gif_file in gif_files: image = Image.open(folder + gif_file) # Only add animated Gifs if image.is_animated: self._gif_files.append(gif_file) #print("Found", self._gif_files) if not self._gif_files: print("No Gif files found in current folder") exit() # pylint: disable=consider-using-sys-exit def preload(self): image = Image.open(self._gif_folder + self._gif_files[self._index]) #print("Loading {}...".format(self._gif_files[self._index])) if "duration" in image.info: self._duration = image.info["duration"] else: self._duration = 0 if "loop" in image.info: self._loop = image.info["loop"] else: self._loop = 1 self._frame_count = image.n_frames del self._frames[:] for frame in range(self._frame_count): image.seek(frame) # Create blank image for drawing. # Make sure to create image with mode 'RGB' for full color. frame_object = Frame(duration=self._duration) if "duration" in image.info: frame_object.duration = image.info["duration"] frame_object.image = ImageOps.pad( # pylint: disable=no-member image.convert("RGB"), (self._width, self._height), method=Image.NEAREST, color=(0, 0, 0), centering=(0.5, 0.5), ) self._frames.append(frame_object) def play(self): # Check if we have loaded any files first if not self._gif_files: print("There are no Gif Images loaded to Play") return False #while True: for frame_object in self._frames: start_time = time.time() self.display.display(frame_object.image) while time.time() < (start_time + frame_object.duration / 1000): pass if self._loop == 1: return True if self._loop > 0: self._loop -= 1 def run(self): while True: auto_advance = self.play() if auto_advance: self.advance()
3,404
Python
31.740384
85
0.529083
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PupperCommand/joystick.py
from UDPComms import Publisher, Subscriber, timeout from PS4Joystick import Joystick import time ## you need to git clone the PS4Joystick repo and run `sudo bash install.sh` ## Configurable ## MESSAGE_RATE = 20 PUPPER_COLOR = {"red":0, "blue":0, "green":255} joystick_pub = Publisher(8830,65530) joystick_subcriber = Subscriber(8840, timeout=0.01) joystick = Joystick() joystick.led_color(**PUPPER_COLOR) while True: values = joystick.get_input() left_y = -values["left_analog_y"] right_y = -values["right_analog_y"] right_x = values["right_analog_x"] left_x = values["left_analog_x"] L2 = values["l2_analog"] R2 = values["r2_analog"] R1 = values["button_r1"] L1 = values["button_l1"] square = values["button_square"] x = values["button_cross"] circle = values["button_circle"] triangle = values["button_triangle"] dpadx = values["dpad_right"] - values["dpad_left"] dpady = values["dpad_up"] - values["dpad_down"] msg = { "ly": left_y, "lx": left_x, "rx": right_x, "ry": right_y, "L2": L2, "R2": R2, "R1": R1, "L1": L1, "dpady": dpady, "dpadx": dpadx, "x": x, "square": square, "circle": circle, "triangle": triangle, "message_rate": MESSAGE_RATE, } joystick_pub.send(msg) try: msg = joystick_subcriber.get() joystick.led_color(**msg["ps4_color"]) except timeout: pass time.sleep(1 / MESSAGE_RATE)
1,539
Python
22.692307
76
0.581546
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PupperCommand/README.md
# PupperCommand ## Installation ```shell git clone https://github.com/stanfordroboticsclub/PupperCommand.git cd PupperCommand sudo bash install.sh ``` Then clone https://github.com/stanfordroboticsclub/PS4Joystick/ and follow the installation instructions in the README. ## Starting the joystick publisher 1. The ```install.sh``` script makes the Raspberry Pi automatically look to pair and connect to PS4 joysticks on boot. 2. So once the Raspberry Pi turns on, put the PS4 controller into pairing mode by holding the share and PS button at the same time. The light should start blinking in bursts of two. 3. By around 10 seconds, the joystick should have paired with the Raspberry Pi and the front light on the joystick will change to whatever color you specify in the ```joystick.py``` script. ## Debugging To see if the controller is publishing to the Rover topic use: ```shell rover peek 8830 ``` You can also check the status of the system daemon (systemd) running the ```joystick.py``` script by doing ```shell sudo systemctl status joystick ``` If it shows that the service failed, you can try ```shell sudo systemctl stop joystick sudo systemctl start joystick ``` ## Notes If a packet is lost over the joystick connection, the PS4Joystick code will raise an exception and cause the program to exit. Systemd will then restart the ```joystick.py``` script, which means you will have to re-pair the joystick (hold share + ps4 button until double blinking).
1,473
Markdown
42.35294
281
0.773931
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Legacy/ImageOps.py
# # The Python Imaging Library. # $Id$ # # standard image operations # # History: # 2001-10-20 fl Created # 2001-10-23 fl Added autocontrast operator # 2001-12-18 fl Added Kevin's fit operator # 2004-03-14 fl Fixed potential division by zero in equalize # 2005-05-05 fl Fixed equalize for low number of values # # Copyright (c) 2001-2004 by Secret Labs AB # Copyright (c) 2001-2004 by Fredrik Lundh # # See the README file for information on usage and redistribution. # from . import Image import operator import functools import warnings # # helpers def _border(border): if isinstance(border, tuple): if len(border) == 2: left, top = right, bottom = border elif len(border) == 4: left, top, right, bottom = border else: left = top = right = bottom = border return left, top, right, bottom def _color(color, mode): if isStringType(color): from . import ImageColor color = ImageColor.getcolor(color, mode) return color def _lut(image, lut): if image.mode == "P": # FIXME: apply to lookup table, not image data raise NotImplementedError("mode P support coming soon") elif image.mode in ("L", "RGB"): if image.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return image.point(lut) else: raise IOError("not supported for this image mode") # # actions def autocontrast(image, cutoff=0, ignore=None): """ Maximize (normalize) image contrast. This function calculates a histogram of the input image, removes **cutoff** percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255). :param image: The image to process. :param cutoff: How many percent to cut off from the histogram. :param ignore: The background pixel value (use None for no background). :return: An image. """ histogram = image.histogram() lut = [] for layer in range(0, len(histogram), 256): h = histogram[layer:layer+256] if ignore is not None: # get rid of outliers try: h[ignore] = 0 except TypeError: # assume sequence for ix in ignore: h[ix] = 0 if cutoff: # cut off pixels from both ends of the histogram # get number of pixels n = 0 for ix in range(256): n = n + h[ix] # remove cutoff% pixels from the low end cut = n * cutoff // 100 for lo in range(256): if cut > h[lo]: cut = cut - h[lo] h[lo] = 0 else: h[lo] -= cut cut = 0 if cut <= 0: break # remove cutoff% samples from the hi end cut = n * cutoff // 100 for hi in range(255, -1, -1): if cut > h[hi]: cut = cut - h[hi] h[hi] = 0 else: h[hi] -= cut cut = 0 if cut <= 0: break # find lowest/highest samples after preprocessing for lo in range(256): if h[lo]: break for hi in range(255, -1, -1): if h[hi]: break if hi <= lo: # don't bother lut.extend(list(range(256))) else: scale = 255.0 / (hi - lo) offset = -lo * scale for ix in range(256): ix = int(ix * scale + offset) if ix < 0: ix = 0 elif ix > 255: ix = 255 lut.append(ix) return _lut(image, lut) def colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127): """ Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If **mid** is specified, it uses three-color mapping. The **black** and **white** arguments should be RGB tuples or color names; optionally you can use three-color mapping by also specifying **mid**. Mapping positions for any of the colors can be specified (e.g. **blackpoint**), where these parameters are the integer value corresponding to where the corresponding color should be mapped. These parameters must have logical order, such that **blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified). :param image: The image to colorize. :param black: The color to use for black input pixels. :param white: The color to use for white input pixels. :param mid: The color to use for midtone input pixels. :param blackpoint: an int value [0, 255] for the black mapping. :param whitepoint: an int value [0, 255] for the white mapping. :param midpoint: an int value [0, 255] for the midtone mapping. :return: An image. """ # Initial asserts assert image.mode == "L" if mid is None: assert 0 <= blackpoint <= whitepoint <= 255 else: assert 0 <= blackpoint <= midpoint <= whitepoint <= 255 # Define colors from arguments black = _color(black, "RGB") white = _color(white, "RGB") if mid is not None: mid = _color(mid, "RGB") # Empty lists for the mapping red = [] green = [] blue = [] # Create the low-end values for i in range(0, blackpoint): red.append(black[0]) green.append(black[1]) blue.append(black[2]) # Create the mapping (2-color) if mid is None: range_map = range(0, whitepoint - blackpoint) for i in range_map: red.append(black[0] + i * (white[0] - black[0]) // len(range_map)) green.append(black[1] + i * (white[1] - black[1]) // len(range_map)) blue.append(black[2] + i * (white[2] - black[2]) // len(range_map)) # Create the mapping (3-color) else: range_map1 = range(0, midpoint - blackpoint) range_map2 = range(0, whitepoint - midpoint) for i in range_map1: red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1)) green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1)) blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1)) for i in range_map2: red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2)) green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2)) blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2)) # Create the high-end values for i in range(0, 256 - whitepoint): red.append(white[0]) green.append(white[1]) blue.append(white[2]) # Return converted image image = image.convert("RGB") return _lut(image, red + green + blue) def pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)): """ Returns a sized and padded version of the image, expanded to fill the requested aspect ratio and size. :param image: The image to size and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: What resampling method to use. Default is :py:attr:`PIL.Image.NEAREST`. :param color: The background color of the padded image. :param centering: Control the position of the original image within the padded version. (0.5, 0.5) will keep the image centered (0, 0) will keep the image aligned to the top left (1, 1) will keep the image aligned to the bottom right :return: An image. """ im_ratio = image.width / image.height dest_ratio = float(size[0]) / size[1] if im_ratio == dest_ratio: out = image.resize(size, resample=method) else: out = Image.new(image.mode, size, color) if im_ratio > dest_ratio: new_height = int(image.height / image.width * size[0]) if new_height != size[1]: image = image.resize((size[0], new_height), resample=method) y = int((size[1] - new_height) * max(0, min(centering[1], 1))) out.paste(image, (0, y)) else: new_width = int(image.width / image.height * size[1]) if new_width != size[0]: image = image.resize((new_width, size[1]), resample=method) x = int((size[0] - new_width) * max(0, min(centering[0], 1))) out.paste(image, (x, 0)) return out def crop(image, border=0): """ Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes. .. seealso:: :py:meth:`~PIL.Image.Image.crop` :param image: The image to crop. :param border: The number of pixels to remove. :return: An image. """ left, top, right, bottom = _border(border) return image.crop( (left, top, image.size[0]-right, image.size[1]-bottom) ) def scale(image, factor, resample=Image.NEAREST): """ Returns a rescaled image by a specific factor given in parameter. A factor greater than 1 expands the image, between 0 and 1 contracts the image. :param image: The image to rescale. :param factor: The expansion factor, as a float. :param resample: An optional resampling filter. Same values possible as in the PIL.Image.resize function. :returns: An :py:class:`~PIL.Image.Image` object. """ if factor == 1: return image.copy() elif factor <= 0: raise ValueError("the factor must be greater than 0") else: size = (int(round(factor * image.width)), int(round(factor * image.height))) return image.resize(size, resample) def deform(image, deformer, resample=Image.BILINEAR): """ Deform the image. :param image: The image to deform. :param deformer: A deformer object. Any object that implements a **getmesh** method can be used. :param resample: An optional resampling filter. Same values possible as in the PIL.Image.transform function. :return: An image. """ return image.transform( image.size, Image.MESH, deformer.getmesh(image), resample ) def equalize(image, mask=None): """ Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. :param image: The image to equalize. :param mask: An optional mask. If given, only the pixels selected by the mask are included in the analysis. :return: An image. """ if image.mode == "P": image = image.convert("RGB") h = image.histogram(mask) lut = [] for b in range(0, len(h), 256): histo = [_f for _f in h[b:b+256] if _f] if len(histo) <= 1: lut.extend(list(range(256))) else: step = (functools.reduce(operator.add, histo) - histo[-1]) // 255 if not step: lut.extend(list(range(256))) else: n = step // 2 for i in range(256): lut.append(n // step) n = n + h[i+b] return _lut(image, lut) def expand(image, border=0, fill=0): """ Add border to the image :param image: The image to expand. :param border: Border width, in pixels. :param fill: Pixel fill value (a color value). Default is 0 (black). :return: An image. """ left, top, right, bottom = _border(border) width = left + image.size[0] + right height = top + image.size[1] + bottom out = Image.new(image.mode, (width, height), _color(fill, image.mode)) out.paste(image, (left, top)) return out def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)): """ Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. This function was contributed by Kevin Cazabon. :param image: The image to size and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: What resampling method to use. Default is :py:attr:`PIL.Image.NEAREST`. :param bleed: Remove a border around the outside of the image from all four edges. The value is a decimal percentage (use 0.01 for one percent). The default value is 0 (no border). Cannot be greater than or equal to 0.5. :param centering: Control the cropping position. Use (0.5, 0.5) for center cropping (e.g. if cropping the width, take 50% off of the left side, and therefore 50% off the right side). (0.0, 0.0) will crop from the top left corner (i.e. if cropping the width, take all of the crop off of the right side, and if cropping the height, take all of it off the bottom). (1.0, 0.0) will crop from the bottom left corner, etc. (i.e. if cropping the width, take all of the crop off the left side, and if cropping the height take none from the top, and therefore all off the bottom). :return: An image. """ # by Kevin Cazabon, Feb 17/2000 # kevin@cazabon.com # http://www.cazabon.com # ensure centering is mutable centering = list(centering) if not 0.0 <= centering[0] <= 1.0: centering[0] = 0.5 if not 0.0 <= centering[1] <= 1.0: centering[1] = 0.5 if not 0.0 <= bleed < 0.5: bleed = 0.0 # calculate the area to use for resizing and cropping, subtracting # the 'bleed' around the edges # number of pixels to trim off on Top and Bottom, Left and Right bleed_pixels = (bleed * image.size[0], bleed * image.size[1]) live_size = (image.size[0] - bleed_pixels[0] * 2, image.size[1] - bleed_pixels[1] * 2) # calculate the aspect ratio of the live_size live_size_ratio = float(live_size[0]) / live_size[1] # calculate the aspect ratio of the output image output_ratio = float(size[0]) / size[1] # figure out if the sides or top/bottom will be cropped off if live_size_ratio >= output_ratio: # live_size is wider than what's needed, crop the sides crop_width = output_ratio * live_size[1] crop_height = live_size[1] else: # live_size is taller than what's needed, crop the top and bottom crop_width = live_size[0] crop_height = live_size[0] / output_ratio # make the crop crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0] crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1] crop = ( crop_left, crop_top, crop_left + crop_width, crop_top + crop_height ) # resize the image and return it return image.resize(size, method, box=crop) def flip(image): """ Flip the image vertically (top to bottom). :param image: The image to flip. :return: An image. """ return image.transpose(Image.FLIP_TOP_BOTTOM) def grayscale(image): """ Convert the image to grayscale. :param image: The image to convert. :return: An image. """ return image.convert("L") def invert(image): """ Invert (negate) the image. :param image: The image to invert. :return: An image. """ lut = [] for i in range(256): lut.append(255-i) return _lut(image, lut) def mirror(image): """ Flip image horizontally (left to right). :param image: The image to mirror. :return: An image. """ return image.transpose(Image.FLIP_LEFT_RIGHT) def posterize(image, bits): """ Reduce the number of bits for each color channel. :param image: The image to posterize. :param bits: The number of bits to keep for each channel (1-8). :return: An image. """ lut = [] mask = ~(2**(8-bits)-1) for i in range(256): lut.append(i & mask) return _lut(image, lut) def solarize(image, threshold=128): """ Invert all pixel values above a threshold. :param image: The image to solarize. :param threshold: All pixels above this greyscale level are inverted. :return: An image. """ lut = [] for i in range(256): if i < threshold: lut.append(i) else: lut.append(255-i) return _lut(image, lut) # -------------------------------------------------------------------- # PIL USM components, from Kevin Cazabon. def gaussian_blur(im, radius=None): """ PIL_usm.gblur(im, [radius])""" warnings.warn( 'PIL.ImageOps.gaussian_blur is deprecated. ' 'Use PIL.ImageFilter.GaussianBlur instead. ' 'This function will be removed in a future version.', DeprecationWarning ) if radius is None: radius = 5.0 im.load() return im.im.gaussian_blur(radius) def gblur(im, radius=None): """ PIL_usm.gblur(im, [radius])""" warnings.warn( 'PIL.ImageOps.gblur is deprecated. ' 'Use PIL.ImageFilter.GaussianBlur instead. ' 'This function will be removed in a future version.', DeprecationWarning ) return gaussian_blur(im, radius) def unsharp_mask(im, radius=None, percent=None, threshold=None): """ PIL_usm.usm(im, [radius, percent, threshold])""" warnings.warn( 'PIL.ImageOps.unsharp_mask is deprecated. ' 'Use PIL.ImageFilter.UnsharpMask instead. ' 'This function will be removed in a future version.', DeprecationWarning ) if radius is None: radius = 5.0 if percent is None: percent = 150 if threshold is None: threshold = 3 im.load() return im.im.unsharp_mask(radius, percent, threshold) def usm(im, radius=None, percent=None, threshold=None): """ PIL_usm.usm(im, [radius, percent, threshold])""" warnings.warn( 'PIL.ImageOps.usm is deprecated. ' 'Use PIL.ImageFilter.UnsharpMask instead. ' 'This function will be removed in a future version.', DeprecationWarning ) return unsharp_mask(im, radius, percent, threshold) def box_blur(image, radius): """ Blur the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear time relative to the size of the image for any radius value. :param image: The image to blur. :param radius: Size of the box in one direction. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total. :return: An image. """ warnings.warn( 'PIL.ImageOps.box_blur is deprecated. ' 'Use PIL.ImageFilter.BoxBlur instead. ' 'This function will be removed in a future version.', DeprecationWarning ) image.load() return image._new(image.im.box_blur(radius))
19,772
Python
30.891935
80
0.581732
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/calibrate_tool.py
import re import tkinter as tk import tkinter.messagebox from tkinter import * import _thread import time import os import sys import numpy as np from pupper.HardwareInterface import HardwareInterface ################################################################### OverLoadCurrentMax = 1500000 OverLoadHoldCounterMax = 100 # almost 3s ServoCalibrationFilePath = '/sys/bus/i2c/devices/3-0050/eeprom' servo1_en = 25 servo2_en = 21 hw_version="" ################################################################### class LegPositionScale: def __init__(self,root,location_x,location_y,leg_name): self.LocationX = location_x self.LocationY = location_y delt_x = 40 delt_y = 45 self.Value1 = DoubleVar() self.Value2 = DoubleVar() self.Value3 = DoubleVar() self.title = Label(root,text = leg_name,font = ('bold',16)) self.label1 = Label(root,text = 'Hip') self.slider1 = Scale(root,from_=-100,to=100,variable = self.Value1,length = 120,orient = HORIZONTAL) self.label2 = Label(root,text = 'Thigh') self.slider2 = Scale(root,from_=-55,to=145,variable = self.Value2,length = 120,orient = HORIZONTAL) self.label3 = Label(root,text = 'Calf') self.slider3 = Scale(root,from_=-145,to=55,variable = self.Value3,length = 120,orient = HORIZONTAL) self.label1.place(x=location_x, y=location_y + 20) self.label2.place(x=location_x, y=location_y + delt_y*1+ 20) self.label3.place(x=location_x, y=location_y + delt_y*2+ 20) self.slider1.place(x=location_x + delt_x, y=location_y ) self.slider2.place(x=location_x + delt_x, y=location_y + delt_y*1) self.slider3.place(x=location_x + delt_x, y=location_y + delt_y*2) self.title.place(x=location_x + 70, y=location_y + delt_y*3) def setValue(self,value): self.slider1.set(value[0]) self.slider2.set(value[1]) self.slider3.set(value[2]) return True def getValue(self): value = [] value.append(self.Value1.get()) value.append(self.Value2.get()) value.append(self.Value3.get()) return value class CalibrationTool: def __init__(self,title, width, height): self.Run = True self.FileAllLines = [] #leg slider value self.Leg1SlidersValue = [0,0,0] self.Leg2SlidersValue = [0,0,0] self.Leg3SlidersValue = [0,0,0] self.Leg4SlidersValue = [0,0,0] # calibration data self.Matrix_EEPROM = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [-45, -45, -45, -45]]) self.ServoStandardLAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]] self.ServoNeutralLAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]] self.NocalibrationServoAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]] self.CalibrationServoAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]] #build main window self.MainWindow = tk.Tk() screenwidth = self.MainWindow.winfo_screenwidth() screenheight = self.MainWindow.winfo_screenheight() size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) self.MainWindow.geometry(size) self.MainWindow.title('MiniPupper') #Mini Pupper Calibration Tool self.MainWindow.update() #init title self.Title = Label(self.MainWindow,text = title,font = ('bold',30)) self.Title.place(x=140,y=15) #init robot image self.photo = tk.PhotoImage(file= '/home/ubuntu/Robotics/QuadrupedRobot/Doc/imgs/MiniPupper.Calibration.png') self.MainImg = Label(self.MainWindow,image = self.photo) self.MainImg.place(x=230,y=60) #init read update button self.ResetButton = Button(self.MainWindow,text = ' Reset ',font = ('bold',20),command=self.ResetButtonEvent) self.UpdateButton = Button(self.MainWindow,text = 'Update',font = ('bold',20),command=self.updateButtonEvent) self.RestoreButton = Button(self.MainWindow,text = 'Restore',font = ('bold',7),command=self.RestoreButtonEvent) self.ResetButton.place(x=600,y=100) self.UpdateButton.place(x=600,y=200) self.RestoreButton.place(x=160,y=80) #build 4 legs sliders self.Leg1Calibration = LegPositionScale(self.MainWindow,20,300, 'Leg 1') self.Leg2Calibration = LegPositionScale(self.MainWindow,220,300,'Leg 2') self.Leg3Calibration = LegPositionScale(self.MainWindow,420,300,'Leg 3') self.Leg4Calibration = LegPositionScale(self.MainWindow,620,300,'Leg 4') self.Leg1Calibration.setValue([self.ServoNeutralLAngle[0][0],self.ServoNeutralLAngle[1][0],self.ServoNeutralLAngle[2][0]]) self.Leg2Calibration.setValue([self.ServoNeutralLAngle[0][1],self.ServoNeutralLAngle[1][1],self.ServoNeutralLAngle[2][1]]) self.Leg3Calibration.setValue([self.ServoNeutralLAngle[0][2],self.ServoNeutralLAngle[1][2],self.ServoNeutralLAngle[2][2]]) self.Leg4Calibration.setValue([self.ServoNeutralLAngle[0][3],self.ServoNeutralLAngle[1][3],self.ServoNeutralLAngle[2][3]]) def setLegSlidersValue(self,value): self.Leg1Calibration.setValue(value[0]) self.Leg2Calibration.setValue(value[1]) self.Leg3Calibration.setValue(value[2]) self.Leg4Calibration.setValue(value[3]) return value def readCalibrationFile(self): #read all lines text from EEPROM try: with open(ServoCalibrationFilePath, "rb") as nv_f: arr1 = np.array(eval(nv_f.readline())) arr2 = np.array(eval(nv_f.readline())) matrix = np.append(arr1, arr2) arr3 = np.array(eval(nv_f.readline())) matrix = np.append(matrix, arr3) matrix.resize(3,4) self.Matrix_EEPROM = matrix print("Get nv calibration params: \n" , self.Matrix_EEPROM) except: matrix = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [-45, -45, -45, -45]]) self.Matrix_EEPROM = matrix #update for i in range(3): for j in range(4): self.NocalibrationServoAngle[i][j] = self.Matrix_EEPROM[i,j] self.CalibrationServoAngle[i][j] = self.Matrix_EEPROM[i,j] return True def updateCalibrationMatrix(self,angle): for i in range(3): for j in range(4): self.Matrix_EEPROM[i,j] = angle[i][j] return True def writeCalibrationFile(self): #write matrix to EEPROM buf_matrix = np.zeros((3, 4)) for i in range(3): for j in range(4): buf_matrix[i,j]= self.Matrix_EEPROM[i,j] # Format array object string for np.array p1 = re.compile("([0-9]\.) ( *)") # pattern to replace the space that follows each number with a comma partially_formatted_matrix = p1.sub(r"\1,\2", str(buf_matrix)) p2 = re.compile("(\]\n)") # pattern to add a comma at the end of the first two lines formatted_matrix_with_required_commas = p2.sub("],\n", partially_formatted_matrix) with open(ServoCalibrationFilePath, "w") as nv_f: _tmp = str(buf_matrix) _tmp = _tmp.replace('.' , ',') _tmp = _tmp.replace('[' , '') _tmp = _tmp.replace(']' , '') print(_tmp, file = nv_f) nv_f.close() return True def getLegSlidersValue(self): value = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] self.Leg1SlidersValue = self.Leg1Calibration.getValue() self.Leg2SlidersValue = self.Leg2Calibration.getValue() self.Leg3SlidersValue = self.Leg3Calibration.getValue() self.Leg4SlidersValue = self.Leg4Calibration.getValue() value[0] = [self.Leg1SlidersValue[0],self.Leg2SlidersValue[0],self.Leg3SlidersValue[0],self.Leg4SlidersValue[0]] value[1] = [self.Leg1SlidersValue[1],self.Leg2SlidersValue[1],self.Leg3SlidersValue[1],self.Leg4SlidersValue[1]] value[2] = [self.Leg1SlidersValue[2],self.Leg2SlidersValue[2],self.Leg3SlidersValue[2],self.Leg4SlidersValue[2]] self.ServoNeutralLAngle = value return value def ResetButtonEvent(self): value = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]] for i in range(3): for j in range(4): value[j][i] = self.ServoStandardLAngle[i][j] self.setLegSlidersValue(value) return True def updateButtonEvent(self): # update angle matrix value = self.getLegSlidersValue() angle = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] for i in range(3): for j in range(4): angle[i][j] = self.ServoStandardLAngle[i][j] - value[i][j] +MainWindow.NocalibrationServoAngle[i][j] # limit angle for i in range(3): for j in range(4): if angle[i][j] > 90: angle[i][j] = 90 elif angle[i][j] < -90: angle[i][j] = -90 # popup message box result = tk.messagebox.askquestion('Info:','****** Angle Matrix ******\n' +str(angle[0])+'\n' +str(angle[1])+'\n' +str(angle[2])+'\n' +'****************************\n' +' Update Matrix?') # update matrix if result == 'yes': self.updateCalibrationMatrix(angle) self.writeCalibrationFile() print('******** Angle Matrix ********') print(angle[0]) print(angle[1]) print(angle[2]) print('******************************') return True def RestoreButtonEvent(self): # update angle matrix value = self.getLegSlidersValue() angle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]] # popup message box result = tk.messagebox.askquestion('Warning','Are you sure you want to Restore Factory Setting!?') # update matrix if result == 'yes': self.updateCalibrationMatrix(angle) self.writeCalibrationFile() print('******** Angle Matrix ********') print(angle[0]) print(angle[1]) print(angle[2]) print('******************************') sys.exit() for i in range(3): for j in range(4): self.NocalibrationServoAngle[i][j] = angle[i][j] #self.CalibrationServoAngle[i][j] = angle[i][j] value = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]] for i in range(3): for j in range(4): value[j][i] = self.ServoStandardLAngle[i][j] self.setLegSlidersValue(value) return True def runMainWindow(self): self.MainWindow.mainloop() return True def stopMainWindow(self): self.Run = False return True OverLoadHoldCounter = 0 def OverLoadDetection(): overload = False global OverLoadHoldCounter r = os.popen("cat /sys/class/power_supply/max1720x_battery/current_now") feedback = str(r.readlines()) current_now = int(feedback[3:len(feedback)-4]) if (current_now > OverLoadCurrentMax): OverLoadHoldCounter = OverLoadHoldCounter + 1 if (OverLoadHoldCounter > OverLoadHoldCounterMax): OverLoadHoldCounter = OverLoadHoldCounterMax os.popen("echo 0 > /sys/class/gpio/gpio"+ str(servo1_en) + "/value") os.popen("echo 0 > /sys/class/gpio/gpio"+ str(servo2_en) + "/value") overload = True else: overload = False else: OverLoadHoldCounter = OverLoadHoldCounter - 10 if (OverLoadHoldCounter < 0): OverLoadHoldCounter = 0 os.popen("echo 1 > /sys/class/gpio/gpio" + str(servo1_en) + "/value") os.popen("echo 1 > /sys/class/gpio/gpio" + str(servo2_en) + "/value") overload = False return overload def updateServoValue(MainWindow,servo): while MainWindow.Run: #update leg slider value value = MainWindow.getLegSlidersValue() # overload detection overload = OverLoadDetection() if overload == True: tk.messagebox.showwarning('Warning','Servos overload, please check !!!') else: #control servo joint_angles = np.zeros((3, 4)) joint_angles2 = np.zeros((3, 4)) for i in range(3): for j in range(4): joint_angles[i,j] = (value[i][j] - (MainWindow.NocalibrationServoAngle[i][j] - MainWindow.CalibrationServoAngle[i][j]))*0.01745 servo.set_actuator_postions(joint_angles) time.sleep(0.01) ############################################## with open("/home/ubuntu/.hw_version", "r") as hw_f: hw_version = hw_f.readline() if hw_version == 'P1\n': ServoCalibrationFilePath = "/home/ubuntu/.nv_fle" servo1_en = 19 servo2_en = 26 else: servo1_en = 25 servo2_en = 21 os.system("sudo systemctl stop robot") os.system("echo 1 > /sys/class/gpio/gpio" + str(servo1_en) + "/value") os.system("echo 1 > /sys/class/gpio/gpio" + str(servo2_en) + "/value") MainWindow = CalibrationTool('MiniPupper Calibration Tool',800,500) MainWindow.readCalibrationFile() hardware_interface = HardwareInterface() try: _thread.start_new_thread( updateServoValue, ( MainWindow, hardware_interface,) ) except: print ('Thread Error') MainWindow.runMainWindow() MainWindow.stopMainWindow() os.system("sudo systemctl start robot") os.system("echo 1 > /sys/class/gpio/gpio"+ str(servo1_en) + "/value") os.system("echo 1 > /sys/class/gpio/gpio"+ str(servo2_en) + "/value")
14,538
Python
34.987624
147
0.554684
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/run_robot.py
import os import sys import threading import time import numpy as np from PIL import Image from multiprocessing import Process import multiprocessing sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot") sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs]) from Mangdang.LCD.ST7789 import ST7789 from Mangdang.LCD.gif import AnimatedGif from src.Controller import Controller from src.JoystickInterface import JoystickInterface from src.State import State from pupper.MovementGroup import MovementLib from src.MovementScheme import MovementScheme from pupper.HardwareInterface import HardwareInterface from pupper.Config import Configuration from pupper.Kinematics import four_legs_inverse_kinematics quat_orientation = np.array([1, 0, 0, 0]) cartoons_folder = "/home/ubuntu/Robotics/QuadrupedRobot/Mangdang/LCD/cartoons/" current_show = "" with open("/home/ubuntu/.hw_version", "r") as hw_f: hw_version = hw_f.readline() if hw_version == 'P1\n': disp = ST7789(14, 15, 47) else : disp = ST7789(27, 24, 26) def pic_show(disp, pic_name, _lock): """ Show the specify picture Parameter: disp : display instance pic_name : picture name to show Return : None """ if pic_name == "": return global current_show if pic_name == current_show: return image=Image.open(cartoons_folder + pic_name) image.resize((320,240)) _lock.acquire() disp.display(image) _lock.release() current_show = pic_name def animated_thr_fun(_disp, duration, is_connect, current_leg, _lock): """ The thread funcation to show sleep animated gif Parameter: None Returen: None """ try: gif_player = AnimatedGif(_disp, width=320, height=240, folder=cartoons_folder) last_time = time.time() last_joint_angles = np.zeros(3) while True: if is_connect.value == 1 : #if ((current_leg[0]==last_joint_angles[0]) and (current_leg[1]==last_joint_angles[1]) and (current_leg[2]==last_joint_angles[2])) == False : if ((current_leg[0]==last_joint_angles[0]) and (current_leg[1]==last_joint_angles[1])) == False : last_time = time.time() last_joint_angles[0] = current_leg[0] last_joint_angles[1] = current_leg[1] #last_joint_angles[2] = current_leg[2] if (time.time() - last_time) > duration : _lock.acquire() gif_player.play() _lock.release() time.sleep(0.5) else : last_time = time.time() time.sleep(1.5) except KeyboardInterrupt: _lock.release() pass def cmd_dump(cmd): """ debug interface to show all info about PS4 command Parameter: None return : None """ print("\nGet PS4 command :") print("horizontal_velocity: ", cmd.horizontal_velocity) print("yaw_rate ", cmd.yaw_rate) print("height", cmd.height) print("pitch ", cmd.pitch) print("roll ", cmd.roll) print("activation ", cmd.activation) print("hop_event ", cmd.hop_event) print("trot_event ", cmd.trot_event) print("activate_event ", cmd.activate_event) def main(): """Main program """ # Create config config = Configuration() hardware_interface = HardwareInterface() # show logo global disp disp.begin() disp.clear() image=Image.open(cartoons_folder + "logo.png") image.resize((320,240)) disp.display(image) shutdown_counter = 0 # counter for shuudown cmd # Start animated process duration = 10 is_connect = multiprocessing.Value('l', 0) current_leg = multiprocessing.Array('d', [0, 0, 0]) lock = multiprocessing.Lock() animated_process = Process(target=animated_thr_fun, args=(disp, duration, is_connect, current_leg, lock)) #animated_process.start() #Create movement group scheme movement_ctl = MovementScheme(MovementLib) # Create controller and user input handles controller = Controller( config, four_legs_inverse_kinematics, ) state = State() print("Creating joystick listener...") joystick_interface = JoystickInterface(config) print("Done.") last_loop = time.time() print("Summary of gait parameters:") print("overlap time: ", config.overlap_time) print("swing time: ", config.swing_time) print("z clearance: ", config.z_clearance) print("x shift: ", config.x_shift) # Wait until the activate button has been pressed while True: print("Waiting for L1 to activate robot.") while True: command = joystick_interface.get_command(state) joystick_interface.set_color(config.ps4_deactivated_color) if command.activate_event == 1: break time.sleep(0.1) print("Robot activated.") is_connect.value = 1 joystick_interface.set_color(config.ps4_color) pic_show(disp, "walk.png", lock) while True: now = time.time() if now - last_loop < config.dt: continue last_loop = time.time() # Parse the udp joystick commands and then update the robot controller's parameters command = joystick_interface.get_command(state) #cmd_dump(command) _pic = "walk.png" if command.yaw_rate ==0 else "turnaround.png" if command.trot_event == True: _pic = "walk_r1.png" pic_show(disp, _pic, lock) if command.activate_event == 1: is_connect.value = 0 pic_show(disp, "notconnect.png", lock) print("Deactivating Robot") break state.quat_orientation = quat_orientation # movement scheme movement_switch = command.dance_switch_event gait_state = command.trot_event dance_state = command.dance_activate_event shutdown_signal = command.shutdown_signal #shutdown counter if shutdown_signal == True: shutdown_counter = shutdown_counter + 1 # press shut dow button more 3s(0.015*200), shut down system if shutdown_counter >= 200: print('shutdown system now') os.system('systemctl stop robot') os.system('shutdown -h now') # gait and movement control if gait_state == True or dance_state == True: # if triger tort event, reset the movement number to 0 movement_ctl.resetMovementNumber() movement_ctl.runMovementScheme(movement_switch) food_location = movement_ctl.getMovemenLegsLocation() attitude_location = movement_ctl.getMovemenAttitude() robot_speed = movement_ctl.getMovemenSpeed() controller.run(state,command,food_location,attitude_location,robot_speed) # Update the pwm widths going to the servos hardware_interface.set_actuator_postions(state.joint_angles) current_leg[0]= state.joint_angles[0][0] current_leg[1]= state.joint_angles[1][0] #current_leg[2]= state.joint_angles[2][0] try: main() except KeyboardInterrupt: pass
7,553
Python
33.81106
158
0.60572
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/MovementScheme.py
from ActuatorControl import ActuatorControl LocationStanding = [[ 0.06,0.06,-0.06,-0.06],[-0.05, 0.05,-0.05,0.05],[ -0.07,-0.07,-0.07,-0.07]] DeltLocationMax = 0.001 AttitudeMinMax = [[-20,20],[-20,20],[-100,100]] class SequenceInterpolation: def __init__(self,name,dimension): self.Name = name self.Dimension = dimension self.InterpolationNumber = 1 self.ExecuteTick = 0 self.SequenceExecuteCounter = 0 self.PhaseNumberMax = 1 self.SequencePoint = [[0,0,0]] # interpolation point data self.PointPhaseStart = 0 self.PointPhaseStop = 1 self.TnterpolationDelt = [0,0,0] self.PointNow = [0,0,0] self.PointPrevious = [0,0,0] def setCycleType(self,cycle_type,cycle_index): if cycle_type == 'Forever': self.SequenceExecuteCounter = 9999 elif cycle_type == 'Multiple': self.SequenceExecuteCounter = cycle_index else: self.SequenceExecuteCounter = 1 return True def setInterpolationNumber(self,interpolation_number): self.InterpolationNumber = interpolation_number return True def setSequencePoint(self,sequence): self.SequencePoint = sequence self.PhaseNumberMax = len(sequence) # init now and pre point phase for xyz in range(self.Dimension): self.PointNow[xyz] = sequence[0][xyz] self.PointPrevious[xyz] = sequence[0][xyz] # init start point phase self.PointPhaseStart = 0 # init stop point phase self.PointPhaseStop = self.PointPhaseStart + 1 if self.PointPhaseStop >= len(sequence): self.PointPhaseStop = self.PointPhaseStart return True def updatePointPhase(self): # update start point phase self.PointPhaseStart = self.PointPhaseStart + 1 if self.PointPhaseStart >= self.PhaseNumberMax: if self.SequenceExecuteCounter >0: self.PointPhaseStart = 0 else: self.SequenceExecuteCounter = 0 self.PointPhaseStart = self.PointPhaseStart - 1 # update stop point phase self.PointPhaseStop = self.PointPhaseStart + 1 if self.PointPhaseStop >= self.PhaseNumberMax: self.SequenceExecuteCounter = self.SequenceExecuteCounter - 1 if self.SequenceExecuteCounter >0: self.PointPhaseStop = 0 else: self.SequenceExecuteCounter = 0 self.PointPhaseStop = self.PointPhaseStop - 1 self.PointPhaseStop = 0 return True def updateInterpolationDelt(self): #get start and stop point point_start = self.SequencePoint[self.PointPhaseStart] point_stop = self.SequencePoint[self.PointPhaseStop] for xyz in range(self.Dimension): diff = point_stop[xyz] - point_start[xyz] self.TnterpolationDelt[xyz] = - diff/self.InterpolationNumber return True def getNewPoint(self): #update movement tick self.ExecuteTick = self.ExecuteTick + 1 if self.ExecuteTick >= self.InterpolationNumber: self.ExecuteTick = 0 self.updatePointPhase() self.updateInterpolationDelt() self.PointNow[0] = self.PointPrevious[0] + self.TnterpolationDelt[0] self.PointNow[1] = self.PointPrevious[1] + self.TnterpolationDelt[1] self.PointNow[2] = self.PointPrevious[2] + self.TnterpolationDelt[2] self.PointPrevious = self.PointNow return self.PointNow class Movements: def __init__(self,name,speed_enable,attitude_enable,legs_enable,actuator_enable): self.MovementName = name self.SpeedEnable = speed_enable self.AttitudeEnable = attitude_enable self.LegsEnable = legs_enable self.ActuatorEnable = actuator_enable self.ExitToStand = True self.SpeedMovements = SequenceInterpolation('speed',2) self.AttitudeMovements = SequenceInterpolation('attitude',3) self.LegsMovements = [] self.LegsMovements.append(SequenceInterpolation('leg1',3)) self.LegsMovements.append(SequenceInterpolation('leg2',3)) self.LegsMovements.append(SequenceInterpolation('leg3',3)) self.LegsMovements.append(SequenceInterpolation('leg4',3)) self.ActuatorsMovements = SequenceInterpolation('actuators',1) # init state value self.SpeedInit = [0,0,0] # x, y speed self.AttitudeInit = [0,0,0] # roll pitch yaw rate self.LegsLocationInit = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] # x,y,z for 4 legs self.ActuatorsAngleInit = [0,0,0] # angle for 3 actuators # output self.SpeedOutput = [0,0,0] # x, y speed self.AttitudeOutput = [0,0,0] # roll pitch yaw rate self.LegsLocationOutput = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] # x,y,z for 4 legs self.ActuatorsAngleOutput = [0,0,0] # angle for 3 actuators def setInterpolationNumber(self,number): self.ActuatorsMovements.setInterpolationNumber(number) for leg in range(4): self.LegsMovements[leg].setInterpolationNumber(number) self.AttitudeMovements.setInterpolationNumber(number) self.SpeedMovements.setInterpolationNumber(number) return True def setExitstate(self,state): if state != 'Stand': self.ExitToStand = False return True def setSpeedSequence(self,sequence,cycle_type,cycle_index): self.SpeedMovements.setSequencePoint(sequence) self.SpeedMovements.setCycleType(cycle_type,cycle_index) self.SpeedInit = sequence[0] def setAttitudeSequence(self,sequence,cycle_type,cycle_index): self.AttitudeMovements.setSequencePoint(sequence) self.AttitudeMovements.setCycleType(cycle_type,cycle_index) self.AttitudeInit = sequence[0] def setLegsSequence(self,sequence,cycle_type,cycle_index): for leg in range(4): self.LegsMovements[leg].setSequencePoint(sequence[leg]) self.LegsMovements[leg].setCycleType(cycle_type,cycle_index) # init location self.LegsLocationInit[0][leg] = sequence[leg][0][0] self.LegsLocationInit[1][leg] = sequence[leg][0][1] self.LegsLocationInit[2][leg] = sequence[leg][0][2] def setActuatorsSequence(self,sequence,cycle_type,cycle_index): self.ActuatorsMovements.setSequencePoint(sequence) self.ActuatorsMovements.setCycleType(cycle_type,cycle_index) self.ActuatorsAngleInit = sequence[0] def runMovementSequence(self): if self.SpeedEnable == 'SpeedEnable': self.SpeedOutput = self.SpeedMovements.getNewPoint() if self.AttitudeEnable == 'AttitudeEnable': self.AttitudeOutput = self.AttitudeMovements.getNewPoint() if self.LegsEnable == 'LegsEnable': for leg in range(4): leg_loaction = self.LegsMovements[leg].getNewPoint() for xyz in range(3): self.LegsLocationOutput[xyz][leg] = leg_loaction[xyz] if self.ActuatorEnable == 'ActuatorEnable': self.ActuatorsAngleOutput = self.ActuatorsMovements.getNewPoint() def getSpeedOutput(self, state = 'Normal'): if state == 'Init': return self.SpeedInit else: return self.SpeedOutput def getAttitudeOutput(self, state = 'Normal'): if state == 'Init': return self.AttitudeInit else: return self.AttitudeOutput def getLegsLocationOutput(self, state = 'Normal'): if state == 'Init': return self.LegsLocationInit else: return self.LegsLocationOutput def getActuatorsAngleOutput(self, state = 'Normal'): if state == 'Init': return self.ActuatorsAngleInit else: return self.ActuatorsAngleOutput def getMovementName(self): return self.MovementName class MovementScheme: def __init__(self,movements_lib): self.movements_lib = movements_lib self.movements_now = movements_lib[0] self.movements_pre = movements_lib[0] self.movement_now_name = movements_lib[0].getMovementName() self.movement_now_number = 0 self.ststus = 'Movement' # 'Entry' 'Movement' 'Exit' self.entry_down = False self.exit_down = False self.tick = 0 self.legs_location_pre = LocationStanding self.legs_location_now = LocationStanding self.attitude_pre = [0,0,0] self.attitude_now = [0,0,0] self.speed_pre = [0,0,0] self.speed_now = [0,0,0] self.actuators_pre = [0,0,0] self.actuators_now = [0,0,0] self.actuator = [] self.actuator.append(ActuatorControl(1)) self.actuator.append(ActuatorControl(2)) self.actuator.append(ActuatorControl(3)) def updateMovementType(self): self.movements_pre = self.movements_lib[self.movement_now_number] self.movement_now_number = self.movement_now_number + 1 if self.movement_now_number>= len(self.movements_lib): self.movement_now_number = 0 self.entry_down = False self.exit_down = False self.movements_now = self.movements_lib[self.movement_now_number] return self.movements_now.getMovementName() def resetMovementNumber(self): self.movements_pre = self.movements_lib[self.movement_now_number] self.movement_now_number = 0 self.entry_down = False self.exit_down = False self.movements_now = self.movements_lib[0] return True def updateMovement(self,movement_type): # movement state transition if movement_type != self.movement_now_name: self.ststus = 'Exit' elif(self.entry_down): self.ststus = 'Movement' elif(self.exit_down): self.ststus = 'Entry' self.movement_now_name = movement_type # update system tick self.tick = self.tick+ 1 # movement execute if self.ststus == 'Entry': location_ready = self.movements_now.getLegsLocationOutput('Init') self.legs_location_now,self.entry_down = self.updateMovementGradient(self.legs_location_pre,location_ready) self.legs_location_pre = self.legs_location_now if self.ststus == 'Exit': if self.movements_pre.ExitToStand == False: self.legs_location_now,self.exit_down = self.updateMovementGradient(self.location_pre,LocationStanding) self.legs_location_pre = self.legs_location_now else: self.legs_location_now = self.legs_location_pre self.exit_down = True elif self.ststus == 'Movement': self.updateMovemenScheme(self.tick) self.legs_location_pre = self.legs_location_now self.attitude_pre = self.attitude_now return self.legs_location_now def updateMovementGradient(self,location_now,location_target): loaction_gradient = location_now gradient_done = False gradient_done_counter = 0 #legs gradient for xyz_index in range(3): for leg_index in range(4): diff = location_now[xyz_index][leg_index] - location_target[xyz_index][leg_index] if diff > DeltLocationMax: loaction_gradient[xyz_index][leg_index] = location_now[xyz_index][leg_index] - DeltLocationMax elif diff < -DeltLocationMax: loaction_gradient[xyz_index][leg_index] = location_now[xyz_index][leg_index] + DeltLocationMax else : loaction_gradient[xyz_index][leg_index] = location_target[xyz_index][leg_index] gradient_done_counter = gradient_done_counter + 1 # movement gradient is down if gradient_done_counter == 12: gradient_done = True return loaction_gradient, gradient_done def updateMovemenScheme(self,tick): # run movement self.movements_now.runMovementSequence() # legs movement self.legs_location_now = self.movements_now.getLegsLocationOutput('normal') # speed movement self.speed_now = self.movements_now.getSpeedOutput('normal') # attitude movement self.attitude_now = self.movements_now.getAttitudeOutput('normal') # attitude movement self.actuators_now = self.movements_now.getActuatorsAngleOutput('normal') # attitude process ''' for rpy in range(3): #limite attitude angle if attitude_now[rpy] < AttitudeMinMax[rpy][0]: attitude_now[rpy] = AttitudeMinMax[rpy][0] elif attitude_now[rpy] > AttitudeMinMax[rpy][1]: attitude_now[rpy] = AttitudeMinMax[rpy][1] ''' # speed process return True def runMovementScheme(self,transition): # update movement movement_name = '' if transition == True: movement_name = self.updateMovementType() self.updateMovement(movement_name) return True def getMovemenSpeed(self): speed_now = [0,0,0] for xyz in range(3): speed_now[xyz] = -self.speed_now[xyz] return speed_now def getMovemenLegsLocation(self): return self.legs_location_now def getMovemenAttitude(self): attitude_now_rad = [0,0,0] for rpy in range(3): #angle to radin attitude_now_rad[rpy] = -self.attitude_now[rpy] / 57.3 return attitude_now_rad def getMovemenActuators(self): return self.actuators_now
14,291
Python
31.930876
130
0.607865
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/ActuatorControl.py
import os import sys import time class ActuatorControl: def __init__(self,pwm_number): self.pwm_number = pwm_number def updateDutyCycle(self,angle): duty_cycle = int((1.11*angle+50)*10000) return duty_cycle def updateActuatorAngle(self,angle): if self.pwm_number == 1: actuator_name = 'pwm1' elif self.pwm_number == 2: actuator_name = 'pwm2' elif self.pwm_number == 3: actuator_name = 'pwm3' duty_cycle = self.updateDutyCycle(angle) file_node = '/sys/class/pwm/pwmchip0/' + actuator_name+ '/duty_cycle' f = open(file_node, "w") f.write(str(duty_cycle)) #test = ActuatorControl(3) #time.sleep(10) #for index in range(30): # test.updateActuatorAngle(index*3) # time.sleep(0.1) # test.updateActuatorAngle(0)
856
Python
22.162162
77
0.600467
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/ServoCalibration.py
# WARNING: This file is machine generated. Edit at your own risk. import numpy as np MICROS_PER_RAD = 11.111 * 180.0 / np.pi
128
Python
17.428569
65
0.703125
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/MovementGroup.py
from src.MovementScheme import Movements def appendDanceMovement(): ''' #demo 1 dance_scheme = Movements('stand','SpeedDisable','AttitudeDisable','LegsEnable','ActuatorDisable') dance_scheme.setExitstate('Stand') dance_all_legs = [] dance_all_legs.append([[ 0.06,-0.05,-0.065]]) # leg1 dance_all_legs.append([[ 0.06, 0.05,-0.065]]) # leg2 dance_all_legs.append([[-0.06,-0.05,-0.065]]) # leg3 dance_all_legs.append([[-0.06, 0.05,-0.065]]) # leg4 dance_scheme.setInterpolationNumber(50) dance_scheme.setLegsSequence(dance_all_legs,'Forever',5) MovementLib.append(dance_scheme) # append dance ''' #demo 2 dance_scheme = Movements('push-up','SpeedEnable','AttitudeDisable','LegsEnable','ActuatorDisable') dance_scheme.setExitstate('Stand') dance_all_legs = [] dance_all_legs.append([[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.07],[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.04]]) # leg1 dance_all_legs.append([[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.07],[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.04]]) # leg2 dance_all_legs.append([[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.07],[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.04]]) # leg3 dance_all_legs.append([[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.07],[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.04]]) # leg4 dance_speed = [[0,0,0],[0,0,0],[0,0,0],[0.25,0,0,0],[0.25,0,0,0]] # speed_, speed_y, no_use dance_attitude = [[0,0,0],[10,0,0],[0,0,0]] # roll, pitch, yaw rate dance_scheme.setInterpolationNumber(70) dance_scheme.setLegsSequence(dance_all_legs,'Forever',1) dance_scheme.setSpeedSequence(dance_speed,'Forever',1) dance_scheme.setAttitudeSequence(dance_attitude,'Forever',1) MovementLib.append(dance_scheme) # append dance MovementLib = [] appendDanceMovement()
1,955
Python
38.918367
137
0.588235
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/HardwareInterface.py
import os import sys sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot/") sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs]) from Mangdang import PWMController from pupper.Config import ServoParams, PWMParams #from __future__ import division import numpy as np class HardwareInterface: def __init__(self): self.pwm_params = PWMParams() self.servo_params = ServoParams() def set_actuator_postions(self, joint_angles): send_servo_commands(self.pwm_params, self.servo_params, joint_angles) def set_actuator_position(self, joint_angle, axis, leg): send_servo_command(self.pwm_params, self.servo_params, joint_angle, axis, leg) def pwm_to_duty_cycle(pulsewidth_micros, pwm_params): """Converts a pwm signal (measured in microseconds) to a corresponding duty cycle on the gpio pwm pin Parameters ---------- pulsewidth_micros : float Width of the pwm signal in microseconds pwm_params : PWMParams PWMParams object Returns ------- float PWM duty cycle corresponding to the pulse width """ pulsewidth_micros = int(pulsewidth_micros / 1e6 * pwm_params.freq * pwm_params.range) if np.isnan(pulsewidth_micros): return 0 return int(np.clip(pulsewidth_micros, 0, 4096)) def angle_to_pwm(angle, servo_params, axis_index, leg_index): """Converts a desired servo angle into the corresponding PWM command Parameters ---------- angle : float Desired servo angle, relative to the vertical (z) axis servo_params : ServoParams ServoParams object axis_index : int Specifies which joint of leg to control. 0 is abduction servo, 1 is inner hip servo, 2 is outer hip servo. leg_index : int Specifies which leg to control. 0 is front-right, 1 is front-left, 2 is back-right, 3 is back-left. Returns ------- float PWM width in microseconds """ angle_deviation = ( angle - servo_params.neutral_angles[axis_index, leg_index] ) * servo_params.servo_multipliers[axis_index, leg_index] pulse_width_micros = ( servo_params.neutral_position_pwm + servo_params.micros_per_rad * angle_deviation ) return pulse_width_micros def angle_to_duty_cycle(angle, pwm_params, servo_params, axis_index, leg_index): duty_cycle_f = angle_to_pwm(angle, servo_params, axis_index, leg_index) * 1e3 if np.isnan(duty_cycle_f): return 0 return int(duty_cycle_f) def initialize_pwm(pi, pwm_params): pi.set_pwm_freq(pwm_params.freq) def send_servo_commands(pwm_params, servo_params, joint_angles): for leg_index in range(4): for axis_index in range(3): duty_cycle = angle_to_duty_cycle( joint_angles[axis_index, leg_index], pwm_params, servo_params, axis_index, leg_index, ) # write duty_cycle to pwm linux kernel node file_node = "/sys/class/pwm/pwmchip0/pwm" + str(pwm_params.pins[axis_index, leg_index]) + "/duty_cycle" f = open(file_node, "w") f.write(str(duty_cycle)) def send_servo_command(pwm_params, servo_params, joint_angle, axis, leg): duty_cycle = angle_to_duty_cycle(joint_angle, pwm_params, servo_params, axis, leg) file_node = "/sys/class/pwm/pwmchip0/pwm" + str(pwm_params.pins[axis, leg]) + "/duty_cycle" f = open(file_node, "w") f.write(str(duty_cycle)) def deactivate_servos(pi, pwm_params): for leg_index in range(4): for axis_index in range(3): pi.set_pwm(pwm_params.pins[axis_index, leg_index], 0, 0)
3,798
Python
33.225225
129
0.639547