ArtusAPI 1.0.1__tar.gz → 1.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. ArtusAPI-1.1.1/ArtusAPI/artus_api.py +393 -0
  2. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/commands/commands.py +40 -7
  3. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/communication/UART/uart.py +9 -6
  4. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/communication/communication.py +11 -7
  5. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/firmware_update/firmware_updater.py +3 -3
  6. ArtusAPI-1.1.1/ArtusAPI/firmware_update/run_full_firmware_update.py +105 -0
  7. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/robot/artus_lite/artus_lite.py +14 -7
  8. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI.egg-info/PKG-INFO +7 -1
  9. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI.egg-info/SOURCES.txt +1 -0
  10. {artusapi-1.0.1 → ArtusAPI-1.1.1}/PKG-INFO +7 -1
  11. {artusapi-1.0.1 → ArtusAPI-1.1.1}/README.md +92 -27
  12. {artusapi-1.0.1 → ArtusAPI-1.1.1}/setup.py +2 -2
  13. artusapi-1.0.1/ArtusAPI/artus_api.py +0 -250
  14. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/__init__.py +0 -0
  15. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/commands/__init__.py +0 -0
  16. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/communication/UART/__init__.py +0 -0
  17. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/communication/WiFi/__init__.py +0 -0
  18. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/communication/WiFi/wifi_server.py +0 -0
  19. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/communication/__init__.py +0 -0
  20. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/firmware_update/__init__.py +0 -0
  21. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/robot/__init__.py +0 -0
  22. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/robot/artus_lite/__init__.py +0 -0
  23. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/robot/artus_lite/artus_lite_left.py +0 -0
  24. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/robot/artus_lite/artus_lite_right.py +0 -0
  25. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI/robot/robot.py +0 -0
  26. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI.egg-info/dependency_links.txt +0 -0
  27. {artusapi-1.0.1 → ArtusAPI-1.1.1}/ArtusAPI.egg-info/top_level.txt +0 -0
  28. {artusapi-1.0.1 → ArtusAPI-1.1.1}/setup.cfg +0 -0
@@ -0,0 +1,393 @@
1
+
2
+ import sys
3
+ import logging
4
+ from pathlib import Path
5
+ # Current file's directory
6
+ current_file_path = Path(__file__).resolve()
7
+ # Add the desired path to the system path
8
+ desired_path = current_file_path.parent.parent
9
+ sys.path.append(str(desired_path))
10
+ print(desired_path)
11
+
12
+
13
+
14
+ from .communication import Communication
15
+ from .commands import Commands
16
+ from .robot import Robot
17
+ from .firmware_update import FirmwareUpdater
18
+ import time
19
+
20
+ class ArtusAPI:
21
+
22
+ def __init__(self,
23
+ # communication
24
+ communication_method='UART',
25
+ communication_channel_identifier='COM9',
26
+ # robot
27
+ robot_type='artus_lite',
28
+ hand_type ='left',
29
+ stream = False,
30
+ communication_frequency = 200, # hz
31
+ logger = None,
32
+ reset_on_start = 0,
33
+ baudrate = 921600,
34
+ awake = False
35
+ ):
36
+ """
37
+ ArtusAPI class controls the communication and control of between a system and an Artus Hand by Sarcomere Dynamics Inc.
38
+ :communication_method: communication method that is supported on the Artus Hand, see Robot folder for supported methods. Default is UART over USBC
39
+ :communication_channel_identifier: channel identifier for the communication method. Usually a COM Port
40
+ :robot_type: name of the series of robot hand. See Robot folder for list of robots
41
+ :hand_type: left or right
42
+ :stream: Whether feedback data should be streamed (True) or require polling (False)
43
+ :communication_frequency: maximum frequency to stream data to the device and feedback data from the device
44
+ :logger: python logger settings to inherit
45
+ :reset_on_start: If hand is powered off in a non-opened state, or software is stopped in a non-opened state, this value should be set to `1` to reduce risk of jamming. May require a calibration.
46
+ :baudrate: Required for difference between serial over USBC (921600) and serial over RS485 (115200)
47
+ :awake: False by default - if the hand is already in a ready state (LED is green) when starting or restarting a control script, set awake to `True` to bypass resending the `wake_up` function. Sending the `wake_up` function when the hand IS NOT in an open state will cause it to lose calibration
48
+ """
49
+
50
+ self._communication_handler = Communication(communication_method=communication_method,
51
+ communication_channel_identifier=communication_channel_identifier,baudrate=baudrate)
52
+ self._command_handler = Commands(reset_on_start=reset_on_start)
53
+ self._robot_handler = Robot(robot_type = robot_type,
54
+ hand_type = hand_type)
55
+
56
+ self._last_command_sent_time = time.perf_counter()
57
+ self._communication_frequency = communication_frequency
58
+ self._communication_period = 1 / self._communication_frequency
59
+ self._communication_period_ms = self._communication_period * 1000
60
+ self.stream = stream
61
+ self.awake = awake
62
+
63
+ # only used during streaming
64
+ self.last_command_recv_time = time.perf_counter()
65
+
66
+ if not logger:
67
+ self.logger = logging.getLogger(__name__)
68
+ else:
69
+ self.logger = logger
70
+
71
+ # communication setup
72
+ def connect(self):
73
+ """
74
+ Open a connection to the Artus Hand
75
+ """
76
+ self._communication_handler.open_connection()
77
+
78
+ time.sleep(1)
79
+ # send wake command with it
80
+ if not self.awake:
81
+ self.wake_up()
82
+ self.awake = True
83
+ return
84
+
85
+ def disconnect(self):
86
+ """
87
+ Close a connection to the Artus Hand
88
+ """
89
+ return self._communication_handler.close_connection()
90
+
91
+ # robot states
92
+ def wake_up(self):
93
+ """
94
+ Wake-up the Artus Hand
95
+ """
96
+ print(f"communication period = {self._communication_period_ms} ms")
97
+ robot_wake_up_command = self._command_handler.get_robot_start_command(self.stream,int(self._communication_period_ms)) # to ms for masterboard
98
+ self._communication_handler.send_data(robot_wake_up_command)
99
+
100
+ # wait for data back
101
+ if self._communication_handler.wait_for_ack():
102
+ self.logger.info(f'Finished calibration')
103
+ else:
104
+ self.logger.warning(f'Error in calibration')
105
+
106
+ def sleep(self):
107
+ """
108
+ Sleep the Artus Hand
109
+ """
110
+ robot_sleep_command = self._command_handler.get_sleep_command()
111
+ return self._communication_handler.send_data(robot_sleep_command)
112
+ def calibrate(self):
113
+ """
114
+ Calibrate the Artus Hand
115
+ """
116
+ if not self.awake:
117
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
118
+ return
119
+ robot_calibrate_command = self._command_handler.get_calibration_command()
120
+ self._communication_handler.send_data(robot_calibrate_command)
121
+
122
+ # wait for data back
123
+ if self._communication_handler.wait_for_ack():
124
+ self.logger.info(f'Finished calibration')
125
+ else:
126
+ self.logger.warning(f'Error in calibration')
127
+
128
+
129
+ # robot control
130
+ def set_joint_angles(self, joint_angles:dict):
131
+ """
132
+ Set joint angle targets and speed values to the Artus Hand
133
+ :joint_angles: dictionary of input angles and input speeds
134
+ """
135
+ if not self.awake:
136
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
137
+ return
138
+ self._robot_handler.set_joint_angles(joint_angles=joint_angles,name=False)
139
+ robot_set_joint_angles_command = self._command_handler.get_target_position_command(self._robot_handler.robot.hand_joints)
140
+ # check communication frequency
141
+ if not self._check_communication_frequency(self._last_command_sent_time):
142
+ return False
143
+ return self._communication_handler.send_data(robot_set_joint_angles_command)
144
+
145
+ def set_home_position(self):
146
+ """
147
+ sends the joints to home positions (0) which opens the Artus Hand
148
+ """
149
+ if not self.awake:
150
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
151
+ return
152
+
153
+ self._robot_handler.set_home_position()
154
+ robot_set_home_position_command = self._command_handler.get_target_position_command(hand_joints=self._robot_handler.robot.hand_joints)
155
+ # check communication frequency
156
+ if not self._check_communication_frequency(self._last_command_sent_time):
157
+ return False
158
+ return self._communication_handler.send_data(robot_set_home_position_command)
159
+
160
+ def _check_communication_frequency(self,last_command_time):
161
+ """
162
+ check if the communication frequency is too high
163
+ """
164
+ current_time = time.perf_counter()
165
+ if current_time - last_command_time < self._communication_period:
166
+ self.logger.warning("Command not sent. Communication frequency is too high.")
167
+ return False
168
+ last_command_time = current_time
169
+ return True
170
+
171
+ # robot feedback
172
+ def _receive_feedback(self):
173
+ """
174
+ Send a request for feedback data and receive feedback data
175
+ """
176
+ if not self.awake:
177
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
178
+ return
179
+
180
+ feedback_command = self._command_handler.get_states_command()
181
+ self._communication_handler.send_data(feedback_command)
182
+ # test
183
+ time.sleep(0.001)
184
+ return self._communication_handler.receive_data()
185
+
186
+ def get_joint_angles(self):
187
+ """
188
+ Populate feedback fields in self._robot_handler.hand_joints dict
189
+ """
190
+ if not self.awake:
191
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
192
+ return
193
+
194
+ feedback_command = self._receive_feedback()
195
+ joint_angles = self._robot_handler.get_joint_angles(feedback_command)
196
+ # print(joint_angles)
197
+ return joint_angles
198
+
199
+ # robot feedback stream
200
+ def get_streamed_joint_angles(self):
201
+ """
202
+ Populate feedback fields in self._robot_handler.hand_joints dict
203
+ """
204
+ if not self.awake:
205
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
206
+ return
207
+
208
+ if not self._check_communication_frequency(self.last_command_recv_time):
209
+ return None
210
+ else:
211
+ feedback_command = self._communication_handler.receive_data()
212
+ if not feedback_command:
213
+ print(f'feedback is none')
214
+ return None
215
+ joint_angles = self._robot_handler.get_joint_angles(feedback_command)
216
+ return joint_angles
217
+
218
+ def update_firmware(self,upload_flag='y',file_location=None,drivers_to_flash=0):
219
+ """
220
+ send firmware update to the actuators
221
+ """
222
+ file_path = None
223
+ fw_size = 0
224
+ # input to upload a new file
225
+ if upload_flag == None:
226
+ upload_flag = input(f'Uploading a new BIN file? (y/n) : ')
227
+ upload = True
228
+
229
+
230
+ # Create new firmware updater instance
231
+ self._firmware_updater = FirmwareUpdater(self._communication_handler,
232
+ self._command_handler)
233
+
234
+ if upload_flag == 'n' or upload_flag == 'N':
235
+ self._firmware_updater.file_location = 'not empty'
236
+ upload = False
237
+ else:
238
+ if file_location is None: file_location = input('Please enter binfile absolute path: ')
239
+ self._firmware_updater.file_location = file_location
240
+
241
+ fw_size = self._firmware_updater.get_bin_file_info()
242
+
243
+ # set which drivers to flash should be 1-8
244
+ if drivers_to_flash == None:
245
+ drivers_to_flash = int(input(f'Which drivers would you like to flash? \n0: All Actuators \n1-8 Specific Actuator \n9: Peripheral Controller \nEnter: '))
246
+
247
+ firmware_command = self._command_handler.get_firmware_command(fw_size,upload,drivers_to_flash)
248
+ self._communication_handler.send_data(firmware_command)
249
+ if upload:
250
+ self._firmware_updater.update_firmware(fw_size)
251
+
252
+ print(f'File size = {fw_size}')
253
+ print(f'flashing...')
254
+ self._communication_handler.wait_for_ack()
255
+ print(f'Power Cycle the device to take effect')
256
+
257
+
258
+
259
+
260
+ def request_joint_and_motor(self):
261
+ """
262
+ request joint and motor from user
263
+ """
264
+ j,m = None,None
265
+ while True:
266
+ j = int(input(f'Enter Joint to reset: '))
267
+ if 0 <= j <= 15:
268
+ break
269
+ else:
270
+ print(f'Invalid joint number, please try again')
271
+ while True:
272
+ m = int(input(f'Enter Motor to reset: '))
273
+ if 0 <= m <= 2:
274
+ break
275
+ else:
276
+ print(f'Invalid motor number, please try again')
277
+ return j,m
278
+
279
+
280
+ def reset(self,j=None,m=None):
281
+ """
282
+ Reset a joint back to it's open state, used if finger is "jammed" in close state
283
+ """
284
+ if not self.awake:
285
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
286
+ return
287
+ if j is None or m is None:
288
+ j,m = self.request_joint_and_motor()
289
+
290
+ reset_command = self._command_handler.get_locked_reset_low_command(j,m)
291
+ self._communication_handler.send_data(reset_command)
292
+
293
+ def hard_close(self,j=None,m=None):
294
+ """
295
+ drive a joint partially closed - used if finger is "jammed" in open state
296
+ """
297
+ if not self.awake:
298
+ self.logger.warning(f'Hand not ready, send `wake_up` command')
299
+ return
300
+ if j is None or m is None:
301
+ j,m = self.request_joint_and_motor()
302
+
303
+ hard_close = self._command_handler.get_hard_close_command(j,m)
304
+ self._communication_handler.send_data(hard_close)
305
+
306
+ def update_param(self):
307
+ """
308
+ Parameter update, used to change the communication method
309
+ """
310
+ com = None
311
+ while com not in ['UART','CAN','RS485']:
312
+ com = input('Enter Communication Protocol you would like to change to (default: UART, CAN, RS485): ')
313
+ if com == 'CAN':
314
+ feed = None
315
+ while feed not in ['P','C','ALL']:
316
+ feed = input('Enter feedback information (P: Positions only, C: Positions and Force, ALL: Position, force and temperature): ')
317
+ else:
318
+ feed = None
319
+ command = self._command_handler.update_param_command(com,feed)
320
+ self._communication_handler.send_data(command)
321
+
322
+ # wait for data back
323
+ if self._communication_handler.wait_for_ack():
324
+ self.logger.info(f'Finished Updating Param')
325
+ else:
326
+ self.logger.warning(f'Error in updating Param')
327
+
328
+ def save_grasp_onhand(self,index=1):
329
+ """
330
+ function to save a grasp on the Artus Hand in non-volatile memory to be called.
331
+ Defeault index is 1, value can be 1-6
332
+ """
333
+ command = [0]*32
334
+ for joint,data in self._robot_handler.robot.hand_joints.items():
335
+ command[data.index] = data.target_angle
336
+ command[data.index+16] = data.velocity
337
+
338
+ self._communication_handler.send_data(self._command_handler.get_save_grasp_command(index,command))
339
+ feedback = None
340
+ while not feedback:
341
+ ack,feedback = self._communication_handler.receive_data()
342
+
343
+ if feedback is not None:
344
+ print(feedback[:33])
345
+
346
+ def get_saved_grasps_onhand(self):
347
+ """
348
+ Function to print saved grasps on the Artus non-volatile memory.
349
+ Prints 6 grasps
350
+ """
351
+ self._communication_handler.send_data(self._command_handler.get_return_grasps_command())
352
+
353
+ for i in range(6):
354
+ feedback = None
355
+ while not feedback:
356
+ ack,feedback = self._communication_handler.receive_data()
357
+
358
+ if feedback is not None:
359
+ print(feedback[:33])
360
+
361
+ def execute_grasp(self,index=1):
362
+ """
363
+ Sends a command to the Artus hand that executes a grasp position from the non-volatile memory grasp array
364
+ """
365
+ self._communication_handler.send_data(self._command_handler.get_execute_grasp_command(index))
366
+ feedback = None
367
+ while not feedback:
368
+ ack,feedback = self._communication_handler.receive_data()
369
+
370
+ if feedback is not None:
371
+ print(feedback[:33])
372
+
373
+ def wipe_sd(self):
374
+ """
375
+ wipe sd card and reset with factory default settings
376
+ """
377
+ self._communication_handler.send_data(self._command_handler.get_wipe_sd_command())
378
+ feedback = None
379
+ while not feedback:
380
+ ack,feedback = self._communication_handler.receive_data()
381
+
382
+
383
+ def test_artus_api():
384
+ artus_api = ArtusAPI()
385
+ artus_api.connect()
386
+ artus_api.wake_up()
387
+ artus_api.calibrate()
388
+ artus_api.set_home_position()
389
+ time.sleep(2)
390
+ artus_api.disconnect()
391
+
392
+ if __name__ == "__main__":
393
+ test_artus_api()
@@ -18,6 +18,7 @@ class Commands:
18
18
  save_grasp_onboard_command = 0xC8,
19
19
  return_grasps_command = 0xD2,
20
20
  execute_grasp_command = 0xE0,
21
+ wipe_sd_command = 0x46,
21
22
  reset_on_start = 0):
22
23
 
23
24
  self.commands = {
@@ -32,10 +33,13 @@ class Commands:
32
33
  'save_grasp_onboard_command': save_grasp_onboard_command,
33
34
  'return_grasps_command': return_grasps_command,
34
35
  'execute_grasp_command': execute_grasp_command,
35
- 'update_param_command' : update_param_command
36
+ 'update_param_command' : update_param_command,
37
+ 'wipe_sd_command' : wipe_sd_command
36
38
  }
37
39
  self.reset_on_start = reset_on_start
38
40
 
41
+ self.command_buffer = None
42
+
39
43
  def get_robot_start_command(self,stream:bool,freq:int) -> list:
40
44
  """
41
45
  Creates a message to start the hand
@@ -149,23 +153,52 @@ class Commands:
149
153
  if communication:
150
154
  command_list[1] = 1
151
155
  if communication == 'UART':
152
- command_list[1+16] = 1
156
+ command_list[17] = 1
153
157
  elif communication == 'CAN':
154
- command_list[1+16] = 2
158
+ command_list[17] = 2
155
159
  elif communication == 'RS485':
156
- command_list[1+16] = 3
160
+ command_list[17] = 3
157
161
 
158
162
  if feedback:
159
163
  command_list[2] = 1
160
164
  if feedback == 'ALL':
161
- command_list[2+16] = 2
165
+ command_list[18] = 2
162
166
  elif feedback == 'PC':
163
- command_list[2+16] = 1
167
+ command_list[18] = 1
164
168
  elif feedback == 'P':
165
- command_list[2+16] = 0
169
+ command_list[18] = 0
170
+
171
+ return command_list
172
+
173
+ def get_save_grasp_command(self,grasp_index=1, command=None):
174
+ """
175
+ Used to save grasps commands directly to the Artus hand's non-volatile memory.
176
+ @param: grasp_index - 1-6
177
+ @param: command should be a 32B integer list, 16 target positions, 16 velocities
178
+ """
179
+ command_list = [(self.commands['save_grasp_onboard_command'])+grasp_index] + command
180
+ if len(command_list) == 33:
181
+ return command_list
182
+ else:
183
+ return None
184
+
185
+ def get_return_grasps_command(self):
186
+ command_list = [0]*32
187
+ command_list.insert(0,self.commands['return_grasps_command'])
188
+
189
+ return command_list
190
+
191
+ def get_execute_grasp_command(self,index=1):
192
+ command_list = [0]*32
193
+ command_list.insert(0,self.commands['execute_grasp_command']+index)
166
194
 
167
195
  return command_list
196
+
197
+ def get_wipe_sd_command(self):
198
+ command_list = [0]*32
199
+ command_list.insert(0,self.commands['wipe_sd_command'])
168
200
 
201
+ return command_list
169
202
 
170
203
  if __name__ == "__main__":
171
204
  None
@@ -33,6 +33,7 @@ class UART:
33
33
  self.esp32.open()
34
34
  self.logger.info(f"Opening {self.port} @ {self.baudrate} baudrate")
35
35
  self.esp32.flush()
36
+ msg_bytes = self.esp32.read_all()
36
37
  except Exception as e:
37
38
  self.logger.error(f'Error opening port {self.port}')
38
39
  self.logger.error(e)
@@ -41,6 +42,7 @@ class UART:
41
42
  # print(data)
42
43
  try:
43
44
  self.esp32.write(data)
45
+ self.esp32.flush()
44
46
 
45
47
  # required delay
46
48
  t = time.perf_counter()
@@ -58,22 +60,23 @@ class UART:
58
60
  # pass
59
61
  try:
60
62
  x = time.perf_counter()
61
- # print(f'time start: {x}')
63
+ # # print(f'time start: {x}')
62
64
  while self.esp32.in_waiting < 65:
63
- if time.perf_counter() - x > 0.02:
65
+ if time.perf_counter() - x > 0.001:
64
66
  break
65
67
  # print(f'elapsed time: {time.perf_counter() - x}')
66
68
  # time.sleep(0.03)
67
69
  # check data
68
70
  if self.esp32.in_waiting >= 65: # get data if greater or equal to 65
69
71
  msg_bytes = self.esp32.read(65)
70
- print(msg_bytes)
72
+ # print(msg_bytes)
71
73
  return msg_bytes
72
- elif self.esp32.in_waiting > 0: # clear buffer if not correct amount of data
73
- msg_bytes = self.esp32.read_all()
74
- self.logger.warning(f"Incomplete data received - package size = {(self.esp32.in_waiting)}")
74
+ elif self.esp32.in_waiting > 0:
75
+ # msg_bytes = self.esp32.read_all()
76
+ # self.logger.warning(f"Incomplete data received - package size = {(self.esp32.in_waiting)}")
75
77
  return None
76
78
  else: # non blocking
79
+ # self.logger.warning(f"No data available to receive")
77
80
  return None
78
81
  except Exception as e:
79
82
  self.logger.warning(f"No data available to receive {e}")
@@ -113,14 +113,15 @@ class Communication:
113
113
  self.logger.error("unable to connect to Robot")
114
114
  print(e)
115
115
 
116
- def send_data(self, message:list):
116
+ def send_data(self, message:list,no_debug=1):
117
117
  """
118
118
  send message
119
119
  """
120
120
  try:
121
121
  # Test
122
122
  self.logger.info(f'data sent to hand {message}')
123
- print(f'data sent to hand = {message}')
123
+ if not no_debug:
124
+ print(f'data sent to hand = {message}')
124
125
  byte_msg = self._list_to_byte_encode(message)
125
126
  self.communicator.send(byte_msg)
126
127
  return True
@@ -136,12 +137,13 @@ class Communication:
136
137
  """
137
138
  byte_msg_recv = None
138
139
  try:
139
- while byte_msg_recv is None:
140
- byte_msg_recv = self.communicator.receive()
141
- if not byte_msg_recv:
142
- # self.logger.warning("No data received")
143
- return None,None
140
+ byte_msg_recv = self.communicator.receive()
141
+ if not byte_msg_recv:
142
+ # self.logger.warning("No data received")
143
+ return None,None
144
144
  ack,message_received = self._byte_to_list_decode(byte_msg_recv)
145
+ if ack == 9:
146
+ self.logger.warning("[E] error ack")
145
147
  # print(ack)
146
148
  except Exception as e:
147
149
  self.logger.warning("unable to receive message")
@@ -154,9 +156,11 @@ class Communication:
154
156
 
155
157
 
156
158
  def wait_for_ack(self):
159
+ start_time = time.perf_counter()
157
160
  while 1:
158
161
  tmp,rc_csum = self.receive_data()
159
162
  if tmp is not None:
163
+ print(f'ack received in {time.perf_counter() - start_time} seconds')
160
164
  return 1
161
165
  time.sleep(0.001)
162
166
 
@@ -1,6 +1,8 @@
1
1
  import os
2
2
  import time
3
3
  import logging
4
+ import platform
5
+ import subprocess
4
6
 
5
7
  BYTES_CHUNK = 32
6
8
  UPLOAD_CHUNKS_COMMAND = 0x30
@@ -74,7 +76,7 @@ class FirmwareUpdater:
74
76
  # print(f'{chunk} {len(chunk)}')
75
77
 
76
78
  # send data
77
- self._communication_handler.send_data(chunk)
79
+ self._communication_handler.send_data(chunk,1)
78
80
 
79
81
  # sleep
80
82
  time.sleep(0.008)
@@ -107,7 +109,6 @@ class FirmwareUpdater:
107
109
  while 1:
108
110
  tmp,rc_csum = self._communication_handler.receive_data()
109
111
  if tmp == 2:
110
- # print(f'{tmp} {rc_csum[0]}')
111
112
  if rc_csum[0] == 1:
112
113
  return True
113
114
  else:
@@ -117,7 +118,6 @@ class FirmwareUpdater:
117
118
  self.logger.error(f'firmware flash failed')
118
119
  return False
119
120
  time.sleep(0.001)
120
-
121
121
 
122
122
 
123
123
  def test_firmware_updater():
@@ -0,0 +1,105 @@
1
+ # ------------------------------------------------------------------------------
2
+ # ---------------------------- Import Libraries --------------------------------
3
+ # ------------------------------------------------------------------------------
4
+ import time
5
+ import json
6
+ # Add the desired path to the system path
7
+ import os
8
+ import sys
9
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
10
+ print("Project Root", PROJECT_ROOT)
11
+ sys.path.append(PROJECT_ROOT)
12
+ # import ArtusAPI
13
+ from ..ArtusAPI.artus_api import ArtusAPI
14
+
15
+ # Determine OS and run appropriate flash script
16
+ import platform
17
+ import subprocess
18
+
19
+ def example():
20
+
21
+ periph = "periph.bin"
22
+ act = "actuator.bin"
23
+ fp = PROJECT_ROOT+"/Sarcomere_Dynamics_Resources/ArtusAPI/firmware_update/bins/"
24
+
25
+ print(fp+periph)
26
+ print(fp+act)
27
+
28
+ input("""
29
+ ╔══════════════════════════════════════════════════════════════════╗
30
+ ║ Make sure ARTUS masterboard is in boot mode ║
31
+ ║ Press Enter when ready ║
32
+ ╚══════════════════════════════════════════════════════════════════╝
33
+ """)
34
+ # Prompt user for communication method and identifier
35
+ communication_method = input(
36
+ """
37
+ ╔══════════════════════════════════════════════════════════════════╗
38
+ ║ Select Communication Method ║
39
+ ╠══════════════════════════════════════════════════════════════════╣
40
+ ║ Options: ║
41
+ ║ 1 -> UART ║
42
+ ║ 2 -> RS485 ║
43
+ ╚══════════════════════════════════════════════════════════════════╝
44
+ >> Input Option (1-2): """
45
+ )
46
+
47
+ if communication_method == "1":
48
+ communication_method = "UART"
49
+ else:
50
+ communication_method = "RS485"
51
+
52
+ communication_channel_identifier = input("Enter COM port (e.g. COM3): ")
53
+
54
+ artusapi = ArtusAPI(communication_method=communication_method,
55
+ communication_channel_identifier=communication_channel_identifier,
56
+ awake = True)
57
+
58
+ # -------------------------------------------------------------------------------
59
+ # --------------------------------- Example -------------------------------------
60
+ # -------------------------------------------------------------------------------
61
+
62
+ os_type = platform.system()
63
+
64
+ if os_type == "Windows":
65
+ flash_script = os.path.join(PROJECT_ROOT, "Sarcomere_Dynamics_Resources", "ArtusAPI", "firmware_update", "flash_script.bat")
66
+ elif os_type in ["Linux", "Darwin"]:
67
+ flash_script = os.path.join(PROJECT_ROOT, "Sarcomere_Dynamics_Resources", "ArtusAPI", "firmware_update", "flash_script.sh")
68
+ else:
69
+ raise OSError(f"Unsupported operating system: {os_type}")
70
+
71
+ print(f"\nRunning firmware update script for {os_type}...")
72
+
73
+ try:
74
+ # Run the flash script
75
+ subprocess.run([flash_script], check=True, shell=True)
76
+ print("Firmware update completed successfully")
77
+ except subprocess.CalledProcessError as e:
78
+ print(f"Error running firmware update script: {e}")
79
+ except FileNotFoundError:
80
+ print(f"Flash script not found at: {flash_script}")
81
+
82
+
83
+ input("""
84
+ ╔══════════════════════════════════════════════════════════════════╗
85
+ ║ Please restart the ARTUS hand in normal mode ║
86
+ ║ Press Enter when ready ║
87
+ ╚══════════════════════════════════════════════════════════════════╝
88
+ """)
89
+
90
+ artusapi.connect()
91
+
92
+
93
+ # update firmware for spi first
94
+ artusapi.update_firmware(upload_flag='y', file_location=fp+periph, drivers_to_flash=9)
95
+ artusapi.update_firmware(upload_flag='y', file_location=fp+act, drivers_to_flash=0)
96
+
97
+ print("""
98
+ ╔══════════════════════════════════════════════════════════════════╗
99
+ ║ Firmware update completed successfully ║
100
+ ║ Please close this script and restart the ARTUS hand ║
101
+ ╚══════════════════════════════════════════════════════════════════╝
102
+ """)
103
+
104
+ if __name__ == "__main__":
105
+ example()
@@ -180,13 +180,20 @@ class ArtusLite:
180
180
  Get the joint angles and feedback list data
181
181
  and populate the feedback fields in the hand_joints dictionary
182
182
  """
183
- print(f'FB PACKAGE = {feedback_package}')
184
- for name,joint_data in self.hand_joints.items():
185
- joint_data.feedback_angle = feedback_package[1][joint_data.index]
186
- joint_data.feedback_current = feedback_package[1][joint_data.index+15]
187
- joint_data.feedback_temperature = feedback_package[1][joint_data.index+31]
188
-
189
- return feedback_package
183
+ # print(f'FB PACKAGE = {feedback_package}')
184
+ try:
185
+ for name,joint_data in self.hand_joints.items():
186
+ joint_data.feedback_angle = feedback_package[1][joint_data.index]
187
+ joint_data.feedback_current = feedback_package[1][joint_data.index+15]
188
+ joint_data.feedback_temperature = feedback_package[1][joint_data.index+31]
189
+
190
+ return feedback_package
191
+ except TypeError:
192
+ # print(f'feedback_package is None')
193
+ return None
194
+ except Exception as e:
195
+ print(e)
196
+ return None
190
197
 
191
198
 
192
199
  def main():
@@ -1,5 +1,11 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ArtusAPI
3
- Version: 1.0.1
3
+ Version: 1.1.1
4
4
  Summary: API to control Artus Family of Robots by Sarcomere Dynamics Inc
5
+ Home-page: UNKNOWN
5
6
  Author: Sarcomere Dynamics Inc.
7
+ License: UNKNOWN
8
+ Platform: UNKNOWN
9
+
10
+ UNKNOWN
11
+
@@ -16,6 +16,7 @@ ArtusAPI/communication/WiFi/__init__.py
16
16
  ArtusAPI/communication/WiFi/wifi_server.py
17
17
  ArtusAPI/firmware_update/__init__.py
18
18
  ArtusAPI/firmware_update/firmware_updater.py
19
+ ArtusAPI/firmware_update/run_full_firmware_update.py
19
20
  ArtusAPI/robot/__init__.py
20
21
  ArtusAPI/robot/robot.py
21
22
  ArtusAPI/robot/artus_lite/__init__.py
@@ -1,5 +1,11 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ArtusAPI
3
- Version: 1.0.1
3
+ Version: 1.1.1
4
4
  Summary: API to control Artus Family of Robots by Sarcomere Dynamics Inc
5
+ Home-page: UNKNOWN
5
6
  Author: Sarcomere Dynamics Inc.
7
+ License: UNKNOWN
8
+ Platform: UNKNOWN
9
+
10
+ UNKNOWN
11
+
@@ -1,10 +1,28 @@
1
1
  <img src='data/images/SarcomereLogoHorizontal.svg'>
2
2
 
3
- # Python Artus Robotic Hand API
4
- This repository contains a Python API for controlling the Artus robotic hands by Sarcomere Dynamics Inc.
3
+ # Python ARTUS Robotic Hand API
4
+
5
+ This repository contains a Python API for controlling the ARTUS robotic hands by Sarcomere Dynamics Inc.
5
6
 
6
7
  Please contact the team if there are any issues that arise through the use of the API.
7
8
 
9
+ ## Introduction
10
+ __Please read through the entire README and the _User Manual_ before using the ARTUS hand__
11
+
12
+ The user manual contains in-depth operational and troubleshooting guidelines for the device.
13
+
14
+ This repository contains the following:
15
+ * [ARTUS API](/ArtusAPI/)
16
+ * [ROS2 Node](/ros2/)
17
+ * [Examples](/examples/)
18
+
19
+ Below is a list of the ARTUS hands that are compatible with the API:
20
+ * ARTUS Lite
21
+
22
+ ### VERY IMPORTANT
23
+ * [Requirements](#requirements)
24
+ * [Normal Startup Procedure](#normal-startup-procedure)
25
+
8
26
  ## Table of Contents
9
27
  * [Getting Started](#getting-started)
10
28
  * [Video Introduction](#video-introduction)
@@ -17,9 +35,14 @@ Please contact the team if there are any issues that arise through the use of th
17
35
  * [Serial Example](#serial-example)
18
36
  * [Normal Startup Procedure](#normal-startup-procedure)
19
37
  * [Interacting with the API](#interacting-with-the-api)
38
+ * [Startup Commands](#startup-commands)
20
39
  * [Setting Joints](#setting-joints)
40
+ * [Input Units](#input-units)
21
41
  * [Getting Feedback](#getting-feedback)
42
+ * [SD Card Interactions](#sd-card-intersactions)
43
+ * [Changing Communication Methods](#changing-communication-methods)
22
44
  * [Controlling Multiple Hands](#controlling-multiple-hands)
45
+ * [Special Commands](#special-commands)
23
46
  * [Teleoperation Considerations](#teleoperation-considerations)
24
47
  * [Directory Structure](#directory-structure)
25
48
 
@@ -41,18 +64,16 @@ pip install pyserial
41
64
  pip install ArtusAPI
42
65
  ```
43
66
 
44
- ## Usage
67
+ __Alternatively, cloning the repository and using the repository locally in a project scope is another option, it may be more up-to-date than the pip stable release.__
45
68
 
46
- ### Running example.py
47
- Before running the example script, determine whether your Artus Lite is running USB Serial or WiFi, and edit the following line with the name of the port over UART or target SSID for WiFi
69
+ ```bash
70
+ pip install -r requirements.txt
71
+ ```
48
72
 
49
- * On Windows, find the port name by navigating to "Device Manager">"Ports". It should show up as a COM port. (e.g. COM3)
50
- * On Linux, use the command `dmesg | grep ttyUSB` to find the usb device. (e.g. /dev/ttyUSB1)
51
- * If a permission error is encountered, use the command `sudo chmod 777 /dev/ttyUSB1`
73
+ ## Usage
52
74
 
53
- ```python
54
- artusapi = ArtusAPI(communication_method='UART',hand_type='right',communication_channel_identifier='/dev/ttyUSB1')
55
- ```
75
+ ### Running example.py
76
+ See [General Example README](/examples/general_example/README.md)
56
77
 
57
78
  ### Creating an ArtusAPI Class Object
58
79
  Below are some examples of instantiating the ArtusAPI class to control a single hand. Below is a description of the parameters and what they mean.
@@ -62,15 +83,16 @@ Below are some examples of instantiating the ArtusAPI class to control a single
62
83
  * `__robot_type__` : The Artus robot hand name
63
84
  * `__hand_type__` : left or right hand
64
85
  * `__stream__` : whether streaming feedback data is required or not. Default: `False`
65
- * `__communication_frequency__` : The frequency of the feedback and command communication. Default: `400` Hz
86
+ * `__communication_frequency__` : The frequency of the feedback and command communication. Default: `200` Hz
66
87
  * `__logger__` : If integrating the API into control code, you may already have a logger. THis will allow for homogeneous logging to the same files as what you currently have. Default: `None`
67
- * `__reset_on_start__` : If the hand is not in a closed state when last powered off, setting to `1` will open the hand before ready to receive commands. This _MUST_ be set if powered off in a closed state, or a calibrate must be run before sending target commands
68
- * `__baudrate__` : required to differentiate between Serial over USB-C and Serial over RS485, default `921600` for SUBC, `115200` for RS485
88
+ * `__reset_on_start__` : If the hand is not in a closed state when last powered off, setting to `1` will open the hand before ready to receive commands. This _MUST_ be set if powered off in a closed state, and a calibrate may need to be run before sending accurate target commands
89
+ * `__baudrate__` : required to differentiate between Serial over USB-C and Serial over RS485, default `921600`
90
+ * `__awake__` : False by default - if the hand is already in a ready state (LED is green) when starting or restarting a control script, set woken to `True` to bypass resending the `wake_up` function, which could lead to lost calibration.
69
91
 
70
92
  #### Serial Example
71
93
  ```python
72
94
  from ArtusAPI.artus_api import ArtusAPI
73
- artus_lite = ArtusAPI(robot_type='artus_lite', communication_type='UART',hand_type='right',communication_channel_identifier='COM7')
95
+ artus_lite = ArtusAPI(robot_type='artus_lite', communication_type='UART',hand_type='right',communication_channel_identifier='COM7',reset_on_start=0)
74
96
 
75
97
  artus_lite.connect()
76
98
  ```
@@ -86,11 +108,24 @@ Second, the `ArtusAPI.wake_up()` function must be run to allow the hand to load
86
108
 
87
109
  Once these two steps are complete, optionally, you can run `ArtusAPI.calibrate()` to calibrate the finger joints. Otherwise, the system is now ready to start sending and receiving data!
88
110
 
111
+ **_Note: If running version v1.0.1, `wake_up` is called inside the `connect()` function_**
112
+
89
113
  ## Interacting with the API
90
114
  To get the most out of the Artus hands, the functions that will likely be most interacted with are `set_joint_angles(self, joint_angles:dict)` and `get_joint_angles(self)`. The `set_joint_angles` function allows the user to set 16 independent joint values with a desired velocity/force value in the form of a dictionary. See the [grasp_close file](data/hand_poses/grasp_close.json) for an example of a full 16 joint dictionary for the Artus Lite. See the [Artus Lite README](ArtusAPI/robot/artus_lite/README.md) for joint mapping.
91
115
 
116
+ e.g.
117
+ ```python
118
+ artusapi.set_joint_angles(pinky_dict)
119
+ ```
120
+ ### Startup Commands
121
+ * `connect` is used to start a connection between the API and the hand via the communication method chosen. It will then send a `wake_up` command if `awake == False`.
122
+ * The `wake_up` command properly configures the hand and the actuators. Once an `ack` is returned, the hand is now ready to be controlled
123
+ * `calibrate` sends a full calibration command sequence for all the fingers.
124
+
125
+
92
126
  ### Setting Joints
93
127
  As mentioned above, there are 16 independent degrees of freedom for the Artus Lite, which can be set simultaneously or independently. If, for example, a user need only curl the pinky, a shorter dictionary like the following could be used as a parameter to the function:
128
+
94
129
  ```
95
130
  pinky_dict = {"pinky_flex" :
96
131
  {
@@ -109,22 +144,50 @@ ArtusAPI.set_joint_angles(pinky_dict)
109
144
 
110
145
  Notice that the above example does not include the `"input_speed"` field that the json file has. The `"input_speed"` field is optional and will default to the nominal speed.
111
146
 
147
+ ### Input Units
148
+ * Input Angle: the input angle is an integer value in degrees
149
+ * velocity: the velocity is in a percentage unit 0-100. Minimum movement requirement is around 30. This value pertains to the gripping force of the movement.
150
+
112
151
  ### Getting Feedback
113
152
  There are two ways to get feedback data depending on how the class is instantiated.
114
153
 
115
154
  1. In streaming mode (`stream = True`), after sending the `wake_up()` command, the system will start streaming feedback data which will populate the `ArtusAPI._robot_handler.robot.hand_joints` dictionary. Fields that hold feedback data are named with `feedback_X` where _X_ could be angle, current or temperature.
116
155
  2. In Request mode (`stream = False`), sending a `get_joint_angles()` command will request the feedback data before anything is sent from the Artus hand. This communication setting is slower than the streaming mode, but for testing purposes and getting familiar with the Artus hand, we recommend starting with this setting.
156
+ 3. Feedback message has the following data: ACK, Feedback angle (degrees), Motor Current (mA), Temperature. The following is a table for the ACK value.
157
+
158
+ | ACK Value | Meaning |
159
+ | :---: | :------: |
160
+ | 2 | ACK_RECEIVED FOR BLOCKING COMMANDS |
161
+ | 9 | ERROR |
162
+ | 25 | TARGET ACHIEVED |
163
+
164
+
165
+ ### SD Card Intersactions
166
+ Before using the Artus Lite's digital IO functionality to communicate with a robotic arm, there are two steps that need to be done.
167
+ 1. Users must set the grasps that they want to call. This is done through the UI or general_example.py, using the `save_grasp_onhand` command. This command will save the last command sent to the hand in the designated position specified (1-6) on the SD card and persist through resets.
168
+ 2. Users can use the `execute_grasp` command to call the grasps through the API.
169
+ 3. Users can print to the terminal all 6 grasps saved to the SD Card using `get_saved_grasps_onhand`
170
+
171
+ Each of the above will print the target command saved on the SD card to the terminal.
172
+
173
+ ### Changing Communication Methods
174
+ To change the communication method between USBC, RS485 and CAN, use the `update_param` command. __Additional steps have to be taken to switch to CAN__. See the User Manual for instructions.
117
175
 
118
176
  ### Controlling multiple hands
119
- We can define two instances of hands with different `port` and `target_ssid`. In theory, it can spin up an unlimited amount of hands, bottlenecked by the amount of wifi controllers and COM ports associated with the machine. e.g.
120
- ```python
121
- artus_liteLeft = Artus3DAPI(target_ssid='Artus3DLH',port='/dev/ttyUSB0',communication_method='UART')
122
- artus_liteRight = Artus3DAPI(target_ssid='Artus3DRH',port='/dev/ttyUSB1',communication_method='UART')
123
- artusHands = [artus_liteLeft,artus_liteRight]
124
- ```
177
+ We can define two instances of hands with different `communication_channel_identifier`. In theory, it can spin up an unlimited amount of hands, bottlenecked by the amount of wifi controllers and COM ports associated with the machine.
178
+
179
+ ### Special Commands
180
+ The following commands are to be used in only certain circumstances with the help of the Sarcomere Dynamics Team. __THESE COMMANDS ARE NOT TO BE USED WITHOUT INSTRUCTION FROM SARCOMERE DYNAMICS INC.__
181
+
182
+ * `reset` command is to be used when a finger is jammed in an closed state and won't respond to a open command, requiring the index of the joint and the motor.
183
+ * `hard_close` command is used when a joint is fully opened and isn't responding to closing command, requiring the index of the joint and the motor.
125
184
 
126
185
  ## Teleoperation Considerations
127
- ** **IT IS IMPORTANT TO ADD A DELAY BETWEEN SENDING MESSAGES, CURRENT SUGGESTED FREQUENCY FOR BEST USE IS 10 Hz OR DELAY OF 0.1s** **
186
+ For teleoperation, there is a parameter for the class that lets the user set the `communication frequency` without adding delays into the communication.
187
+
188
+ ```python
189
+ artus_liteLeft = Artus3DAPI(target_ssid='Artus3DLH',port='COM5',communication_method='UART',communication_frequency = 40)
190
+ ```
128
191
 
129
192
  ## Directory Structure
130
193
  ```bash
@@ -145,8 +208,10 @@ artusHands = [artus_liteLeft,artus_liteRight]
145
208
  ```
146
209
 
147
210
  ## Revision Control
148
- | Date | Revision | Description |
149
- | :---: | :------: | :---------: |
150
- | Nov. 14, 2023 | v1.0b | Initial release - Artus Lite Mk 5 |
151
- | Apr. 23, 2024 | v1.1b | Beta release - Artus Lite Mk 6 |
152
- | Oct. 9, 2024 | v1.0 | Artus Lite Release |
211
+ | Date | Revision | Description | Pip Release |
212
+ | :---: | :------: | :---------: | :----------: |
213
+ | Nov. 14, 2023 | v1.0b | Initial release - Artus Lite Mk 5 | NA |
214
+ | Apr. 23, 2024 | v1.1b | Beta release - Artus Lite Mk 6 | NA |
215
+ | Oct. 9, 2024 | v1.0 | Artus Lite Release | v1.0 |
216
+ | Oct. 23, 2024 | v1.0.2 | awake parameter added, wake up function in connect | v1.0.1 |
217
+ | Nov. 14, 2024 | v1.1 | firmware v1.1 release | v1.1 |
@@ -2,10 +2,10 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name='ArtusAPI',
5
- version='1.0.1',
5
+ version='1.1.1',
6
6
  description='API to control Artus Family of Robots by Sarcomere Dynamics Inc',
7
7
  # package_dir={'': '/'}, # tells setuptools that your packages are under src
8
- packages=find_packages(exclude=['data*', 'examples*', 'tests*','venv*']),
8
+ packages=find_packages(exclude=['data*', 'examples*', 'tests*','venv*', 'urdf*', 'ros2*']),
9
9
  author='Sarcomere Dynamics Inc.'
10
10
  # packages=find_packages(where='/'),
11
11
  # other setup configurations
@@ -1,250 +0,0 @@
1
-
2
- import sys
3
- import logging
4
- from pathlib import Path
5
- # Current file's directory
6
- current_file_path = Path(__file__).resolve()
7
- # Add the desired path to the system path
8
- desired_path = current_file_path.parent.parent
9
- sys.path.append(str(desired_path))
10
- print(desired_path)
11
-
12
-
13
-
14
- from .communication import Communication
15
- from .commands import Commands
16
- from .robot import Robot
17
- from .firmware_update import FirmwareUpdater
18
- import time
19
-
20
- class ArtusAPI:
21
-
22
- def __init__(self,
23
- # communication
24
- communication_method='UART',
25
- communication_channel_identifier='COM9',
26
- # robot
27
- robot_type='artus_lite',
28
- hand_type ='left',
29
- stream = False,
30
- communication_frequency = 400, # hz
31
- logger = None,
32
- reset_on_start = 0,
33
- baudrate = 921600
34
- ):
35
- """
36
- ArtusAPI class controls the communication and control of between a system and an Artus Hand by Sarcomere Dynamics Inc.
37
- :communication_method: communication method that is supported on the Artus Hand
38
- :communication_channel_identifier: channel identifier for the communication method
39
- :robot_type: name of the series of robot hand
40
- :hand_type: left or right
41
- :stream: streaming feedback data
42
- :communication_frequency: maximum frequency to stream data
43
- :logger: python logger settings to inherit
44
- """
45
-
46
- self._communication_handler = Communication(communication_method=communication_method,
47
- communication_channel_identifier=communication_channel_identifier,baudrate=baudrate)
48
- self._command_handler = Commands(reset_on_start=reset_on_start)
49
- self._robot_handler = Robot(robot_type = robot_type,
50
- hand_type = hand_type)
51
-
52
- self._last_command_sent_time = time.perf_counter()
53
- self._communication_frequency = 1 / communication_frequency
54
- self._communication_frequency_us = int(self._communication_frequency * 1000000)
55
- self.stream = stream
56
-
57
- if not logger:
58
- self.logger = logging.getLogger(__name__)
59
- else:
60
- self.logger = logger
61
-
62
- # communication setup
63
- def connect(self):
64
- """
65
- Open a connection to the Artus Hand
66
- """
67
- self._communication_handler.open_connection()
68
-
69
- time.sleep(1)
70
- # send wake command with it
71
- return self.wake_up()
72
-
73
- def disconnect(self):
74
- """
75
- Close a connection to the Artus Hand
76
- """
77
- return self._communication_handler.close_connection()
78
-
79
-
80
-
81
-
82
- # robot states
83
- def wake_up(self):
84
- """
85
- Wake-up the Artus Hand
86
- """
87
- print(f"communication frequency in useconds = {self._communication_frequency_us}")
88
- robot_wake_up_command = self._command_handler.get_robot_start_command(self.stream,self._communication_frequency_us) # to ms for masterboard
89
- self._communication_handler.send_data(robot_wake_up_command)
90
-
91
- # wait for data back
92
- if self._communication_handler.wait_for_ack():
93
- self.logger.info(f'Finished calibration')
94
- else:
95
- self.logger.warning(f'Error in calibration')
96
-
97
- def sleep(self):
98
- """
99
- Sleep the Artus Hand
100
- """
101
- robot_sleep_command = self._command_handler.get_sleep_command()
102
- return self._communication_handler.send_data(robot_sleep_command)
103
- def calibrate(self):
104
- """
105
- Calibrate the Artus Hand
106
- """
107
- robot_calibrate_command = self._command_handler.get_calibration_command()
108
- self._communication_handler.send_data(robot_calibrate_command)
109
-
110
- # wait for data back
111
- if self._communication_handler.wait_for_ack():
112
- self.logger.info(f'Finished calibration')
113
- else:
114
- self.logger.warning(f'Error in calibration')
115
-
116
-
117
- # robot control
118
- def set_joint_angles(self, joint_angles:dict):
119
- """
120
- Set joint angle targets and speed values to the Artus Hand
121
- :joint_angles: dictionary of input angles and input speeds
122
- """
123
- self._robot_handler.set_joint_angles(joint_angles=joint_angles,name=False)
124
- robot_set_joint_angles_command = self._command_handler.get_target_position_command(self._robot_handler.robot.hand_joints)
125
- # check communication frequency
126
- if not self._check_communication_frequency():
127
- return False
128
- return self._communication_handler.send_data(robot_set_joint_angles_command)
129
-
130
- def set_home_position(self):
131
- """
132
- sends the joints to home positions (0) which opens the Artus Hand
133
- """
134
- self._robot_handler.set_home_position()
135
- robot_set_home_position_command = self._command_handler.get_target_position_command(hand_joints=self._robot_handler.robot.hand_joints)
136
- # check communication frequency
137
- if not self._check_communication_frequency():
138
- return False
139
- return self._communication_handler.send_data(robot_set_home_position_command)
140
-
141
- def _check_communication_frequency(self):
142
- """
143
- check if the communication frequency is too high
144
- """
145
- current_time = time.perf_counter()
146
- if current_time - self._last_command_sent_time < self._communication_frequency:
147
- self.logger.warning("Command not sent. Communication frequency is too high.")
148
- return False
149
- self._last_command_sent_time = current_time
150
- return True
151
-
152
- # robot feedback
153
- def _receive_feedback(self):
154
- feedback_command = self._command_handler.get_states_command()
155
- self._communication_handler.send_data(feedback_command)
156
- # test
157
- time.sleep(0.005)
158
- return self._communication_handler.receive_data()
159
-
160
- def get_joint_angles(self):
161
- """
162
- Populate feedback fields in self._robot_handler.hand_joints dict
163
- """
164
- feedback_command = self._receive_feedback()
165
- joint_angles = self._robot_handler.get_joint_angles(feedback_command)
166
- print(joint_angles)
167
- return joint_angles
168
-
169
- # robot feedback stream
170
- def get_streamed_joint_angles(self):
171
- """
172
- Populate feedback fields in self._robot_handler.hand_joints dict
173
- """
174
- if not self._check_communication_frequency():
175
- return False
176
- feedback_command = self._communication_handler.receive_data()
177
- if not feedback_command:
178
- return None
179
- joint_angles = self._robot_handler.get_joint_angles(feedback_command)
180
- return joint_angles
181
-
182
- def update_firmware(self):
183
- file_path = None
184
- fw_size = 0
185
- # input to upload a new file
186
- upload_flag = input(f'Uploading a new BIN file? (y/n) : ')
187
- upload = True
188
-
189
-
190
- self._firmware_updater = FirmwareUpdater(self._communication_handler,
191
- self._command_handler)
192
-
193
- if upload_flag == 'n' or upload_flag == 'N':
194
- self._firmware_updater.file_location = 'not empty'
195
- upload = False
196
- else:
197
-
198
- self._firmware_updater.file_location = input('Please enter binfile absolute path: ')
199
-
200
- fw_size = self._firmware_updater.get_bin_file_info()
201
-
202
- # set which drivers to flash should be 1-8
203
- drivers_to_flash = int(input(f'Which drivers would you like to flash? \n0:ALL\nor 1-8\n: '))
204
- if not drivers_to_flash:
205
- drivers_to_flash = 0
206
-
207
- firmware_command = self._command_handler.get_firmware_command(fw_size,upload,drivers_to_flash)
208
- self._communication_handler.send_data(firmware_command)
209
- if upload:
210
- self._firmware_updater.update_firmware(fw_size)
211
-
212
- print(f'File size = {fw_size}')
213
- print(f'flashing...')
214
- self._communication_handler.wait_for_ack()
215
- print(f'Power Cycle the device to take effect')
216
-
217
- def reset(self):
218
- j = int(input(f'Enter Joint to reset: '))
219
- m = int(input(f'Enter Motor to reset: '))
220
- reset_command = self._command_handler.get_locked_reset_low_command(j,m)
221
- self._communication_handler.send_data(reset_command)
222
-
223
- def hard_close(self):
224
- j = int(input(f'Enter Joint to reset: '))
225
- m = int(input(f'Enter Motor to reset: '))
226
- hard_close = self._command_handler.get_hard_close_command(j,m)
227
- self._communication_handler.send_data(hard_close)
228
-
229
- def update_param(self):
230
- com = input('Enter Communication Protocol you would like to change to (default: UART, CAN, RS485): ')
231
- if com == 'CAN':
232
- feed = None
233
- while feed not in ['P','C','ALL']:
234
- feed = input('Enter feedback information (P: Positions only, C: Positions and Force, ALL: Position, force and temperature): ')
235
- else:
236
- feed = None
237
- command = self._command_handler.update_param_command(com,feed)
238
- self._communication_handler.send_data(command)
239
-
240
- def test_artus_api():
241
- artus_api = ArtusAPI()
242
- artus_api.connect()
243
- artus_api.wake_up()
244
- artus_api.calibrate()
245
- artus_api.set_home_position()
246
- time.sleep(2)
247
- artus_api.disconnect()
248
-
249
- if __name__ == "__main__":
250
- test_artus_api()
File without changes
File without changes