MarkoprintWiFi/MkpWIFI/protocol.py

63 lines
2.0 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 14:35:31 2019
@author: Guido Longoni - guidolongoni@gmail.com
"""
import commands as cmd
import re
def cmdString(cmdName, **cmdArgs):
cmdDict = cmd.MKPcommands[cmdName]
mandatory_args = set(cmdDict['args'])
optional_args = set(cmdDict['optargs'])
my_args = set(cmdArgs.keys())
if my_args.intersection(mandatory_args) != my_args:
raise ValueError('Argomenti obbligatori errati o mancanti.')
if len(my_args-mandatory_args-optional_args) > 0:
raise Warning('Forniti argomenti sconosciuti!')
argDict = {**{a: cmdArgs[a] for a in mandatory_args}
** {a: cmdArgs[a] if a in my_args else '' for a in optional_args}
}
return str(cmd.DEFprefix['begin'] if cmdDict['defPrefix'] else cmdDict['begin']) \
+ re.sub(r';+', ';', cmdDict['command'].format(argDict)) \
+ str(cmd.DEFprefix['end']
if cmdDict['defPrefix'] else cmdDict['end'])
def checkResponse(cmdName, response):
sucKey = 'success'
cmdDict = cmd.MKPcommands[cmdName]
if sucKey in cmdDict and cmdDict[sucKey] is not None:
if cmdDict[sucKey] == True:
error = checkError(cmdName, response)
if error is None:
return None
else:
return error
if re.match(cmdDict[sucKey], response, re.I):
return True
error = checkError(cmdName, response)
if error is None:
raise NotImplementedError(
'Ricevuta risposta sconosciuta: {}'.format(response))
else:
return error
else:
error = checkError(cmdName, response)
return error
def checkError(cmdName, response):
errKey = 'error'
cmdDict = cmd.MKPcommands[cmdName]
if errKey in cmdDict and cmdDict[errKey] is not None:
return None
error_codes = re.match(cmdDict[errKey], response, re.I)
if error_codes:
return error_codes.groups()
return None