param.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 # vim:set ts=4 sw=4 et:
3 #
4 # Copyright 2014 Vladimir Ermakov.
5 #
6 # This file is part of the mavros package and subject to the license terms
7 # in the top-level LICENSE file of the mavros repository.
8 # https://github.com/mavlink/mavros/tree/master/LICENSE.md
9 
10 import csv
11 import time
12 import rospy
13 import mavros
14 
15 from mavros_msgs.msg import ParamValue
16 from mavros_msgs.srv import ParamPull, ParamPush, ParamGet, ParamSet
17 
18 
19 class Parameter(object):
20  """Class representing one parameter"""
21  def __init__(self, param_id, param_value=0):
22  self.param_id = param_id
23  self.param_value = param_value
24 
25  def __repr__(self):
26  return "<Parameter '{}': {}>".format(self.param_id, self.param_value)
27 
28 
29 class ParamFile(object):
30  """Base class for param file parsers"""
31  def __init__(self, args):
32  pass
33 
34  def read(self, file_):
35  """Returns a iterable of Parameters"""
36  raise NotImplementedError
37 
38  def write(self, file_, parametes):
39  """Writes Parameters to file"""
40  raise NotImplementedError
41 
42 
44  """Parse MissionPlanner param files"""
45 
46  class CSVDialect(csv.Dialect):
47  delimiter = ','
48  doublequote = False
49  skipinitialspace = True
50  lineterminator = '\r\n'
51  quoting = csv.QUOTE_NONE
52 
53  def read(self, file_):
54  to_numeric = lambda x: float(x) if '.' in x else int(x)
55 
56  for data in csv.reader(file_, self.CSVDialect):
57  if data[0].startswith('#'):
58  continue # skip comments
59 
60  if len(data) != 2:
61  raise ValueError("wrong field count")
62 
63  yield Parameter(data[0].strip(), to_numeric(data[1]));
64 
65  def write(self, file_, parameters):
66  writer = csv.writer(file_, self.CSVDialect)
67  writer.writerow(("#NOTE: " + time.strftime("%d.%m.%Y %T") ,))
68  for p in parameters:
69  writer.writerow((p.param_id, p.param_value))
70 
71 
73  """Parse QGC param files"""
74 
75  class CSVDialect(csv.Dialect):
76  delimiter = '\t'
77  doublequote = False
78  skipinitialspace = True
79  lineterminator = '\n'
80  quoting = csv.QUOTE_NONE
81 
82  def read(self, file_):
83  to_numeric = lambda x: float(x) if '.' in x else int(x)
84 
85  for data in csv.reader(file_, self.CSVDialect):
86  if data[0].startswith('#'):
87  continue # skip comments
88 
89  if len(data) != 5:
90  raise ValueError("wrong field count")
91 
92  yield Parameter(data[2].strip(), to_numeric(data[3]));
93 
94  def write(self, file_, parameters):
95  def to_type(x):
96  if isinstance(x, float):
97  return 9 # REAL32
98  elif isinstance(x, int):
99  return 6 # INT32
100  else:
101  raise ValueError("unknown type: " + repr(type(x)))
102 
103  sysid = rospy.get_param(mavros.get_topic('target_system_id'), 1)
104  compid = rospy.get_param(mavros.get_topic('target_component_id'), 1)
105 
106  writer = csv.writer(file_, self.CSVDialect)
107  writer.writerow(("# NOTE: " + time.strftime("%d.%m.%Y %T"), ))
108  writer.writerow(("# Onboard parameters saved by mavparam for ({}, {})".format(sysid, compid), ))
109  writer.writerow(("# MAV ID" , "COMPONENT ID", "PARAM NAME", "VALUE", "(TYPE)"))
110  for p in parameters:
111  writer.writerow((sysid, compid, p.param_id, p.param_value, to_type(p.param_value), )) # XXX
112 
113 
115  if ret.value.integer != 0:
116  return ret.value.integer
117  elif ret.value.real != 0.0:
118  return ret.value.real
119  else:
120  return 0
121 
122 
123 def param_get(param_id):
124  try:
125  get = rospy.ServiceProxy(mavros.get_topic('param', 'get'), ParamGet)
126  ret = get(param_id=param_id)
127  except rospy.ServiceException as ex:
128  raise IOError(str(ex))
129 
130  if not ret.success:
131  raise IOError("Request failed.")
132 
133  return param_ret_value(ret)
134 
135 
136 def param_set(param_id, value):
137  if isinstance(value, float):
138  val = ParamValue(integer=0, real=value)
139  else:
140  val = ParamValue(integer=value, real=0.0)
141 
142  try:
143  set = rospy.ServiceProxy(mavros.get_topic('param', 'set'), ParamSet)
144  ret = set(param_id=param_id, value=val)
145  except rospy.ServiceException as ex:
146  raise IOError(str(ex))
147 
148  if not ret.success:
149  raise IOError("Request failed.")
150 
151  return param_ret_value(ret)
152 
153 
154 def param_get_all(force_pull=False):
155  try:
156  pull = rospy.ServiceProxy(mavros.get_topic('param', 'pull'), ParamPull)
157  ret = pull(force_pull=force_pull)
158  except rospy.ServiceException as ex:
159  raise IOError(str(ex))
160 
161  if not ret.success:
162  raise IOError("Request failed.")
163 
164  params = rospy.get_param(mavros.get_topic('param'))
165 
166  return (ret.param_received,
167  sorted((Parameter(k, v) for k, v in params.items()),
168  key=lambda p: p.param_id)
169  )
170 
171 
172 def param_set_list(param_list):
173  # 1. load parameters to parameter server
174  for p in param_list:
175  rospy.set_param(mavros.get_topic('param', p.param_id), p.param_value)
176 
177  # 2. request push all
178  try:
179  push = rospy.ServiceProxy(mavros.get_topic('param', 'push'), ParamPush)
180  ret = push()
181  except rospy.ServiceException as ex:
182  raise IOError(str(ex))
183 
184  if not ret.success:
185  raise IOError("Request failed.")
186 
187  return ret.param_transfered
def read(self, file_)
Definition: param.py:53
def __init__(self, args)
Definition: param.py:31
def read(self, file_)
Definition: param.py:82
std::string format(const std::string &fmt, Args...args)
def param_set(param_id, value)
Definition: param.py:136
def get_topic(args)
Definition: __init__.py:49
def write(self, file_, parametes)
Definition: param.py:38
def __repr__(self)
Definition: param.py:25
def write(self, file_, parameters)
Definition: param.py:94
def read(self, file_)
Definition: param.py:34
ssize_t len
def param_get_all(force_pull=False)
Definition: param.py:154
def write(self, file_, parameters)
Definition: param.py:65
def param_ret_value(ret)
Definition: param.py:114
def param_get(param_id)
Definition: param.py:123
def __init__(self, param_id, param_value=0)
Definition: param.py:21
def param_set_list(param_list)
Definition: param.py:172


mavros
Author(s): Vladimir Ermakov
autogenerated on Mon Jul 8 2019 03:20:11