def serializeFromSerial(): serial.open() data = serial.readline() # Read the next line from serial serial.close() print(data) # Print the data to terminal for debugging purposes j = json.loads(data) # Load the raw string as JSON return j # Return the JSON
def Main(args): global port if len(args) != 2: print("Invalid input arguments") return 1 serial.port = args[1] serial.baudrate = 115200 serial.timeout = 3 serial.open() input("Press enter to send data...") nCmdsGood = 0 print("Starting upload on " + args[1] + "...") while True: cmd = bytes([ (0x80 if ((nCmdsGood % 5) == 0) else 0) | (0x01 if ((nCmdsGood % 3) == 0) else 0), 0 ]) serial.write(cmd) resp = serial.read(len(cmd)) if len(resp) > 0: if resp == cmd: nCmdsGood += 1 print(resp) else: print("Waited too long.") break input("Press enter to close serial port...") serial.close() print("Done!")
def put(self): serial = open_serial() serial.open() command = request.form['data'] def change_input(command): if command == "in_nxt": serial.write(b"1") serial.close() elif command == "in_prev": serial.write(b"2") serial.close() elif command == "in_usb": serial.write(b"a") serial.close() elif command == "in_opt1": serial.write(b"d") serial.close() elif command == "in_opt2": serial.write(b"e") serial.close() elif command == "in_coax1": serial.write(b"b") serial.close() elif command == "in_coax2": serial.write(b"c") serial.close() else: syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server") change_input(command)
def test_serial(): try: serial = open_serial() serial.open() serial.close() except: syslog.syslog(syslog.LOG_CRIT, "Failed to open serial device") sys.exit(os.EX_UNAVAILABLE)
def on_command(logger, SERVICES): logger.info("Querying quaternion values from IMU...") while True: input("pause") try: request = ''' { qua { success errors quaData { q1 q2 q3 q4 } } } ''' response = SERVICES.query(service="imu-service", query=request) result = response["qua"] success = result["success"] errors = result["errors"] quaData = result["quaData"] q1 = quaData["q1"] q2 = quaData["q2"] q3 = quaData["q3"] q4 = quaData["q4"] if success: logger.info('Quaternion: ({}, {}, {}, {})'.format(q1,q2,q3,q4)) else: logger.warning("Unable to retrieve quaternion data: {}".format(errors)) try: # open uart port serial.close() serial.open() if serial.isOpen(): message = (q1,q2,q3,q4) # if uart port is open, try to send encoded string message serial.write(str(message).encode('utf-8')) serial.close() logger.debug("UART port is open. Sent message: {}".format(str(message))) else: # if could not open uart port, return failure serial.close() logger.warn("Could not open serial port") # return failure if exception during write/encoding except Exception as e: logger.warn("Error sending message {} over uart port: {}".format(str(message), str(e))) except Exception as e: logger.warning("Unsuccessful getting data from quaternion: {}-{}".format(type(e).__name__,str(e)))
def reconnect(serial): print('re') try: serial.close() serial.open() status = 1 return status except: status = 0 return status
def open_serial(): serial = SerialConnection() devices = serial.get_available_devices() print(devices) serial.open(devices[0]) cmd = {'s': {'meta': 1}} cmdStr = json.dumps(cmd, separators=(',', ':')) + '\r' serial.write(cmdStr) print(serial.read_line())
def put(self): serial = open_serial() serial.open() command = request.form['data'] def change_power(command): if command == "pwr_event": serial.write(b"6") serial.close() else: syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server") change_power(command)
def put(self): serial = open_serial() serial.open() command = request.form['data'] def misc_commands(command): if command == "gain_sel": serial.write(b"f") serial.close() else: syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server") misc_commands(command)
def initSerial(port, baudrate): serial.port = port serial.baudrate = baudrate serial.timeout = 1 serial.writeTimeout = 1 serial.open() serial.flush() logd('Opening port %s - %s' % (port, baudrate)) if serial.isOpen(): logd('Success') else: logd('Failed') exit(2)
def initSerial(port, baudrate): serial.port = port serial.baudrate = baudrate serial.timeout = 1 serial.writeTimeout = 1 serial.open() serial.flush() logd( 'Opening port %s - %s' %(port, baudrate) ) if serial.isOpen(): logd('Success') else: logd('Failed') exit(2)
def inner(self): try: if not serial.isOpen(): if not serial.open(QIODevice.ReadWrite): self.error.emit( "can't not open %s,error code:%d" % (serial.portName(), serial.error())) return # locker = QMutexLocker(self.mutex) ## when wait for read can't wait for waitWritten if serial.waitForReadyRead(10): # if serial.bytesAvailable() > 0: requestData = bytes() requestData = serial.readAll() while serial.waitForReadyRead(10): requestData += serial.readAll() bData = bytes(requestData) hexData = ' '.join('{:02x}'.format(x) for x in bData) # m = re.search('(7e.{31,31}e7)', hex) # if m: # requestStr = m.group(0) # # requestStr = str(bytes(requestData)) # self.request.emit(requestStr) self.request.emit(hexData) else: self.timeout.emit("Wait read ready timeout %s" % (QTime.currentTime().toString())) except TypeError as e: print('Got Error', e)
def main(): parser = argparse.ArgumentParser(description='HTTP Server') parser.add_argument('port', type=int, help='Listening port for HTTP Server') parser.add_argument('ip', help='HTTP Server IP') args = parser.parse_args() server = HTTPServer((args.ip, args.port), HTTPRequestHandler) print('HTTP Server Running...........') # server.serve_forever() threading.Thread(target=server.serve_forever).start() loop = asyncio.get_event_loop() # sim = sim_vehicle() loop.run_until_complete(get_pose()) pp = [] for i in range(10): pp.append([i, i * 2]) sim.add_path(pp) print(sim.get_path()) #28H 测距定位使能:0:不测距 1 单次测量 2 持续测量 3 单 次自动输出 4 持续自动输出 # client = ModbusClient(method='rtu', port='COM1', timeout=1, baudrate=115200) # client.connect() # client.write_register(0x28, 2) serial = serial.Serial("COM3", 115200) serial.open() serial.write( [0x01, 0x10, 0x00, 0x28, 0x00, 0x01, 0x02, 0x00, 0x02, 0x21, 0xB9]) n = serial.inWaiting() time.sleep(0.1) serial.read(n) while True: #0x2C标签X坐标,0x2D Y坐标 # request = client.read_input_registers(0x2C, 2) # request = client.read_holding_registers(0x2C, 2) n2 = serial.inWaiting() serial.write([0x01, 0x03, 0x00, 0x2A, 0x00, 0x0D, 0xA5, 0xC7]) time.sleep(0.1) rec_data = serial.read(n2) rec_data[7:9] position[0] = request.registers[0] position[1] = request.registers[1] print('positon: x {}, y{}'.format(positon[0], positon[1])) time.sleep(0.1)
def initSerial(port, baudrate): # Serial port Configuration serial.port = "/dev/" + port serial.baudrate = baudrate serial.timeout = 1 serial.writeTimeout = 1 serial.open() serial.flush() logd('Opening port %s - %s' % (port, baudrate)) serial.isOpen() if serial.isOpen(): logd('Success') else: logd('Failed') exit(2)
def Main(args): global port if len(args) != 4: print("Invalid input arguments") return 1 f = open(args[1], "rb") fout = open(args[2], "wb") cmds = UploadAndExecute(f.read()) f.close() serial.port = args[3] serial.baudrate = 115200 serial.timeout = 10 serial.open() input("Press enter to send data.") nCmdsGood = 0 print("Starting upload on " + args[3] + "...") for cmd in cmds: fout.write(cmd) serial.write(cmd) resp = serial.read(12) if len(resp) > 0: if resp == cmd: nCmdsGood += 1 print(resp) else: print("Waited too long.") break if nCmdsGood == len(cmds): print("All commands transferred 'successfully'.") else: print("Error! # of commands: {0} # of successes: {1}".format( len(cmds), nCmdsGood)) input("Press enter to close serial port.") fout.close() serial.close() print("Done!")
def put(self): serial = open_serial() serial.open() command = request.form['data'] def change_vol(command): if command == "vol_down": serial.write(b"5") serial.close() elif command == "vol_up": serial.write(b"4") serial.close() elif command == "vol_mute": serial.write(b"3") serial.close() else: syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server") change_vol(command)
def laser_record(): global laser_filename global time_now print('laser record...') time_now = str(int(time.time())) print(serial.port) #file_dir = "./" laser_filename = save_dir['datadir'] + 'laser_' + time_now + '_' + fj_id[ 'id'] + '.txt' print(laser_filename) time1 = int(time.time()) #laser_record_time = 5 if not serial.is_open: print('open') serial.open() try: while True: Byte_H = serial.read(1) Byte_L = serial.read(1) res = (ord(Byte_H) & 0x7f) * 128 + (ord(Byte_L) & 0x7f) print(res) ss = str(res) + '\n' with open(laser_filename, 'a') as f: f.write(ss) time2 = int(time.time()) #print(time2) #print(time1) print(time2 - time1) if (time2 - time1 == collectTime): print('close') serial.close() print(serial.isOpen()) except Exception as e: print(e)
def to_arduino(): working=0 v=["99!","98!","97!","96!","95!","94!","93!","92!","91!","90!","89!","88!","87!","86!","85!","84!","83!","82!","81!","80!","79!","78!","77!","76!","75!","74!","73!","72!","71!","70!","69!","68!","67!","66!","65!","64!","63!","62!","61!","60!","59!","58!","57!","56!","55!","54!","53!","52!","51!","50!","49!","48!","47!","46!","45!","44!","43!","42!","41!","40!","39!","38!","37!","36!","35!","34!","33!","32!","31!","30!","29!","28!","27!","26!","25!","24!","23!","22!","21!","20!","19!","18!","17!","16!","15!","14!","13!","12!","11!","10!","9!","8!","7!","6!","5!","4!","3!","2!","2!","2!"] d=[7,7,7,7,7,6,6,6,6,6,5,5,5,5,5,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2.25,2.25,2,2,2,2,2,1.85,1.85,1.85,1.85,1.85,1.75,1.75,1.75,1.75,1.75,1.6,1.6,1.6,1.6,1.6,1.5,1.5,1.5,1.5,1.5,1.35,1.35,1.35,1.35,1.35,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25] while True: if controller_h.state==1: try: controller_h.update() value = int(controller_h.dim) if value<0: value=99 delay=d[value] value=v[value].encode('UTF-8') if working == 0: working =1 serial.close() serial.open() serial.write(value) serial.flush() serial.close() time.sleep(delay) working=0 except: pass
def inner(self): try: if not serial.isOpen(): if not serial.open(): # self.error.emit("can't not open %s,error code:%d"%(serial.portName(),serial.error())) return if serial.inWaiting() == 0: return data = bytes() requestData = bytes() # print('wait:',serial.in_waiting) requestData = serial.read(serial.inWaiting()) hexData = ' '.join('{:02x}'.format(x) for x in requestData) self.request.emit(hexData) # else: # self.timeout.emit("Wait read ready timeout %s"%(QTime.currentTime().toString())) except TypeError as e: print('Got Error', e)
# imported modules import os # portable way of using operating system dependent functionality import sys # provides access to some variables used or maintained by the interpreter import time # provides various time-related functions import fcntl # performs file control and I/O control on file descriptors import serial # encapsulates the access for the serial port #from pretty import switchColor, printc # provides colored text for xterm & VT100 type terminals using ANSI escape sequences if __name__ == '__main__': serial = serial.Serial() serial.port = '/dev/ttyUSB0' serial.baudrate = 9600 serial.timeout = 1 serial.writeTimeout = 1 serial.open() # make stdin a non-blocking file fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK) # post startup message to other XBee's and at stdout serial.writelines("RPi #1 is up and running.\r\n") print "RPi #1 is up and running." #switchColor(CMD_OUTPUT_TEXT) print "Entering loop to read and print messages (Ctrl-C to abort)..." try: while True: # read a line from XBee and convert it from b'xxx\r\n' to xxx and print at stdout #switchColor(TERM_OUTPUT_TEXT)
import serial import time import sys # open serial port port = '/dev/ttyAMA0' baud = 115200 serial = serial.Serial(port, baud, timeout=2) serial.flush() serial.write("G28\r\n") serial.write("G29\r\n") coms=2 serial.open() while True and coms>0: line=serial.readline() if line!="": if line.rstrip()=="ok": coms-=1 else: if line[0:3]=="Bed": line=line.split(" ") print(str(line[2].rstrip())+","+ str(line[4].rstrip())+","+str(line[6].rstrip())) line="" pass serial.close() #print ("completed!") sys.exit()
def open(self, baudRate): return serial.open(self.port, baudRate)
def get_power_level(self): self.short_at_command("PL") return int(self.rx(1)) def get_pan_id(self): self.short_at_command("ID") return self.rx(4) def translate_power_level_value(self, value): """Provides understanding of power level value.""" if value == 1: return "-10/10 dBm" elif value == 4: return "0/18 dBm" if __name__ == '__main__': serial = Serial() serial.open("/dev/ttyUSB0", 9600) driver = XBee() driver.open(serial) driver.init_at() # initialize AT mode print "Test" print "PAN (PERSONAL AREA NETWORK) ID", "=", driver.get_pan_id() print "RF module's unique EEEI address", "=", driver.get_serial_number() print "Modem firmware version", "=", driver.get_firmware_version() print "Hardware version", "=", driver.get_hardware_version() power_level = driver.get_power_level() print "Power level =", power_level,\ "(%s)" % driver.translate_power_level_value(power_level) driver.close()
def init(): try: serial.open() except serial.SerialException, exception: sys.stderr.write("Opening port %r failed: %s\n" % (serial.port, exception)) sys.exit(1)
data2 = np.array([]) fig, (ax1, ax2) = plt.subplots(2) plt.xkcd() plt.style.use('ggplot') ax1, ax2.set_ylim(0, 1) ax2.set_xlabel("SAMPLES", size=15, color="orange", fontname='Comic Sans MS') ax1.set_ylabel("COUNTS", size=15, color="blue", fontname='Comic Sans MS') ax2.set_ylabel("COUNTS", size=15, color="orange", fontname='Comic Sans MS') ax1.grid(True) ax2.grid(True) sr = sr.Serial() sr.port = 'COM4' #Arduino serial port sr.baudrate = 9600 sr.timeout = 10 #specify timeout when using readline() sr.open() def CountFrequency(data): return collections.Counter(data) def animate(i): if sr.is_open == True: a = sr.readline() a = a.decode() print(a) print(a[0]) global data1, data2 ctd = 0 try:
def GET(self): serial.open() serial.write("d") serial.close() return
def open_HMIPort( serial ): serial.open()
if packet_size_return == 2 and command_return == command: print('Measurement processed by psoc') else: print('Error! Printing incorrect command or packet size.') print('Command:', command_return, 'Packet size:', packet_size_return) # testing # Serial configuration ser = ser.Serial(port='COM5', baudrate=115200, parity='N') if ser.is_open: ser.close() ser.open() else: ser.open() psoc = psoc_interface(ser) # test_double = psoc.relay_double(1.234567) # print(test_double) psoc.send_sim_env_info(Kinf=np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]), Ts=5, Finf=np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]]))
def Main(args): try: buff = '' if len(args) != 2: return 1 serial.port = args[1] serial.baudrate = 115200 serial.timeout = 10 serial.open() framecount = 0 while True: buff = input() if (buff == 'START'): #Set everything to zero to start framecount += 1 b = 0 y = 0 select = 0 start = 0 up = 0 down = 0 left = 0 right = 0 a = 0 x = 0 lb = 0 rb = 0 home = 0 app = 0 click = 0 volm = 0 buff = input() mode = int(buff) if (mode == 1): buff = input() #<crapcode> if (buff == ''): buf = 0 else: buf = float(buff) if (buf < -0.55): left = 1 right = 0 elif (buf < -0.35): left = 1 if (framecount % 3 != 0) else 0 right = 0 elif (buf < -0.20): left = 1 if ((framecount % 5) % 2 == 0) else 0 right = 0 elif (buf < -0.08): left = 1 if (framecount % 2 == 0) else 0 right = 0 elif (buf > 0.55): right = 1 left = 0 elif (buf > 0.35): right = 1 if (framecount % 3 != 0) else 0 left = 0 elif (buf > 0.20): right = 1 if ((framecount % 5) % 2 == 0) else 0 left = 0 elif (buf > 0.08): right = 1 if (framecount % 2 == 0) else 0 left = 0 #</crapcode> buff = input() if (buff): home = 1 up = home buff = input() if (buff): app = 1 down = app if (home or app): a = 1 buff = input() if (buff): click = 1 lb = click buff = input() if (buff): volm = 1 start = volm #<crapcode2.0> buff = input() if (buff == ''): buf = 0 else: buf = int(buff) if (buf < 128 and buf > 0): y = 1 b = 0 elif (buf > 128): b = 1 y = 0 else: b = 0 y = 0 buff = input() pass #</crapcode2.0> if (mode == 2): buff = input() pass buff = input() if (buff): home = 1 b = home buff = input() if (buff): app = 1 x = app buff = input() pass buff = input() pass buff = input() xTouch = int(buff) - 128 if buff else 0 buff = input() yTouch = int(buff) - 128 if buff else 0 #Do the math to turn the touchpad to a d pad if (xTouch != 0 and yTouch != 0 and (math.sqrt(xTouch**2 + yTouch**2)) > 55): angle = (math.atan2(xTouch, yTouch) * 360 / 6.28) + 180 if (angle < 45 or angle > 315): left = 1 elif (angle > 45 and angle < 135): down = 1 elif (angle > 135 and angle < 225): right = 1 elif (angle > 225 and angle < 315): up = 1 buff = '' controllerData = str(b) + str(y) + str(select) + str(start) + str( up) + str(down) + str(left) + str(right) + str(a) + str( x) + str(lb) + str(rb) + '0000' contDataBytes = bitstring_to_bytes(controllerData) print(contDataBytes) serial.reset_output_buffer() serial.write(contDataBytes) echo = serial.read(len(contDataBytes)) if len(echo) != len(contDataBytes): print("BAD!") #print(controllerData) except KeyboardInterrupt: sys.stdout.flush() serial.close() pass print("DONE")
def run(): try: config.kStationType except AttributeError: print "Configuration Error:" print print "Please edit the config.py file and choose a Station Type. ('kStationType')" return try: config.kCommPort except AttributeError: print "Configuration Error:" print print "Please edit the config.py file and pick a Serial Port ('kCommPort')." return if config.kWundergroundUserID == "userid": print "Configuration Error:" print print "Please edit the config.py file and enter your Wunderground " print "Person Weather Station Userid and Password. To sign up, " print "visit: http://www.wunderground.com/weatherstation/usersignup.asp" print return if config.kStationType == kStation_Davis: import station_davis module = station_davis elif config.kStationType == kStation_Rainwise: import station_rainwise module = station_rainwise elif config.kStationType == kStation_WM918: import station_wm918 module = station_wm918 elif config.kStationType == kStation_WMR968: import station_wmr968 module = station_wmr968 log("acquiring Serial Port") cfg = module.GetSerialConfig(config) port = serial.open(cfg) wl = module.DataLogger(config, port) # sleep_time = ((time.localtime(time.time())[4] / config.kWunderground_UpdateInterval) + 1) * config.kWunderground_UpdateInterval # if sleep_time > 59: sleep_time = 60 - time.localtime(time.time())[4] # else: sleep_time = sleep_time - time.localtime(time.time())[4] # sleep_seconds = time.localtime(time.time())[5] # log("Next update: " + str(sleep_seconds) + " seconds") # wl.SetUpdater(Wunderground(config, ((sleep_time * 60) - sleep_seconds))) wl.SetUpdater(Wunderground(config, config.kWunderground_UpdateInterval)) wl.SetUpdater(CSVUpdate(config, config.kCSV_UpdateInterval)) wl.SetUpdater(ShellUpdate(config, config.kShell_UpdateInterval)) if config.kWeatherServer: import weatherServer su = weatherServer.SocketUpdater(config, 5) wl.SetUpdater(su) su.run() try: while 1: try: wl.StartLoop() except serial.TimeoutError, msg: log("timeout error - pi") import traceback traceback.print_exc() log(msg) except CommError, msg: log("comm error - pi") import traceback traceback.print_exc() log("Communicatons Error", msg)