Beispiel #1
0
def job_submit_handler():
    job_data = request.forms.get('job_data')
    if job_data and SerialManager.is_connected():
        SerialManager.queue_gcode(job_data)
        return "__ok__"
    else:
        return "serial disconnected"
Beispiel #2
0
def job_submit_handler():
    job_data = request.forms.get('job_data')
    if job_data and SerialManager.is_connected():
        SerialManager.queue_gcode(job_data)
        return "__ok__"
    else:
        return "serial disconnected"
Beispiel #3
0
def run_with_callback(host):
    """ Start a wsgiref server instance with control over the main loop.
        This is a function that I derived from the bottle.py run()
    """
    handler = default_app()
    server = wsgiref.simple_server.make_server(host, NETWORK_PORT, handler)
    server.timeout = 0.01
    server.quiet = True
    print "-----------------------------------------------------------------------------"
    print "Bottle server starting up ..."
    print "Serial is set to %d bps" % BITSPERSECOND
    print "Point your browser to: "
    print "http://%s:%d/      (local)" % ("127.0.0.1", NETWORK_PORT)
    if host == "":
        print "http://%s:%d/   (public)" % (socket.gethostbyname(socket.gethostname()), NETWORK_PORT)
    print "Use Ctrl-C to quit."
    print "-----------------------------------------------------------------------------"
    print
    try:
        webbrowser.open_new_tab("http://127.0.0.1:" + str(NETWORK_PORT))
    except webbrowser.Error:
        print "Cannot open Webbrowser, please do so manually."
    sys.stdout.flush()  # make sure everything gets flushed
    while 1:
        try:
            SerialManager.send_queue_as_ready()
            server.handle_request()
        except KeyboardInterrupt:
            break
    print "\nShutting down..."
    SerialManager.close()
Beispiel #4
0
def gcode_handler(gcode_line):
    if SerialManager.is_connected():    
        print gcode_line
        SerialManager.queue_for_sending(gcode_line)
        return "Queued for sending."
    else:
        return ""
Beispiel #5
0
def run_with_callback(host, port=4444, timeout=0.01):
    """ Start a wsgiref server instance with control over the main loop.
        This is a function that I derived from the bottle.py run()
    """
    handler = default_app()
    server = wsgiref.simple_server.make_server(host, port, handler)
    server.timeout = timeout
    print "-----------------------------------------------------------------------------"
    print "Bottle server starting up ..."
    print "Serial is set to %d bps" % BITSPERSECOND
    print "Point your browser to: "    
    print "http://%s:%d/      (local)" % ('127.0.0.1', port)    
    if host == '':
        print "http://%s:%d/   (public)" % (socket.gethostbyname(socket.gethostname()), port)
    print "Use Ctrl-C to quit."
    print "-----------------------------------------------------------------------------"    
    print
    while 1:
        try:
            SerialManager.send_queue_as_ready()
            server.handle_request()
        except KeyboardInterrupt:
            break
    print "\nShutting down..."
    SerialManager.close()
Beispiel #6
0
def serial_handler(connect):
    if connect == '1':
        print 'js is asking to connect serial'      
        if not SerialManager.is_connected():
            try:
                global SERIAL_PORT, BITSPERSECOND
                SerialManager.connect(SERIAL_PORT, BITSPERSECOND)
                ret = "Serial connected to %s:%d." % (SERIAL_PORT, BITSPERSECOND)  + '<br>'
                time.sleep(1.0) # allow some time to receive a prompt/welcome
                SerialManager.flush_input()
                SerialManager.flush_output()
                return ret
            except serial.SerialException:
                print "Failed to connect to serial."    
                return ""          
    elif connect == '0':
        print 'js is asking to close serial'    
        if SerialManager.is_connected():
            if SerialManager.close(): return "1"
            else: return ""  
    elif connect == "2":
        print 'js is asking if serial connected'
        if SerialManager.is_connected(): return "1"
        else: return ""
    else:
        print 'ambigious connect request from js: ' + connect            
        return ""
Beispiel #7
0
def checkErr(* flag):
    for index in range(len(flag)):
        if flag[index] != 0:
            SerialManager.read_existing() #clear rx_buffer
            if SerialManager.write('O000'+'\r'):
                relayStatus=SerialManager.read_to('\r')
                print 'relay status is:',relayStatus
Beispiel #8
0
 def connectToSerialDevices(self):
     sc_port = self.ui.sc_port.itemText(self.ui.sc_port.currentIndex())
     ub_port = self.ui.ub_port.itemText(self.ui.ub_port.currentIndex())
     self.serialManager = SerialManager(sc_port, ub_port,
                                        config.SERIAL_PUBLISH,
                                        config.SERIAL_SUBSCRIBE,
                                        config.SERIAL_NFF_SUBSCRIBE)
     self.serialManager.start()
Beispiel #9
0
def flash_firmware_handler():
    if SerialManager.is_connected():
        SerialManager.close()
    global SERIAL_PORT, GUESS_PREFIX
    if not SERIAL_PORT:
        SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX)        
    flash_upload(SERIAL_PORT, resources_dir())
    return '<h2>flashing finished!</h2> Check Log window for possible errors.<br><a href="/">return</a>'
Beispiel #10
0
 def __init__(self):
     self.serial_manager = SerialManager()
     try:
         self.database = Database()
     except KeyError:
         print('Error loading database')
         self.abort_test()
     self.csv_logger = CSVLogger()
def sendCommand(command):
	
	#clear rx_buffer
    SerialManager.read_existing() 
	
    if SerialManager.write(command + '\r'):
        return SerialManager.read_to('\r')
    else:
        return 'error'
def sendCommand(command):

    #clear rx_buffer
    SerialManager.read_existing()

    if SerialManager.write(command + '\r'):
        return SerialManager.read_to('\r')
    else:
        return 'error'
Beispiel #13
0
def flash_firmware_handler(firmware_file=FIRMWARE):
    global SERIAL_PORT, GUESS_PREFIX
    return_code = 1
    if SerialManager.is_connected():
        SerialManager.close()
    # get serial port by url argument
    # e.g: /flash_firmware?port=COM3
    if 'port' in request.GET.keys():
        serial_port = request.GET['port']
        if serial_port[:3] == "COM" or serial_port[:4] == "tty.":
            SERIAL_PORT = serial_port
    # get serial port by enumeration method
    # currenty this works on windows only for updating the firmware
    if not SERIAL_PORT:
        SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)
    # resort to brute force methode
    # find available com ports and try them all
    if not SERIAL_PORT:
        comport_list = SerialManager.list_devices(BITSPERSECOND)
        for port in comport_list:
            print "Trying com port: " + port
            return_code = flash_upload(port, resources_dir(), firmware_file,
                                       HARDWARE)
            if return_code == 0:
                print "Success with com port: " + port
                SERIAL_PORT = port
                break
    else:
        return_code = flash_upload(SERIAL_PORT, resources_dir(), firmware_file,
                                   HARDWARE)
    ret = []
    ret.append('Using com port: %s<br>' % (SERIAL_PORT))
    ret.append('Using firmware: %s<br>' % (firmware_file))
    if return_code == 0:
        print "SUCCESS: Arduino appears to be flashed."
        ret.append('<h2>Successfully Flashed!</h2><br>')
        ret.append('<a href="/">return</a>')
        return ''.join(ret)
    else:
        print "ERROR: Failed to flash Arduino."
        ret.append(
            '<h2>Flashing Failed!</h2> Check terminal window for possible errors. '
        )
        ret.append(
            'Most likely LasaurApp could not find the right serial port.')
        ret.append('<br><a href="/flash_firmware/' + firmware_file +
                   '">try again</a> or <a href="/">return</a><br><br>')
        if os.name != 'posix':
            ret.append(
                'If you know the COM ports the Arduino is connected to you can specifically select it here:'
            )
            for i in range(1, 13):
                ret.append(
                    '<br><a href="/flash_firmware?port=COM%s">COM%s</a>' %
                    (i, i))
        return ''.join(ret)
Beispiel #14
0
def job_submit_handler():
    job_data = request.forms.get('job_data')
    if job_data and SerialManager.is_connected():
        lines = job_data.split('\n')
        print "Adding to queue %s lines" % len(lines)
        for line in lines:
            SerialManager.queue_gcode_line(line)
        return "__ok__"
    else:
        return "serial disconnected"
Beispiel #15
0
def gcode_submit_handler():
    gcode_program = request.forms.get('gcode_program')
    if gcode_program and SerialManager.is_connected():
        lines = gcode_program.split('\n')
        print "Adding to queue %s lines" % len(lines)
        for line in lines:
            SerialManager.queue_gcode_line(line)
        return "__ok__"
    else:
        return "serial disconnected"
Beispiel #16
0
def gcode_submit_handler():
    gcode_program = request.forms.get("gcode_program")
    if gcode_program and SerialManager.is_connected():
        lines = gcode_program.split("\n")
        print "Adding to queue %s lines" % len(lines)
        for line in lines:
            SerialManager.queue_for_sending(line)
        return "Queued for sending."
    else:
        return ""
Beispiel #17
0
def job_submit_handler():
    job_data = request.forms.get('job_data')
    if job_data and SerialManager.is_connected():
        lines = job_data.split('\n')
        print "Adding to queue %s lines" % len(lines)
        for line in lines:
            SerialManager.queue_gcode_line(line)
        return "__ok__"
    else:
        return "serial disconnected"
Beispiel #18
0
def gcode_submit_handler():
    gcode_program = request.forms.get('gcode_program')
    if gcode_program and SerialManager.is_connected():
        lines = gcode_program.split('\n')
        print "Adding to queue %s lines" % len(lines)
        for line in lines:
            SerialManager.queue_gcode_line(line)
        return "__ok__"
    else:
        return "serial disconnected"
Beispiel #19
0
def get_status():
    if args.raspberrypi:
        powertimer.reset()
    status = copy.deepcopy(SerialManager.get_hardware_status())
    status['serial_connected'] = SerialManager.is_connected()
    print "Connected: %d" % SerialManager.is_connected()
    status['lasaurapp_version'] = VERSION
    global user_approved
    global user_admin
    global current_user
    if args.disable_rfid:
        return json.dumps(status)
    card_id = reader.getid()
    print "Card ID %s" % card_id
    username = ''
    global current_cardid
    if len(card_id) == 0:
        print "No card inserted"
        username = '******'
        user_approved = False
        if current_user != '':
            logger.log(current_user, 'Card removed')
        current_user = ''
    elif len(card_id) == 12:
        if not card_id in card_data:
            print "Card not found"
            username = '******'
            user_approved = False
            if card_id != current_cardid:
                logger.log(card_id, 'Unknown card')
        else:
            print "Card found"
            data = card_data[card_id]
            username = data['name']
            if data['approved']:
                user_approved = True
            else:
                user_approved = False
            if data['admin']:
                user_admin = True
            else:
                user_admin = False
            if current_user == '':
                logger.log(username, 'Card inserted')
            current_user = username
            print "Approved: %s" % user_approved
        current_cardid = card_id
    else:
        print "Bad length: %d" % len(card_id)
    status['username'] = username
    global shutdown_msg
    status['shutdown_msg'] = shutdown_msg
    shutdown_msg = ''
    return json.dumps(status)
 def __init__(self):
     self.serial_manager = SerialManager()
     try:
         self.database = Database()
     except KeyError:
         print(
             'Error loading database. Did you set the TEST_STAND_DB '
             'environment variable to the name of your InfluxDB database?')
         self.abort_test()
     self.csv_logger = CSVLogger()
     # thread for interpreting incoming serial data
     self.telemetry_thread = threading.Thread(target=self.telemetry_loop)
     self.thread_is_running = False
Beispiel #21
0
def job_submit_handler():
    job_data = request.forms.get('gcode_program')
    if not job_data:
        return HTTPResponse(status=400)

    if SerialManager.is_connected():
        lines = job_data.split('\n')
        print "Adding to queue %s lines" % len(lines)
        for line in lines:
            SerialManager.queue_gcode_line(line)
        return "__ok__"
    else:
        return HTTPResponse(status=502, body="serial disconnected")
Beispiel #22
0
def job_submit_handler():
    job_data = request.forms.get('job_data')
    global user_approved
    global current_user
    if not user_approved and job_data[0] != "!":
        print 'User not approved'
        return 'Access denied'
    if job_data and SerialManager.is_connected():
        SerialManager.queue_gcode(job_data)
        logger.log(current_user, 'Run job: '+re.sub('[\s+]', ' ', job_data)[:50])
        return "__ok__"
    else:
        return "serial disconnected"
Beispiel #23
0
def job_submit_handler():
    job_data = request.forms.get('gcode_program')
    if not job_data:
        return HTTPResponse(status=400)

    if SerialManager.is_connected():
        lines = job_data.split('\n')
        print "Adding to queue %s lines" % len(lines)
        for line in lines:
            SerialManager.queue_gcode_line(line)
        return "__ok__"
    else:
        return HTTPResponse(status=502, body="serial disconnected")
Beispiel #24
0
def set_pause(flag):
    if flag == '1':
        if SerialManager.set_pause(True):
            print "pausing ..."
            return '1'
        else:
            print "warn: nothing to pause"
            return ''
    elif flag == '0':
        print "resuming ..."
        if SerialManager.set_pause(False):
            return '1'
        else:
            return ''
Beispiel #25
0
def flash_firmware_handler(firmware_file=FIRMWARE):
    global user_approved
    global user_admin
    if not user_approved and user_admin:
        return 'Access denied'
    logger.log(current_user, 'Flashing ATMEGA')
    return_code = 1
    if SerialManager.is_connected():
        SerialManager.close()
    # get serial port by url argument
    # e.g: /flash_firmware?port=COM3
    if 'port' in request.GET.keys():
        serial_port = request.GET['port']
        if serial_port[:3] == "COM" or serial_port[:4] == "tty.":
            SERIAL_PORT = serial_port
    # get serial port by enumeration method
    # currenty this works on windows only for updating the firmware
    if not SERIAL_PORT:
        SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)
    # resort to brute force methode
    # find available com ports and try them all
    if not SERIAL_PORT:
        comport_list = SerialManager.list_devices(BITSPERSECOND)
        for port in comport_list:
            print "Trying com port: " + port
            return_code = flash_upload(port, resources_dir(), firmware_file, HARDWARE)
            if return_code == 0:
                print "Success with com port: " + port
                SERIAL_PORT = port
                break
    else:
        return_code = flash_upload(SERIAL_PORT, resources_dir(), firmware_file, HARDWARE)
    ret = []
    ret.append('Using com port: %s<br>' % (SERIAL_PORT))
    ret.append('Using firmware: %s<br>' % (firmware_file))
    if return_code == 0:
        print "SUCCESS: Arduino appears to be flashed."
        ret.append('<h2>Successfully Flashed!</h2><br>')
        ret.append('<a href="/">return</a>')
        return ''.join(ret)
    else:
        print "ERROR: Failed to flash Arduino."
        ret.append('<h2>Flashing Failed!</h2> Check terminal window for possible errors. ')
        ret.append('Most likely LasaurApp could not find the right serial port.')
        ret.append('<br><a href="/flash_firmware/'+firmware_file+'">try again</a> or <a href="/">return</a><br><br>')
        if os.name != 'posix':
            ret. append('If you know the COM ports the Arduino is connected to you can specifically select it here:')
            for i in range(1,13):
                ret. append('<br><a href="/flash_firmware?port=COM%s">COM%s</a>' % (i, i))
        return ''.join(ret)
Beispiel #26
0
class TelemHandler(object):

    def __init__(self):
        self.man = SerialManager()
        self.par = LineParser()
        self.cache = PlotCache()

    def get_data(self):
        self.man.update()
        lines = self.man.getLines()
        if len(lines) > 0:
            data = [self.par.parseLine(l) for l in lines]
            self.cache.process_data(data)
        return self.cache.get()
Beispiel #27
0
def set_pause(flag):
    if flag == '1':
        if SerialManager.set_pause(True):
            print "pausing ..."
            return '1'
        else:
            print "warn: nothing to pause"
            return ''
    elif flag == '0':
        print "resuming ..."
        if SerialManager.set_pause(False):
            return '1'
        else:
            return ''
Beispiel #28
0
def set_pause(flag):
    # returns pause status
    if flag == "1":
        if SerialManager.set_pause(True):
            print "pausing ..."
            return "1"
        else:
            return "0"
    elif flag == "0":
        print "resuming ..."
        if SerialManager.set_pause(False):
            return "1"
        else:
            return "0"
Beispiel #29
0
def set_pause(flag):
    # returns pause status
    if flag == '1':
        if SerialManager.set_pause(True):
            print "pausing ..."
            return '1'
        else:
            return '0'
    elif flag == '0':
        print "resuming ..."
        if SerialManager.set_pause(False):
            return '1'
        else:
            return '0'
Beispiel #30
0
def set_pause(flag):
    # returns pause status
    if flag == '1':
        if SerialManager.set_pause(True):
            print "pausing ..."
            return '1'
        else:
            return '0'
    elif flag == '0':
        print "resuming ..."
        if SerialManager.set_pause(False):
            return '1'
        else:
            return '0'
Beispiel #31
0
def get_status():
    status = copy.deepcopy(SerialManager.get_hardware_status())
    status['serial_connected'] = SerialManager.is_connected()
    if HARDWARE == 'raspberrypi':
      status['power'] = RPiPowerControl.get_power_status()
      status['assist_air'] = RPiPowerControl.get_assist_air_status()
      RPiPowerControl.set_process_status(status['serial_connected'] and not status['ready'])
    else:
      status['power'] = 1;
      status['assist_air'] = 1;
    status['lasaurapp_version'] = VERSION
    status['admin'] = admin_check()
    status['user'] = accessUser
    status['accounts'] = accountsTable
    status['statistics'] = statistics
    return status
Beispiel #32
0
def checkStatus():
    global lastCheck
    checkFlag = 1
    now = time.time()
    if now - lastCheck < 1.0:
      return checkFlag
    status = get_status()
    if (int(status['power']) > 0) and not status['door_open'] and status['ready'] and status['serial_connected']:
      SerialManager.queue_gcode('!\n')
      time.sleep(1.0)
      SerialManager.queue_gcode('~\nG90\nG30\n')
      checkFlag = 0
    if (int(status['power']) == 0):
      checkFlag = 0
    lastCheck = now
    return checkFlag
Beispiel #33
0
def run_with_callback(host, port):
    """ Start a wsgiref server instance with control over the main loop.
        This is a function that I derived from the bottle.py run()
    """
    handler = default_app()
    server = make_server(host,
                         port,
                         handler,
                         handler_class=HackedWSGIRequestHandler)
    server.timeout = 0.01
    server.quiet = True
    print "Persistent storage root is: " + storage_dir()
    print "-----------------------------------------------------------------------------"
    print "Bottle server starting up ..."
    print "Serial is set to %d bps" % BITSPERSECOND
    print "Point your browser to: "
    print "http://%s:%d/      (local)" % ('127.0.0.1', port)
    # if host == '':
    #     try:
    #         print "http://%s:%d/   (public)" % (socket.gethostbyname(socket.gethostname()), port)
    #     except socket.gaierror:
    #         # print "http://beaglebone.local:4444/      (public)"
    #         pass
    print "Use Ctrl-C to quit."
    print "-----------------------------------------------------------------------------"
    print
    # auto-connect on startup
    global SERIAL_PORT
    if not SERIAL_PORT:
        SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)
    SerialManager.connect(SERIAL_PORT, BITSPERSECOND)
    # open web-browser
    try:
        webbrowser.open_new_tab('http://127.0.0.1:' + str(port))
        pass
    except webbrowser.Error:
        print "Cannot open Webbrowser, please do so manually."
    sys.stdout.flush()  # make sure everything gets flushed
    while 1:
        try:
            server.handle_request()
            #tm.run()
        except KeyboardInterrupt:
            break
    print "\nShutting down..."
    SerialManager.close()
Beispiel #34
0
def set_pause(flag):
    global user_approved
    if not user_approved:
        return 'Access denied'
    # returns pause status
    if flag == '1':
        if SerialManager.set_pause(True):
            print "pausing ..."
            return '1'
        else:
            return '0'
    elif flag == '0':
        print "resuming ..."
        if SerialManager.set_pause(False):
            return '1'
        else:
            return '0'
Beispiel #35
0
def flash_firmware_handler():
    global SERIAL_PORT, GUESS_PREFIX
    return_code = 1
    if SerialManager.is_connected():
        SerialManager.close()
    # get serial port by url argument
    # e.g: /flash_firmware?port=COM3
    if "port" in request.GET.keys():
        serial_port = request.GET["port"]
        if serial_port[:3] == "COM" or serial_port[:4] == "tty.":
            SERIAL_PORT = serial_port
    # get serial port by enumeration method
    # currenty this works on windows only for updating the firmware
    if not SERIAL_PORT:
        SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)
    # resort to brute force methode
    # find available com ports and try them all
    if not SERIAL_PORT:
        comport_list = SerialManager.list_devices(BITSPERSECOND)
        for port in comport_list:
            print "Trying com port: " + port
            return_code = flash_upload(port, resources_dir())
            if return_code == 0:
                print "Success with com port: " + port
                SERIAL_PORT = port
                break
    else:
        return_code = flash_upload(SERIAL_PORT, resources_dir())
    ret = []
    ret.append("Using com port: %s<br>" % (SERIAL_PORT))
    if return_code == 0:
        print "SUCCESS: Arduino appears to be flashed."
        ret.append("<h2>Successfully Flashed!</h2><br>")
        ret.append('<a href="/">return</a>')
        return "".join(ret)
    else:
        SERIAL_PORT = None
        print "ERROR: Failed to flash Arduino."
        ret.append("<h2>Flashing Failed!</h2> Check Log window for possible errors. ")
        ret.append('Most likely LasaurApp could not find the right serial port.<br><a href="/">return</a><br><br>')
        if os.name != "posix":
            ret.append("If you know the COM ports the Arduino is connected to you can specifically select it here:")
            for i in range(1, 13):
                ret.append('<br><a href="/flash_firmware?port=COM%s">COM%s</a>' % (i, i))
        return "".join(ret)
Beispiel #36
0
def run_with_callback(host, port):
    """ Start a wsgiref server instance with control over the main loop.
        This is a function that I derived from the bottle.py run()
    """
    handler = default_app()
    server = make_server(host, port, handler, handler_class=HackedWSGIRequestHandler)
    server.timeout = 0.01
    server.quiet = True
    print "Persistent storage root is: " + storage_dir()
    print "-----------------------------------------------------------------------------"
    print "Bottle server starting up ..."
    print "Serial is set to %d bps" % BITSPERSECOND
    print "Point your browser to: "    
    print "http://%s:%d/      (local)" % ('127.0.0.1', port)  
    # if host == '':
    #     try:
    #         print "http://%s:%d/   (public)" % (socket.gethostbyname(socket.gethostname()), port)
    #     except socket.gaierror:
    #         # print "http://beaglebone.local:4444/      (public)"
    #         pass
    print "Use Ctrl-C to quit."
    print "-----------------------------------------------------------------------------"    
    print
    # auto-connect on startup
    global SERIAL_PORT
    if not SERIAL_PORT:
        SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)
    SerialManager.connect(SERIAL_PORT, BITSPERSECOND)
    # open web-browser
    try:
        webbrowser.open_new_tab('http://127.0.0.1:'+str(port))
        pass
    except webbrowser.Error:
        print "Cannot open Webbrowser, please do so manually."
    sys.stdout.flush()  # make sure everything gets flushed
    while 1:
        try:
            server.handle_request()
            #tm.run()
        except KeyboardInterrupt:
            break
    print "\nShutting down..."
    SerialManager.close()
Beispiel #37
0
def run_with_callback(host):
    """ Start a wsgiref server instance with control over the main loop.
        This is a function that I derived from the bottle.py run()
    """
    handler = default_app()
    server = wsgiref.simple_server.make_server(host, NETWORK_PORT, handler)
    server.timeout = 0.01
    server.quiet = True
    print "-----------------------------------------------------------------------------"
    print "Bottle server starting up ..."
    print "Serial is set to %d bps" % BITSPERSECOND
    print "Point your browser to: "
    print "http://%s:%d/      (local)" % ('127.0.0.1', NETWORK_PORT)
    if host == '':
        try:
            print "http://%s:%d/   (public)" % (socket.gethostbyname(
                socket.gethostname()), NETWORK_PORT)
        except socket.gaierror:
            # print "http://beaglebone.local:4444/      (public)"
            pass
    print "Use Ctrl-C to quit."
    print "-----------------------------------------------------------------------------"
    print
    try:
        webbrowser.open_new_tab('http://127.0.0.1:' + str(NETWORK_PORT))
        pass
    except webbrowser.Error:
        print "Cannot open Webbrowser, please do so manually."
    sys.stdout.flush()  # make sure everything gets flushed
    while 1:
        try:
            SerialManager.send_queue_as_ready()
            server.handle_request()
        except KeyboardInterrupt:
            break
    print "\nShutting down..."
    SerialManager.close()
Beispiel #38
0
class TestStand:
    def __init__(self):
        self.serial_manager = SerialManager()
        try:
            self.database = Database()
        except KeyError:
            print('Error loading database')
            self.abort_test()
        self.csv_logger = CSVLogger()

    # create test log directories, select a serial port and begin the test
    def start_test(self):
        self.test_num = self.database.find_next_test_number()
        self.csv_logger.test_num = self.test_num
        print(f'\nStarting test {self.csv_logger.test_num}\n')
        self.csv_logger.make_test_data_dir()
        self.csv_logger.make_test_dir()

        print('Scanning serial ports\n')
        ports = self.serial_manager.get_available_serial_ports()
        if not ports:
            print('No serial ports were found')
            self.quit_test()
        else:
            # let user select the correct serial port
            print(('Choose a port from the options below.\n'
                   'Type the number of the port and press enter:'))
            for port in ports:
                print(ports.index(port) + 1, ' - ', port)
            choice = input()
            self.port = ports[int(choice) - 1]

        print(f'Press enter to start test {self.test_num}\n')
        input()
        self.run_test()

    # connect to the serial port, start the listener thread
    def run_test(self):
        self.serial_manager.open_port(self.port)
        print("Test started!")
        try:
            while True:
                # log serial telemetry to the influx database
                data = self.serial_manager.read_telemetry()
                if data:
                    data['test_number'] = self.test_num
                    self.database.log_data(data)
        except KeyboardInterrupt:
            self.finish_test()

    # allow the user to make notes about the test, then
    # log the test's notes and data inside it's directory
    def finish_test(self):
        print()
        print("Ending test")
        results = self.database.export_test(self.test_num)
        if results:
            self.csv_logger.log_as_csv(results)

    def abort_test(self):
        try:
            self.csv_logger.delete_test_files()
        except AttributeError:
            pass
        sys.exit()
Beispiel #39
0
def get_status():
    status = copy.deepcopy(SerialManager.get_hardware_status())
    status['serial_connected'] = SerialManager.is_connected()
    return json.dumps(status)
Beispiel #40
0
def serial_handler(connect):
    if connect == '1':
        # print 'js is asking to connect serial'
        if not SerialManager.is_connected():
            try:
                global SERIAL_PORT, BITSPERSECOND, GUESS_PREFIX
                if not SERIAL_PORT:
                    SERIAL_PORT = SerialManager.match_device(
                        GUESS_PREFIX, BITSPERSECOND)
                SerialManager.connect(SERIAL_PORT, BITSPERSECOND)
                ret = "Serial connected to %s:%d." % (SERIAL_PORT,
                                                      BITSPERSECOND) + '<br>'
                time.sleep(1.0)  # allow some time to receive a prompt/welcome
                SerialManager.flush_input()
                SerialManager.flush_output()
                return ret
            except serial.SerialException:
                SERIAL_PORT = None
                print "Failed to connect to serial."
                return ""
    elif connect == '0':
        # print 'js is asking to close serial'
        if SerialManager.is_connected():
            if SerialManager.close(): return "1"
            else: return ""
    elif connect == "2":
        # print 'js is asking if serial connected'
        if SerialManager.is_connected(): return "1"
        else: return ""
    else:
        print 'ambigious connect request from js: ' + connect
        return ""
Beispiel #41
0
def longtest_handler():
    fp = open("longtest.ngc")
    for line in fp:
        SerialManager.queue_gcode_line(line)
    return "Longtest queued."
Beispiel #42
0
# Define command line argument interface
parser = argparse.ArgumentParser(
    description=
    'Stream g-code file to grbl. (pySerial and argparse libraries required)')
parser.add_argument('gcode_file',
                    type=argparse.FileType('r'),
                    help='g-code filename to be streamed')
parser.add_argument('device_file', help='serial device path')
parser.add_argument('-q',
                    '--quiet',
                    action='store_true',
                    default=False,
                    help='suppress output text')
args = parser.parse_args()

SerialManager.connect(args.device_file, 9600)
s = SerialManager
# Periodic timer to query for status reports
# TODO: Need to track down why this doesn't restart consistently before a release.
# def periodic():
#     s.write('?')
#     t = threading.Timer(0.1, periodic) # In seconds
#     t.start()

# Initialize

f = args.gcode_file
verbose = True
if args.quiet: verbose = False

# Wake up grbl
Beispiel #43
0
def get_status():
    status = copy.deepcopy(SerialManager.get_hardware_status())
    status['serial_connected'] = SerialManager.is_connected()
    status['lasaurapp_version'] = VERSION
    return json.dumps(status)
Beispiel #44
0
from __future__ import unicode_literals
import sys
from os import path

sys.path.append(path.dirname(__file__) + 'lib/')  #for generic functionality
sys.path.append(path.dirname(__file__) +
                'modules/')  #specific to various hardware

import random
import struct
from utilities import Utility
from serial_manager import SerialManager

utils = Utility()

manager = SerialManager()
print('\nSelect a port to connect to or a menu option below')
manager.list_ports()

from threads import AutoTimer, EventWrapper

from data_structures import v2_drivetrain as v2dt
from data_structures import mini_arm as marm

marm.status = ord('k')
v2dt.speed1 = 1
v2dt.speed2 = 255
v2dt.status = ord('k')


def e0():
        initialQuantity = pickle.load(open('data.pickle', 'r'))
        for index in range(len(initialQuantity)):
            dischargeQuantity[index] = initialQuantity[
                index] - totalCurrent * batteryTime / 3600
            SOC[index] = dischargeQuantity[index] / BATTERYCAPACITY
        totalQuantity = sum(dischargeQuantity)
        totalSOC = totalQuantity / (BATTERYCAPACITY * numberOfCells *
                                    numberOfStacks)
        f.write(str(totalSOC) + '\t')
        f.write('\n')
        f.close()


def infoUpdata():

    f = open('PID.txt', 'a')
    for number in range(numberOfCells * numberOfStacks):
        f.write(str(batteryTime) + '\t')
        f.write(str(voltage[number]) + '\t')
    f.write('\n')
    f.close()


if __name__ == '__main__':

    if not SERIAL_PORT:
        SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)
    SerialManager.connect(SERIAL_PORT, BITSPERSECOND)

    commandGenerator()
Beispiel #46
0
def queue_pct_done_handler():
    return SerialManager.get_queue_percentage_done()
Beispiel #47
0
        SERIAL_PORT = args.port
        print "Using serial device '" + SERIAL_PORT + "' from command line."
    else:
        print 'Please select a serialport via args'
if os.name == 'nt':  #sys.platform == 'win32':
    GUESS_PREFIX = "Arduino"
elif os.name == 'posix':
    if sys.platform == "linux" or sys.platform == "linux2":
        GUESS_PREFIX = "2341"  # match by arduino VID
    else:
        GUESS_PREFIX = "tty.usbmodem"
else:
    GUESS_PREFIX = "no prefix"

if __name__ == '__main__':
    #if not SERIAL_PORT:
    #    SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)

    SerialManager.connect(SERIAL_PORT, BITSPERSECOND)
    while SerialManager.is_connected():
        command = raw_input("Input your command>>>")
        if len(command) != 0:
            SerialManager.read_existing()  #clear rx_buffer
            if SerialManager.write(command + '\r'):
                str = SerialManager.read_to('\r')
                print(str)
            else:
                print("write error!")
                break
    print("Port closed!")
Beispiel #48
0
def get_status():
    status = copy.deepcopy(SerialManager.get_hardware_status())
    status['serial_connected'] = SerialManager.is_connected()
    status['lasaurapp_version'] = VERSION
    return json.dumps(status)
Beispiel #49
0
    pinTX = 14
    pinRX = 15
    # read sens pin
    GPIO.setup(pinSense, GPIO.IN)
    isSMC11 = GPIO.input(pinSense)
    # atmega reset pin
    GPIO.setup(pinReset, GPIO.OUT)
    GPIO.output(pinReset, GPIO.HIGH)
    # no need to setup the serial pins
    # although /boot/cmdline.txt and /etc/inittab needs
    # to be edited to deactivate the serial terminal login
    # (basically anything related to ttyAMA0)


if args.list_serial_devices:
    SerialManager.list_devices(BITSPERSECOND)
else:
    if not SERIAL_PORT:
        if args.port:
            # (1) get the serial device from the argument list
            SERIAL_PORT = args.port
            print "Using serial device '"+ SERIAL_PORT +"' from command line."
        else:
            # (2) get the serial device from the config file
            if os.path.isfile(CONFIG_FILE):
                fp = open(CONFIG_FILE)
                line = fp.readline().strip()
                if len(line) > 3:
                    SERIAL_PORT = line
                    print "Using serial device '"+ SERIAL_PORT +"' from '" + CONFIG_FILE + "'."
Beispiel #50
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_mainWindow()
        self.styleFile = open("styles.qss").read()
        self.setStyleSheet(self.styleFile)
        self.ui.setupUi(self)
        self.socketThread = None
        #self.show()
        self.listSerialDevices()
        self.ui.buttonConnect.clicked.connect(self.openMonitor)

    def openMonitor(self):
        print("opening monitor")
        self.connectToSerialDevices()
        #self.socketThread = None
        self.monitor_window = QWidget()
        self.monitor_window.setStyleSheet(self.styleFile)
        self.monitor = Ui_Monitor()
        self.monitor.setupUi(self.monitor_window)
        self.close()
        self.monitor_window.show()
        self.console = ConsoleWidget()
        self.monitor.console.addWidget(self.console)
        self.runServer()
        self.openSockets()
        self.initNFFSim()

    def listSerialDevices(self):
        comlist = serial.tools.list_ports.comports()
        for x in comlist:
            self.ui.sc_port.addItem(x.device)
            self.ui.ub_port.addItem(x.device)

    def connectToSerialDevices(self):
        sc_port = self.ui.sc_port.itemText(self.ui.sc_port.currentIndex())
        ub_port = self.ui.ub_port.itemText(self.ui.ub_port.currentIndex())
        self.serialManager = SerialManager(sc_port, ub_port,
                                           config.SERIAL_PUBLISH,
                                           config.SERIAL_SUBSCRIBE,
                                           config.SERIAL_NFF_SUBSCRIBE)
        self.serialManager.start()

    def runServer(self):
        self.server = Server(self.monitor, config.SERVER_SUBSCRIBE,
                             config.SERVER_PUBLISH)
        self.server.start()

    def openSockets(self):
        print("opening gui sockets")
        try:
            context = zmq.Context()
            self.telemSocket = context.socket(zmq.SUB)
            self.telemSocket.connect(config.GUI_SUBSCRIBE)
            self.telemSocket.setsockopt_string(zmq.SUBSCRIBE, '')

            self.commandSocket = context.socket(zmq.PUB)
            self.commandSocket.bind(config.GUI_PUBLISH)
            # print("sockets open")
        except (zmq.ZMQError, zmq.ZMQBindError) as err:
            print("Error: {}".format(err))
            return

        if (self.socketThread is not None):
            self.socketThread.terminate()
            self.socketThread.socket.close()

        self.socketThread = SocketMonitor(self.telemSocket)
        self.socketThread.signal.connect(self.gotSig)
        self.socketThread.start()

    def initNFFSim(self):
        self.nffSim = NFFSim(self.monitor, config.NFF_PUBLISH)
        self.monitor.run_sim.clicked.connect(self.nffSim.start)
        self.monitor.pause_sim.clicked.connect(self.nffSim.pause)
        self.monitor.abort_sim.clicked.connect(self.nffSim.stop)

    def gotSig(self, msg):
        #print("\nReceived New Packet...")
        # print(msg)
        for key in msg:
            # print(key)
            # print(msg[key][0])
            if self.monitor.nff_groupbox.findChild(QLabel, key):
                item = self.monitor.nff_groupbox.findChild(QLabel, key)
            elif self.monitor.sc_groupbox.findChild(QLabel, key):
                item = self.monitor.sc_groupbox.findChild(QLabel, key)
            elif self.monitor.ub_groupbox.findChild(QLabel, key):
                item = self.monitor.ub_groupbox.findChild(QLabel, key)
            else:
                continue
            item.setText(str(msg[key][0]))
            if msg[key][1] == 1:
                item.setStyleSheet('color: #f93943')  #red
            else:
                item.setStyleSheet('color: #063D23')  #green
Beispiel #51
0
def get_status():
    status = copy.deepcopy(SerialManager.get_hardware_status())
    status["serial_connected"] = SerialManager.is_connected()
    return json.dumps(status)
Beispiel #52
0
def queue_pct_done_handler():
    return SerialManager.get_queue_percentage_done()
class TestStand:
    def __init__(self):
        self.serial_manager = SerialManager()
        try:
            self.database = Database()
        except KeyError:
            print(
                'Error loading database. Did you set the TEST_STAND_DB '
                'environment variable to the name of your InfluxDB database?')
            self.abort_test()
        self.csv_logger = CSVLogger()
        # thread for interpreting incoming serial data
        self.telemetry_thread = threading.Thread(target=self.telemetry_loop)
        self.thread_is_running = False

    # create test log directories, select a serial port and begin the test
    def start_test(self):
        self.test_num = self.database.find_next_test_number()
        self.csv_logger.test_num = self.test_num
        print(f'\nStarting test {self.csv_logger.test_num}\n')
        self.csv_logger.make_test_data_dir()
        self.csv_logger.make_test_dir()

        print('Scanning serial ports\n')
        ports = self.serial_manager.get_available_serial_ports()
        if not ports:
            print('No serial ports were found')
            self.quit_test()
        else:
            # let user select the correct serial port
            print(('Choose a port from the options below.\n'
                   'Type the number of the port and press enter:'))
            for port in ports:
                print(ports.index(port) + 1, ' - ', port)
            choice = input()
            self.port = ports[int(choice) - 1]

        print(f'Ready to start test {self.test_num}\n')
        keyword = input('To begin type "start": ')
        while keyword != 'start':
            keyword = input('Wrong keyword. To begin type "start": ')
        self.run_test()

    # connect to the serial port, start the listener thread and allow the user
    # to control the solenoid with the enter/return key
    def run_test(self):
        self.serial_manager.open_port(self.port)
        self.thread_is_running = True
        self.telemetry_thread.start()
        print('Press enter to toggle solenoid')
        while True:
            if input() == 'q':
                print('\n')
                self.finish_test()
                break
            self.serial_manager.toggle_solenoid()

    # drive the solenoid low, allow the user to make notes about the test, then
    # log the test's notes and data inside it's directory
    def finish_test(self):
        if self.serial_manager.solenoid_state:
            self.serial_manager.toggle_solenoid()
            while self.serial_manager.solenoid_event_queued:
                pass
        self.thread_is_running = False
        notes = []
        note = input('Make any notes about this test below:\n')
        while note != '':
            notes.append(note)
            note = input()
        self.csv_logger.log_notes(notes)

        results = self.database.export_test(self.test_num)
        if results:
            self.csv_logger.log_as_csv(results)

    def abort_test(self):
        self.thread_is_running = False
        try:
            self.csv_logger.delete_test_files()
        except AttributeError:
            pass
        sys.exit()

    def telemetry_loop(self):
        while self.thread_is_running:
            # if there is a toggle queued for the solenoid
            if self.serial_manager.solenoid_event_queued:
                # write a 0 or 1 to the serial port to toggle the solenoid
                self.serial_manager.serial.write(
                    str(self.serial_manager.solenoid_state).encode())
                self.serial_manager.solenoid_event_queued = False
            # log serial telemetry to the influx database
            data = self.serial_manager.read_telemetry()
            if data:
                data['test_number'] = self.test_num
                self.database.log_data(data)
Beispiel #54
0
def stopBalancing(stackNum,cellNum):
    balanceCommand='S'+str(stackNum)+str(cellNum)
    SerialManager.read_existing() #clear rx_buffer
    if SerialManager.write( balanceCommand +'\r'):
        balanceStopTime=SerialManager.read_to('\r')
        print 'balance stop time is:',balanceStopTime
        
if __name__ == '__main__':
    #if not SERIAL_PORT:
    #    SERIAL_PORT = SerialManager.match_device(GUESS_PREFIX, BITSPERSECOND)
    commandGenerator();
    flag=[]
    voltage=[]
    temperature=[]
    relayStatus=0
    SerialManager.connect(SERIAL_PORT, BITSPERSECOND)
    #while SerialManager.is_connected():

    SerialManager.read_existing() #clear rx_buffer
    if SerialManager.write('C000'+'\r'):
        relayStatus=SerialManager.read_to('\r')
        print 'relay status is:',relayStatus

    SerialManager.read_existing() #clear rx_buffer
    if SerialManager.write('R000'+'\r'):
        totalVoltage=SerialManager.read_to('\r')
        print 'total voltage is:',totalVoltage
    
    SerialManager.read_existing() #clear rx_buffer
    if SerialManager.write('I000'+'\r'):
        totalCurrent=SerialManager.read_to('\r')
Beispiel #55
0
    pinExt3 = 17
    pinTX = 14
    pinRX = 15
    # read sens pin
    GPIO.setup(pinSense, GPIO.IN)
    isSMC11 = GPIO.input(pinSense)
    # atmega reset pin
    GPIO.setup(pinReset, GPIO.OUT)
    GPIO.output(pinReset, GPIO.HIGH)
    # no need to setup the serial pins
    # although /boot/cmdline.txt and /etc/inittab needs
    # to be edited to deactivate the serial terminal login
    # (basically anything related to ttyAMA0)

if args.list_serial_devices:
    SerialManager.list_devices(BITSPERSECOND)
else:
    if not SERIAL_PORT:
        if args.port:
            # (1) get the serial device from the argument list
            SERIAL_PORT = args.port
            print "Using serial device '" + SERIAL_PORT + "' from command line."
        else:
            # (2) get the serial device from the config file
            if os.path.isfile(CONFIG_FILE):
                fp = open(CONFIG_FILE)
                line = fp.readline().strip()
                if len(line) > 3:
                    SERIAL_PORT = line
                    print "Using serial device '" + SERIAL_PORT + "' from '" + CONFIG_FILE + "'."
Beispiel #56
0
def stopBalancing(stackNum,cellNum):
    balanceCommand='S'+str(stackNum)+str(cellNum)
    SerialManager.read_existing() #clear rx_buffer
    if SerialManager.write( balanceCommand +'\r'):
        balanceStopTime=SerialManager.read_to('\r')
        print 'balance stop time is:',balanceStopTime
Beispiel #57
0
def longtest_handler():
    fp = open("longtest.ngc")
    for line in fp:
        SerialManager.queue_for_sending(line)
    return "Longtest queued."