How to communicate Python with Siemens PLC using Python-snap7 and plcsim? - python

I used pycharm for writing my code and plcsim for simulatio. When I run my code and run plcsim I get an error.
I used Tia portal V16 and s7-1200 and I want to communicate between S7-1200 and python-snap7
This is the error:
PS C:\Users\Badro\PycharmProjects\pythonProject1\venv> py test.py
b' TCP : Unreachable peer'
Traceback (most recent call last):
- File "C:\Users\Badro\PycharmProjects\pythonProject1\venv\test.py", line 8, in <module>
plc.connect(IP, RACK, SLOT)
- File "C:\Users\Badro\AppData\Local\Programs\Python\Python310\lib\site-
packages\snap7\client.py",
line 24, in f
check_error(code, context="client")
- File "C:\Users\Badro\AppData\Local\Programs\Python\Python310\lib\site-
packages\snap7\common.py",
line 89, in check_error
raise RuntimeError(error)
RuntimeError: b' TCP : Unreachable peer'enter code here
and this is my code:
import snap7
IP = '192.168.100.100'
RACK = 0
SLOT = 1
plc = snap7.client.Client()
plc.connect(IP, RACK, SLOT)
print(plc.get_cpu_state())
I watched this videohttps://www.youtube.com/watch?v=BKnK4AT_WKs
Where is the problem or is the problem that plcsim must be the real plc for simulation not plcsim?

PLCSIM cannot simulate a network interface on simulated PLCs.
You have to install PLCSIM Advanced V3.0, which also simulates the network interface for each simulated PLC.

I have PLCSIM V13 SP1 and have tested your program and it works.
I think you need to install NetToPLCSim which allows you to connect to the Plc to test your application using the network interface of the PC running the simulation.
It is recommended that you run NetToPLCSim as an administrator.

Related

Connect from a cisco device to http server on debian

I'm trying to communicate with a http server which is running on debian strech from a brand new out of the box cisco device. Now, the so called zero touch configuration is no problem:
The Switch gets an IP address and such via DHCP and a link to where to fetch it's initial configuration.
The switch gets its basic configuration such as user credentials etc.
The problem rises when I try to search through a database on the server from the switch. In this database some variables are stored. Depending the serialnumber of the switch, it should receive a specific hostname, Mgmt address etc.
On those new switches there is a python module integrated so I ran some tests. I tried to fetch the serial number and got them whithout any problems. The moment I tried to write the serial number on a txt file on the server I got this error
Traceback (most recent call last): File "", line 1, in
IOError: [Errno 2] No such file or directory:
'http://10.232.152.19:80/temp.txt'
Code so far:
from cli import cli
def get_serial():
serial = cli("show version | include System Serial\n")
serial = (serial.split()[-1])
f = open ("http://10.232.152.19:80/temp.txt", "a")
f.write(serial)
f.close
get_serial()
The problem you are facing is because you are trying to open a file from the network. You need to download the file first in you system and then open it. You should use urllib to fetch the file and then open it. then save it and again push it back.
import urllib
txt = urllib.urlopen(target_url).read()

pydbus reconnection after target is rebooted

I'm facing the following problem.
I'm using pydbus python package to test API by connecting to a target linux machine which is in the same network by using the environment variable DBUS_SYSTEM_BUS_ADDRESS
Under normal circumstances this works well, I'm able to call any valid API over the proxy object created.
Eg:
import os
import pydbus
os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = \
"tcp:host=192.168.1.100,port=55556,family=ipv4"
bus = pydbus.SystemBus()
proxy = bus.get("busname", "object_path")
return_value = proxy.method-name(args)
As part of my testing, my target linux machine gets rebooted in between and when I re-use the proxy object, I get the following error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/harman/.local/lib/python2.7/site-packages/pydbus/proxy.py", line 47, in get
0, timeout_to_glib(timeout), None)
GLib.Error: g-io-error-quark: The connection is closed (18)
I realize that the previous connection no longer exists, so I tried re-initialising the connection with the following
bus = pydbus.SystemBus()
proxy = bus.get("busname", "object_path")
I get the same error on the bus.get() statement.
Is there a solution/possible workaround to this problem?

BlueZ AutoReconnect as device to PC

I'm working on a HID bluetooth device with the code on the device in Python; at the moment it can connect to a PC by running:
os.system("hciconfig hcio class 0x002560")
os.system("hciconfig hcio name DataPaqWalk")
Then we can use pybluez to connect the sockets and wait for a connection:
print("Waiting for connections")
self.scontrol=BluetoothSocket(L2CAP)
self.sinterrupt=BluetoothSocket(L2CAP)
self.scontrol.listen(1) # Limit of 1 connection
self.sinterrupt.listen(1)
self.ccontrol,cinfo = self.scontrol.accept()
self.cinterrupt, cinfo = self.sinterrupt.accept()
This works and we have a thread polling with hcitool con to detect the Windows PC (adapter) disconnecting where we dump the sockets and listen again. The hci is setup with no security so the PC connecting to it automatically pairs - this all works.
However the issue comes when the device is powered off; the PC correctly detects that the device is gone and it remains in the paired state. What I want to do is to get the device to automatically connect to the PC it is paired with. I've obviously got the Mac address of the PC and I am trying to connect using:
(P_CTRL is 17 and P_INTR is 19)
self.ccontrol,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_CTRL))
self.controlClientMac = cinfo[0]
self.controlClientPsm = cinfo[1]
print ('control is ' + self.controlClientMac + " " + str(self.controlClientPsm))
self.cinterrupt,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_INTR))
self.interruptClientMac = cinfo[0]
self.interruptClientPsm = cinfo[1]
print ('interrupt is ' + self.interruptClientMac + " " + str(self.interruptClientPsm))
This basically tries to connect and gives me back:
Traceback (most recent call last):
File "server/btk_server.py", line 267, in <module>
myservice = BTKbService();
File "server/btk_server.py", line 226, in __init__
self.device.listen();
File "server/btk_server.py", line 174, in listen
self.ccontrol,cinfo = self.scontrol.connect(('C8:FF:28:79:05:D4', self.P_CTRL))
File "<string>", line 5, in connect
bluetooth.btcommon.BluetoothError: (111, 'Connection refused')
In the bluetooth windows dialog you can see that it flicks to connected but straight back to paired. The question is; how do I get the device to connect to the paired windows adapter? Note that I'm getting a similar response in bluetoothctl.
Wouldnt you be able to run a script on the rpi upon startup automatically that starts looking for a bluetooth socket? https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/

pjsua.error, error = address already in use

I am trying to make calls using PJSIP module in python. For setup of SIP transport, I am doing like
trans_cfg = pj.TransportConfig()
# port for VoIP communication
trans_cfg.port = 5060
# local system address
trans_cfg.bound_addr = inputs.client_addr
transport = lib.create_transport(pj.TransportType.UDP,trans_cfg)
when I finish the call I am clearing the transport setup as, transport = None.
I am able to make call to user by running my program. But every time I restart my PC alone, I get an error while I run my python program
File "pjsuatrail_all.py", line 225, in <module>
main()
File "pjsuatrail_all.py", line 169, in main
transport = transport_setup()
File "pjsuatrail_all.py", line 54, in transport_setup
transport = lib.create_transport(pj.TransportType.UDP,trans_cfg)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 2304, in
create_transport
self._err_check("create_transport()", self, err)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 2723, in _err_check
raise Error(op_name, obj, err_code, err_msg)
pjsua.Error: Object: Lib, operation=create_transport(), error=Address already in use
Exception AttributeError: "'NoneType' object has no attribute 'destroy'" in <bound method Lib.__del__ of <pjsua.Lib instance at 0x7f8a4bbb6170>> ignored
For this currently I am doing like
$sudo lsof -t -i:5060
>> 1137
$sudo kill 1137
Then I run my code it works fine.
By instance from error, I can understand that somewhere I am not closing my transport configuration properly. Can anyone help in this regards.
Reference code used
From the inputs you give, it can be understood that its not the problem with pjsip wrapper. Transport configurations looks fine.
Looking in to the 'create_transport' error, the program is not able to create the connection because 5060 port is already occupied with some other program.
For that you are killing that process and you are able to run the program with out any error. And you say it only on restart, so on your system restart some program is occupying the port.
You can try like this
sudo netstat -nlp|grep 5060
in your case it will give like
1137/ProgramName
go to the 'ProgramName' in your startup configurations and make modifications such that it wont pickup the port.

Executing sparql query from python to virtuoso server in linux?

I am having problem for running the following program (sparql_test.py). I am running it from Linux machine. I am installing Virtuoso server in the same Linux machine. In the Linux server, I don't have sudo permission nor browser access. But, I can execute SPARQL query from isql prompt (SQL>) successfully.
Program: sparql_test.py
from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper("http://localhost:8890/sparql")
sparql.setQuery("select ?s where { ?s a <http://ehrofip.com/data/Admissions>.} limit 10")
sparql.setReturnFormat(JSON)
result = sparql.query().convert()
for res in result["results"]["bindings"]:
print(res)
I got the following error:
[suresh#deodar complex2vec]$ python sparql_test.py
Traceback (most recent call last):
File "sparql1.py", line 14, in "<module>"
result = sparql.query().convert()
File "/home/suresh/.local/lib/python2.7/site-packages/SPARQLWrapper/Wrapper.py", line 687, in query
return QueryResult(self._query())
File "/home/suresh/.local/lib/python2.7/site-packages/SPARQLWrapper/Wrapper.py", line 667, in _query
raise e
urllib2.HTTPError: HTTP Error 502: Bad Gateway
However, the above program run smoothly in my own laptop. What might be the problem? Is this issue of connection?
Thank you
Best,
Suresh
I do not believe this error is raised by Virtuoso. I believe it is raised by SPARQLWrapper.
It looks like there's something between the outside world (which includes the Linux machine itself) and the Virtuoso listener on port 8890. The "Bad Gateway" suggests there may be two things -- a reverse proxy, and a firewall.
Port 8890 (set as [HttpServer]:Listen in the INI file) must be open to communications, direct or proxied, for SPARQL access to work.
iSQL talks to port 1111 (set as [Parameters]:Listen in the INI file), which apparently doesn't have a similar block/proxy.

Categories

Resources