Perl conversion to python...

Benjamin Schollnick bschollnick at gmail.com
Mon Nov 23 08:26:18 EST 2009


Folks,

I'm having some issues here with pyserial & trying to translate a perl
script to python...  It's probably my inexperience with PySerial &
perl that is troubling me...

Can anyone assist?

I'm concerned, since I can't seem to receive the data in any reliable
manner..  I've tested multiple times, and only once received data...
So I suspect that my Transmit & receive code is faulty...

def		xmit ( data, serialport ):
	for x in data:
		xmit_byte (x, serialport)
#	serialport.write ( binascii.unhexlify ( data ) )
#	for x in data:
#		print str(x).encode ('hex')
#		serialport.write ( x.encode('hex'))

def		receive ( serialport ):
	received = serialport.read (20)
	print received, "!"

----- Perl Code ----
sub tx_command {
	my $port = shift;
	my $cmd = shift;

#	warn "tx_command($cmd)\n";

	my @cmd_bytes = split(/\s/, $cmd);

	foreach my $byte (@cmd_bytes) {
		$byte = pack('C', hex($byte));

		$port -> write($byte);
		select(undef, undef, undef, 0.01);
	}
}

# returns the rtt, or 0 if no response
sub rx_response {
	my ($port, $address) = @_;

	$port->read_char_time(0);     # don't wait for each character
	$port->read_const_time(5000); # timeout if we don't get what we're
looking for

	my $buf = '';

	my $t_start = time;

	### accumulate one byte at a time until we see the substring we're
looking for

	while (1) {
		my ($count_in, $string_in) = $port->read(1);

		if ($count_in == 0) {
		#	warn "TIMEOUT\n";
			return 0;
		}

		$buf .= $string_in;

		my $bufstring = packed_to_text($buf);

		#warn "bufstring: ".$bufstring;

		if ($bufstring =~/02 50 $address (.. .. ..) (..) (.. ..)/) {

			my $powerlinc_addr = $1;
			my $flags = $2;
			my $command = $3;

		#	warn "got response!\n";

			my $rtt = time() - $t_start;

			return $rtt;
		}

	}
}




More information about the Python-list mailing list