How to send the contents of a variable to Micropython repl - python

I am trying to create a file in an ESP32 named "PassWord" containing a password, using Micropython Serial. The code below works with a "hardwired" password, but I would like to be able to send the contents of a variable that was typed in by the user. The sending script is running in Win10 using Python 3.7.9
import serial
import time
def Send(s):
ser.write((s +'\r\n').encode())
time.sleep(.3)
z = ser.read(ser.in_waiting)
portx = "COM6"
bps = 115200
timex = 5
ser = serial.Serial(portx,bps,timeout=timex)
Send("f = open('Password,'w')")
Send("f.write('MyPassWord\\n')")
Send("f.close()")

You could do something like this. Just made this as an exaggerated example so you can learn. You could put this whole thing into the send function input if you wanted.
import serial
import time
MyPassWord = "This is the password"
def Send(s):
ser.write((s +'\r\n').encode())
time.sleep(.3)
z = ser.read(ser.in_waiting)
portx = "COM6"
bps = 115200
timex = 5
ser = serial.Serial(portx,bps,timeout=timex)
StringToSend = """f.write('""" + MyPassWord+ """\\n')"""
Send("f = open('Password,'w')")
Send(StringToSend)
Send("f.close()")

Related

Python - Class from Serial

how do I create a class that Inheritates from serial using the python serial module?
I need to create a module so another user can import to his code and create an object by just passing the COM.
This is my module, called py232
from serial import Serial
class serialPort(Serial):
def __init__(self, COM):
serial.__init__(self)
self.COMPort = COM
self.baudrate = 9600
self.bytesize = 8
self.stopbits = serial.STOPBITS_ONE
self.parity = serial.PARITY_NONE
self.timeout = 2
#serialPort = serial.Serial(port=self.COMPort, baudrate= self.baudrate, stopbits= self.stopbits, parity= self.parity, timeout= self.timeout)
self.createSerial()
def createSerial(self):
sPort = serial.Serial(port = self.COMPort, baudrate=self.baudrate, bytesize=self.bytesize, timeout= self.timeout, stopbits = self.stopbits, parity=self.parity)
return sPort
I am trying to use it in another script:
import py232
s = py232.serialPort('COM6')
s.sndSerial('test')
Why don't you just create an instance of serial in a function. No need to create a sub-class.
from serial import Serial
def create_serial(port):
s = Serial(
port,
baudrate=9600,
bytesize=8,
timeout=2,
# etc
)
return s
It can then be used in another script.
import py232
s = py232.create_serial('COM6')

Pyserial package doesnot read all the data from the COM port ( reads only 6000 to 6150 bytes always)

I wrote a small pyserial interface to read the data from the COM port after issuing a command. For eg : in my case my system has a lot of network interface so i need to validate whether all the interfaces are up using ifconfig command. But when i gave this command , the output of the command is getting truncated at the last few lines. The approximate size of the output in bytes would be 6500-7000 bytes but i am receiving only around 6000-6150 bytes all the time. Please find my code below
'''
import serial
import time
com_serial = serial.Serial("COM6", 115200, timeout = 10)
com_serial.reset_input_buffer()
com_serial.write(b"ifconfig\n")
data_all = b" "
time.sleep(5)
while True:
bytetoread = com_serial.inWaiting()
time.sleep(2)
print ("Bytetoread: " , bytetoread)
data = com_serial.read(bytetoread)
data_all += data
if bytetoread < 1:
break
print ("Data:", data_all)
com_serial.close()
'''
**Output:
Bytetoread: 3967
Bytetoread: 179
Bytetoread: 2049
Bytetoread: 0
**
Data: *********with missing data at the end.
I am not sure why the logs are missing?
I have tried another approach.
'''
import serial
import time
com_serial = serial.Serial("COM6", 115200, timeout = 10)
com_serial.reset_input_buffer()
com_serial.write(b"ifconfig\n")
time.sleep(5)
data_all = b" "
data_all = com_serial.read(100000000)
print (data_all)
com_serial.close()
'''
Here also the last few logs are getting truncated.
The root cause seems to be inadequate buffer size of the Tx and Rx serial buffer. By increasing the buffer size using .set_buffer_size() resolved the issue.
'''
import serial
import time
com_serial = serial.Serial("COM6", 115200, timeout = 10)
com_serial.set_buffer_size(rx_size = 12800, tx_size = 12800)
com_serial.reset_input_buffer()
com_serial.write(b"ifconfig\n")
data_all = b" "
data_all = com_serial.read(100000000)
print (data_all)
com_serial.close()
'''

How to see the error frames of a CAN network with Python-CAN

I wrote the program below,
can = CAN("can0", bitrate=50000, listen_only=True, error_reporting=True)
while True:
msg = can.recv()
print "Msg: ", msg
But it only displays the standard S or Extended X flags even though when I run the command in Terminal to check the network activity, I can see that the error counter is increasing.
import can
import CAN
import time
import logging
#logging.basicConfig(level=logging.DEBUG)
print("Initializing Listener")
can1 = CAN('can0', bitrate=500000, listen_only=True, err_reporting=True)
#print "Bus is : ", can1.bus.get_can_bus()
can1.bus.set_filters(can_filters=[{"can_mask":0x7FF, "can_id":0x00000000, "extended":False}])
CAN_ERR_FLAG = 0x20000000
while 1:
msg = can1.recv()
if (msg.arbitration_id & CAN_ERR_FLAG) == CAN_ERR_FLAG:
print "Can Error Caught"
elif msg.is_error_frame:
print "Finally Error Frame"
How can I read the error-frames of the CAN-bus ?
Things work fine when I use commnad candump -e any,0:0,#FFFFFFFF
Use Python - 3
import binascii
channel_name = "vcan0"
socketID = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
# socketID.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_ERR_FILTER, 0x1FFFFFFF)
error = socketID.bind((channel_name,))
print(binascii.hexlify(socketID.recv(32)))

SAS IOM Bridge with Python

I'm making a connection to a remote SAS Workspace Server using IOM Bridge:
import win32com.client
objFactory = win32com.client.Dispatch("SASObjectManager.ObjectFactoryMulti2")
objServerDef = win32com.client.Dispatch("SASObjectManager.ServerDef")
objServerDef.MachineDNSName = "servername"
objServerDef.Port = 8591 # workspace server port
objServerDef.Protocol = 2 # 2 = IOM protocol
objServerDef.BridgeSecurityPackage = "Username/Password"
objServerDef.ClassIdentifier = "workspace server id"
objSAS = objFactory.CreateObjectByServer("SASApp", True, objServerDef, "uid", "pw")
program = "ods listing;proc means data=sashelp.cars mean mode min max; run;"
objSAS.LanguageService.Submit(program)
_list = objSAS.LanguageService.FlushList(999999)
print(_list)
log = objSAS.LanguageService.FlushLog(999999)
print(log)
objSAS.Close()
It work fine. But I cant seem to find the right attribut for CreateObjectByServer, when trying with a Stored Process Server (when I change 'Port' and 'ClassIdentifier'):
import win32com.client
objFactory = win32com.client.Dispatch("SASObjectManager.ObjectFactoryMulti2")
objServerDef = win32com.client.Dispatch("SASObjectManager.ServerDef")
objServerDef.MachineDNSName = "servername"
objServerDef.Port = 8601 # stored process server port
objServerDef.Protocol = 2 # 2 = IOM protocol
objServerDef.BridgeSecurityPackage = "Username/Password"
objServerDef.ClassIdentifier = "stp server id"
objSAS = objFactory.CreateObjectByServer("SASApp", True, objServerDef, "uid", "pw")
objSAS.StoredProcessService.Repository("path", "stp", "params")
_list = objSAS.LanguageService.FlushList(999999)
print(_list)
log = objSAS.LanguageService.FlushLog(999999)
print(log)
objSAS.Close()
When trying the above I get:
AttributeError: CreateObjectByServer.StoredProcessService
I cant seem to find much documentation IOM to Stored Process Servers. Anyone got any suggestions?

How to receive multiple ATCommand response packets from the local xbee for the "FN" (finding neighbour) AT command using python digi-xbee library

This is the code which works well for all AT commands except "FN":
from digi.xbee.devices import XBeeDevice
#Initialise a serial port for the local xbee
local_xbee = XBeeDevice("/dev/tty.usbserial-AH02D9Q4", 9600).
#Opens serial port for sending commands
local_xbee.open()
#Sets new timeout for sync command operation
local.set_sync_ops_timeout(10).
#Send "FN" AT command to local xbee to receive neighbour list
neighbour_xbee_list = local.get_parameter("FN")
print(neighbour_xbee_list)
local_xbee.close()
Note:
The above code returns only one neighbour whereas I have more than one nodes in the network.
I believe the point of the question is not how to use the FN command, but how to discover neighbors.
For this, you can use the start_discovery_process function described here.
http://xbplib.readthedocs.io/en/latest/user_doc/discovering_the_xbee_network.html#discovernetwork
import serial
from digi.xbee.packets.common import ATCommPacket
from digi.xbee.devices import XBeeDevice
from digi.xbee.reader import PacketListener
from digi.xbee.serial import XBeeSerialPort
from digi.xbee.util import utils
import time
local_xbee = XBeeDevice("/dev/tty.usbserial-AH02D9Q4", 9600)
local_xbee.open()
print("This is : ", local_xbee.get_node_id())
print(local_xbee._packet_listener.is_running())
parameter = "FN"
frame_id = 33
my_packet = ATCommPacket(frame_id, parameter)
#print(my_packet)
#print(my_packet.frame_id)
#print(my_packet.command)
final_send = my_packet.output()
local_xbee._serial_port.write(final_send)
print("Finding Neighbours")
while True:
print(".")
Queue = local_xbee._packet_listener.get_queue()
received_packet = Queue.get_by_id(frame_id)
if received_packet != None:
#if received_packet.status == ATCommandStatus.OK:
final = received_packet._get_api_packet_spec_data().__str__()
print(final)
time.sleep(0.5)
local_xbee.close()

Categories