Exemple #1
0
async def producer():
    global distributedMessage
    if (shouldUpdateMessage()):
        try:
            distributedMessage = loadJsonObject(printerStateFileName)
        except Exception as e:
            time.sleep(1)
            distributedMessage = loadJsonObject(printerStateFileName)
    await asyncio.sleep(UPDATE_INTERVAL / 1000)
    return json.dumps({
        'type': 'printer-state',
        'data': distributedMessage['printers'],
        'timestamp': distributedMessage['timestamp'],
    })
Exemple #2
0
async def run(command, printers, fileName, toolTemperature, bedTemperature):
    print('making request')
    tasks = []
    printerState = loadJsonObject(PRINTER_STATE_PATH)['printers']

    if (command == actions.COMMAND_FINISH):
        finishPrint(printers)
        return ['', 200]

    async with ClientSession() as session:
        apiRoute = ''
        if (command == actions.COMMAND_LOAD):
            apiRoute = '/api/files/local'
        elif (command == actions.COMMAND_LOAD_FILE):
            apiRoute = '/api/files/local/{0}'.format(fileName)
        elif (command == actions.COMMAND_PREHEAT):
            apiRoute = '/api/printer/{0}'
        elif (command == actions.COMMAND_SHUTDOWN):
            apiRoute = '/api/system/commands/core/shutdown'
        else:
            apiRoute = '/api/job'
        for printer in printers:
            if (canPerformCommand(command, printerState[printer]['state'])):
                url = 'http://{address}:{port}{apiRoute}'.format(
                    address=printers[printer]['address'],
                    port=printers[printer]['port'],
                    apiRoute=apiRoute)
                if (command == actions.COMMAND_LOAD):
                    task = asyncio.ensure_future(
                        sendFile(session, url, printers[printer]['apiKey'],
                                 command, fileName))
                    tasks.append(task)
                elif (command == actions.COMMAND_PREHEAT):
                    tasks.append(
                        asyncio.ensure_future(
                            sendToolCommand(session, url.format('tool'),
                                            printers[printer]['apiKey'],
                                            toolTemperature)))

                    tasks.append(
                        asyncio.ensure_future(
                            sendBedCommand(session, url.format('bed'),
                                           printers[printer]['apiKey'],
                                           bedTemperature)))
                else:
                    task = asyncio.ensure_future(
                        sendCommand(session, url, printers[printer]['apiKey'],
                                    command))
                    tasks.append(task)
            else:
                tasks.append(asyncio.ensure_future(invalidAction()))

        responses = await asyncio.gather(*tasks)
        return responses
Exemple #3
0
async def producer():
    '''
    Handles getting printer state from file
    Returns:
        str: JSON serialized printer state object
        If specified interval has passed, loads in new data into the dict
    '''
    #TODO needs review/rewrite, split into smaller parts
    global distributedMessage
    if (shouldUpdateMessage()):
        try:
            distributedMessage = loadJsonObject(printerStateFileName)
        except Exception as e:
            time.sleep(1)
            distributedMessage = loadJsonObject(printerStateFileName)
    await asyncio.sleep(UPDATE_INTERVAL / 1000)
    return json.dumps({
        'type': 'printer-state',
        'data': distributedMessage['printers'],
        'timestamp': distributedMessage['timestamp'],
    })
Exemple #4
0
def finishPrint(printers):
    fakePrinterState = loadJsonObject(FAKE_PRINTER_STATE_PATH)
    for printer in fakePrinterState:
        if (printer in printers):
            fakePrinterState[printer] = False
    writeJsonObject(FAKE_PRINTER_STATE_PATH, fakePrinterState)
Exemple #5
0
async def run():
    global previousPrinterState
    urlJobs = "http://{address}:{port}/api/job"
    urlPrinter = "http://{address}:{port}/api/printer"
    tasks = []
    config = loadConfig('config/printers.yml')
    async with ClientSession() as session:
        printers = config['printers']
        for key in config['printers']:
            task = asyncio.ensure_future(
                fetch(
                    urlJobs.format(address=printers[key]['address'],
                                   port=printers[key]['port']), session,
                    printers[key]['apiKey'], key, JOB_INFO))
            tasks.append(task)
            task = asyncio.ensure_future(
                fetch(
                    urlPrinter.format(address=printers[key]['address'],
                                      port=printers[key]['port']), session,
                    printers[key]['apiKey'], key, PRINTER_INFO))
            tasks.append(task)

        responses = await asyncio.gather(*tasks)

        data = {}
        fakePrinterState = {}
        if (os.path.isfile(FAKE_PRINTER_STATE_PATH)):
            fakePrinterState = loadJsonObject(FAKE_PRINTER_STATE_PATH)
            # print(fakePrinterState)
        else:
            for key in config['printers']:
                fakePrinterState[key] = False

        for key in config['printers']:
            response_data_printer = {}
            response_data_job = {}
            for response in responses:
                if (response[1] == key):
                    try:
                        if (response[2] == PRINTER_INFO
                                and response[0] != UNREACHABLE):
                            response_data_printer = json.loads(
                                response[0].decode('utf-8'))
                        elif (response[2] == JOB_INFO
                              and response[0] != UNREACHABLE):
                            response_data_job = json.loads(
                                response[0].decode('utf-8'))
                        else:
                            response_data_printer = UNREACHABLE
                            response_data_job = UNREACHABLE
                    except Exception as e:
                        response_data_printer = OFFLINE
                        response_data_job = OFFLINE
            if (response_data_printer != OFFLINE
                    and response_data_printer != UNREACHABLE):
                data[key] = {
                    'state':
                    'Finished' if fakePrinterState[key] == 'Finished' else
                    response_data_printer['state']['text'],
                    'progress':
                    response_data_job['progress']['completion'],
                    'nozzleTemperature':
                    response_data_printer['temperature']['tool0']['actual'],
                    'bedTemperature':
                    response_data_printer['temperature']['bed']['actual'],
                    'fileName':
                    response_data_job['job']['file']['name'],
                    'timePrinting':
                    response_data_job['progress']['printTime'],
                    'timeRemaining':
                    response_data_job['progress']['printTimeLeft'],
                }

                if (previousPrinterState):
                    if (isFinished(previousPrinterState[key], data[key])):
                        fakePrinterState[key] = 'Finished'
                        data[key]['state'] = 'Finished'

            elif (response_data_printer == OFFLINE):
                data[key] = getOfflinePrinterDictionary()
            elif (response_data_printer == UNREACHABLE):
                data[key] = getUnreachablePrinterDictionary()

        data_json = json.dumps({
            'timestamp': int(time.time()),
            'printers': data,
        })
        path = os.path.dirname(__file__)
        with open(os.path.join(path, 'data/printer-state.json'), 'w') as file:
            file.write(data_json)
        with open(os.path.join(path, FAKE_PRINTER_STATE_PATH), 'w') as file:
            file.write(json.dumps(fakePrinterState))
        previousPrinterState = data