PySerial serial port send/receive - python-3.x

I need some help on how to configure a new port and how to send/receive data from that port.
thus far I have:
import serial
ourPort1 = serial.Serial(
port = 0, #how to define for rs-232, rs-485, or usb
baudrate = 9600, #can i set this so its can also use 38600?
parity = serial.PARITY_NONE,
bytesize = serial.EIGHTBITS,
stopbits = serial.STOPBITS_ONE
)
I have tried reading the official documentation but I'm not sure how to approach sending 5byte commands and receiving 24 byte status packets with PySerial. Any help or references would help me a lot. I can't seem to find much for this module.

This may be way too late an answer, but I'll take a crack at it anyway:
the port property should be a string with the name of the port you want to connect to: on Windows it'll be something like "COM1", on Linux "/dev/ttyS0".
You can then use ourPort1.write(msg) to send your 5-byte message, where msg is a string 5 characters long. Be aware that if you want to send literal integers as bytes instead of ASCII values, you'll need to do a bit of extra work.
Use reply = ourPort1.read(24) to read 24 bytes into a variable called reply. Once again, this will be stored as a string full of ASCII characters by default -- you'll have to use chr() and ord() to convert back and forth between byte value and ASCII letters.
For more info, start here: http://pyserial.sourceforge.net/pyserial_api.html

Related

send binary on node.JS serial

I'm using SerialPort https://www.npmjs.com/package/serialport in a node.JS test script. I need to write the following sequence:
"\xc0\x00--EOF-Pattern--"
The device behind the Serial port expects the bytes to transmit and then the EOF pattern to show the end of the payload. A number of other binary send works fine.
However when I try to send "0xC0" it always ends in sending crap bytes. It looks that my hex is always somewhere translated into Unicode (or something similar).
Even when I do something like
var buff = Buffer.from("c0002d2d454f462d2d5061747465726e2d2d","hex");
and send "buff" to the SerialPort the Hex sequence is destroyed. Again - this only happens when a "0xC0" is in.
Any hint what I can do ? How to prevent ANY recoding on the serial line API ?

Write pcap file about TCP traffic of a web-crawler

url request and sniff(count=x) don't work together. sniff(count) is waiting for x packets to sniff, and though I have to put the line before the url-request it blocks the program, the url-request never starts and it never sniffs any packet.
When I opened 2 Windows in ubuntu command line, it worked. In the first window I activated the interactive mode of python and activated the sniffer. After doing that, I started the web-crawler int the second window and the sniffer in the 1st window received the packets correctly and put it on the screen / into a pcap-file.
Now the easiest way would be to write 2 scripts and start them from 2 different Windows, but I want to do the complete work in one script: Webcrawling, sniffing the packets and putting them into a pcap-file
Here is the code that does not work:
class spider():
…
def parse():
a = sniff(filter="icmp and host 128.65.210.181", count=1)
req = urllib.request.urlopen(self.next_url.replace(" ",""))
a.nsummary()
charset = req.info().get_content_charset()
Now the first line blocks the program, waiting 4 the packet to come in, what cannot do so because only in the next line the request is done. Swapping the lines also doesn't work. I think that the only way to resolve the problem is to work with paralessisms, so I've also tried this:
class protocoller():
...
def run(self):
self.pkt = sniff(count=5) # and here it blocks
…
prot = protocoller()
Main.thr = threading.Thread(target=prot.run())
Main.thr.start()
I Always thought that the thread is running indipendently from the main program, but it blocks it as if it would be part of it. Any suggestions?
So what I would need is a solution in which the web-crawler and the IP/TCP protocoller based on scapy are running independently from each other.
Could the sr()-function of scapy be an alternative?
https://scapy.readthedocs.io/en/latest/usage.html
Is it possible to put the request manually in the packet and to put the received packet into the pcap-file?
Your example doesn't show what's going on in other threads so I assume you've got a second thread to do the request etc. If all that is in order the obvious error is here:
Main.thr = threading.Thread(target=prot.run())
This executes the function prot.run and passes the result to the target parameter of Thread. It should be:
Main.thr = threading.Thread(target=prot.run)
This passes the function itself into Thread
The other answer works great.
FYI, Scapy 2.4.3 also has a native way of doing this:
https://scapy.readthedocs.io/en/latest/usage.html#asynchronous-sniffing

Raspberry Pi, JCblock and Trendnet TFM 561U. Dosen't seem to work

The dev suggested to ask here to get more help.
This is what is happening, I bought a Raspberry Pi (second one, I know how to handle them, and I'm used to apt and ssh) and a Trendnet TFM561U modem, downloaded NOOBS, did the initial setup with an extra in the shape of Webmin. So far aside from Webmin, it's a vanilla Raspbian. I then downloaded JCblock ( http://sourceforge.net/projects/jcblock/ ) and following the instructions here http://weeklytechforum.com/2013/03/28/block-unwanted-calls-with-a-raspberry-pi/ I edited the files that needed editing and finally compiled. I found out what serial port the modem was using (same as the guide! cool) and finally proceeded to test it. That's where the trouble started.
The differences between me and the guide is that I'm in Italy, so the dev of JCblock made me edit the source with a few extra lines of code to talk to the modem... now it's a great time to point out that while I can edit code and recompile it, this is C and I absolutly have no clue about it, knowing just some basics from Pascal and a bit of Visual Basic, so in the end I'm editing the source blindly, just guessing where things need to go. Anyway the edits are to send the Country Code command: AT+GCI=59\r and Caller ID command: AT+VCID=1\r but we do not seem to be geting caller ID data from the modem.
What I'm expecting to see: I call with my cellphone (and that number is in the blacklist) the Raspberry doesn't make the phone ring, or in case of wrong configuration of the blacklist I get some output that will show a call not filtered.
What I get: the phone rings, the modem data light flashes, the program dosen't output anything.
Any help will be appreciated, thanks.
EDIT:
So, I went ahead and used NCID to see what would happen.
As it generates a cornucopia of data, I think it can be useful
Started: 10/27/2014 22:24:54
Server: ncidd (NCID) 1.0
API: 1.0 Feature Set 1 2 3 4
Command line: ncidd
-Dv3
Logfile: /var/log/ncidd.log
Processed config file: /etc/ncid/ncidd.conf
Verbose level: 3
Configured to send 'cidlog' to clients.
Configured to send 'cidinfo' to clients.
Helper tools:
/usr/bin/cidupdate
/usr/bin/ncidutil
Processed alias file: /etc/ncid/ncidd.alias
Alias Table:
Number of Entries: 1
Leading 1 from a call required in an alias definition
Calls in the blacklist file will be terminated
Processed blacklist file: /etc/ncid/ncidd.blacklist
Blacklist Table:
Number of Entries: 12
Calls in the whitelist file will not be terminated
Processed whitelist file: /etc/ncid/ncidd.whitelist
Whitelist Table:
Number of Entries: 0
CID logfile: /var/log/cidcall.log
CID logfile maximum size: 110000 bytes
Data logfile not present: /var/log/ciddata.log
Maximum number of clients/gateways: 25
Telephone Line Identifier: -
TTY port opened: /dev/ttyACM0
TTY port speed: 19200
TTY lock file: /var/lock/LCK..ttyACM0
TTY port control signals enabled
CallerID from AT Modem and optional gateways
Handles modem calls without Caller ID
Sent Modem 20 of 20 characters:
AT Z S0=0 E1 V1 Q0
Modem response: 26 characters in 1 read:
AT Z S0=0 E1 V1 Q0
OK
Try 1 to init modem: return = 0.
Modem initialized.
Sent Modem 6 of 6 characters:
ATI3
Modem response: 39 characters in 1 read:
ATI3
CX93001-EIS_V0.2002-V92
OK
Sent Modem 9 of 9 characters:
AT+GCI?
Modem response: 27 characters in 1 read:
AT+GCI?
+GCI: 59
OK
Sent Modem 13 of 13 characters:
AT+FCLASS=?
Modem response: 32 characters in 1 read:
AT+FCLASS=?
0,1,1.0,8
OK
Sent Modem 11 of 11 characters:
AT+VCID=1
Modem response: 17 characters in 1 read:
AT+VCID=1
OK
Modem set for CallerID.
Hangup option set to hangup on a blacklisted call
Modem used for CID and to terminate calls
Network Port: 3333
Debug Mode
Not using PID file, there was no '-P' option.
Modem is fd 4
NCID connection socket is sd 5 pos 1
RING
CIDINFO: *LINE*POTS*RING*1*TIME*22:25:21*
CIDINFO: *LINE*POTS*RING*0*TIME*22:25:33*
What I can tell from this, is that it should be properly set up to hang up for a blacklisted number (my cellphone, for testing purposes) and that no caller id gets to the software. About that, it's important to point out how we have a mess of different phones (make, model, cordless, wired...) at home, and all of them do show 1 missed call from me. So at least I can confirm that the caller id is being sent.
I looked on Trendnet TFM561U description page and Amazon for this modem and didn't see "caller ID" in the description.
Your modem looks like it has Caller ID because its response to the activate caller ID command is "OK":
AT+VCID=1
OK
But looking at
Testing Modem Caller ID Support with HyperTerminal (or Putty) page
However, if, in step 8), the modem responded with "OK", then you probably have the correct string. In this case, either your phone line does not have caller id enabled (this can be tested with a hardware caller id device), or the modem does not support caller id. The latter is possible even if, in step 8), the modem responded with "OK", since many modems use the same firmware regardless of whether the modem contains the appropriate caller id hardware. In other words, many modems don't know whether they have caller id support!
I would say return your modem and get one that has "caller ID" in the description.

Converting Open Sound Control ByteArray into String in Smalltalk VisualWorks 7.9.1

I'm receiving UDP packets from a server ( exactly: Open Sound Control packets). i'm storing those packets in a ByteArray.
I want to convert this ByteArray into String so i can exploit the data received. I tried a lot of conversion but each time i'm having non readable charachters.
Here is the code :
| server peerAddr |
server := SocketAccessor newUDPserverAtPort: 3333.
peerAddr := IPSocketAddress new.
buffer := ByteArray new: 1024.
[ server readWait.
server receiveFrom: peerAddr buffer: buffer.
Transcript show: (buffer asString) ; cr ; flush. ] repeat.
I also tried the following conversion but in vain:
buffer asByteString.
buffer asStringEncoding:#UTF8.
buffer asStringEncoding:#UTF16.
buffer asString.
buffer asBase64String.
buffer asFourByteString
buffer withEncoding: #ASCII
Here is the string output :
Any help?
Additional info: The received data is open sound control data so it has a specific formatting, that's why it's diplayed like that, i need to parse ints, floats, strings, whitin a specific bytearray indexs. Does anyone recomand a package that offer those possibilities ?
Thx in advance.
if you want to read the data from the byte array, use the UninterpretedBytes class for that.
You can do:
ubytes := UninterpretedBytes from: aByteArray.
ubytes doubleAt: 5.
stuff like that.
you can also use the uninterpreted bytes to read a string from the bytes.
The correct way to convert bytes to string is definitely applying the right character encoding. The following
(65 to: 75) asByteArray asStringEncoding: #UTF8
should yield
'ABCDEFGHIJK'
Using #asStringEncoding: is the right way to do this. However looking at your screen capture it seems that the bytes you're receiving are not a straight string. There's probably some binary packet format that you need to take apart first and then only decode into strings those parts that you know are actually utf8 encoded (or whatever the encoding is).
You probably can borrow a lot of the code for Squeak's OSC package: http://opensoundcontrol.org/implementation/squeak-osc

Serial Port Communication

I want to send data hex format (0x01) or (0xff) to the port where rs232 cable is connected. I am using the MSCOMM control in VC++ 6.0. Is that the correct way to send the hex data. This is the code I have.
CString output;
UCHAR data1,data2;
data1=0x01;
output.Format("%x",data1);
m_mscom.SetOutput(COleVariant(output));
data2=0xff;
output.Format("%x",data2);
m_mscom.SetOutput(COleVariant(output));
If it is not correct, please tell me how to send hex format data to the port.
Thanks in Advance
If your data is simply a hex value that you want to send out (as opposed to a hex formatted string), you probably want "%c" rather than "%x". Given a data value of (e.g.) 0x65, "%x" will produce two bytes on the serial port: '6' (ascii value 54) and '5' (ascii value 53). "%c" will produce a single byte on the serial port: 'e' (ascii value 100 or 0x65).
As far as sending data on a serial port in C, have a look at CSerial or CSerialPort: they may simplify things for you a bit (note that I've not used them, I tend to do serial port apps in python with the pyserial module or in wxWidgets with the ctb library).
Edit: The other one that's quite good (I have used it before, but couldn't find the link when I wrote the original post) is CSerialFile, part of the WFC libraries. As I said, I tend to use wxWidgets now, but if you're using the Microsoft foundation classes, CSerialFile does make serial access very easy.
I'm no familiar with MSCOM but it seems like it won't work. Format may re-format the data to an ASCII string representation instead.
Alternatively, you can just use any serial port as a 'file' in Windows. Look at the windows api for opening files and you will see that you can address certain devices as files by using a filename like 'COM1:' instead.
Then, you can read/write from it like a file.

Resources