Python LT8900 via SPI

Check-in [fc5d84e9e1]
Login

Check-in [fc5d84e9e1]

Overview
Comment:Added a software tx queue and support for setting the syncword as part of the transmit call
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: fc5d84e9e16ea2a09f75094ae82d8bf71b1afd1439c431ce8cf456fffd6b0732
User & Date: rkeene on 2020-04-30 17:50:51
Other Links: manifest | tags
Context
2020-05-01
01:33
Added support for multiple queues, and ensured queue management is locked check-in: 089d2c0ce8 user: rkeene tags: trunk
2020-04-30
17:50
Added a software tx queue and support for setting the syncword as part of the transmit call check-in: fc5d84e9e1 user: rkeene tags: trunk
03:29
lt8900_spi v2.2 check-in: ef0aed0308 user: rkeene tags: 2.2, trunk
Changes

Modified lt8900_spi/__init__.py from [640dc549d5] to [05e9f1b5b0].

17
18
19
20
21
22
23







24
25
26
27
28
29
30
# |-------+-------+-------+-------+-------+-------+--------|
# | P1-17 | P1-18 | P1-21 | P1-19 | P1-23 | P1-24 | P1-25  |
# -________________________________________________________-
#                     Raspberry Pi

import spidev
import time








class Radio:
	_register_map = [
		{'name': "Unknown"}, # 0
		{'name': "Unknown"}, # 1
		{'name': "Unknown"}, # 2
		{                    # 3







>
>
>
>
>
>
>







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# |-------+-------+-------+-------+-------+-------+--------|
# | P1-17 | P1-18 | P1-21 | P1-19 | P1-23 | P1-24 | P1-25  |
# -________________________________________________________-
#                     Raspberry Pi

import spidev
import time
import threading

class dummy_context_mgr():
	def __enter__(self):
		return None
	def __exit__(self, exc_type, exc_value, traceback):
		return False

class Radio:
	_register_map = [
		{'name': "Unknown"}, # 0
		{'name': "Unknown"}, # 1
		{'name': "Unknown"}, # 2
		{                    # 3
217
218
219
220
221
222
223



224
225
226
227
228


229
230
231
232
233
234
235
236
237
238
239







240

241



242





243

244
245
246
247
248
249
250
251
		}
	]

	def __init__(self, spi_bus, spi_dev, config = None):
		spi = spidev.SpiDev()
		spi.open(spi_bus, spi_dev)
		self._spi = spi




		self.configure(config)

		if len(self._register_map) != 53:
			raise ValueError('Inconsistent register map!')



		return None

	def __del__(self):
		self._spi.close()

	def _debug(self, message):
		if self._config is not None and 'debug_log_command' in self._config:
			self._config['debug_log_command'](message)
		return None








	def _reset_device(self):

		if self._config is not None:



			if self._config['reset_command'] is not None:





				return self._config['reset_command']()

		return None

	def _register_name(self, reg_number):
		return self._register_map[reg_number]['name']

	def _register_number(self, reg_string):
		reg_string_orig = reg_string








>
>
>





>
>











>
>
>
>
>
>
>

>
|
>
>
>
|
>
>
>
>
>
|
>
|







224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
		}
	]

	def __init__(self, spi_bus, spi_dev, config = None):
		spi = spidev.SpiDev()
		spi.open(spi_bus, spi_dev)
		self._spi = spi

		self._dequeue_thread = None
		self._syncword = None

		self.configure(config)

		if len(self._register_map) != 53:
			raise ValueError('Inconsistent register map!')

		self._channel_queue = {}

		return None

	def __del__(self):
		self._spi.close()

	def _debug(self, message):
		if self._config is not None and 'debug_log_command' in self._config:
			self._config['debug_log_command'](message)
		return None

	def _get_mutex(self, real_mutex = True):
		if not real_mutex:
			return dummy_context_mgr()

		mutex = self._config.get('mutex', dummy_context_mgr())
		return mutex

	def _reset_device(self):
		reset_command = self._config.get('reset_command', None)

		if reset_command is None:
			return None

		reset_command()

		return None

	def _should_use_queue(self):
		if 'use_software_tx_queue' in self._config:
			return self._config['use_software_tx_queue']

		return False

	def _register_name(self, reg_number):
		return self._register_map[reg_number]['name']

	def _register_number(self, reg_string):
		reg_string_orig = reg_string

306
307
308
309
310
311
312

313
314
315
316
317
318
319
		self.put_register_bits('vco_calibrate', {'enabled': 1})
		self.put_register_bits('scan_rssi_state', {'enabled': 0, 'channel_offset': 0, 'wait_time': 15})

		return True

	def _put_register_high_low(self, reg, high, low, delay = 7):
		reg = self._register_number(reg)

		result = self._spi.xfer([reg, high, low], self._spi.max_speed_hz, delay)

		if reg & 0x80 == 0x80:
			self._debug(" regRead[%02X] = %s" % ((reg & 0x7f), result))
		else:
			self._debug("regWrite[%02X:0x%02X%02X] = %s" % (reg, high, low, result))








>







335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
		self.put_register_bits('vco_calibrate', {'enabled': 1})
		self.put_register_bits('scan_rssi_state', {'enabled': 0, 'channel_offset': 0, 'wait_time': 15})

		return True

	def _put_register_high_low(self, reg, high, low, delay = 7):
		reg = self._register_number(reg)

		result = self._spi.xfer([reg, high, low], self._spi.max_speed_hz, delay)

		if reg & 0x80 == 0x80:
			self._debug(" regRead[%02X] = %s" % ((reg & 0x7f), result))
		else:
			self._debug("regWrite[%02X:0x%02X%02X] = %s" % (reg, high, low, result))

382
383
384
385
386
387
388

389
390
391
392
393

394
395
396
397
398
399
400










401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421













422
423
424
425
426
427
428
			key_value = (value & mask) >> bit_range[0]
			result[key] = key_value

		# Return the filled in structure
		return result

	def configure(self, config):

		self._config = config

		if config is None:
			return None


		self._spi.max_speed_hz = self._config.get('frequency', 4000000)
		self._spi.bits_per_word = self._config.get('bits_per_word', 8)
		self._spi.cshigh = self._config.get('csigh', False)
		self._spi.no_cs  = self._config.get('no_cs', False)
		self._spi.lsbfirst = self._config.get('lsbfirst', False)
		self._spi.threewire = self._config.get('threewire', False)
		self._spi.mode = self._config.get('mode', 1)











		return None

	def initialize(self):
		self._reset_device()

		self._set_defaults()

		if not self._check_radio():
			return False
		return True

	def set_channel(self, channel):
		state = self.get_register_bits('radio_state')
		state['channel'] = channel

		self.put_register_bits('radio_state', state)

		return state

	def set_syncword(self, syncword):













		packet_config = self.get_register_bits('packet_config')
		packet_config['syncword_len'] = len(syncword) - 1

		self.put_register_bits('packet_config', packet_config)

		if len(syncword) == 1:
			self.put_register("syncword_0", syncword[0])







>
|

|
<

>
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>




















|
>
>
>
>
>
>
>
>
>
>
>
>
>







412
413
414
415
416
417
418
419
420
421
422

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
			key_value = (value & mask) >> bit_range[0]
			result[key] = key_value

		# Return the filled in structure
		return result

	def configure(self, config):
		if config is None:
			config = {}

		self._config = config


		with self._get_mutex():
			self._spi.max_speed_hz = self._config.get('frequency', 4000000)
			self._spi.bits_per_word = self._config.get('bits_per_word', 8)
			self._spi.cshigh = self._config.get('csigh', False)
			self._spi.no_cs  = self._config.get('no_cs', False)
			self._spi.lsbfirst = self._config.get('lsbfirst', False)
			self._spi.threewire = self._config.get('threewire', False)
			self._spi.mode = self._config.get('mode', 1)

		# If using a queue, start a thread to run the queue
		if self._should_use_queue():
			if self._dequeue_thread is None:
				self._dequeue_thread = threading.Thread(target = self._run_queue)
				self._dequeue_thread.start()
		else:
			if self._dequeue_thread is not None:
				self._dequeue_thread.join()
				self._dequeue_thread = None

		return None

	def initialize(self):
		self._reset_device()

		self._set_defaults()

		if not self._check_radio():
			return False
		return True

	def set_channel(self, channel):
		state = self.get_register_bits('radio_state')
		state['channel'] = channel

		self.put_register_bits('radio_state', state)

		return state

	def set_syncword(self, syncword, force = False, _queue_instead_of_xmit = True):
		# If queuing is being used, just store this message
		if _queue_instead_of_xmit and self._should_use_queue():
			self._enqueue(syncword, None, None)
			return None

		# Do not set the syncword again if it's not needed
		if not force:
			if self._syncword is not None:
				if syncword == self._syncword:
					return None

		self._syncword = syncword

		packet_config = self.get_register_bits('packet_config')
		packet_config['syncword_len'] = len(syncword) - 1

		self.put_register_bits('packet_config', packet_config)

		if len(syncword) == 1:
			self.put_register("syncword_0", syncword[0])
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453

454

455
456
457
458
459















460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493




494
495












496







































497




498









499




500





501

















502

503


504




505
506
507
508
509
510
511
512
513
			self.put_register("syncword_2", syncword[1])
			self.put_register("syncword_3", syncword[0])
		elif len(syncword) > 4:
			raise ValueError("SyncWord length must be less than 5")

		return None

	def fill_fifo(self, message, include_length = True):
		new_message = [self._register_number('fifo')]
		if include_length:
			new_message = new_message + [len(message)]
		new_message = new_message + message
		log_message = [] + new_message

		# Transfer the message

		result = self._spi.xfer(new_message, self._spi.max_speed_hz, 10)

		self._debug("Writing: {} = {}".format(log_message, result))

		return new_message

	def transmit(self, message, channel = None):















		if channel is None:
			state = self.get_register_bits('radio_state')
			channel = state['channel']

		# Initialize the transmitter
		self.put_register_bits('radio_state', {
			'tx_enabled': 0,
			'rx_enabled': 0,
			'channel': 0
		})

		self.put_register_bits('fifo_state', {
			'clear_read': 1,
			'clear_write': 1
		})

		# Format message to send to fifo
		self.fill_fifo(message, True)

		# Tell the radio to transmit the FIFO buffer to the specified channel
		self.put_register_bits('radio_state', {
			'tx_enabled': 1,
			'rx_enabled': 0,
			'channel': channel
		})

		# Wait for buffer to empty
		# XXX: Untested
		while True:
			radio_status = self.get_register_bits('status')
			self._debug("radio_status={}".format(radio_status))

			if radio_status['packet_flag'] == 1:
				break




			time.sleep(0.001)













		return True












































	def multi_transmit(self, message, channels, retries = 3, delay = 0.1):









		for channel in channels:




			for i in range(retries):





				if not self.transmit(message, channel):

















					return False

				if delay != 0:


					time.sleep(delay / retries)




		return True

	def start_listening(self, channel):
		# Initialize the receiver
		self.stop_listening()

		# Go into listening mode
		self.put_register_bits('radio_state', {
			'tx_enabled': 0,







|







>
|
>




|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|

|
|
|
|
|
|

|
|
|
|

|
|

|
|
|
|
|
|

|
|
|
|
|

|
|
>
>
>
>
|

>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
|
>
>
>
>
>
>
>
>
>
|
>
>
>
>
|
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>
|
>
>
>
>
|
|







493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
			self.put_register("syncword_2", syncword[1])
			self.put_register("syncword_3", syncword[0])
		elif len(syncword) > 4:
			raise ValueError("SyncWord length must be less than 5")

		return None

	def fill_fifo(self, message, include_length = True, lock = True):
		new_message = [self._register_number('fifo')]
		if include_length:
			new_message = new_message + [len(message)]
		new_message = new_message + message
		log_message = [] + new_message

		# Transfer the message
		with self._get_mutex(lock):
			result = self._spi.xfer(new_message, self._spi.max_speed_hz, 10)

		self._debug("Writing: {} = {}".format(log_message, result))

		return new_message

	def transmit(self, message, channel = None, lock = True, _queue_instead_of_xmit = True, post_delay = 0, syncword = None):
		# If we are using a radio transmit queue, just queue this message
		# (unless we are called from the dequeue procedure)
		if _queue_instead_of_xmit and self._should_use_queue():
			if syncword is None:
				syncword = self._syncword
			self._enqueue(syncword, message, channel, post_delay = post_delay)
			return True

		sent_packet = True

		with self._get_mutex(lock):
			# Set the syncword
			if syncword is not None:
				self.set_syncword(syncword, _queue_instead_of_xmit = False)

			if channel is None:
				state = self.get_register_bits('radio_state')
				channel = state['channel']

			# Initialize the transmitter
			self.put_register_bits('radio_state', {
				'tx_enabled': 0,
				'rx_enabled': 0,
				'channel': 0
			})

			self.put_register_bits('fifo_state', {
				'clear_read': 1,
				'clear_write': 1
			})

			# Format message to send to fifo
			self.fill_fifo(message, include_length = True, lock = False)

			# Tell the radio to transmit the FIFO buffer to the specified channel
			self.put_register_bits('radio_state', {
				'tx_enabled': 1,
				'rx_enabled': 0,
				'channel': channel
			})

			# Wait for buffer to empty
			# XXX: Untested
			while True:
				radio_status = self.get_register_bits('status')
				self._debug("radio_status={}".format(radio_status))

				if radio_status['packet_flag'] == 1:
					break

				if radio_status['framer_status'] == 0:
					sent_packet = False
					break
				time.sleep(0.001)

		if post_delay != 0:
			time.sleep(post_delay)

		return sent_packet

	def multi_transmit(self, message, channels, retries = 3, delay = 0.1, syncword = None):
		delay = delay / len(channels)
		for channel in channels:
			for i in range(retries):
				if not self.transmit(message, channel, post_delay = delay, syncword = syncword):
					return False

		return True

	def _enqueue(self, syncword, message, channel, post_delay = 0.01):
		if channel not in self._channel_queue:
			self._channel_queue[channel] = []
			dispatch_time = time.time()
		else:
			last_item = self._channel_queue[channel][-1]
			dispatch_time = last_item['time'] + last_item['post_delay']

		self._channel_queue[channel].append({
			'syncword': syncword,
			'message': message,
			'channel': channel,
			'time': dispatch_time,
			'post_delay': post_delay,
			'transmitted': False
		})

		return None

	def _run_queue(self):
		self._debug("Started run_queue process")
		# Do not run the queue if we are using a queue
		if not self._should_use_queue():
			self._debug("Ending run_queue process, not using the queue")
			return None

		sleep_time = 0
		while True:
			time.sleep(sleep_time)
			item_count = self._run_queue_once()
			self._debug("Running the queue, {} items left".format(item_count))

			if item_count == 0:
				# If the queue is empty and we are no longer queuing
				# events, exit this function (which should be joined)
				if not self._should_use_queue():
					self._debug("Request to stop run_queue process, exiting")
					break

				# If there are no events, wait a bit
				# longer before trying again
				sleep_time = 0.5
				continue

			# If there are more events to process, try again in 1ms
			sleep_time = 0.001

		return None

	def _run_queue_once(self):
		now = time.time()
		to_transmit = []
		items_remaining = 0
		for channel in self._channel_queue:
			found_item_in_queue = False
			for item in self._channel_queue[channel]:
				if item['transmitted']:
					continue

				found_item_in_queue = True
				if item['time'] <= now:
					item['transmitted'] = True
					to_transmit.append(item)
					continue

				items_remaining += 1
			# If the channel has only transmitted items, clear it
			# out except for the last item (which will have a
			# record of when the next event should take place)
			if not found_item_in_queue:
				self._channel_queue[channel] = [self._channel_queue[channel][-1]]

		default_syncword = None

		with self._get_mutex():
			for item in to_transmit:
				syncword = item['syncword']
				message = item['message']
				channel = item['channel']

				if syncword is not None:
					default_syncword = syncword
				else:
					syncword = default_syncword

				if message is None or channel is None:
					continue

				for retry in range(3):
					if self.transmit(message, channel, lock = False, _queue_instead_of_xmit = False, syncword = syncword):
						break

		return items_remaining
		
	def start_listening(self, channel):
		# Initialize the receiver
		self.stop_listening()

		# Go into listening mode
		self.put_register_bits('radio_state', {
			'tx_enabled': 0,
529
530
531
532
533
534
535

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552

553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
			'clear_read': 1,
			'clear_write': 1
		})

		return True

	def receive(self, channel = None, wait = False, length = None, wait_time = 0.1):

		if wait:
			if channel is None:
				state = self.get_register_bits('radio_state')
				channel = state['channel']

			self.start_listening(channel)

		message = []

		while True:
			radio_status = self.get_register_bits('status')
			self._debug("radio_status={}".format(radio_status))
			if radio_status['packet_flag'] == 0:
				if wait:
					time.sleep(wait_time)
					continue
				else:

					return None

			if radio_status['crc_error'] == 1:
				# Handle invalid packet ?
				self.start_listening(channel)
				continue

			# Data is available, read it from the FIFO register
			# The first result will include the length
			# XXX *IF* length encoding is enabled ?
			fifo_data = self.get_register('fifo')
			message_length = fifo_data >> 8

			if message_length == 0:
				self.start_listening(channel)
				continue

			# Keep track of the total message length to truncate it
			final_message_length = message_length

			message += [fifo_data & 0xff]
			message_length -= 1

			# Read subsequent bytes from the FIFO register until
			# there are no more bytes to read
			while message_length > 0:
				fifo_data = self.get_register('fifo')
				message += [fifo_data >> 8, fifo_data & 0xff]
				message_length -= 2

			# Truncate the message to its final size, since we have
			# to read in 16-bit words, we may have an extra byte
			message = message[0:final_message_length]
			break

		return message







>
|
|
|
|

|

|

|
|
|
|
|
|
|
|
>
|

|
|
|
|

|
|
|
|
|

|
|
|

|
|

|
|

|
|
|
|
|
|

|
|
|
|


701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
			'clear_read': 1,
			'clear_write': 1
		})

		return True

	def receive(self, channel = None, wait = False, length = None, wait_time = 0.1):
		with self._get_mutex():
			if wait:
				if channel is None:
					state = self.get_register_bits('radio_state')
					channel = state['channel']

				self.start_listening(channel)

			message = []

			while True:
				radio_status = self.get_register_bits('status')
				self._debug("radio_status={}".format(radio_status))
				if radio_status['packet_flag'] == 0:
					if wait:
						time.sleep(wait_time)
						continue
					else:
						self._unlock_radio()
						return None

				if radio_status['crc_error'] == 1:
					# Handle invalid packet ?
					self.start_listening(channel)
					continue

				# Data is available, read it from the FIFO register
				# The first result will include the length
				# XXX *IF* length encoding is enabled ?
				fifo_data = self.get_register('fifo')
				message_length = fifo_data >> 8

				if message_length == 0:
					self.start_listening(channel)
					continue

				# Keep track of the total message length to truncate it
				final_message_length = message_length

				message += [fifo_data & 0xff]
				message_length -= 1

				# Read subsequent bytes from the FIFO register until
				# there are no more bytes to read
				while message_length > 0:
					fifo_data = self.get_register('fifo')
					message += [fifo_data >> 8, fifo_data & 0xff]
					message_length -= 2

				# Truncate the message to its final size, since we have
				# to read in 16-bit words, we may have an extra byte
				message = message[0:final_message_length]
				break

		return message