Trying to send data Python CAN - python-3.x

I am using the python can library. I am running the following example code but can not get it to work
from __future__ import print_function
import can
def send_one():
bus = can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)
msg = can.Message(arbitration_id=0xc0ffee,
data=[0, 25, 0, 1, 3, 1, 4, 1],
is_extended_id=True)
try:
bus.send(msg)
print("Message sent on {}".format(bus.channel_info))
except can.CanError:
print("Message NOT sent")
if __name__ == '__main__':
send_one()
Here is the error message:
OSError: [WinError 10047] An address incompatible with the requested protocol was used
I'm not sure where I am going wrong. I am completely new to using CAN to receive and send data. My current set up for testing this out is as follow:
Laptop -> USB Wire -> CANable Adapter -> CAN Line -> CANable Adapter -> USB Wire -> RaspberryPi
I also can't seem to find any documentation that has clear and concise examples. Thank you to all of those who reply in advance.
Link To Docs: https://buildmedia.readthedocs.org/media/pdf/python-can/develop/python-can.pdf

In your code, you are trying to use the socketcan interface, which is not available on Windows.
Your CANable adapter provides a serial interface. Try the following line:
bus = can.interface.Bus(bustype='serial', channel='COM1', bitrate=250000)
Maybe you have to use a different COM-port-number instead of COM1
Check the python-can documentation chapter CAN over serial for more details.

Related

Building a webserver on ESP32 using MicroPython

Before reading my question, my english skill is poor, so please send me feedback or advise in easy words. Thank you.
What I Want To Do
I want to build a webserver on ESP32-WROOM-32(ESP32-DevKitc_V4) with MicroPython(v1.16 on 2021-06-23: latest firmware available). My Goal is building a webserver inside ESP32 and collecting the data of sensors connected to ESP32 periodically.
Environment
Windows10(64bit)
MicroPython (v1.16 on 2021-06-23)
Editor : Thonny Editor (v3.3.11)
ESP32 Devkitc_v4
ampy (v1.1.0)
What I did
Firstly I wrote a code according to this article : RandomNerdTutorial: ESP32/ESP8266 MicroPython Web Server – Control Outputs. My code is as follows:
import network
import usys
try:
import usocket as socket
except:
import socket
def connect(SSID,PASS):
AP = network.WLAN(network.AP_IF)
if AP.isconnected():
print("Already connected.")
return AP
else:
AP.active(True)
AP.connect(SSID,PASS)
while not AP.isconnected():
print(".",end="")
utime.sleep(0.5)
if AP.isconnected():
print("Network connection is established.")
return AP
else:
print("Connection failed.")
return False
wifi = connect("myssid","mypass")
if not wifi:
usys.exit(0)
html_strings = """
<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='utf-8'>
<title>SERVER TEST</title>
</head>
<body>
<h1>SERVER TEST</h1>
</body>
</html>
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = socket.getaddrinfo(("0,0,0,0",80))[0][-1]
s.bind(addr)
s.listen(1)
print("Linstening on ", addr)
while True:
conn,addr = s.accept()
print("connected from : ",addr)
request = conn.recv(1024)
respose = html_strings
conn.send("HTTP/1.0 200 OK\r\n")
conn.send("Content-type: text/html\r\n")
conn.send("\r\n")
conn.send(response)
conn.close()
I connect ESP32 board with USB cable to PC and Windows10 recognize this device as COM4. I wrote this code on Thonny Editor on windows10(64bit) and then transfer this code as main.py using ampy command on command line like this:
> ampy --port COM4 put main.pye
Tansfer was always successful and then connecting ESP32 from Thonny editor. firstly this message is shown in the shell console like this:
MicroPython v1.16 on 2021-06-23; ESP32 module with ESP32
Type "help()" for more information.
And then when I press reset button on ESP32, Error was shown like this:
Traceback(most recent call last)
File "main.py", line 48, in <module>
TypeError: function mising 1 required positional arguments
The line 48 corresponds this line:
addr = socket.getaddrinfo(("0,0,0,0",80))
According to the official documentation Docs » MicroPython libraries » usocket – socket module,it seems that prividing only two parameters: hostname nad port is enough. I also tried by writing like this:
addr = socket.getaddrinfo(('',80))[#][-1]
But the result was same. I do not understand what is the required another positional argument. So I want advice or feedback to solve this issue.
Thank you for your cooperation.
The getaddrinfo method expects two arguments:
socket.getaddrinfo('hostname', port)
You are passing a single argument -- a 2-tuple. Instead of:
addr = socket.getaddrinfo(("0.0.0.0", 80))
You want:
addr = socket.getaddrinfo("0.0.0.0",80)
Note that I've removed one set of parentheses.
Here's a complete example at the REPL:
>>> import socket
>>> s = socket.socket()
>>> addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
>>> s.bind(addr)
>>> s.listen(1)
>>> conn,addr = s.accept()
>>> addr
('192.168.1.175', 43384)
>>> conn.send('HTTP/1.0 200 OK\r\n')
17
>>> conn.close()

I'm trying to read sensor data through serial communication but when I try to read it just kept on runnin in python but it doesn't display any value

I have light detector sensors connected to a data acquisition box and it is connected to my laptop via RS232 usb cable. I have stabilized serial communication to that port in python. But when I try to read the data it just keeps on running and it doesn't display any value. I have tried this same think in MATALB and it works properly, so I know that port and sensors are working fine. I am just not able to read the data in python. I have three ways(shown below in python code) but nothing works. Please help me.
Here is my python code:
import serial
from serial import Serial
s = serial.Serial('COM3') # open serial port
print(ser.name)
# Set the serial port to desired COM
s = serial.Serial(port = 'COM3', bytesize = serial.EIGHTBITS, parity = serial.PARITY_NONE, baudrate = 9600, stopbits = serial.STOPBITS_ONE)
# Read the data(method 1)
while 1:
while (s.inWaiting() > 0):
try:
inc = s.readline().strip()
print(inc)
# Read the data(method 2)
data = str(s.read(size = 1))
print(data)
# Read all the data(method 3)
while i <10:
b = s.readlines(100) # reading all the lines
in matlab it gave values with a space but in same line
That indicates there are no newline characters sent by the device.
I've never used your device or the Python serial module. But from the docs, this is what I would do:
from time import sleep
while s.is_open():
n = s.in_waiting()
if n == 0:
print "no data"
sleep(1)
continue
try:
inc = s.read(n)
print(inc)
catch serial.SerialException as oops:
print(oops)
catch serial.SerialTimeoutException as oops:
print(oops)
print("serial port closed")
This gives you feedback for each condition: port open/closed, data ready/not, and the data, if any. From there you can figure out what to do.
The documentation says inWaiting is deprecated, so I used in_waiting.
I wouldn't be surprised if the problem lies in configuring the serial port in the first place. Serial ports are tricky like that.

Python scapy Beacon Frames

I'm trying to build a scapy program that scans for Beacon Frames. Every router should send beacon frames to the air in an interval of X milliseconds so the possible hosts know the router(AP) is alive.
I'm getting nothing, the only kind of Dot11 frames I've been able to get so far is Prob Request, very rarely some data or control frames as well. I setup my wireless card to monitor mode before running the script and it supports it as well. I don't what I might be doing wrong... Here's the code :
from scapy.all import *
global list_prob
list_prob = []
def search_prob(packet1):
if (packet1.haslayer(Dot11)) and (packet1[Dot11].type == 0) and\
(packet1[Dot11].subtype == 8) : #type 4 == ProbRequest
if packet1[Dot11].addr2 not in list_prob:
if packet1[Dot11].info not in list_prob:
print('[>]AP',packet1[Dot11].addr2,'SSID',packet1[Dot11].info)
list_prob.append(packet1[Dot11].addr2)
list_prob.append(packet1[Dot11].info)
sniff(iface='wlan0mon',prn=search_prob)
Ive also tried it with Dot11Beacon instead of subtype 8 and nothing changed . I'm programming with python3.5 on Linux.
Any ideas ?
Code to constantly change channel of network interface using python :
from threading import Thread
import subprocess,shlex,time
import threading
locky = threading.Lock()
def Change_Freq_channel(channel_c):
print('Channel:',str(channel_c))
command = 'iwconfig wlan1mon channel '+str(channel_c)
command = shlex.split(command)
subprocess.Popen(command,shell=False) # To prevent shell injection attacks !
while True:
for channel_c in range(1,15):
t = Thread(target=Change_Freq_channel,args=(channel_c,))
t.daemon = True
locky.acquire()
t.start()
time.sleep(0.1)
locky.release()

Creating an access point with wpa_supplicant via dbus interface

I was told that it's possible to create an access point with wpa_supplicant over its dbus interface. All I found with a google is this forum thread, which, despite having exact same title, isn't much informative to me.
Is it possible to do this via wpa_supplicant dbus interface and what exact steps does it take to create one with custom parameters (like frequency, etc.)?
After all, I've found a way to launch access point with wpa_supplicant's dbus inteface. Below is pretty self explanatory python code that's is trying to launch AP with the first interface (adapter) it have found.
import dbus
import sys
ssid = "TEST_WPA_DBUS_HOTSPOT"
frequency = 2412
bus = dbus.SystemBus()
wpa_sup_obj = bus.get_object('fi.w1.wpa_supplicant1', '/fi/w1/wpa_supplicant1')
props_iface = dbus.Interface(wpa_sup_obj, "org.freedesktop.DBus.Properties")
interfaces = props_iface.Get('fi.w1.wpa_supplicant1', "Interfaces")
try:
interface = interfaces[0]
except IndexError:
sys.exit("No interfaces availible")
print "Creating ap with %s" % (interface)
interface_obj = bus.get_object('fi.w1.wpa_supplicant1', interface)
interface_interface_props = dbus.Interface(interface_obj, "org.freedesktop.DBus.Properties")
interface_interface = dbus.Interface(interface_obj, "fi.w1.wpa_supplicant1.Interface")
adapters_name = interface_interface_props.Get("fi.w1.wpa_supplicant1.Interface", "Ifname")
print "Interface's name is %s" % adapters_name
key_mgmt = "NONE"
args = dbus.Dictionary({
'ssid': ssid,
'key_mgmt': key_mgmt,
'mode': 2,
'frequency': frequency
}, signature='sv')
netw = interface_interface.AddNetwork(args)
interface_interface.SelectNetwork(netw)
print "AP %s with frequency %i created with adapter %s" % ( ssid, frequency, adapters_name)
Note, that, after all, I've found wpa_supplicant not quite reliable for my needs (in my particular case, I wasn't able to launch 5GHz AP) and have switched to launching hostapd with different configuration files.

How do I get a list of my device's audio sample rates using PyAudio or PortAudio?

I'd like to query my audio device and get all its available sample rates. I'm using PyAudio 0.2, which runs on top of PortAudio v19, on an Ubuntu machine with Python 2.6.
In the pyaudio distribution, test/system_info.py shows how to determine supported sample rates for devices. See the section that starts at line 49.
In short, you use the PyAudio.is_format_supported method, e.g.
devinfo = p.get_device_info_by_index(1) # Or whatever device you care about.
if p.is_format_supported(44100.0, # Sample rate
input_device=devinfo['index'],
input_channels=devinfo['maxInputChannels'],
input_format=pyaudio.paInt16):
print 'Yay!'
With the sounddevice module, you can do it like that:
import sounddevice as sd
samplerates = 32000, 44100, 48000, 96000, 128000
device = 0
supported_samplerates = []
for fs in samplerates:
try:
sd.check_output_settings(device=device, samplerate=fs)
except Exception as e:
print(fs, e)
else:
supported_samplerates.append(fs)
print(supported_samplerates)
When I tried this, I got:
32000 Invalid sample rate
128000 Invalid sample rate
[44100, 48000, 96000]
You can also check if a certain number of channels or a certain data type is supported.
For more details, check the documentation: check_output_settings().
You can of course also check if a device is a supported input device with check_input_settings().
If you don't know the device ID, have a look at query_devices().
I don't think that's still relevant, but this also works with Python 2.6, you just have to remove the parentheses from the print statements and replace except Exception as e: with except Exception, e:.
Directly using Portaudio you can run the command below:
for (int i = 0, end = Pa_GetDeviceCount(); i != end; ++i) {
PaDeviceInfo const* info = Pa_GetDeviceInfo(i);
if (!info) continue;
printf("%d: %s\n", i, info->name);
}
Thanks to another thread

Resources