pymodbus read_input_registers error : ModbusIOException' object has no attribute 'registers' - pymodbus

I'm using pymodbus (v3.0.2) on ubuntu linux server 22.04
using to read modbus rtu device (masibus datalogger)
when I'm trying to read input register, it some time returning the data which is correct, and most of the time giving this error
"ModbusIOException' object has no attribute 'registers'
here is my code to
#!/usr/bin/python3
import time
import datetime
from datetime import timedelta
import mysql.connector
from mysql.connector import Error
from pymodbus.client import ModbusSerialClient
client = ModbusSerialClient(
method="rtu",
port="/dev/ttyUSB0",
stopbits=2,
bytesize=8,
parity="N",
baudrate=9600)
connection = client.connect()
if connection is True:
print("Modbus Connection Successful")
def read_mbr():
readreg = client.read_input_registers(0, 15, unit=1).registers
# print(f'Data = {readreg}')
return readreg
while(1):
try:
data = read_mbr()
print(data)
except Exception as e:
print(e)
time.sleep(1)
time.sleep(1)
I've tried to add more time detail, but did not worked.

Related

MicroPython: How to auto reconnect STA to AP if AP gets power cycled?

I am writing a python code on ESP8266 using MicroPython to configure it as STA, connect it to an AccessPoint and then send some data on UDP Socket.
I want to implement a scenario where in case if AccessPoint due to some reason goes down and comes back after some time, the the ESP8266 acting as STA should automatically reconnect to specific AP.
I am not sure if there's a functionality to setup a callback on STA if it misses few Beacons (e.g. upto 5 or 10)
This is the code that I have written so far:
import network
import esp
import gc
import time
try:
import usocket as socket
except ModuleNotFoundError as e:
import socket
def main():
count = 0
esp.osdebug(None)
gc.collect()
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('HumidityServer', 'password#123')
while not sta.active():
pass
print('Connection successful')
print(sta.ifconfig())
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('192.168.45.1', 9000))
while True:
str_to_send = "Hello ESP8266: " + str(count)
s.sendto(str_to_send, ('192.168.45.1', 9000))
request = s.recv(1024)
print('Content = %s' % str(request))
count = count + 1
time.sleep(5)
if __name__ == "__main__":
main()

FastAPI StreamingResponse with picamera2 - browser refresh problem

I'm trying to make FastAPI server which streams MJPEG from Raspberry Pi via picamera2 library. It works, but when I reload browser on /mjpeg multiple times, it will stuck. But with this example it works perfectly - you can reload browsers as many times as you want. Can you spot the problem?
For server I'm using uvicorn with default settings.
Thanks!
import io
import os
from threading import Condition
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from picamera2 import Picamera2
from picamera2.encoders import JpegEncoder
from picamera2.outputs import FileOutput
from fastapi.responses import HTMLResponse, StreamingResponse
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins="http://localhost:8000",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class StreamingOutput(io.BufferedIOBase):
def __init__(self):
self.frame = None
self.condition = Condition()
def write(self, buf):
with self.condition:
self.frame = buf
self.condition.notify_all()
picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"size": (640, 480)}))
output = StreamingOutput()
picam2.start_recording(JpegEncoder(), FileOutput(output))
def get_frame():
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
yield (
b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n"
)
except Exception as e:
print("Error! Frames")
#app.get("/mjpeg", response_class=StreamingResponse)
def mjpeg(request: Request):
try:
frames = get_frame()
response = StreamingResponse(
frames,
headers={
"Cache-Control": "no-cache, private",
"Pragma": "no-cache",
},
media_type="multipart/x-mixed-replace; boundary=frame",
)
return response
except Exception as e:
print("Error! Route")

When execute the test script in appium it display AttributeError: can't set attribute

import time
import ScrollUtil
from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['deviceName'] = 'Android'
desired_caps['appPackage'] = 'com.samsung.android.dialer'
desired_caps['appActivity'] = 'com.samsung.android.dialer.DialtactsActivity'
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
driver.implicitly_wait(10)
ScrollUtil.swipeUp(4,driver)
ScrollUtil.swipeDown(4,driver)
# driver.find_element_by_android_uiautomator(
# 'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains("Akash").instance(0))').click()
time.sleep(2)
driver.quit()
`
When I execute the above scripts I receive the below error messages and cannot be executed. I have already open the Appium Server
self.capabilities = response.get('value')
AttributeError: can't set attribute
Error message
Reinstall Appium-Python-Client using pip, instead of npm
And make sure selenium 3.XX version is installed

Parameterize the find method in python using mongo

Files to upload will be like WFSIV0101202001.318.tar.gz,WFSIV0101202001.2624.tar.gz etc.
INPUT_FILE_PATH = 'C:\Files to upload'
try:
import os
from google.cloud import storage
import sys
import pymongo
import pymongo.errors
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
except:
print("missing modules")
try:
mongo_client = MongoClient(host="xyz.com", port=27017)
Db = mongo_client['abcd']
coll = Db['shopper_journey_sitedata']
except ConnectionFailure:
print("Connection failed")
date=[]
# Thirdpartyid=[]
input_files = os.listdir(INPUT_FILE_PATH)
# looping through input files
for input_file in input_files:
x = input_file.split(".")
date.append(x[0][5:13])
tp_site_id = x[1]
# print(tp_site_id)
cur = coll.find({"third_party_site_id":tp_site_id})
for doc in cur:
print(doc)
Now i want to parameterize the find() method for every id, so that on each iteration i should get st_site_id ?
above code i tried but ist giving error as "Datas:name error"
You can do one thing
coll.find({"third_party_site_id": { $in :
[318,2624,2621,2622,102,078]}})
If Tid is an array, then you could replace 318 in your query to Tid[I]

flask/MongoDB error on local server using raspberry pi3 - raspbian os

i've made a local server using flask and mongoDB which works great on windows, but when i moved my code to the raspberry pi, i've got an error which i couldn't figure out why it occurs.
the code im using:
1) for the flask server
from flask import Flask
from flask import jsonify
from flask import request
import pymongo
import time
import datetime
import json
app = Flask(__name__)
client = pymongo.MongoClient("localhost", 27017)
db = client['mqtt-db']
obs_collection = db['mqtt-collection']
#app.route("/obs")
def obs():
data_str = request.args.get("data")
print data_str
data = json.loads(data_str)
print data
data["date"] = datetime.datetime.now()
obs_collection.save(data)
return "success"
#app.route("/get_obs")
def get_obs():
res = []
for row in obs_collection.find():
del row['_id']
res.append(row)
return jsonify(res)
#app.route("/delete_all")
def delete_all():
res = obs_collection.delete_many({})
return jsonify({"deleted": res.deleted_count})
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
2) script for inserting messages into db , using mqtt protocol:
import paho.mqtt.client as mqtt
import pymongo
import json
import datetime
topic = "sensor"
host = "10.0.0.6"
client = pymongo.MongoClient("localhost", 27017)
db = client['mqtt-db']
mqtt_collection = db['mqtt-collection']
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(topic)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
data_str = str(msg.payload)
data = json.loads(data_str)
print data_str
print data
data["date"] = datetime.datetime.now()
mqtt_collection.save(data)
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(host, 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
the error occurs when i try to retrieve data from the server using "get_obs" function.
the error is: "Value Error: dictionary update sequence element #0 has length 4; 2 is required"
appreciate your help.
as #davidism suggested, the solution was to update to the latest version of Flask