-
Notifications
You must be signed in to change notification settings - Fork 58
-
Hello, I am using a Waveshare usb device in homeassistant RPi3 with HAOS, and are trying to read the 8 channel WaveShare modbus device. After getting advice from their Helpdesk and a working python script- I want to call this with HACS > pyscript integration.
I have this scripts (got it setup and working on the /pyscript folder - other scripts are working). The issue is to wait for the USB RS485 dongle to send back the registers info after asking the device for it. the issue is that time.sleep() worked until recently, now pyscript wants asyncio.sleep(1). This script is not reporting info back from the log.error(f"Pyscript app modbus4 - modbus.readregisters - variables: {state_var_json}")
logs - so it looks like it is not working.
Any ideas anyone?
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import serial
import pycrc
import time
import json
import asyncio
# Define the serial port and baud rate
vUSB = "ttyUSB0"
ser = "/dev/" + str(vUSB)
baud = 9600
@service("modbus.readregisters")
def read_modbus_registers():
"""yaml
name: Reads Modbus registers from a device (in app modbus4)
"""
try:
s = serial.Serial(ser, baud)
cmd = [0x00, 0x03, 0x00, 0x40, 0x00, 0x01, 0x00, 0x00]
crc = pycrc.ModbusCRC(cmd[0:6])
cmd[6] = crc & 0xFF
cmd[7] = crc >> 8
log.error(f"Sending command list (for info): {cmd} to port {s}")
s.write(cmd)
asyncio.sleep(1) # gets a warning - time.sleep(1)
count = s.inWaiting()
if count != 0:
rec_b = s.read(count)
rec_list = list(rec_b)
state_var = {
"device": rec_list[0],
"command": rec_list[1],
"register": rec_list[3],
"val": rec_list[4]
}
state_var_json = json.dumps(state_var)
log.error(f"Pyscript app modbus4 - modbus.readregisters - variables: {state_var_json}")
except Exception as e:
log.error(f"An error occurred: {str(e)}")
finally:
if s.is_open:
s.close()
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 1 reply
-
I don't think serial
is async, so I'd recommend calling it using its own thread and with native python; you can then safely use time.sleep()
if you must.
Here's how to do that. You should move the body of the service function to a new function, remove anything that is pyscript
specific (eg, remove log.error()
and replace asyncio.sleep()
with time.sleep()
.) Then add a @pyscript_executor
decorator to that new function. That will cause it to be compiled as native python, and it will run in its own thread every time it is called. That allows it to safely block without stalling the HASS main event loop. See the docs.
Beta Was this translation helpful? Give feedback.
All reactions
-
Wow, thanks, will try this. Had no idea this is possible, although it is clearly documented. Do not know python from a bar-of-soap, but will try ....
Beta Was this translation helpful? Give feedback.