Advertisement
Guest User

Untitled

a guest
Nov 12th, 2021
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.14 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. #
  3. # || ____ _ __
  4. # +------+ / __ )(_) /_______________ _____ ___
  5. # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
  6. # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
  7. # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
  8. #
  9. # Copyright (C) 2014 Bitcraze AB
  10. #
  11. # Crazyflie Nano Quadcopter Client
  12. #
  13. # This program is free software; you can redistribute it and/or
  14. # modify it under the terms of the GNU General Public License
  15. # as published by the Free Software Foundation; either version 2
  16. # of the License, or (at your option) any later version.
  17. #
  18. # This program is distributed in the hope that it will be useful,
  19. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. # GNU General Public License for more details.
  22. # You should have received a copy of the GNU General Public License
  23. # along with this program; if not, write to the Free Software
  24. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  25. # MA 02110-1301, USA.
  26. """
  27. Simple example that connects to the first Crazyflie found, logs the Stabilizer
  28. and prints it to the console. After 10s the application disconnects and exits.
  29. """
  30. import logging
  31. import time
  32. from threading import Timer
  33. from datetime import datetime
  34.  
  35. import cflib.crtp # noqa
  36. from cflib.crazyflie import Crazyflie
  37. from cflib.crazyflie.log import LogConfig
  38. from cflib.utils import uri_helper
  39.  
  40. uri = uri_helper.uri_from_env(default='radio://0/25/2M/E7E7E7E702')
  41.  
  42. # Only output errors from the logging framework
  43. logging.basicConfig(level=logging.ERROR)
  44.  
  45.  
  46. class LoggingExample:
  47. """
  48. Simple logging example class that logs the Stabilizer from a supplied
  49. link uri and disconnects after 5s.
  50. """
  51. def __init__(self, link_uri):
  52. """ Initialize and run the example with the specified link_uri """
  53.  
  54. self._cf = Crazyflie(rw_cache='./cache')
  55.  
  56. # Connect some callbacks from the Crazyflie API
  57. self._cf.connected.add_callback(self._connected)
  58. self._cf.disconnected.add_callback(self._disconnected)
  59. self._cf.connection_failed.add_callback(self._connection_failed)
  60. self._cf.connection_lost.add_callback(self._connection_lost)
  61.  
  62. print('Connecting to %s' % link_uri)
  63.  
  64. # Try to connect to the Crazyflie
  65. self._cf.open_link(link_uri)
  66.  
  67. # Variable used to keep main loop occupied until disconnect
  68. self.is_connected = True
  69.  
  70. def _connected(self, link_uri):
  71. """ This callback is called form the Crazyflie API when a Crazyflie
  72. has been connected and the TOCs have been downloaded."""
  73. print('Connected to %s' % link_uri)
  74.  
  75. # The definition of the logconfig can be made before connecting
  76. ## self._lg_stab = LogConfig(name='Stabilizer', period_in_ms=1000)
  77. ## self._lg_stab.add_variable('stateEstimate.x', 'float')
  78. ## self._lg_stab.add_variable('stateEstimate.y', 'float')
  79. ## self._lg_stab.add_variable('stateEstimate.z', 'float')
  80. ## self._lg_stab.add_variable('stabilizer.roll', 'float')
  81. ## self._lg_stab.add_variable('stabilizer.pitch', 'float')
  82. ## self._lg_stab.add_variable('stabilizer.yaw', 'float')
  83. ## # The fetch-as argument can be set to FP16 to save space in the log packet
  84. ## self._lg_stab.add_variable('pm.vbat', 'FP16')
  85.  
  86.  
  87. self._lg_stab = LogConfig(name = "Battery Level", period_in_ms=2500)
  88. self._lg_stab.add_variable("pm.batteryLevel", "float")
  89. #self._lg_stab.add_variable("pm.state", "float")\
  90.  
  91.  
  92.  
  93. # Adding the configuration cannot be done until a Crazyflie is
  94. # connected, since we need to check that the variables we
  95. # would like to log are in the TOC.
  96. try:
  97. self._cf.log.add_config(self._lg_stab)
  98. # This callback will receive the data
  99. self._lg_stab.data_received_cb.add_callback(self._stab_log_data)
  100. # This callback will be called on errors
  101. self._lg_stab.error_cb.add_callback(self._stab_log_error)
  102. # Start the logging
  103. self._lg_stab.start()
  104. except KeyError as e:
  105. print('Could not start log configuration,'
  106. '{} not found in TOC'.format(str(e)))
  107. except AttributeError:
  108. print('Could not add Stabilizer log config, bad configuration.')
  109.  
  110. # Start a timer to disconnect in 10s
  111. t = Timer(25, self._cf.close_link)
  112. t.start()
  113.  
  114. def _stab_log_error(self, logconf, msg):
  115. """Callback from the log API when an error occurs"""
  116. print('Error when logging %s: %s' % (logconf.name, msg))
  117.  
  118. def _stab_log_data(self, now, data, logconf):
  119. """Callback from a the log API when data arrives"""
  120. now = datetime.now()
  121. dt_string = now.strftime("%m/%d/%Y %H:%M:%S")
  122. print(f'[{dt_string}][{logconf.name}]: ', end='')
  123. for name, value in data.items():
  124. print(f'{name}: {value:3.2f}\n', end='')
  125. time.sleep(1)
  126.  
  127. def _connection_failed(self, link_uri, msg):
  128. """Callback when connection initial connection fails (i.e no Crazyflie
  129. at the specified address)"""
  130. print('Connection to %s failed: %s' % (link_uri, msg))
  131. self.is_connected = False
  132.  
  133. def _connection_lost(self, link_uri, msg):
  134. """Callback when disconnected after a connection has been made (i.e
  135. Crazyflie moves out of range)"""
  136. print('Connection to %s lost: %s' % (link_uri, msg))
  137.  
  138. def _disconnected(self, link_uri):
  139. """Callback when the Crazyflie is disconnected (called in all cases)"""
  140. print('Disconnected from %s' % link_uri)
  141. self.is_connected = False
  142.  
  143.  
  144. if __name__ == '__main__':
  145. # Initialize the low-level drivers
  146. cflib.crtp.init_drivers()
  147. le = LoggingExample(uri)
  148.  
  149. # The Crazyflie lib doesn't contain anything to keep the application alive,
  150. # so this is where your application should do something. In our case we
  151. # are just waiting until we are disconnected.
  152. while le.is_connected:
  153. time.sleep(1)
  154.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement