PyTmcStepper 0.7__py3-none-any.whl

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.

Potentially problematic release.


This version of PyTmcStepper might be problematic. Click here for more details.

@@ -0,0 +1,177 @@
1
+ #pylint: disable=import-error
2
+ #pylint: disable=broad-exception-caught
3
+ #pylint: disable=unused-import
4
+ #pylint: disable=wildcard-import
5
+ #pylint: disable=unused-wildcard-import
6
+ #pylint: disable=too-few-public-methods
7
+ """
8
+ TmcComSpi stepper driver spi module
9
+ """
10
+
11
+ import sys
12
+ import spidev
13
+ from ._tmc_com import *
14
+
15
+ # class MockSpiDev:
16
+ # """MockSpiDev"""
17
+
18
+ # def SpiDev(self):
19
+ # """SpiDev"""
20
+
21
+ # try:
22
+ # import spidev
23
+ # except ImportError:
24
+ # print("spidev not found. Using MockSpiDev")
25
+ # spidev = MockSpiDev()
26
+
27
+
28
+
29
+
30
+ class TmcComSpi(TmcCom):
31
+ """TmcComSpi
32
+
33
+ this class is used to communicate with the TMC via SPI
34
+ it can be used to change the settings of the TMC.
35
+ like the current or the microsteppingmode
36
+ """
37
+
38
+ _spi = spidev.SpiDev()
39
+ _spi_bus: int
40
+ _spi_dev: int
41
+
42
+ def __init__(self,
43
+ spi_bus,
44
+ spi_dev,
45
+ mtr_id:int = 0,
46
+ tmc_logger = None
47
+ ):
48
+ """constructor
49
+
50
+ Args:
51
+ _tmc_logger (class): TMCLogger class
52
+ mtr_id (int, optional): driver address [0-3]. Defaults to 0.
53
+ """
54
+ super().__init__(mtr_id, tmc_logger)
55
+
56
+ self._spi_bus = spi_bus
57
+ self._spi_dev = spi_dev
58
+
59
+ self._r_frame = [0x55, 0, 0, 0, 0]
60
+ self._w_frame = [0x55, 0, 0, 0, 0]
61
+
62
+
63
+ def init(self):
64
+ """init"""
65
+ try:
66
+ self._spi.open(self._spi_bus, self._spi_dev)
67
+ except Exception as e:
68
+ self._tmc_logger.log(f"Error opening SPI: {e}", Loglevel.ERROR)
69
+ errnum = e.args[0]
70
+ if errnum == 2:
71
+ self._tmc_logger.log(f"SPI Device {self._spi_dev} on Bus {self._spi_bus} does not exist.", Loglevel.ERROR)
72
+ self._tmc_logger.log("You need to activate the SPI interface with \"sudo raspi-config\"", Loglevel.ERROR)
73
+ sys.exit()
74
+
75
+ self._spi.max_speed_hz = 5000
76
+ self._spi.mode = 0b11
77
+ self._spi.lsbfirst = False
78
+
79
+
80
+ def __del__(self):
81
+ """destructor"""
82
+
83
+
84
+ def read_reg(self, addr:hex):
85
+ """reads the registry on the TMC with a given address.
86
+ returns the binary value of that register
87
+
88
+ Args:
89
+ addr (int): HEX, which register to read
90
+ """
91
+ self._w_frame = [addr, 0x00, 0x00, 0x00, 0x00]
92
+ dummy_data = [0x00, 0x00, 0x00, 0x00, 0x00]
93
+
94
+ self._spi.xfer2(self._w_frame)
95
+ rtn = self._spi.xfer2(dummy_data)
96
+
97
+ reset_flag = rtn[0] >> 0 & 0x01
98
+ driver_error = rtn[0] >> 1 & 0x01
99
+ sg2 = rtn[0] >> 2 & 0x01
100
+ standstill = rtn[0] >> 3 & 0x01
101
+
102
+
103
+ if reset_flag:
104
+ self._tmc_logger.log("TMC reset flag is set", Loglevel.ERROR)
105
+ if driver_error:
106
+ self._tmc_logger.log("TMC driver error flag is set", Loglevel.ERROR)
107
+ if sg2:
108
+ self._tmc_logger.log("TMC stallguard2 flag is set", Loglevel.MOVEMENT)
109
+ if standstill:
110
+ self._tmc_logger.log("TMC standstill flag is set", Loglevel.MOVEMENT)
111
+
112
+
113
+ return rtn[1:]
114
+
115
+
116
+ def read_int(self, addr:hex, tries:int = 10):
117
+ """this function tries to read the registry of the TMC 10 times
118
+ if a valid answer is returned, this function returns it as an integer
119
+
120
+ Args:
121
+ addr (int): HEX, which register to read
122
+ tries (int): how many tries, before error is raised (Default value = 10)
123
+ """
124
+ data = self.read_reg(addr)
125
+ return int.from_bytes(data, byteorder='big', signed=False)
126
+
127
+
128
+ def write_reg(self, addr:hex, val:int):
129
+ """this function can write a value to the register of the tmc
130
+ 1. use read_int to get the current setting of the TMC
131
+ 2. then modify the settings as wished
132
+ 3. write them back to the driver with this function
133
+
134
+ Args:
135
+ addr (int): HEX, which register to write
136
+ val (int): value for that register
137
+ """
138
+ self._w_frame[0] = addr | 0x80 # set write bit
139
+
140
+ self._w_frame[1] = 0xFF & (val>>24)
141
+ self._w_frame[2] = 0xFF & (val>>16)
142
+ self._w_frame[3] = 0xFF & (val>>8)
143
+ self._w_frame[4] = 0xFF & val
144
+ # self.w_frame[7] = compute_crc8_atm(self.w_frame[:-1])
145
+
146
+ self._spi.xfer2(self._w_frame)
147
+
148
+
149
+ def write_reg_check(self, addr:hex, val:int, tries:int=10):
150
+ """this function als writes a value to the register of the TMC
151
+ but it also checks if the writing process was successfully by checking
152
+ the InterfaceTransmissionCounter before and after writing
153
+
154
+ Args:
155
+ addr: HEX, which register to write
156
+ val: value for that register
157
+ tries: how many tries, before error is raised (Default value = 10)
158
+ """
159
+ self.write_reg(addr, val)
160
+
161
+
162
+ def flush_serial_buffer(self):
163
+ """this function clear the communication buffers of the Raspberry Pi"""
164
+
165
+
166
+ def handle_error(self):
167
+ """error handling"""
168
+ raise NotImplementedError
169
+
170
+
171
+ def test_com(self, addr):
172
+ """test com connection
173
+
174
+ Args:
175
+ addr (int): HEX, which register to test
176
+ """
177
+ raise NotImplementedError
@@ -0,0 +1,336 @@
1
+ #pylint: disable=import-error
2
+ #pylint: disable=broad-exception-caught
3
+ #pylint: disable=wildcard-import
4
+ #pylint: disable=unused-wildcard-import
5
+ """
6
+ TmcComUart stepper driver uart module
7
+ """
8
+
9
+ import sys
10
+ import serial
11
+ from ._tmc_com import *
12
+
13
+
14
+
15
+ class TmcComUart(TmcCom):
16
+ """TmcComUart
17
+
18
+ this class is used to communicate with the TMC via UART
19
+ it can be used to change the settings of the TMC.
20
+ like the current or the microsteppingmode
21
+ """
22
+
23
+ ser:serial.Serial = serial.Serial()
24
+
25
+
26
+ def __init__(self,
27
+ serialport:str ,
28
+ baudrate:int = 115200,
29
+ mtr_id:int = 0,
30
+ tmc_logger = None
31
+ ):
32
+ """constructor
33
+
34
+ Args:
35
+ _tmc_logger (class): TMCLogger class
36
+ serialport (string): serialport path
37
+ baudrate (int): baudrate
38
+ mtr_id (int, optional): driver address [0-3]. Defaults to 0.
39
+ """
40
+ super().__init__(mtr_id, tmc_logger)
41
+
42
+ if serialport is None:
43
+ return
44
+
45
+ self.ser.port = serialport
46
+ self.ser.baudrate = baudrate
47
+
48
+ self.r_frame = [0x55, 0, 0, 0 ]
49
+ self.w_frame = [0x55, 0, 0, 0 , 0, 0, 0, 0 ]
50
+
51
+
52
+ def init(self):
53
+ """init"""
54
+ try:
55
+ self.ser.open()
56
+ except Exception as e:
57
+ errnum = e.args[0]
58
+ self._tmc_logger.log(f"SERIAL ERROR: {e}")
59
+ if errnum == 2:
60
+ self._tmc_logger.log(f""""{self.ser.serialport} does not exist.
61
+ You need to activate the serial port with \"sudo raspi-config\"""", Loglevel.ERROR)
62
+ sys.exit()
63
+
64
+ if errnum == 13:
65
+ self._tmc_logger.log("""you have no permission to use the serial port.
66
+ You may need to add your user to the dialout group
67
+ with \"sudo usermod -a -G dialout pi\"""", Loglevel.ERROR)
68
+ sys.exit()
69
+
70
+ # adjust per baud and hardware. Sequential reads without some delay fail.
71
+ self.communication_pause = 500 / self.ser.baudrate
72
+
73
+ if self.ser is None:
74
+ return
75
+
76
+ self.ser.BYTESIZES = 1
77
+ self.ser.PARITIES = serial.PARITY_NONE
78
+ self.ser.STOPBITS = 1
79
+
80
+ # adjust per baud and hardware. Sequential reads without some delay fail.
81
+ self.ser.timeout = 20000/self.ser.baudrate
82
+
83
+ self.ser.reset_output_buffer()
84
+ self.ser.reset_input_buffer()
85
+
86
+
87
+ def __del__(self):
88
+ """destructor"""
89
+ if self.ser is not None and isinstance(self.ser, serial.Serial):
90
+ self.ser.close()
91
+
92
+
93
+ def read_reg(self, addr:hex):
94
+ """reads the registry on the TMC with a given address.
95
+ returns the binary value of that register
96
+
97
+ Args:
98
+ register (int): HEX, which register to read
99
+ """
100
+ if self.ser is None:
101
+ self._tmc_logger.log("Cannot read reg, serial is not initialized", Loglevel.ERROR)
102
+ return False
103
+
104
+ self.ser.reset_output_buffer()
105
+ self.ser.reset_input_buffer()
106
+
107
+ self.r_frame[1] = self.mtr_id
108
+ self.r_frame[2] = addr
109
+ self.r_frame[3] = compute_crc8_atm(self.r_frame[:-1])
110
+
111
+ rtn = self.ser.write(self.r_frame)
112
+ if rtn != len(self.r_frame):
113
+ self._tmc_logger.log("Err in write", Loglevel.ERROR)
114
+ return False
115
+
116
+ # adjust per baud and hardware. Sequential reads without some delay fail.
117
+ time.sleep(self.communication_pause)
118
+
119
+ rtn = self.ser.read(12)
120
+ #self._tmc_logger.log(f"received {len(rtn)} bytes; {len(rtn*8)} bits")
121
+ #self._tmc_logger.log(rtn.hex())
122
+
123
+ time.sleep(self.communication_pause)
124
+
125
+ return rtn
126
+
127
+
128
+ def read_int(self, addr:hex, tries:int = 10):
129
+ """this function tries to read the registry of the TMC 10 times
130
+ if a valid answer is returned, this function returns it as an integer
131
+
132
+ Args:
133
+ addr (int): HEX, which register to read
134
+ tries (int): how many tries, before error is raised (Default value = 10)
135
+ """
136
+ if self.ser is None:
137
+ self._tmc_logger.log("Cannot read int, serial is not initialized", Loglevel.ERROR)
138
+ return -1
139
+ while True:
140
+ tries -= 1
141
+ rtn = self.read_reg(addr)
142
+ rtn_data = rtn[7:11]
143
+ not_zero_count = len([elem for elem in rtn if elem != 0])
144
+
145
+ if(len(rtn)<12 or not_zero_count == 0):
146
+ self._tmc_logger.log(f"""UART Communication Error:
147
+ {len(rtn_data)} data bytes |
148
+ {len(rtn)} total bytes""", Loglevel.ERROR)
149
+ elif rtn[11] != compute_crc8_atm(rtn[4:11]):
150
+ self._tmc_logger.log("UART Communication Error: CRC MISMATCH", Loglevel.ERROR)
151
+ else:
152
+ break
153
+
154
+ if tries<=0:
155
+ self._tmc_logger.log("after 10 tries not valid answer", Loglevel.ERROR)
156
+ self._tmc_logger.log(f"snd:\t{bytes(self.r_frame)}", Loglevel.DEBUG)
157
+ self._tmc_logger.log(f"rtn:\t{rtn}", Loglevel.DEBUG)
158
+ self.handle_error()
159
+ return -1
160
+
161
+ val = struct.unpack(">i",rtn_data)[0]
162
+ return val
163
+
164
+
165
+ def write_reg(self, addr:hex, val:int):
166
+ """this function can write a value to the register of the tmc
167
+ 1. use read_int to get the current setting of the TMC
168
+ 2. then modify the settings as wished
169
+ 3. write them back to the driver with this function
170
+
171
+ Args:
172
+ addr (int): HEX, which register to write
173
+ val (int): value for that register
174
+ """
175
+ if self.ser is None:
176
+ self._tmc_logger.log("Cannot write reg, serial is not initialized", Loglevel.ERROR)
177
+ return False
178
+
179
+ self.ser.reset_output_buffer()
180
+ self.ser.reset_input_buffer()
181
+
182
+ self.w_frame[1] = self.mtr_id
183
+ self.w_frame[2] = addr | 0x80 # set write bit
184
+
185
+ self.w_frame[3] = 0xFF & (val>>24)
186
+ self.w_frame[4] = 0xFF & (val>>16)
187
+ self.w_frame[5] = 0xFF & (val>>8)
188
+ self.w_frame[6] = 0xFF & val
189
+
190
+ self.w_frame[7] = compute_crc8_atm(self.w_frame[:-1])
191
+
192
+
193
+ rtn = self.ser.write(self.w_frame)
194
+ if rtn != len(self.w_frame):
195
+ self._tmc_logger.log("Err in write", Loglevel.ERROR)
196
+ return False
197
+
198
+ time.sleep(self.communication_pause)
199
+
200
+ return True
201
+
202
+
203
+ def write_reg_check(self, addr:hex, val:int, tries:int=10):
204
+ """this function als writes a value to the register of the TMC
205
+ but it also checks if the writing process was successfully by checking
206
+ the InterfaceTransmissionCounter before and after writing
207
+
208
+ Args:
209
+ addr: HEX, which register to write
210
+ val: value for that register
211
+ tries: how many tries, before error is raised (Default value = 10)
212
+ """
213
+ if self.ser is None:
214
+ self._tmc_logger.log("Cannot write reg check, serial is not initialized", Loglevel.ERROR)
215
+ return False
216
+ self._tmc_registers["ifcnt"].read()
217
+ ifcnt1 = self._tmc_registers["ifcnt"].ifcnt
218
+
219
+ if ifcnt1 == 255:
220
+ ifcnt1 = -1
221
+
222
+ while True:
223
+ self.write_reg(addr, val)
224
+ tries -= 1
225
+ self._tmc_registers["ifcnt"].read()
226
+ ifcnt2 = self._tmc_registers["ifcnt"].ifcnt
227
+ if ifcnt1 >= ifcnt2:
228
+ self._tmc_logger.log("writing not successful!", Loglevel.ERROR)
229
+ self._tmc_logger.log(f"ifcnt: {ifcnt1}, {ifcnt2}", Loglevel.DEBUG)
230
+ else:
231
+ return True
232
+ if tries<=0:
233
+ self._tmc_logger.log("after 10 tries no valid write access", Loglevel.ERROR)
234
+ self.handle_error()
235
+ return -1
236
+
237
+
238
+ def flush_serial_buffer(self):
239
+ """this function clear the communication buffers of the Raspberry Pi"""
240
+ if self.ser is None:
241
+ return
242
+ self.ser.reset_output_buffer()
243
+ self.ser.reset_input_buffer()
244
+
245
+
246
+ def handle_error(self):
247
+ """error handling"""
248
+ if self.error_handler_running:
249
+ return
250
+ self.error_handler_running = True
251
+ self._tmc_registers["gstat"].read()
252
+ self._tmc_registers["gstat"].log(self.tmc_logger)
253
+
254
+ self._tmc_logger.log("EXITING!", Loglevel.INFO)
255
+ raise SystemExit
256
+
257
+
258
+ def test_com(self, addr):
259
+ """test UART connection
260
+
261
+ Args:
262
+ addr (int): HEX, which register to test
263
+ """
264
+ if self.ser is None:
265
+ self._tmc_logger.log("Cannot test UART, serial is not initialized", Loglevel.ERROR)
266
+ return False
267
+
268
+ self.ser.reset_output_buffer()
269
+ self.ser.reset_input_buffer()
270
+
271
+ self.r_frame[1] = self.mtr_id
272
+ self.r_frame[2] = addr
273
+ self.r_frame[3] = compute_crc8_atm(self.r_frame[:-1])
274
+
275
+ rtn = self.ser.write(self.r_frame)
276
+ if rtn != len(self.r_frame):
277
+ self._tmc_logger.log("Err in write", Loglevel.ERROR)
278
+ return False
279
+
280
+
281
+ snd = bytes(self.r_frame)
282
+
283
+ rtn = self.ser.read(12)
284
+ self._tmc_logger.log(f"received {len(rtn)} bytes; {len(rtn)*8} bits", Loglevel.DEBUG)
285
+ self._tmc_logger.log(f"hex: {rtn.hex()}", Loglevel.DEBUG)
286
+ rtn_bin = format(int(rtn.hex(),16), f"0>{len(rtn)*8}b")
287
+ self._tmc_logger.log(f"bin: {rtn_bin}", Loglevel.DEBUG)
288
+
289
+
290
+ self.tmc_logger.log(f"length snd: {len(snd)}", Loglevel.DEBUG)
291
+ self.tmc_logger.log(f"length rtn: {len(rtn)}", Loglevel.DEBUG)
292
+
293
+
294
+ self.tmc_logger.log("complete messages:", Loglevel.DEBUG)
295
+ self.tmc_logger.log(str(snd.hex()), Loglevel.DEBUG)
296
+ self.tmc_logger.log(str(rtn.hex()), Loglevel.DEBUG)
297
+
298
+ self.tmc_logger.log("just the first 4 bytes:", Loglevel.DEBUG)
299
+ self.tmc_logger.log(str(snd[0:4].hex()), Loglevel.DEBUG)
300
+ self.tmc_logger.log(str(rtn[0:4].hex()), Loglevel.DEBUG)
301
+
302
+ status = True
303
+
304
+ if len(rtn)==12:
305
+ self.tmc_logger.log("""the Raspberry Pi received the sent
306
+ bytes and the answer from the TMC""", Loglevel.DEBUG)
307
+ elif len(rtn)==4:
308
+ self.tmc_logger.log("the Raspberry Pi received only the sent bytes",
309
+ Loglevel.ERROR)
310
+ status = False
311
+ elif len(rtn)==0:
312
+ self.tmc_logger.log("the Raspberry Pi did not receive anything",
313
+ Loglevel.ERROR)
314
+ status = False
315
+ else:
316
+ self.tmc_logger.log(f"the Raspberry Pi received an unexpected amount of bytes: {len(rtn)}",
317
+ Loglevel.ERROR)
318
+ status = False
319
+
320
+ if snd[0:4] == rtn[0:4]:
321
+ self.tmc_logger.log("""the Raspberry Pi received exactly the bytes it has send.
322
+ the first 4 bytes are the same""", Loglevel.DEBUG)
323
+ else:
324
+ self.tmc_logger.log("""the Raspberry Pi did not received the bytes it has send.
325
+ the first 4 bytes are different""", Loglevel.DEBUG)
326
+ status = False
327
+
328
+ self.tmc_logger.log("---")
329
+ if status:
330
+ self.tmc_logger.log("UART connection: OK", Loglevel.INFO)
331
+ else:
332
+ self.tmc_logger.log("UART connection: not OK", Loglevel.ERROR)
333
+
334
+ self.tmc_logger.log("---")
335
+
336
+ return status
File without changes
@@ -0,0 +1,26 @@
1
+ """
2
+ Enable Control base module
3
+ """
4
+
5
+ from .._tmc_logger import TmcLogger
6
+
7
+
8
+ class TmcEnableControl():
9
+ """Enable Control base class"""
10
+
11
+ _tmc_logger:TmcLogger
12
+
13
+
14
+
15
+ def init(self, tmc_logger: TmcLogger):
16
+ """init: called by the Tmc class"""
17
+ self._tmc_logger = tmc_logger
18
+
19
+
20
+ def set_motor_enabled(self, en):
21
+ """enables or disables the motor current output
22
+
23
+ Args:
24
+ en (bool): whether the motor current output should be enabled
25
+ """
26
+ raise NotImplementedError
@@ -0,0 +1,48 @@
1
+ """
2
+ Enable Control base module
3
+ """
4
+
5
+ from ._tmc_ec import TmcEnableControl
6
+ from .._tmc_gpio_board import Gpio, GpioMode, tmc_gpio
7
+ from .._tmc_logger import TmcLogger, Loglevel
8
+
9
+
10
+ class TmcEnableControlPin(TmcEnableControl):
11
+ """Enable Control base class"""
12
+
13
+ _pin_en:int = None
14
+
15
+
16
+ @property
17
+ def pin_en(self):
18
+ """pin_en property"""
19
+ return self._pin_en
20
+
21
+
22
+ def __init__(self, pin_en:int = None):
23
+ """constructor"""
24
+ self._pin_en = pin_en
25
+
26
+
27
+ def init(self, tmc_logger: TmcLogger):
28
+ """init: called by the Tmc class"""
29
+ super().init(tmc_logger)
30
+ self._tmc_logger.log(f"EN Pin: {self._pin_en}", Loglevel.DEBUG)
31
+ tmc_gpio.gpio_setup(self._pin_en, GpioMode.OUT, initial=Gpio.HIGH)
32
+
33
+
34
+ def __del__(self):
35
+ """destructor"""
36
+ if self._pin_en is not None:
37
+ tmc_gpio.gpio_cleanup(self._pin_en)
38
+
39
+
40
+ def set_motor_enabled(self, en):
41
+ """enables or disables the motor current output
42
+
43
+ Args:
44
+ en (bool): whether the motor current output should be enabled
45
+ """
46
+ if self._pin_en is not None:
47
+ tmc_gpio.gpio_output(self._pin_en, not en)
48
+ self._tmc_logger.log(f"Motor output active: {en}", Loglevel.INFO)
@@ -0,0 +1,39 @@
1
+ """
2
+ Enable Control base module
3
+ """
4
+
5
+ from ._tmc_ec import TmcEnableControl
6
+ from ..com._tmc_com import TmcCom
7
+ from .._tmc_logger import Loglevel
8
+
9
+
10
+ class TmcEnableControlToff(TmcEnableControl):
11
+ """Enable Control base class"""
12
+
13
+ _tmc_com:TmcCom = None
14
+
15
+ _default_toff = 3
16
+
17
+
18
+ @property
19
+ def tmc_com(self):
20
+ """get the tmc_logger"""
21
+ return self._tmc_com
22
+
23
+ @tmc_com.setter
24
+ def tmc_com(self, tmc_com):
25
+ """set the tmc_logger"""
26
+ self._tmc_com = tmc_com
27
+
28
+
29
+ def set_motor_enabled(self, en):
30
+ """enables or disables the motor current output
31
+
32
+ Args:
33
+ en (bool): whether the motor current output should be enabled
34
+ """
35
+ self._tmc_logger.log(f"Motor output active: {en}", Loglevel.INFO)
36
+
37
+ val = self._default_toff if en else 0
38
+
39
+ self._tmc_com.tmc_registers["chopconf"].modify("toff", val)
File without changes