I am trying to communicate and read the words on a Mitsubishi PLC (Q06udeh) using the following code:
from pymodbus.client.sync import ModbusTcpClient
client = ModbusTcpClient('10.1.1.4',port=5007)
client.connect()
result = client.read_holding_registers(1,1)
print result
t = result.registers[0]
print t
I am getting following output:
None
Traceback (most recent call last):
File "C:\Users\serkan\Desktop\sasda.py", line 8, in <module>
t = result.registers[0]
AttributeError: 'NoneType' object has no attribute 'registers'
No matter how I changed the accessing words with different parameters no hope, I still have no success.
Please help.
Using modbus_tk
First of all, you will need to install modbus_tk package:
pip install modbus_tk
Then, try to run this sample code:
# General MODBUS includes
import modbus_tk
import modbus_tk.defines as cst
# TCP MODBUS includes
from modbus_tk import modbus_tcp
def main():
device_id = 1
master = modbus_tcp.TcpMaster("10.1.1.4")
master.set_timeout(3) #it's really optional
master.set_verbose(True) # this is optional too
data = master.execute(device_id, cst.READ_HOLDING_REGISTERS, 100, 1) #Usage: 100 is registry number and 1 means that size of data is 16bit (modbus protocol specification)
print "data ", data
print "data[0] ", data[0]
if __name__ == "__main__":
main()
You can find more examples here:
https://github.com/ljean/modbus-tk/tree/master/examples
Related
Edit;
My original post was too vague regarding what my problem was, so after working on my assignment for some time I've adjusted/fixed most of my code. However, I'm still having trouble getting it to work. Now when I run the script from the cmd prompt I get this message...
Traceback (most recent call last):
File "/PythonScriptsR2/autoadmin_a1_errors.py", line 45, in <module>
log_handle_three = win32evtlog.OpenEventLog(computer,log_type_three)
pywintypes.error: (1722, 'OpenEventLogW', 'The RPC server is
unavailable.')
Here is what my current code looks like
(I wrote some comments on and around line 45 so it's easier to find);
import win32evtlog
import win32evtlogutil
import win32security
import win32con
import time
import winerror
import re
import string
import sys
import traceback
####################################################################
# All error entries for the last 3 months
########
#set date format
def date2sec(self,evt_date):
'''
convert '12/23/99 15:54:09' to seconds
print '333333',evt_date
'''
regexp=re.compile('(.*)\\s(.*)')
reg_result=regexp.search(evt_date)
date = reg.result.group(1)
time = reg_result.group(2)
(mon,day,yr) = map(lambda x: sring.atoi(x),string.split(date,'/'))
(hr,min,sec) = map(lambda x: sring.atoi(x),string.split(time,':'))
tup = [yr,mon,day,hr,min,sec,0,0,0]
sec = time.mktime(tup)
return sec
################
#Initialize variables
flags_three=win32evtlog.EVENTLOG_BACKWARDS_READ|\
win32evtlog.EVENTLOG_SEQUENTIAL_READ
#Dictionary to convert event type into human readable form
evt_dict={win32con.EVENTLOG_AUDIT_FAILURE:'EVENTLOG_AUDIT_FAILURE',\
win32con.EVENTLOG_AUDIT_SUCCESS:'EVENTLOG_AUDIT_SUCCESS',\
win32con.EVENTLOG_INFORMATION_TYPE:'EVENTLOG_INFORMATION_TYPE',\
win32con.EVENTLOG_WARNING_TYPE:'EVENTLOG_WARNING_TYPE',\
win32con.EVENTLOG_ERROR_TYPE:'EVENTLOG_ERROR_TYPE'}
computer='bedrock'
log_type_three='System'
begin_sec=time.time()
begin_time=time.strftime('%H:%M:%S ',time.localtime(begin_sec))
############ \/ Line 45 \/ #############
log_handle_three=win32evtlog.OpenEventLog(computer,log_type_three) #line45
############ /\ Line 45 /\ #############
################
#Open the Event Log
print(log_type_three,' error events found from the last three months
since:',begin_time)
try:
ev_ents=1
while ev_ents:
ev_ents=win32evtlog.ReadEventLog(log_handle_three,flags_three, 0)
for ev_obj in ev_ents:
#################
#check if the event is recent enough
#checking data from the last three months
date = ev_ent.TimeGenerated.Format()
time = ev_ent.TimeGenerated.Format()
seconds = date2sec(date)
if seconds < begin_sec-7862400: break
#################
#if the data is recent enough/from the correct time frame,
#print it
source=str(ev_obj.SourceName)
message=str(win32evtlogutil.SafeFormatMessage(ev_obj,\
logtype))
record = str(ev_obj.RecordNumber)
print(string.join((record,source,date,\
time,message[0:15]),':'))
if seconds < begin_sec-7862400: break #You need to get out of
#the while loop as well
win32evtlog.CloseEventLog(log_handle_three)
except:
print(traceback.print_exc(sys.exc_info()))
So right now my questions are, what does this error message mean, why am I getting this error message, and what are some things I could do to try and fix it.
I think he may want us to use windows powershell to call the script, however, when I did this I got the same error message as I did at the cmd prompt so I'm not sure if it makes a difference.
For some reason, I think it's probably trying to access "bedrock" using the network stack instead of just grabbing it from the local machine. I would make sure that "bedrock" is the actual computer name that you get when you execute "hostname" from the CLI.
I ran into a similar issue using a computer name of "localhost" where it didn't work in certain environments with the same error. Changing that value to the actual local computer name resolved the problem for me.
I'm trying to run a python script that simulates traffic sensors sending in data in real time to PubSub on my Google Cloud Shell. I'm getting this error
Traceback (most recent call last):
File "./send_sensor_data.py", line 87, in <module>
psclient = pubsub.Client()
AttributeError: 'module' object has no attribute 'Client'
Tried running google.cloud.pubsub.__file__, no duplicates exist.
I've been searching everywhere and the popular consensus was to install the pubsub package into a virtual environment which I've tried to no avail.
What I've tried so far:
Set VM to clean state
Uninstalled and reinstalled all gcloud components
Updated all gcloud components to the latest version
uninsalled and reinstalled python pubsub library
Installed pubsub inside a virtualenv
Tried from a different project
Tried from a different GCP account
This is my script:
import time
import gzip
import logging
import argparse
import datetime
from google.cloud import pubsub
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
TOPIC = 'sandiego'
INPUT = 'sensor_obs2008.csv.gz'
def publish(topic, events):
numobs = len(events)
if numobs > 0:
with topic.batch() as batch:
logging.info('Publishing {} events from {}'.
format(numobs, get_timestamp(events[0])))
for event_data in events:
batch.publish(event_data)
def get_timestamp(line):
# look at first field of row
timestamp = line.split(',')[0]
return datetime.datetime.strptime(timestamp, TIME_FORMAT)
def simulate(topic, ifp, firstObsTime, programStart, speedFactor):
# sleep computation
def compute_sleep_secs(obs_time):
time_elapsed = (datetime.datetime.utcnow() - programStart).seconds
sim_time_elapsed = (obs_time - firstObsTime).seconds / speedFactor
to_sleep_secs = sim_time_elapsed - time_elapsed
return to_sleep_secs
topublish = list()
for line in ifp:
event_data = line # entire line of input CSV is the message
obs_time = get_timestamp(line) # from first column
# how much time should we sleep?
if compute_sleep_secs(obs_time) > 1:
# notify the accumulated topublish
publish(topic, topublish) # notify accumulated messages
topublish = list() # empty out list
# recompute sleep, since notification takes a while
to_sleep_secs = compute_sleep_secs(obs_time)
if to_sleep_secs > 0:
logging.info('Sleeping {} seconds'.format(to_sleep_secs))
time.sleep(to_sleep_secs)
topublish.append(event_data)
# left-over records; notify again
publish(topic, topublish)
def peek_timestamp(ifp):
# peek ahead to next line, get timestamp and go back
pos = ifp.tell()
line = ifp.readline()
ifp.seek(pos)
return get_timestamp(line)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Send sensor data to Cloud Pub/Sub in small groups, simulating real-time behavior')
parser.add_argument('--speedFactor', help='Example: 60 implies 1 hour of data sent to Cloud Pub/Sub in 1 minute', required=True, type=float)
args = parser.parse_args()
# create Pub/Sub notification topic
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
psclient = pubsub.Client()
topic = psclient.topic(TOPIC)
if not topic.exists():
logging.info('Creating pub/sub topic {}'.format(TOPIC))
topic.create()
else:
logging.info('Reusing pub/sub topic {}'.format(TOPIC))
# notify about each line in the input file
programStartTime = datetime.datetime.utcnow()
with gzip.open(INPUT, 'rb') as ifp:
header = ifp.readline() # skip header
firstObsTime = peek_timestamp(ifp)
logging.info('Sending sensor data from {}'.format(firstObsTime))
simulate(topic, ifp, firstObsTime, programStartTime, args.speedFactor)
The pubsub.Client class exists until the 0.27.0 version of the pubsub python package. So I just created a virtual environment and installed the 0.27.0 version of pubsub into it.
Here are the commands:
virtualenv venv
source venv/bin/activate
pip install google-cloud-pubsub==0.27.0
Solution for Google Cloud Platforms is:
Modify the send_senor_data.py file as follows:
a. Comment the original import statement for pub_sub and use _v1 version
#from google.cloud import pubsub
from google.cloud import pubsub_v1
b. Find this code and replace it as follows:
#publisher = pubsub.PublisherClient()
publisher = pubsub_v1.PublisherClient()
Then execute your send_sensor_data.py as follows:
./send_sensor_data.py --speedFactor=60 --project=YOUR-PROJECT-NAME
There's no pubsub.Client class. You
need to choose a PublisherClient or SubscriberClient
see https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/pubsub/google/cloud/pubsub.py
I've been using code on my RPi2 to communicate to an RS485 Shield to drive various relays. I recently got a RPi3, and the code that has previously worked on the RPi2 has an error on the RPi3.
To begin with, I know that the uart (/dev/ttyAMA0) is "stolen" on the RPi3 for the bluetooth controller. Using this post, I reassigned the uart to the GPIO header so the RS485 shield should work as before. I give you this history, even though I suspect the problem is not with the hardware per se.
Here's the problem. When I execute the code below on the RPi3, I get an error:
Traceback (most recent call last):
File "serialtest.py", line 15, in <module>
if usart.is_open:
AttributeError: 'Serial' object has no attribute 'is_open'
Obviously, within the pySerial library, the serial object DOES have the 'is_open' attribute. Any suggestions on why this error is thrown? I haven't found any references to this specific error in web searches.
#!/usr/bin/env python
import serial
import time
import binascii
data = "55AA08060100024D5E77"
usart = serial.Serial ("/dev/ttyAMA0",19200)
usart.timeout = 2
message_bytes = data.decode("hex")
try:
usart.write(message_bytes)
#print usart.is_open # True for opened
if usart.is_open:
time.sleep(0.5)
size = usart.inWaiting()
if size:
data = usart.read(size)
print binascii.hexlify(data)
else:
print('no data')
else:
print('usart not open')
except IOError as e :
print("Failed to write to the port. ({})".format(e))
If you have an old version of pyserial on the Raspberry Pi, pyserial might not have the is_open, but isOpen() method instead. The isOpen() method was depricated in version 3.0 according to the documentation. You can check the pyserial version with serial.VERSION.
I'm currently trying to build a Script that interacts with Google's API's, but I keep getting an Attribute error:
Traceback (most recent call last):
File "service_catalog_automation.py", line 18, in <module>
feed = client.GetDocumentListFeed()
AttributeError: 'DocsClient' object has no attribute 'GetDocumentListFeed'
This is the code I'm trying to use
import gdata.gauth
import gdata.docs.client
import sys
def sys_print(text):
sys.stdout.write(str(text))
sys.stdout.flush()
CONSUMER_KEY = 'domain.com'
CONSUMER_SECRET = 'abcde1234'
requestor_id = 'myuser#domain.com'
client = gdata.docs.client.DocsClient(source='my-script-v1')
client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
CONSUMER_KEY, CONSUMER_SECRET, requestor_id)
# Retrieve user's list of Google Docs
feed = client.GetDocumentListFeed()
for entry in feed.entry:
sys_print(entry.title.text)
sys_print('\n')
I've pulled client.getDocumentListFeed() portion of code from their sample code here and have even tried a bare minimum approach using their sample code under the 2LeggedOAuth section here. (I also have tried GetDocList() from that example with the same error)
I have downloaded Google's gdata-python-client to a linux vm's home directory and installed it by running python setup.py install and ran the test python all_tests.py with no errors.
Any help would be greatly apperciated
In the first example, they're assigning their client object as the return of gdata.docs.service.DocsService().
The second example also returns the client object as a DocsService type:
client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
This would seem to imply that gd_client is of type DocsService, not DocsClient
I'm trying to print the data that comes across the serial from an Arduino but I am unable to do so. My attempted code is this:
import serial
import time
s = serial.Serial('/dev/tty.usbmodemfd141',9600)
while 1:
if s.inWaiting():
val = s.readline(s.inWaiting())
print val
Yet after about 30 lines or so are spit out I get the following error message:
Traceback (most recent call last):
File "py_test.py", line 7, in <module>
val = s.readline(s.inWaiting())
File "build/bdist.macosx-10.8-intel/egg/serial/serialposix.py", line 460, in read
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
I imagine I am using inWaiting incorrectly, but I do not see how to use it any other way.
Have you tried wrapping the readline in a try/except SerialException block? You could then just pass on the SerialException. It could be an issue with the serial driver reporting data in the receive buffer when there is not any, in which case your code will just keep running. Not a great fix, but it may lead you to the correct solution.
try:
s.read(s.inWaiting())
except serial.serialutil.SerialException:
pass # or maybe print s.inWaiting() to identify out how many chars the driver thinks there is
I believe you want to use function read(), not readline(). You are retrieving the number of characters in the buffer, they don't necessarily end with a new-line
Your loop becomes:
while 1:
if s.inWaiting():
val = s.read(s.inWaiting())
print val
if you want to simply print the data coming out of the serially connected device.you can
simply do it by using readline().
first open the port by using open() then you need to use the readline().
note:/dev/ttyUSB0 is a port number for linux and com0 is windows
here is the code
import serial
BAUDRATE = 115200
device_name = "ttyUSB0"
tty = device_name
s = serial.Serial("/dev/" + tty, baudrate=BAUDRATE)
s.open()
print s
try:
while True:
line = s.readline() //after this you can give the sleep time also as time.sleep(1) before that import time module.
print line
finally:
s.close()