Example #1
0
def serOpen():
    """
     @return ser type Serial
    """

    SERIAL_PORT = 'COM7'
    SERIAL_SPEED = 9600

    ser = Serial()
    ser.port = SERIAL_PORT
    ser.baudrate = SERIAL_SPEED
    ser.bytesize = EIGHTBITS  #number of bits per bytes
    ser.timeout = 1  #non-block read
    ser.writeTimeout = 2  #timeout for write
    ser.xonxoff = False  #disable software flow control
    ser.rtscts = False  #disable hardware (RTS/CTS) flow control
    ser.dsrdtr = False  #disable hardware (DSR/DTR) flow control

    try:
        """
             Пытаемся открыть серийный порт
          """
        ser.open()

    except SerialException as e:

        logger.debug("error open serial port: " + str(e))

        exit(2)

    return ser
Example #2
0
 def __init__(self, port, baudrate, protocol):
     com = Serial()
     com.port = port
     com.baudrate = baudrate
     com.bytesize = 8
     com.parity = 'N'
     com.open()
     super(SerialReaderThread, self).__init__(com, protocol)
Example #3
0
 def __init__(self, ser: serial.Serial):
     ser.baudrate = 115200
     ser.bytesize = serial.EIGHTBITS
     ser.parity = serial.PARITY_NONE
     ser.stopbits = serial.STOPBITS_ONE
     ser.xonxoff = 0
     ser.rtscts = 0
     ser.timeout = 60
     ser.port = "/dev/ttyUSB0"
     self._serial = ser
Example #4
0
def get_port(p_name='com2', p_baud=115200, p_bysz=8, p_stpb=1, p_prt='N'):
    # 设置串口
    t = Serial(p_name)
    t.baudrate = p_baud
    t.bytesize = p_bysz
    t.stopbits = p_stpb
    t.parity = p_prt
    # t.timeout = tmot
    t.close()
    return t
Example #5
0
def DOpenPort(portx, bps):
    ret = False
    try:
        # 打开串口,并得到串口对象
        ser = Serial(portx, bps, timeout=0.5)
        ser.bytesize = 8  # 可有可无
        ser.parity = 'N'  # 可有可无
        ser.stopbits = 1  # 可有可无
        # 判断是否打开成功
        if (ser.is_open):
            ret = True
    except Exception as e:
        print(e)
    return ser, ret
Example #6
0
def get_port(p_name='com1',
             p_baud=9600,
             p_bysz=8,
             p_stpb=1,
             p_prt='N',
             tmot=1):
    # 设置串口
    t = Serial(p_name)
    t.baudrate = p_baud
    t.bytesize = p_bysz
    t.stopbits = p_stpb
    t.parity = p_prt
    t.timeout = tmot
    return t
Example #7
0
    def __init__(self, com='Com4'):
        ser = Serial(com, 9600, timeout=0.5)
        ser.bytesize = serial.EIGHTBITS  # Number of data bits
        ser.parity = serial.PARITY_NONE  # Enable parity checking
        ser.stopbits = serial.STOPBITS_ONE  # Number of stop bits
        try:
            ser.close()
            ser.open()
            print('open serial port')
            self.ser = ser
        except:
            raise NotImplementedError('open serial port failed')

        self.is_on = False
        self.max_current = 3.5
        self.max_vol = 3
        self.set_current_limit(self.max_current)
        self.set_voltage_limit(self.max_vol)
        self.set_up(3.2, 3)
        self.off()
Example #8
0
 
 
while True:
    button, value = window.ReadNonBlocking()
    window.FindElement('message').Update(text)
    if button==None and value==None:
        print('结束程序')
        isRun=False
        break
 
    if button=='连接串口':
        ser = Serial()
        ser.baudrate = int(value[1])  #波特率
        ser.port = value[0]    #com口
        ser.stopbits=int(value[2])     #停止位 1 1.5 2
        ser.bytesize=int(value[3])       #数据位
 
        if value[5]=='无':     #奇偶位  N没有  E偶数  O奇数
            ser.parity='N'
        elif value[5]=='奇校验':
            ser.parity = 'O'
        elif value[5] == '偶校验':
            ser.parity = 'E'
 
        ser.timeout=5       #超时时间
        try:
            ser.open()
            sg.Popup('连接成功')
            t = Thread(target=readData, name='read_data')
            t.start()   #开始线程
        except Exception as e:
Example #9
0
def main():
    # DEBUG port ('/dev/ttyUSB3', 'COM6', etc.), typically the last one.
    port = sys.argv[1]

    # Recovery directory (recovery protocol version 2).
    recovery_dir = sys.argv[2]

    # Device capabilities file (with matching device id).
    device_caps = sys.argv[3]

    recovery_1bl      = os.path.join(recovery_dir, "recovery-1bl-rtm.bin")
    recovery_runtime  = os.path.join(recovery_dir, "recovery-runtime.bin")
    recovery_manifest = os.path.join(recovery_dir, "recovery.imagemanifest")

    # XXX: These sizes are hardcoded in the 'ServerMessageType.ImageRequestAck'
    # messages below.
    assert_file_size(device_caps, 0x188)
    assert_file_size(recovery_runtime, 0xeda4)
    assert_file_size(recovery_manifest, 0x5d8)

    timeout = 2

    serial = Serial(
        port=port,
        baudrate=115200,
        parity=PARITY_NONE,
        bytesize=8,
        stopbits=1,
        rtscts=0,
        timeout=timeout)

    # Check that the board is in recovery mode.
    # If you open the port directly and hit the RESET button, you should see:
    # RECOVERY
    # 0000362000008A01020A00008FC8C833
    # CCC
    #
    # 'C's mean that this is XMODEM with CRC-16 and the receiver is ready to
    # receive data.
    # http://web.mit.edu/6.115/www/amulet/xmodem.htm

    serial.timeout = 10
    output = read(serial, 10)
    serial.timeout = timeout

    # If you're getting an error here:
    # - the board is not in recovery mode
    # - you connected too early, try again
    # - something is wrong with the serial port (try opening it in ExtraPutty,
    #   it supports XMODEM too).
    assert b"CC" in output

    # Send the recovery 1BL over XMODEM.
    print(yellow("[<] Sending recovery 1BL"))
    stream = open(recovery_1bl, "rb")
    xmodem_send(serial, stream, timeout)

    # Output: b'+GOOD\r\n'
    readline(serial)

    # Output: b'[1BL] BOOT: INIT\r\n'
    # or
    # Output: b'[1BL] BOOT: 28030000/00000010/07000000\r\n'
    # The postcode (the last three numbers) might be different.
    #
    # In C# code: 'WaitForRecoveryBoot', 'VerifyBootMessage', 'DeviceResponses'.
    readline(serial)

    # Output: b'\x02\x89\x02\x01\x02\x85\x02\x01\x01\x01\x81006fe629beb69fc3bb06cf8494ccc25461f597aae076aa0d1f9b49656d60b63557becad65b338a1a5b4104f769649aaa35340eca1f1899df610305506cd7bee8\x03\xbe\x03\x00 (repeated)'
    #
    # Format:
    # \x02\x89\x02\x01\x02\x85\x02\x01\x01\x01\x81
    # 006...bee8 -- Device ID
    # \x03\xbe\x03
    # \x00 -- end of packet
    #
    # COBS uses the NULL byte as the packet delimiter.
    # Decoded: b'\x89\x00\x01\x00\x85\x00\x01\x00\x00\x00006fe629beb69fc3bb06cf8494ccc25461f597aae076aa0d1f9b49656d60b63557becad65b338a1a5b4104f769649aaa35340eca1f1899df610305506cd7bee8\x00\xbe\x03'
    #
    # Format:
    # \x89\x00 -- packet size (137, little-endian)
    # \x01\x00 -- ClientMessageType.Initialization (1, little-endian)
    # \x85\x00 -- data size (133, little-endian)
    # \x01\x00\x00\x00 -- version (1, little-endian)
    # 006...bee8 -- Device ID
    # \x00  -- NULL terminator
    # \xbe\x03 -- unk (probably CRC-16).
    output, leftovers = read_decode(serial)

    # In C# code: 'ServerMessageType', 'ControlProtocol'.
    #
    # Format (case for payload length == 0):
    # The array that CRC-16 is calculated on:
    # 04 00 a0 00 00 00
    # \x04\x00 -- size
    # \xa0\x00 -- ServerMessageType.InitializationAck (0x00A0)
    # \x00\x00 -- end of the message.
    #
    # CRC-16 value: 0xecd7.
    #
    # The final array should be:
    # 02 04 02 a0 01 01 03 d7 ec 00
    # last \x00 -- packet delimiter.
    #
    # b"\x02\x04\x02\xa0\x01\x01\x03\xd7\xec\x00"
    write_encode(serial, b"\xa0\x00\x00\x00")

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent
    # \x01\x00 -- payload size (1, little-endian)
    # \x01 -- RecoveryEventType.BLInitializationComplete
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x01"

    # Format:
    # \t\x00 -- ClientMessageType.LogConfigQuery (0x0009)
    # \x00\x00 -- payload size (0, little-endian)
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\t\x00\x00\x00"

    # Sending: b'\x02\x05\x02\xa3\x02\x01\x01\x03!\x8a\x00'
    #
    # In C# code: 'BuildResponse', 'SimpleAckResponse'.
    # Format:
    # \xa3\x00 -- ServerMessageType.SimpleQueryAck (0x00a3)
    # \x01\x00 -- payload size (1, little-endian)
    # \x00     -- ackResponse (0 or 1)
    # XXX: Try sending 1 here as ackResponse.
    write_encode(serial, b"\xa3\x00\x01\x00\x00")

    # In C# code: class 'RequestFileBase'.
    #
    # Format:
    # \x04\x00 -- ClientMessageType.ImageRequestCapability (0x0004)
    # \x08\x00 -- payload size (8, little-endian)
    # \x00\x00\x00\x00 -- index?
    # \xff\xff\xff\xff -- file size?
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x04\x00\x08\x00\x00\x00\x00\x00\xff\xff\xff\xff"

    # Format:
    # \xa4\x00 -- ServerMessageType.ImageRequestAck (0x00a4)
    # \x0c\x00 -- payload size (12, little-endian)
    # \x00\x00\x00\x00 -- start index?
    # \x88\x01\x00\x00 -- send size?
    # \x88\x01\x00\x00 -- total size?
    write_encode(
        serial,
        (b"\xa4\x00" +
         b"\x0c\x00" +
         b"\x00\x00\x00\x00" +
         b"\x88\x01\x00\x00" +
         b"\x88\x01\x00\x00"))

    # Send device capabilities over XMODEM.
    print(yellow("[<] Sending device capabilities"))
    stream = open(device_caps, "rb")
    xmodem_send(serial, stream, timeout)

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x02 -- RecoveryEventType.BLCapabilityImageReceived
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x02"

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x03 -- RecoveryEventType.BLCapabilityImageLoaded
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x03"

    # Format:
    # \x07\x00 -- ClientMessageType.ImageRequestByFilename
    # \x1d\x00 -- size (29, little-endian)
    # \x00\x00\x00\x00 -- index?
    # \xff\xff\xff\xff -- file size?
    # recovery-runtime.bin -- filename
    # \x00 -- terminator
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x07\x00\x1d\x00\x00\x00\x00\x00\xff\xff\xff\xffrecovery-runtime.bin\x00"

    # Format:
    # \xa4\x00 -- ServerMessageType.ImageRequestAck (0x00a4)
    # \x0c\x00 -- payload size (12, little-endian)
    # \x00\x00\x00\x00 -- start index?
    # \xa4\xed\x00\x00 -- send size?
    # \xa4\xed\x00\x00 -- total size?
    write_encode(
        serial,
        (b"\xa4\x00"
         b"\x0c\x00"
         b"\x00\x00\x00\x00"
         b"\xa4\xed\x00\x00"
         b"\xa4\xed\x00\x00"))

    # Send the recovery runtime over XMODEM.
    print(yellow("[<] Sending recovery runtime"))
    stream = open(recovery_runtime, "rb")
    xmodem_send(serial, stream, timeout)

    # Format:
    # \t\x00 -- ClientMessageType.LogConfigQuery (0x0009)
    # \x00\x00 -- payload size (0, little-endian)
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\t\x00\x00\x00"

    # Format:
    # \xa3\x00 -- ServerMessageType.SimpleQueryAck (0x00a3)
    # \x01\x00 -- payload size (1, little-endian)
    # \x00     -- ackResponse (0 or 1)
    write_encode(serial, b"\xa3\x00\x01\x00\x00")

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x06 -- RecoveryEventType.RABootComplete
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x06"

    # Format:
    # \x03\x00 -- ClientMessageType.BaudrateSwitchQuery (0x0003)
    # \x00\x00 -- payload size (0, little-endian)
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x03\x00\x00\x00"

    # Format:
    # \xa3\x00 -- ServerMessageType.SimpleQueryAck (0x00a3)
    # \x01\x00 -- payload size (1, little-endian)
    # \x01     -- ackResponse (0 or 1)
    #
    # Baudrate settings:
    # {
    #   PortMode.Bootloader,
    #   new SerialPortConfiguration()
    #   {
    #     BaudRate = 115200,
    #     Parity = Parity.None,
    #     DataBits = 8,
    #     StopBits = StopBits.One,
    #     Handshake = Handshake.None
    #   }
    # },
    # {
    #   PortMode.ImagingMt3620,
    #   new SerialPortConfiguration()
    #   {
    #     BaudRate = 3000000,
    #     Parity = Parity.None,
    #     DataBits = 8,
    #     StopBits = StopBits.One,
    #     Handshake = Handshake.RequestToSend
    #   }
    # },
    # {
    #   PortMode.ImagingMt3620LowSpeed,
    #   new SerialPortConfiguration()
    #   {
    #     BaudRate = 115200,
    #     Parity = Parity.None,
    #     DataBits = 8,
    #     StopBits = StopBits.One,
    #     Handshake = Handshake.RequestToSend
    #   }
    # }
    # write_encode(serial, b"\xa3\x00\x01\x00\x01")  # XXX: doesn't work
    write_encode(serial, b"\xa3\x00\x01\x00\x00")

    # serial.baudrate = 3000000  # XXX: doesn't work
    serial.baudrate = 115200
    serial.parity = PARITY_NONE
    serial.bytesize = 8
    serial.stopbits = 1
    serial.rtscts = 1

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x07     -- RecoveryEventType.RAEraseFlashStarted
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x07"

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x08     -- RecoveryEventType.RAEraseFlashComplete
    print("[i] Waiting for flash erase to complete")
    while True:
        try:
            output, leftovers = smart_decode(serial, leftovers)
            break
        except EmptyOutputError:
            continue
    assert output == b"\x0b\x00\x01\x00\x08"

    # Format:
    # \x07\x00 -- ClientMessageType.ImageRequestByFilename
    # \x1f\x00 -- size (31, little-endian)
    # \x00\x00\x00\x00 -- index?
    # \xff\xff\xff\xff -- file size?
    # recovery.imagemanifest -- filename
    # \x00 -- terminator
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x07\x00\x1f\x00\x00\x00\x00\x00\xff\xff\xff\xffrecovery.imagemanifest\x00"

    # Format:
    # \xa4\x00 -- ServerMessageType.ImageRequestAck (0x00a4)
    # \x0c\x00 -- payload size (12, little-endian)
    # \x00\x00\x00\x00 -- start index?
    # \xd8\x05\x00\x00 -- send size?
    # \xd8\x05\x00\x00 -- total size?
    write_encode(
        serial,
        (b"\xa4\x00" +
         b"\x0c\x00" +
         b"\x00\x00\x00\x00" +
         b"\xd8\x05\x00\x00" +
         b"\xd8\x05\x00\x00"))

    # Send the recovery manifest over XMODEM.
    print(yellow("[<] Sending recovery manifest"))
    stream = open(recovery_manifest, "rb")
    xmodem_send(serial, stream, timeout)

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent
    # \x01\x00 -- payload size (1, little-endian)
    # \x09 -- RecoveryEventType.RAManifestReceived
    output, leftovers = smart_decode(serial, leftovers)
    assert output ==  b"\x0b\x00\x01\x00\t"
Example #10
0
# !/usr/bin/env python3
# _*_ coding: utf-8 _*_
# create on 2017.3.1
# author:fan

import struct
import binascii
import time
from serial import Serial  # 导入模块
t = Serial('com2')  # 创建Serial实例
t.baudrate = 115200  # 设置参数(参数设置请以实际为准)
t.bytesize = 7
t.stopbits = 1
t.parity = 'E'

print('''
            com = %s
      baud_rate = %d
      data_size = %d
         parity = %s
      stop_bits = %d''' %
      (t.port, t.baudrate, t.bytesize, t.parity, t.stopbits))


def watch_com(read_size=4, write_data='ff', sleep_time=0.1):
    i = 0
    while i < 10:
        i += 1
        if i == 32767:
            i = 0
        time.sleep(sleep_time)
Example #11
0
#**********************Программа******************************************

from serial import Serial, SerialException, EIGHTBITS, PARITY_NONE

import time

import logging
logger = logging.getLogger(__name__)
logging.basicConfig(filename='cmplr.log', filemode='w', level=logging.DEBUG)

SERIAL_PORT = 'COM7'
SERIAL_SPEED = 9600
ser = Serial()
ser.port = SERIAL_PORT
ser.baudrate = SERIAL_SPEED
ser.bytesize = EIGHTBITS  #number of bits per bytes
ser.timeout = 1  #non-block read
ser.writeTimeout = 2  #timeout for write
ser.xonxoff = False  #disable software flow control
ser.rtscts = False  #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False  #disable hardware (DSR/DTR) flow control

try:
    """
         Пытаемся открыть серийный порт
      """
    ser.open()

except SerialException as e:

    logger.debug("error open serial port: " + str(e))