首页 \ 问答 \ 我可以使用Python读取从站计算机上收到的Modbus RS485数据吗?(Can I read Modbus RS485 data received on a slave computer with Python?)

我可以使用Python读取从站计算机上收到的Modbus RS485数据吗?(Can I read Modbus RS485 data received on a slave computer with Python?)

我正在从计算机上工作,并希望通过Modbus RS485将从主站传输的数据保存到文本文件中。 主计算机不断向我工作的从属计算机发送写入和读取请求,下面是一个由串行端口监视器捕获的图像。

在这里输入图像描述

我刚刚发现用最少的modbus就可以读取寄存器。 但它似乎只有你是主设备才有效。 我可以做一些类似的东西,但在从属计算机上? http://minimalmodbus.readthedocs.io/en/master/usage.html

#!/usr/bin/env python
import minimalmodbus

instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) # port name, slave 
#address (in decimal)

## Read temperature (PV = ProcessValue) ##
temperature = instrument.read_register(289, 1) # Registernumber, number of 
#decimals
print temperature

## Change temperature setpoint (SP) ##
NEW_TEMPERATURE = 95
instrument.write_register(24, NEW_TEMPERATURE, 1) # Registernumber, value, 
#number of decimals for storage

I am working on a slave computer and want to save the data transmitted from the master via Modbus RS485, into a text file. The master computer constantly send writing and reading request to the slave computer I am working on, below is a picture captured by serial port monitor.

enter image description here

I just found with minimalmodbus you can read registers. But it seems to only work if you are a master device. Can I do something similar but on a slave computer? http://minimalmodbus.readthedocs.io/en/master/usage.html

#!/usr/bin/env python
import minimalmodbus

instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) # port name, slave 
#address (in decimal)

## Read temperature (PV = ProcessValue) ##
temperature = instrument.read_register(289, 1) # Registernumber, number of 
#decimals
print temperature

## Change temperature setpoint (SP) ##
NEW_TEMPERATURE = 95
instrument.write_register(24, NEW_TEMPERATURE, 1) # Registernumber, value, 
#number of decimals for storage

原文:https://stackoverflow.com/questions/47926257
更新时间:2023-10-25 07:10

最满意答案

试用PythonCalendar Quickstart 。 它包括登录并使用该身份验证来生成令牌。 这些令牌将用于执行日历API调用。 玩它并添加您自己的代码。

这是一个片段:

def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')

store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials

Here's how I managed to get it working:

models.py

from django.db import models
from oauth2client.contrib.django_orm import CredentialsField

class Credentials(models.Model):
    id = models.OneToOneField(User, primary_key=True)
    credential = CredentialsField()

    class Meta:
        db_table = 'credentials'

settings.py

.
.
.
GOOGLE_CLIENT_ID = ''  
GOOGLE_CLIENT_SECRET = ''
GOOGLE_SCOPE = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar'
OAUTH_REDIRECT_URI = 'http://<domain>/oauth2/redirect/'
.
.
.

views.py

import httplib2
from django.conf import settings
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.http import (HttpResponse, HttpResponseBadRequest,
                         HttpResponseRedirect)
from django.shortcuts import redirect
from oauth2client.contrib import xsrfutil
from oauth2client.contrib.django_orm import Storage

from .models import Credentials


def get_flow(request):    
    flow = OAuth2WebServerFlow(
        client_id=settings.GOOGLE_CLIENT_ID,
        client_secret=settings.GOOGLE_CLIENT_SECRET,
        scope=settings.GOOGLE_SCOPE,
        redirect_uri=settings.OAUTH_REDIRECT_URI,
        access_type='offline',
        state=''
    )
    return flow


def login(request):
    next = request.GET.get('next', 'home')
    request.session['next'] = next

    if not request.user.is_authenticated():
        flow = get_flow(request)
        flow.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                       request.user)
        request.session['flow'] = pickle.dumps(flow).decode('iso-8859-1')
        redirect_uri = flow.step1_get_authorize_url()
        return redirect(redirect_uri)
    else:
        return redirect(reverse_lazy(next))


def oauth2redirect(request):
    # Make sure that the request is from who we think it is
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.GET.get('state').encode('utf8'),
                                   request.user):
        return HttpResponseBadRequest()

    code = request.GET.get('code')
    error = request.GET.get('error')

    if code:
        flow = get_flow(request)
        credentials = flow.step2_exchange(code)

        request.session['creds'] = credentials.to_json()
        email = credentials.id_token.get("email")
        user_exists = False
        try:
            user = User.objects.get(email=email)
            user_exists = True
        except User.DoesNotExist:
            user = create_user(credentials)

        # Since we've oauth2'd the user, we should set the backend appropriately
        # This is usually done by the authenticate() method.
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        # Refresh token is needed for renewing google api access token
        if credentials.refresh_token:
            user.refresh_token = credentials.refresh_token
        user.save()

        storage = Storage(Credentials, 'id', user, 'credential')
        storage.put(credentials)

        # Register that the user has successfully logged in
        auth_login(request, user)

        next = request.session.get('next', reverse_lazy('/'))
        return HttpResponseRedirect(next)
    elif code is None and error:
        return HttpResponse(str(error))
    else:
        return HttpResponseBadRequest()


@login_required
def logout(request):
    user = request.user
    credentials = Credentials.objects.get(id=user.id)
    credentials.revoke(httplib2.Http())
    credentials.delete()
    storage = Storage(Credentials, 'id', user, 'credential')
    storage.delete()

    auth_logout(request)
    return HttpResponseRedirect('/')

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)