I want to connect my phone with the raspberry pi via bluetooth and for that, I'm using this code
from bluedot.btcomm import BluetoothServer
from signal import pause
def data_received(data):
print(data)
s.send(data)
s = BluetoothServer(data_received)
pause()
Sometimes It's working fine I'm able to connect my phone and send data but some times its shows error like
Bluetooth address B8:27:EB:DA:25:25 is already in use - is the server already running?
Traceback (most recent call last):
File "mypyscript/mainscript.py", line 8, in s = BluetoothServer(data_received)
File "/home/pi/.local/lib/python2.7/site-packages/bluedot/btcomm.py", line 358, in start
raise e
socket.error: [Errno 98] Address already in use
I copied this code from here
Related
I am trying to communicate a Modbus slave device that uses Modbus RTU protocol, with RPi having pymodbus lib in python 3.8.
Here's a link for this library
http://riptideio.github.io/pymodbus/
My concern is when printing holding registers responses. I have read other posts regarding it and people have suggested using '.registers' with the print command.
How to read from Registers with pymodbus
At times, I get the value printed out but other times I see this error
Traceback (most recent call last):
File "/home/user123/VsCode/Modbus_Rtu_sample.py", line 65, in <module>
value = result.registers
AttributeError: 'ModbusIOException' object has no attribute 'registers'
Firstly, I want to know why does this works sometimes and not other times. as I can see in the pymodbus documentation, there's no attribute called registers then how does it work the first time? this is my code:
with ModbusClient(method='rtu', port='/dev/ttyUSB0', stopbits=1, bytesize=8 , parity='N', baudrate=9600, timeout=2) as client:
if not client.connect():
connection = client.connect()
connection = client.connect()
print("Your connection is set to",connection)
if client.connect():
read=client.read_holding_registers(address = 0x1000,count =4,unit=1)
value = read.registers
print(value)
#print(read.registers)
else:
print("Cannot connect to modbus slave")
client.close()
Is there any better lib/method/way to overcome this issue? all I want is to have stable read / write outputs for registers. later I want to call a class made from this so don't want to have a situation where sometimes I do get output and other times an error is thrown.
I am developing some software in python 3.9 and I am at the point where I have a device connected to my USB port and would like to send a basic packet to test the interface before I proceed. I am using this example to try and get my interface to work. I am not bothered about speed or byte count. I would like to see any response on the interface (But on reflection Im wondering if usb speed could be the issue):
import usb1
import usb.util
import os
import sys
import libusb
import usb.core
from usb import util
import math
dev = usb.core.find(idVendor=0x11ac,idProduct=0x317d)
with usb1.USBContext() as context:
handle=context.openByVendorIDAndProductID(
0x11ac,
0x317d,)
handle.claimInterface(0)
handle.setInterface(0)
data = bytearray(b"\\xf0\\x0f"* (int(math.ceil(0xb5db91/4.0))))
handle.controlWrite(0x40, 0xb0, 0xb5A6, 0xdb91, b"")
handle.bulkWrite(2,data,timeout=5000)
`
https://github.com/vpelletier/python-libusb1/issues/21
I have had a look in various forums for several days and cannot seem to get an answer that works. Here is the trace: Its worth noting that from time to time, this py file does run without error but does nothing, and I see no traffic traveling to the USB interface.
Can someone please help me configure a working example of how to send a packet to the interface? I have tried various things like detaching the kernel, setting configuration, etc.
For 4 days I have struggled with libusb01 & 10, after discovering libusb1, I have changed my wrapper and got a lot more success
I also see a lot of examples in forums like this one, and I always get the same response. Also Im curious as to where it appears that 0x40 is the endpoint(out)
Traceback (most recent call last):
File "/home/jbgilbert/Desktop/Packets/Backend_replace.py", line 16, in <module>
handle.claimInterface(0)
File "/usr/lib/python3/dist-packages/usb1/__init__.py", line 1213, in claimInterface
libusb1.libusb_claim_interface(self.__handle, interface),
File "/usr/lib/python3/dist-packages/usb1/__init__.py", line 133, in mayRaiseUSBError
__raiseUSBError(value)
File "/usr/lib/python3/dist-packages/usb1/__init__.py", line 125, in raiseUSBError
raise __STATUS_TO_EXCEPTION_DICT.get(value, __USBError)(value)
usb1.USBErrorBusy: LIBUSB_ERROR_BUSY [-6]
My device is a laptop, using lsmod reveals all devices linked to that particular end point, in this case because if the presence of a webcam I was unable to write to an available end point. Despite disabling the driver I had no avail and had to try to code on a machine that had less onboard accessories that proved more successful
I am trying to update the firmware of a controller through a serial interface. To do this, I must send a reboot message to the controller (no problem there) and then send another message (the character 'w') THE MOMENT it starts up so that it may start up in write mode. This is easily done with the minicom utility by pressing w continuously while the device restarts.
I want to achieve this functionality using python code instead, but I can't figure out how to send a message until the device is up without throwing exceptions (since the device is not connected).
This is what I have tried, but it does not work (with pyserial):
def send_w(serial_port, baud_rate):
msgw = "w_"
ans = ""
ser = serial.Serial(port=serial_port, baudrate=baud_rate,timeout = 10)
ser.write(msgw)
ans = ser.read(24)
ser.close()
print(ans)
return ans
def set_firmware_version(serial_port, baud_rate):
s = ""
try:
with serial.Serial(serial_port,baud_rate,timeout=1) as ser:
msgr = "%reset "+sk+"_"
ser.write(msgr)
ser.close()
print("reset")
except (IOError) as e:
print("Error in: set_firmware_version")
print(e)
return s
time.sleep(1)
send_w(serial_port, baud_rate)
set_firmware_version(sp,br)
This gives the following error:
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
I also tried sending the messages in a loop with a short timeout, but had the same problem. Is there any way to send a message continuously and disregard exceptions if the device is not found?
Any help will be greatly appreciated.
Full Traceback:
Traceback (most recent call last):
File "mc_config.py", line 69, in <module>
set_firmware_version(sp,br)
File "mc_config.py", line 64, in set_firmware_version
send_w(serial_port, baud_rate)
File "mc_config.py", line 46, in send_w
ans = ser.read(24)
File "/home/avidbots/.local/lib/python2.7/site-packages/serial/serialposix.py", line 501, in read
'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
(I am using ubuntu 16.04 and python 3)
What if you put the excepting code into a try and then catch the exception with an except serial.serialutil.SerialException {...} block?
Clearly there's a significant window of time to submit the w ( otherwise the "press w" method wouldn't often work.) Your requirement, then, would be to retry only the part of the code that's absolutely necessary to send the w, so that you send it quickly enough to "catch" the system in its bootup state. Since the backtrace shows that the exceptions occurs in send_w, then you can add try/except blocks and a while loop around what is now one line at the end of set_firmware_version.
Instead of just this:
send_w(serial_port, baud_rate)
Something like this might solve the problem:
while True:
try:
send_w(serial_port, baud_rate)
break
except serial.serialutil.SerialException:
pass # retry
You may need to change your imports to expose that exception, fyi. And you may need to consider whether you're catching too many possible exceptions - it's possible that exception might also represent other errors that shouldn't be retried. You might also need to add a small sleep time there - this is essentially a busy wait loop (https://en.wikipedia.org/wiki/Busy_waiting).
I'm trying to run a function on the server with Pyro4.
Have a look at the code:
==========================Client======================
import Pyro4
def square(x):
return x**2
remoteServer = Pyro4.Proxy('PYRONAME:server')
print(remoteServer.evaluate(square, 4))
===========================Server==========================
import Pyro4
class Server(object):
def evaluate(self, func, args):
return func(*args)
def main():
server = Server()
Pyro4.Daemon.serveSimple({server: "server"},ns=True)
if __name__ == '__main__':
main()
========================Naming Server========================
import Pyro4
Pyro4.naming.startNSloop()
===========================================================
And got an error: "Pyro4.errors.ConnectionClosedError: receiving: not enough data". Look at the full stack trace below:
Traceback (most recent call last):
File "C:\Users\Alex\Desktop\2.py", line 9, in <module>
print(remoteServer.evaluate(square, 4))
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\core.py", line 169, in __call__
return self.__send(self.__name, args, kwargs)
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\core.py", line 380, in _pyroInvoke
msg = message.Message.recv(self._pyroConnection, [message.MSG_RESULT], hmac_key=self._pyroHmacKey)
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\message.py", line 161, in recv
msg = cls.from_header(connection.recv(cls.header_size))
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\socketutil.py", line 460, in recv
return receiveData(self.sock, size)
File "C:\Users\Alex\AppData\Roaming\Python\Python34\site-packages\Pyro4\socketutil.py", line 195, in receiveData
raise err
Pyro4.errors.ConnectionClosedError: receiving: not enough data
I want the server executes the function that is passed to a method (function).
PS: Windows7, Python 3.4.1
I've found similar question (How to send a function to a remote Pyro object), but didn't work for me.
Tried to use callback decorator #pyro4.callback, but even official example (https://github.com/delmic/Pyro4/tree/master/examples/callback : server2.py, client2.py) didn't work (with python 3.4 and python 2.7) => only message: "server: doing callback 1 to client" is showed and nothing happens.
Thanks
The github repo you're linking to is not the official one. It's a clone (from quite an old version). This is the official repo: https://github.com/irmen/Pyro4
As to your problem: it is not possible to serialize functions and send them over the wire. If you tell Pyro to use pickle as a serialization protocol, you can do more tricks, but pickle still needs to have the module source or bytecodes available on both sides of the connetion.
The reason your client crashes is because the server aborts the connection due to a Pyro protocol error. If you enable the logging it will show up in the server's logfile, something like: "Pyro4.errors.ProtocolError: unsupported serialized class: builtins.function".
Also a tip: you don't have to start the name server using a separate source code file. You can start it directly from the command line.
Lastly, the #pyro4.callback decorator is unrelated, please read http://pythonhosted.org/Pyro4/clientcode.html?highlight=callback#pyro-callbacks for what it is intended for. It influences the way Pyro handles exceptions, nothing more.
edit: note that since Pyro 4.35 this error will be correctly reported back to the client and it will no longer get an aborted connection.
I have a bluetooth serial port and am trying to connect to it. I do:
sudo rfcomm bind 13 00:0A:3A:26:4A:86
and that seems to succeed. I then try to access it:
>>> f=file('/dev/rfcomm13','rw')
>>> f.close()
>>> f=file('/dev/rfcomm13','rw')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 16] Device or resource busy: '/dev/rfcomm13'
This seems to be consistent -- it can be opened once, but ever afterwards it is "busy" until I unbind and rebind it. Doing this in python shows the error most clearly, but it seems to happen everywhere.
It seems that the close syscall isn't cleaning up some key resource. From a quick skim of the driver source, it's probably a dlci channel or something similar, but I'm pretty vague on what those are.
Is there any way to open the connection multiple times per bind?
Thanks