I am new at programming and am trying to communicate with my vehicle with an OBD II device. Serial to USB. I've done what I want it to do but I get the command I entered to print out. How do I just get the information from the device?
Heres my code. I am using Python 3.2.3
import serial
import time
import string
import io
import os
import sys
ser = serial.Serial("/dev/ttyUSB1")
ser.baudrate = 38400
s = input('Enter AT command --> ')
print ('AT command = ' + s)
ser.write(bytes(s + '\r\n', encoding = 'utf-8'))
ser.timeout = 1
response = ser.read(999).decode('utf-8')
print(response)
ser.close()
And here is what prints out when I enter the command 'atrv'.
>>>
Enter AT command --> atrv
AT command = atrv
atrv
0.1V
>>>
How do I prevent the 'atrv' above the 0.1V from printing out?
Send ATE0 to the ELM-device.
This disables the echo, so atrv won't be send back to you!
Have a look into this: http://elmelectronics.com/DSheets/ELM327DS.pdf , collection of lots of AT commands, could be helpful!
on a raspberry PI i had to modify the code to:
import serial
import time
import string
import io
import os
import sys
ser = serial.Serial("/dev/rfcomm0")
ser.baudrate = 115200
s = input('Enter AT command --> ')
print ('AT command = ' + s)
ser.flushInput();
ser.write(bytes(s + '\r\n', encoding = 'utf-8'))
ser.flush();
ser.timeout = 1
response = ser.read(999).decode('utf-8')
print(response)
ser.close()
Related
I'm trying to create a very simple PCAP file (1 UDP message).
Tried using dpkt (pcap.Writer), no luck, and the documentation is scarce.
Can anyone post a working example?
(or any other alternative - I'm not bound to dpkt)
You may use Scapy.
https://scapy.readthedocs.io/en/latest/installation.html
If using Python 3:
pip3 install scapy
Then in Python:
from scapy.all import wrpcap, Ether, IP, UDP
packet = Ether() / IP(dst="1.2.3.4") / UDP(dport=123)
wrpcap('foo.pcap', [packet])
you need to write the packet into a libpcap format
Global Header + Packet Header + Packet Data + Packet Header + Packet Data
this link should help you
http://www.codeproject.com/Tips/612847/Generate-a-quick-and-easy-custom-pcap-file-using-P
construct's cap (broken link) shows how to use construct for this. Construct also has a rudimentary ip stack (broken link) example. The nice thing about Construct is that it is symmetrical, i.e. you can put data into it, convert it to a set of Python objects and you can then dump out the objects to create the original data blob again.
You can try the code below :
#!/usr/bin/env python3
import sys
import struct
import os
import argparse
from scapy.all import sniff, sendp, hexdump, linehexdump, get_if_list, get_if_hwaddr
from scapy.all import Packet, IPOption
from scapy.all import ShortField, IntField, LongField, BitField, FieldListField, FieldLenField
from scapy.all import IP, TCP, UDP, Raw
from scapy.layers.inet import _IPOption_HDR
from scapy.all import raw
from scapy.all import bytes_hex
import hashlib
import pcapng.blocks as blocks
from pcapng import FileWriter
counter = 1
def get_if():
ifs=get_if_list()
iface=None
for i in get_if_list():
if "enp1s0f1" in i:
iface=i
break;
if not iface:
print("Cannot find eth0 interface")
exit(1)
return iface
def main():
global counter
ifaces = [i for i in os.listdir('/sys/class/net/') ]
iface = get_if()
print(("sniffing on %s" % iface))
sys.stdout.flush()
writer = FileWriter(args.outfile, shb)
orig_packets = sniff(filter='tcp and port 5201',iface = iface)
for packet in orig_packets:
spb = shb.new_member(blocks.SimplePacket)
spb.packet_data = bytes(packet)
writer.write_block(spb)
print("C=",counter)
counter=counter+1
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("outfile", type=argparse.FileType("wb"))
args = parser.parse_args()
shb = blocks.SectionHeader(
options={
"shb_hardware": "artificial",
"shb_os": "python",
"shb_userappl": "python-pcapng",
})
idb = shb.new_member(
blocks.InterfaceDescription,
link_type=1,
options={
"if_description": "Hand-rolled",
"if_os": "Python",
"if_filter": [(0, b"tcp port 5201 and host 192.168.1.3")],
},)
main()
I am trying to make a data-logger than writes the output from a serial device that only outputs once per minute. I need it to have a time stamp on the output. The code I have so far will log the output but it keeps logging blanks with a timestamp in-between the device's output. How do I get it to only write a line with the timestamp when the device has output?
#!/usr/bin/env python
Log data from serial port
import argparse
import serial
import datetime
import time
import os
timestr = time.strftime("%Y%m%d")
Tstamp = time.strftime("%Y/%m/%d %H:%M ")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
outputFile.write(Tstamp + " " + data + '\n')
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")
Sorry for the poor formatting I am not sure how to make it look right on here.
By adding if x!= "" and indenting properly I got it to work. Now I just need ot fix it to append the file and not overwrite it.
#!/usr/bin/env python
# Log data from serial port
import argparse
import serial
import datetime
import time
import os
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
if data !="":
outputFile.write(time.strftime("%Y/%m/%d %H:%M ") + " " + data )
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")
'''
Please help me out at this stage.i want to do this program with win32com & pyttsx 3. tried both but not working . Below is my code please check and help.
I want program to answer me back as as per defined answers.
Program is working fine and replying as a text but i am not getting any response by voice..
'''
# audio.py File
import pyaudio
import speech_recognition as sr
import pyglet
from commands import Commander
import subprocess
import win32com.client as wincl
import wave
import pyttsx3
running = True #ss
def say(text):
speak = wincl("SAPI.SpVoice")
speak.Speak('say ' + text, shell=True)
def play_audio(filename):
chunk = 1024
wf = wave.open(filename, 'rb')
pa = pyaudio.PyAudio()
stream = pa.open(
format=pa.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True
)
data_stream = wf.readframes(chunk)
while data_stream:
stream.write(data_stream)
data_stream = wf.readframes(chunk)
stream.close()
pa.terminate()
play_audio("./audio/after.wav")
# Upper part is to play sound using pyaudio
r = sr.Recognizer()
cmd = Commander() #
def initSpeech():
print("Listening.....")
play_audio("./audio/before.wav")
with sr.Microphone() as source:
print("Say Something")
audio = r.listen(source)
play_audio("./audio/before.wav")
command = ""
try:
command = r.recognize_google(audio)
except:
print("Couldn't understand you bro. ")
print("Your Command: ")
print(command)
if command == "quit":
running = False #
#echo('You Said: ' + command)
cmd.discover(command) #
#speak.Speak('You Said: ' + command) -------> no comment
while running == True:
initSpeech()
-----------------------------------------------------------------------------------------------------
# commands.py File
import subprocess
import os
class Commander:
def __init__(self):
self.confirm = ["yes", "affirmative", "si", "sure", "do it", "yeah", "confirm"]
self.cancel = ["no", "negative", "negative soldier", "don't", "wait", "cancel"]
def discover(self, text):
if "what" in text and "your name" in text:
if "my" in text:
self.respond("You haven't told your name yet")
self.respond("My name is python commander. How are you")
def respond(self, response):
print(response)
speak.Speak('say ' + response, shell=True) # This Speak is
from pywin32
import RPi.GPIO as GPIO
import urllib.request
import urllib.response
import urllib.error
GPIO.setmode (GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(40,GPIO.OUT)
true = 1
while(true):
try:
response = urllib.request.urlopen('xxxxxxxxxx')
status = response.read()
except urllib.error.HTTPError as e:
print (e.code)
except urllib.error.HTTPError as e:
print (e.args)
print (status)
if status=='ON':
print ("setting GPIO 40 ")
GPIO.output(40,True)
elif status=='OFF':
GPIO.output(40,False)
Error im getting is status is not defined. If i define status as a empty string, the output is not displaying. I am trying to control my Rpi GPIO using a website. I used this link as guidance https://medium.com/#softxide/remote-control-raspberrypi-leds-from-web-browser-ui-84205993b98f.
Thank u in advanced.
While learning through the network automation with python, I have created a script to capture the few network switch details with some sorts of commands. i have explicitely kept the commands in commands.txt and login credentilas in a file devices.json in a Jason format to pick it from and when i run this it works as expected by creating a file with command out details with time stamp.
What i Want: As i have commands.txt file which has diffrent commands, where i would like to have an idea of creating a separate file for each command which i have into commands.txt. as of now everything getting captured to a single file, desired example ..
prod-stvdx-sw_vcs_details.txt-Apr-10-2018:12:53
prod-stvdx-sw_vcs.txt-Apr-10-2018:12:53
prod-stvdx-sw_fabric_trunk.txt-Apr-10-2018:12:53
Below is the script version:
from __future__ import absolute_import, division, print_function
import json
import netmiko
import signal
import sys
import time
timestamp = time.strftime('%b-%d-%Y:%H:%M')
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # IOError: Broken pipe
signal.signal(signal.SIGINT, signal.SIG_DFL) # KeyboardInterrupt: Ctrl-C
if len(sys.argv) < 3:
print('Usage: cmdrunner.py commands.txt devices.json')
exit()
netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
netmiko.ssh_exception.NetMikoAuthenticationException)
#username, password = getPass.get_credentials()
with open(sys.argv[1]) as cmd_file:
commands = cmd_file.readlines()
with open(sys.argv[2]) as dev_file:
devices = json.load(dev_file)
for device in devices:
#device['username'] = username
#device['password'] = password
try:
print('~' * 79)
print('Connecting to device:', device['ip'])
connection = netmiko.ConnectHandler(**device)
filename = connection.base_prompt + '.txt' + '-' + timestamp
with open(filename, 'w') as out_file:
for command in commands:
out_file.write('++++ Output of ' + command + '\n\n')
out_file.write(connection.send_command(command) + '\n\n')
connection.disconnect()
except netmiko_exceptions as e:
print('Failed to ', device['ip'], e)
My commands.txt File:
$ cat commands.txt
show vcs details
show vcs
show fabric islports
show fabric isl
show fabric trunk
show logging raslog
show version
show ip int brief
Run
$ ./brocade_2.py commands.txt devices.json
-rw-r--r-- 1 moli moli 286K Apr 10 12:53 prod-stvdx-sw.txt-Apr-10-2018:12:53
I think if I understand correctly, you want to capture the output of each command in a separate file:
from __future__ import absolute_import, division, print_function
import json
import netmiko
import signal
import sys
import time
timestamp = time.strftime('%b-%d-%Y:%H:%M')
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # IOError: Broken pipe
signal.signal(signal.SIGINT, signal.SIG_DFL) # KeyboardInterrupt: Ctrl-C
if len(sys.argv) < 3:
print('Usage: cmdrunner.py commands.txt devices.json')
exit()
netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
netmiko.ssh_exception.NetMikoAuthenticationException)
#username, password = getPass.get_credentials()
with open(sys.argv[1]) as cmd_file:
commands = cmd_file.readlines()
with open(sys.argv[2]) as dev_file:
devices = json.load(dev_file)
for device in devices:
#device['username'] = username
#device['password'] = password
try:
print('~' * 79)
print('Connecting to device:', device['ip'])
connection = netmiko.ConnectHandler(**device)
for command in commands:
filename = connection.base_prompt +'-'+ command+'.txt' + '-' + timestamp
with open(filename, 'w') as out_file:
out_file.write('++++ Output of ' + command + '\n\n')
out_file.write(connection.send_command(command) + '\n\n')
connection.disconnect()
except netmiko_exceptions as e:
print('Failed to ', device['ip'], e)