You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. # -*- test-case-name: twisted.positioning.test.test_base,twisted.positioning.test.test_sentence -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Generic positioning base classes.
  6. @since: 14.0
  7. """
  8. from __future__ import absolute_import, division
  9. from functools import partial
  10. from operator import attrgetter
  11. from zope.interface import implementer
  12. from constantly import Names, NamedConstant
  13. from twisted.python.util import FancyEqMixin
  14. from twisted.positioning import ipositioning
  15. MPS_PER_KNOT = 0.5144444444444444
  16. MPS_PER_KPH = 0.27777777777777777
  17. METERS_PER_FOOT = 0.3048
  18. class Angles(Names):
  19. """
  20. The types of angles.
  21. @cvar LATITUDE: Angle representing a latitude of an object.
  22. @type LATITUDE: L{NamedConstant}
  23. @cvar LONGITUDE: Angle representing the longitude of an object.
  24. @type LONGITUDE: L{NamedConstant}
  25. @cvar HEADING: Angle representing the heading of an object.
  26. @type HEADING: L{NamedConstant}
  27. @cvar VARIATION: Angle representing a magnetic variation.
  28. @type VARIATION: L{NamedConstant}
  29. """
  30. LATITUDE = NamedConstant()
  31. LONGITUDE = NamedConstant()
  32. HEADING = NamedConstant()
  33. VARIATION = NamedConstant()
  34. class Directions(Names):
  35. """
  36. The four cardinal directions (north, east, south, west).
  37. """
  38. NORTH = NamedConstant()
  39. EAST = NamedConstant()
  40. SOUTH = NamedConstant()
  41. WEST = NamedConstant()
  42. @implementer(ipositioning.IPositioningReceiver)
  43. class BasePositioningReceiver(object):
  44. """
  45. A base positioning receiver.
  46. This class would be a good base class for building positioning
  47. receivers. It implements the interface (so you don't have to) with stub
  48. methods.
  49. People who want to implement positioning receivers should subclass this
  50. class and override the specific callbacks they want to handle.
  51. """
  52. def timeReceived(self, time):
  53. """
  54. Implements L{IPositioningReceiver.timeReceived} stub.
  55. """
  56. def headingReceived(self, heading):
  57. """
  58. Implements L{IPositioningReceiver.headingReceived} stub.
  59. """
  60. def speedReceived(self, speed):
  61. """
  62. Implements L{IPositioningReceiver.speedReceived} stub.
  63. """
  64. def climbReceived(self, climb):
  65. """
  66. Implements L{IPositioningReceiver.climbReceived} stub.
  67. """
  68. def positionReceived(self, latitude, longitude):
  69. """
  70. Implements L{IPositioningReceiver.positionReceived} stub.
  71. """
  72. def positionErrorReceived(self, positionError):
  73. """
  74. Implements L{IPositioningReceiver.positionErrorReceived} stub.
  75. """
  76. def altitudeReceived(self, altitude):
  77. """
  78. Implements L{IPositioningReceiver.altitudeReceived} stub.
  79. """
  80. def beaconInformationReceived(self, beaconInformation):
  81. """
  82. Implements L{IPositioningReceiver.beaconInformationReceived} stub.
  83. """
  84. class InvalidSentence(Exception):
  85. """
  86. An exception raised when a sentence is invalid.
  87. """
  88. class InvalidChecksum(Exception):
  89. """
  90. An exception raised when the checksum of a sentence is invalid.
  91. """
  92. class Angle(FancyEqMixin, object):
  93. """
  94. An object representing an angle.
  95. @cvar _RANGE_EXPRESSIONS: A collection of expressions for the allowable
  96. range for the angular value of a particular coordinate value.
  97. @type _RANGE_EXPRESSIONS: C{dict} of L{Angles} constants to callables
  98. @cvar _ANGLE_TYPE_NAMES: English names for angle types.
  99. @type _ANGLE_TYPE_NAMES: C{dict} of L{Angles} constants to C{str}
  100. """
  101. _RANGE_EXPRESSIONS = {
  102. Angles.LATITUDE: lambda latitude: -90.0 < latitude < 90.0,
  103. Angles.LONGITUDE: lambda longitude: -180.0 < longitude < 180.0,
  104. Angles.HEADING: lambda heading: 0 <= heading < 360,
  105. Angles.VARIATION: lambda variation: -180 < variation <= 180,
  106. }
  107. _ANGLE_TYPE_NAMES = {
  108. Angles.LATITUDE: "Latitude",
  109. Angles.LONGITUDE: "Longitude",
  110. Angles.VARIATION: "Variation",
  111. Angles.HEADING: "Heading",
  112. }
  113. compareAttributes = 'angleType', 'inDecimalDegrees'
  114. def __init__(self, angle=None, angleType=None):
  115. """
  116. Initializes an angle.
  117. @param angle: The value of the angle in decimal degrees. (L{None} if
  118. unknown).
  119. @type angle: C{float} or L{None}
  120. @param angleType: A symbolic constant describing the angle type. Should
  121. be one of L{Angles} or {None} if unknown.
  122. @raises ValueError: If the angle type is not the default argument,
  123. but it is an unknown type (not in C{Angle._RANGE_EXPRESSIONS}),
  124. or it is a known type but the supplied value was out of the
  125. allowable range for said type.
  126. """
  127. if angleType is not None and angleType not in self._RANGE_EXPRESSIONS:
  128. raise ValueError("Unknown angle type")
  129. if angle is not None and angleType is not None:
  130. rangeExpression = self._RANGE_EXPRESSIONS[angleType]
  131. if not rangeExpression(angle):
  132. template = "Angle {0} not in allowed range for type {1}"
  133. raise ValueError(template.format(angle, angleType))
  134. self.angleType = angleType
  135. self._angle = angle
  136. @property
  137. def inDecimalDegrees(self):
  138. """
  139. The value of this angle in decimal degrees. This value is immutable.
  140. @return: This angle expressed in decimal degrees, or L{None} if the
  141. angle is unknown.
  142. @rtype: C{float} (or L{None})
  143. """
  144. return self._angle
  145. @property
  146. def inDegreesMinutesSeconds(self):
  147. """
  148. The value of this angle as a degrees, minutes, seconds tuple. This
  149. value is immutable.
  150. @return: This angle expressed in degrees, minutes, seconds. L{None} if
  151. the angle is unknown.
  152. @rtype: 3-C{tuple} of C{int} (or L{None})
  153. """
  154. if self._angle is None:
  155. return None
  156. degrees = abs(int(self._angle))
  157. fractionalDegrees = abs(self._angle - int(self._angle))
  158. decimalMinutes = 60 * fractionalDegrees
  159. minutes = int(decimalMinutes)
  160. fractionalMinutes = decimalMinutes - int(decimalMinutes)
  161. decimalSeconds = 60 * fractionalMinutes
  162. return degrees, minutes, int(decimalSeconds)
  163. def setSign(self, sign):
  164. """
  165. Sets the sign of this angle.
  166. @param sign: The new sign. C{1} for positive and C{-1} for negative
  167. signs, respectively.
  168. @type sign: C{int}
  169. @raise ValueError: If the C{sign} parameter is not C{-1} or C{1}.
  170. """
  171. if sign not in (-1, 1):
  172. raise ValueError("bad sign (got %s, expected -1 or 1)" % sign)
  173. self._angle = sign * abs(self._angle)
  174. def __float__(self):
  175. """
  176. Returns this angle as a float.
  177. @return: The float value of this angle, expressed in degrees.
  178. @rtype: C{float}
  179. """
  180. return self._angle
  181. def __repr__(self):
  182. """
  183. Returns a string representation of this angle.
  184. @return: The string representation.
  185. @rtype: C{str}
  186. """
  187. return "<{s._angleTypeNameRepr} ({s._angleValueRepr})>".format(s=self)
  188. @property
  189. def _angleValueRepr(self):
  190. """
  191. Returns a string representation of the angular value of this angle.
  192. This is a helper function for the actual C{__repr__}.
  193. @return: The string representation.
  194. @rtype: C{str}
  195. """
  196. if self.inDecimalDegrees is not None:
  197. return "%s degrees" % round(self.inDecimalDegrees, 2)
  198. else:
  199. return "unknown value"
  200. @property
  201. def _angleTypeNameRepr(self):
  202. """
  203. Returns a string representation of the type of this angle.
  204. This is a helper function for the actual C{__repr__}.
  205. @return: The string representation.
  206. @rtype: C{str}
  207. """
  208. try:
  209. return self._ANGLE_TYPE_NAMES[self.angleType]
  210. except KeyError:
  211. return "Angle of unknown type"
  212. class Heading(Angle):
  213. """
  214. The heading of a mobile object.
  215. @ivar variation: The (optional) magnetic variation.
  216. The sign of the variation is positive for variations towards the east
  217. (clockwise from north), and negative for variations towards the west
  218. (counterclockwise from north).
  219. If the variation is unknown or not applicable, this is L{None}.
  220. @type variation: C{Angle} or L{None}.
  221. @ivar correctedHeading: The heading, corrected for variation. If the
  222. variation is unknown (L{None}), is None. This attribute is read-only
  223. (its value is determined by the angle and variation attributes). The
  224. value is coerced to being between 0 (inclusive) and 360 (exclusive).
  225. """
  226. def __init__(self, angle=None, variation=None):
  227. """
  228. Initializes an angle with an optional variation.
  229. """
  230. Angle.__init__(self, angle, Angles.HEADING)
  231. self.variation = variation
  232. @classmethod
  233. def fromFloats(cls, angleValue=None, variationValue=None):
  234. """
  235. Constructs a Heading from the float values of the angle and variation.
  236. @param angleValue: The angle value of this heading.
  237. @type angleValue: C{float}
  238. @param variationValue: The value of the variation of this heading.
  239. @type variationValue: C{float}
  240. @return A C{Heading } with the given values.
  241. """
  242. variation = Angle(variationValue, Angles.VARIATION)
  243. return cls(angleValue, variation)
  244. @property
  245. def correctedHeading(self):
  246. """
  247. Corrects the heading by the given variation. This is sometimes known as
  248. the true heading.
  249. @return: The heading, corrected by the variation. If the variation or
  250. the angle are unknown, returns L{None}.
  251. @rtype: C{float} or L{None}
  252. """
  253. if self._angle is None or self.variation is None:
  254. return None
  255. angle = (self.inDecimalDegrees - self.variation.inDecimalDegrees) % 360
  256. return Angle(angle, Angles.HEADING)
  257. def setSign(self, sign):
  258. """
  259. Sets the sign of the variation of this heading.
  260. @param sign: The new sign. C{1} for positive and C{-1} for negative
  261. signs, respectively.
  262. @type sign: C{int}
  263. @raise ValueError: If the C{sign} parameter is not C{-1} or C{1}.
  264. """
  265. if self.variation.inDecimalDegrees is None:
  266. raise ValueError("can't set the sign of an unknown variation")
  267. self.variation.setSign(sign)
  268. compareAttributes = list(Angle.compareAttributes) + ["variation"]
  269. def __repr__(self):
  270. """
  271. Returns a string representation of this angle.
  272. @return: The string representation.
  273. @rtype: C{str}
  274. """
  275. if self.variation is None:
  276. variationRepr = "unknown variation"
  277. else:
  278. variationRepr = repr(self.variation)
  279. return "<%s (%s, %s)>" % (
  280. self._angleTypeNameRepr, self._angleValueRepr, variationRepr)
  281. class Coordinate(Angle):
  282. """
  283. A coordinate.
  284. @ivar angle: The value of the coordinate in decimal degrees, with the usual
  285. rules for sign (northern and eastern hemispheres are positive, southern
  286. and western hemispheres are negative).
  287. @type angle: C{float}
  288. """
  289. def __init__(self, angle, coordinateType=None):
  290. """
  291. Initializes a coordinate.
  292. @param angle: The angle of this coordinate in decimal degrees. The
  293. hemisphere is determined by the sign (north and east are positive).
  294. If this coordinate describes a latitude, this value must be within
  295. -90.0 and +90.0 (exclusive). If this value describes a longitude,
  296. this value must be within -180.0 and +180.0 (exclusive).
  297. @type angle: C{float}
  298. @param coordinateType: The coordinate type. One of L{Angles.LATITUDE},
  299. L{Angles.LONGITUDE} or L{None} if unknown.
  300. """
  301. if coordinateType not in [Angles.LATITUDE, Angles.LONGITUDE, None]:
  302. raise ValueError("coordinateType must be one of Angles.LATITUDE, "
  303. "Angles.LONGITUDE or None, was {!r}"
  304. .format(coordinateType))
  305. Angle.__init__(self, angle, coordinateType)
  306. @property
  307. def hemisphere(self):
  308. """
  309. Gets the hemisphere of this coordinate.
  310. @return: A symbolic constant representing a hemisphere (one of
  311. L{Angles})
  312. """
  313. if self.angleType is Angles.LATITUDE:
  314. if self.inDecimalDegrees < 0:
  315. return Directions.SOUTH
  316. else:
  317. return Directions.NORTH
  318. elif self.angleType is Angles.LONGITUDE:
  319. if self.inDecimalDegrees < 0:
  320. return Directions.WEST
  321. else:
  322. return Directions.EAST
  323. else:
  324. raise ValueError("unknown coordinate type (cant find hemisphere)")
  325. class Altitude(FancyEqMixin, object):
  326. """
  327. An altitude.
  328. @ivar inMeters: The altitude represented by this object, in meters. This
  329. attribute is read-only.
  330. @type inMeters: C{float}
  331. @ivar inFeet: As above, but expressed in feet.
  332. @type inFeet: C{float}
  333. """
  334. compareAttributes = 'inMeters',
  335. def __init__(self, altitude):
  336. """
  337. Initializes an altitude.
  338. @param altitude: The altitude in meters.
  339. @type altitude: C{float}
  340. """
  341. self._altitude = altitude
  342. @property
  343. def inFeet(self):
  344. """
  345. Gets the altitude this object represents, in feet.
  346. @return: The altitude, expressed in feet.
  347. @rtype: C{float}
  348. """
  349. return self._altitude / METERS_PER_FOOT
  350. @property
  351. def inMeters(self):
  352. """
  353. Returns the altitude this object represents, in meters.
  354. @return: The altitude, expressed in feet.
  355. @rtype: C{float}
  356. """
  357. return self._altitude
  358. def __float__(self):
  359. """
  360. Returns the altitude represented by this object expressed in meters.
  361. @return: The altitude represented by this object, expressed in meters.
  362. @rtype: C{float}
  363. """
  364. return self._altitude
  365. def __repr__(self):
  366. """
  367. Returns a string representation of this altitude.
  368. @return: The string representation.
  369. @rtype: C{str}
  370. """
  371. return "<Altitude (%s m)>" % (self._altitude,)
  372. class _BaseSpeed(FancyEqMixin, object):
  373. """
  374. An object representing the abstract concept of the speed (rate of
  375. movement) of a mobile object.
  376. This primarily has behavior for converting between units and comparison.
  377. """
  378. compareAttributes = 'inMetersPerSecond',
  379. def __init__(self, speed):
  380. """
  381. Initializes a speed.
  382. @param speed: The speed that this object represents, expressed in
  383. meters per second.
  384. @type speed: C{float}
  385. @raises ValueError: Raised if value was invalid for this particular
  386. kind of speed. Only happens in subclasses.
  387. """
  388. self._speed = speed
  389. @property
  390. def inMetersPerSecond(self):
  391. """
  392. The speed that this object represents, expressed in meters per second.
  393. This attribute is immutable.
  394. @return: The speed this object represents, in meters per second.
  395. @rtype: C{float}
  396. """
  397. return self._speed
  398. @property
  399. def inKnots(self):
  400. """
  401. Returns the speed represented by this object, expressed in knots. This
  402. attribute is immutable.
  403. @return: The speed this object represents, in knots.
  404. @rtype: C{float}
  405. """
  406. return self._speed / MPS_PER_KNOT
  407. def __float__(self):
  408. """
  409. Returns the speed represented by this object expressed in meters per
  410. second.
  411. @return: The speed represented by this object, expressed in meters per
  412. second.
  413. @rtype: C{float}
  414. """
  415. return self._speed
  416. def __repr__(self):
  417. """
  418. Returns a string representation of this speed object.
  419. @return: The string representation.
  420. @rtype: C{str}
  421. """
  422. speedValue = round(self.inMetersPerSecond, 2)
  423. return "<%s (%s m/s)>" % (self.__class__.__name__, speedValue)
  424. class Speed(_BaseSpeed):
  425. """
  426. The speed (rate of movement) of a mobile object.
  427. """
  428. def __init__(self, speed):
  429. """
  430. Initializes a L{Speed} object.
  431. @param speed: The speed that this object represents, expressed in
  432. meters per second.
  433. @type speed: C{float}
  434. @raises ValueError: Raised if C{speed} is negative.
  435. """
  436. if speed < 0:
  437. raise ValueError("negative speed: %r" % (speed,))
  438. _BaseSpeed.__init__(self, speed)
  439. class Climb(_BaseSpeed):
  440. """
  441. The climb ("vertical speed") of an object.
  442. """
  443. def __init__(self, climb):
  444. """
  445. Initializes a L{Climb} object.
  446. @param climb: The climb that this object represents, expressed in
  447. meters per second.
  448. @type climb: C{float}
  449. """
  450. _BaseSpeed.__init__(self, climb)
  451. class PositionError(FancyEqMixin, object):
  452. """
  453. Position error information.
  454. @cvar _ALLOWABLE_THRESHOLD: The maximum allowable difference between PDOP
  455. and the geometric mean of VDOP and HDOP. That difference is supposed
  456. to be zero, but can be non-zero because of rounding error and limited
  457. reporting precision. You should never have to change this value.
  458. @type _ALLOWABLE_THRESHOLD: C{float}
  459. @cvar _DOP_EXPRESSIONS: A mapping of DOP types (C[hvp]dop) to a list of
  460. callables that take self and return that DOP type, or raise
  461. C{TypeError}. This allows a DOP value to either be returned directly
  462. if it's know, or computed from other DOP types if it isn't.
  463. @type _DOP_EXPRESSIONS: C{dict} of C{str} to callables
  464. @ivar pdop: The position dilution of precision. L{None} if unknown.
  465. @type pdop: C{float} or L{None}
  466. @ivar hdop: The horizontal dilution of precision. L{None} if unknown.
  467. @type hdop: C{float} or L{None}
  468. @ivar vdop: The vertical dilution of precision. L{None} if unknown.
  469. @type vdop: C{float} or L{None}
  470. """
  471. compareAttributes = 'pdop', 'hdop', 'vdop'
  472. def __init__(self, pdop=None, hdop=None, vdop=None, testInvariant=False):
  473. """
  474. Initializes a positioning error object.
  475. @param pdop: The position dilution of precision. L{None} if unknown.
  476. @type pdop: C{float} or L{None}
  477. @param hdop: The horizontal dilution of precision. L{None} if unknown.
  478. @type hdop: C{float} or L{None}
  479. @param vdop: The vertical dilution of precision. L{None} if unknown.
  480. @type vdop: C{float} or L{None}
  481. @param testInvariant: Flag to test if the DOP invariant is valid or
  482. not. If C{True}, the invariant (PDOP = (HDOP**2 + VDOP**2)*.5) is
  483. checked at every mutation. By default, this is false, because the
  484. vast majority of DOP-providing devices ignore this invariant.
  485. @type testInvariant: c{bool}
  486. """
  487. self._pdop = pdop
  488. self._hdop = hdop
  489. self._vdop = vdop
  490. self._testInvariant = testInvariant
  491. self._testDilutionOfPositionInvariant()
  492. _ALLOWABLE_TRESHOLD = 0.01
  493. def _testDilutionOfPositionInvariant(self):
  494. """
  495. Tests if this positioning error object satisfies the dilution of
  496. position invariant (PDOP = (HDOP**2 + VDOP**2)*.5), unless the
  497. C{self._testInvariant} instance variable is C{False}.
  498. @return: L{None} if the invariant was not satisfied or not tested.
  499. @raises ValueError: Raised if the invariant was tested but not
  500. satisfied.
  501. """
  502. if not self._testInvariant:
  503. return
  504. for x in (self.pdop, self.hdop, self.vdop):
  505. if x is None:
  506. return
  507. delta = abs(self.pdop - (self.hdop**2 + self.vdop**2)**.5)
  508. if delta > self._ALLOWABLE_TRESHOLD:
  509. raise ValueError("invalid combination of dilutions of precision: "
  510. "position: %s, horizontal: %s, vertical: %s"
  511. % (self.pdop, self.hdop, self.vdop))
  512. _DOP_EXPRESSIONS = {
  513. 'pdop': [
  514. lambda self: float(self._pdop),
  515. lambda self: (self._hdop**2 + self._vdop**2)**.5,
  516. ],
  517. 'hdop': [
  518. lambda self: float(self._hdop),
  519. lambda self: (self._pdop**2 - self._vdop**2)**.5,
  520. ],
  521. 'vdop': [
  522. lambda self: float(self._vdop),
  523. lambda self: (self._pdop**2 - self._hdop**2)**.5,
  524. ],
  525. }
  526. def _getDOP(self, dopType):
  527. """
  528. Gets a particular dilution of position value.
  529. @param dopType: The type of dilution of position to get. One of
  530. ('pdop', 'hdop', 'vdop').
  531. @type dopType: C{str}
  532. @return: The DOP if it is known, L{None} otherwise.
  533. @rtype: C{float} or L{None}
  534. """
  535. for dopExpression in self._DOP_EXPRESSIONS[dopType]:
  536. try:
  537. return dopExpression(self)
  538. except TypeError:
  539. continue
  540. def _setDOP(self, dopType, value):
  541. """
  542. Sets a particular dilution of position value.
  543. @param dopType: The type of dilution of position to set. One of
  544. ('pdop', 'hdop', 'vdop').
  545. @type dopType: C{str}
  546. @param value: The value to set the dilution of position type to.
  547. @type value: C{float}
  548. If this position error tests dilution of precision invariants,
  549. it will be checked. If the invariant is not satisfied, the
  550. assignment will be undone and C{ValueError} is raised.
  551. """
  552. attributeName = "_" + dopType
  553. oldValue = getattr(self, attributeName)
  554. setattr(self, attributeName, float(value))
  555. try:
  556. self._testDilutionOfPositionInvariant()
  557. except ValueError:
  558. setattr(self, attributeName, oldValue)
  559. raise
  560. pdop = property(fget=lambda self: self._getDOP('pdop'),
  561. fset=lambda self, value: self._setDOP('pdop', value))
  562. hdop = property(fget=lambda self: self._getDOP('hdop'),
  563. fset=lambda self, value: self._setDOP('hdop', value))
  564. vdop = property(fget=lambda self: self._getDOP('vdop'),
  565. fset=lambda self, value: self._setDOP('vdop', value))
  566. _REPR_TEMPLATE = "<PositionError (pdop: %s, hdop: %s, vdop: %s)>"
  567. def __repr__(self):
  568. """
  569. Returns a string representation of positioning information object.
  570. @return: The string representation.
  571. @rtype: C{str}
  572. """
  573. return self._REPR_TEMPLATE % (self.pdop, self.hdop, self.vdop)
  574. class BeaconInformation(object):
  575. """
  576. Information about positioning beacons (a generalized term for the reference
  577. objects that help you determine your position, such as satellites or cell
  578. towers).
  579. @ivar seenBeacons: A set of visible beacons. Note that visible beacons are not
  580. necessarily used in acquiring a positioning fix.
  581. @type seenBeacons: C{set} of L{IPositioningBeacon}
  582. @ivar usedBeacons: A set of the beacons that were used in obtaining a
  583. positioning fix. This only contains beacons that are actually used, not
  584. beacons for which it is unknown if they are used or not.
  585. @type usedBeacons: C{set} of L{IPositioningBeacon}
  586. """
  587. def __init__(self, seenBeacons=()):
  588. """
  589. Initializes a beacon information object.
  590. @param seenBeacons: A collection of beacons that are currently seen.
  591. @type seenBeacons: iterable of L{IPositioningBeacon}s
  592. """
  593. self.seenBeacons = set(seenBeacons)
  594. self.usedBeacons = set()
  595. def __repr__(self):
  596. """
  597. Returns a string representation of this beacon information object.
  598. The beacons are sorted by their identifier.
  599. @return: The string representation.
  600. @rtype: C{str}
  601. """
  602. sortedBeacons = partial(sorted, key=attrgetter("identifier"))
  603. usedBeacons = sortedBeacons(self.usedBeacons)
  604. unusedBeacons = sortedBeacons(self.seenBeacons - self.usedBeacons)
  605. template = ("<BeaconInformation ("
  606. "used beacons ({numUsed}): {usedBeacons}, "
  607. "unused beacons: {unusedBeacons})>")
  608. formatted = template.format(numUsed=len(self.usedBeacons),
  609. usedBeacons=usedBeacons,
  610. unusedBeacons=unusedBeacons)
  611. return formatted
  612. @implementer(ipositioning.IPositioningBeacon)
  613. class PositioningBeacon(object):
  614. """
  615. A positioning beacon.
  616. @ivar identifier: The unique identifier for this beacon. This is usually
  617. an integer. For GPS, this is also known as the PRN.
  618. @type identifier: Pretty much anything that can be used as a unique
  619. identifier. Depends on the implementation.
  620. """
  621. def __init__(self, identifier):
  622. """
  623. Initializes a positioning beacon.
  624. @param identifier: The identifier for this beacon.
  625. @type identifier: Can be pretty much anything (see ivar documentation).
  626. """
  627. self.identifier = identifier
  628. def __hash__(self):
  629. """
  630. Returns the hash of the identifier for this beacon.
  631. @return: The hash of the identifier. (C{hash(self.identifier)})
  632. @rtype: C{int}
  633. """
  634. return hash(self.identifier)
  635. def __repr__(self):
  636. """
  637. Returns a string representation of this beacon.
  638. @return: The string representation.
  639. @rtype: C{str}
  640. """
  641. return "<Beacon ({s.identifier})>".format(s=self)
  642. class Satellite(PositioningBeacon):
  643. """
  644. A satellite.
  645. @ivar azimuth: The azimuth of the satellite. This is the heading (positive
  646. angle relative to true north) where the satellite appears to be to the
  647. device.
  648. @ivar elevation: The (positive) angle above the horizon where this
  649. satellite appears to be to the device.
  650. @ivar signalToNoiseRatio: The signal to noise ratio of the signal coming
  651. from this satellite.
  652. """
  653. def __init__(self,
  654. identifier,
  655. azimuth=None,
  656. elevation=None,
  657. signalToNoiseRatio=None):
  658. """
  659. Initializes a satellite object.
  660. @param identifier: The PRN (unique identifier) of this satellite.
  661. @type identifier: C{int}
  662. @param azimuth: The azimuth of the satellite (see instance variable
  663. documentation).
  664. @type azimuth: C{float}
  665. @param elevation: The elevation of the satellite (see instance variable
  666. documentation).
  667. @type elevation: C{float}
  668. @param signalToNoiseRatio: The signal to noise ratio of the connection
  669. to this satellite (see instance variable documentation).
  670. @type signalToNoiseRatio: C{float}
  671. """
  672. PositioningBeacon.__init__(self, int(identifier))
  673. self.azimuth = azimuth
  674. self.elevation = elevation
  675. self.signalToNoiseRatio = signalToNoiseRatio
  676. def __repr__(self):
  677. """
  678. Returns a string representation of this Satellite.
  679. @return: The string representation.
  680. @rtype: C{str}
  681. """
  682. template = ("<Satellite ({s.identifier}), "
  683. "azimuth: {s.azimuth}, "
  684. "elevation: {s.elevation}, "
  685. "snr: {s.signalToNoiseRatio}>")
  686. return template.format(s=self)
  687. __all__ = [
  688. 'Altitude',
  689. 'Angle',
  690. 'Angles',
  691. 'BasePositioningReceiver',
  692. 'BeaconInformation',
  693. 'Climb',
  694. 'Coordinate',
  695. 'Directions',
  696. 'Heading',
  697. 'InvalidChecksum',
  698. 'InvalidSentence',
  699. 'METERS_PER_FOOT',
  700. 'MPS_PER_KNOT',
  701. 'MPS_PER_KPH',
  702. 'PositionError',
  703. 'PositioningBeacon',
  704. 'Satellite',
  705. 'Speed'
  706. ]