class FileParser: def __init__(self, fileName): ''' :param fileName: ''' self.logger = Logger(logger="FileParser").getlog() try: self.config = ConfigParser() self.config.read(fileName, encoding='utf-8') except: self.logger.exception('文件名不存在,请检查配置!') def get(self, section, option): ''' :param section: :param option: :return:value ''' # 获取对应环境的配置信息,使用get('env',url) # if section == 'env': # section = self.config.get(section, 'env') # return self.config.get(section, option) return self.config.get(section, option)
def __validate_dispense_both_response( response_frame, template ): logger = Logger() logger.debug('Dispenser_LCDM4000: Validate response_frame to dispense_both : %s' % response_frame) template['status'] = response_frame[12] in [0x30, 0x31] template['error_cause'] = response_frame[12] template['upper_chk_requested_10'] = chr(response_frame[4]) template['upper_chk_requested_1'] = chr(response_frame[5]) template['upper_exit_requested_10'] = chr(response_frame[6]) template['upper_exit_requested_1'] = chr(response_frame[7]) template['lower_chk_requested_10'] = chr(response_frame[8]) template['lower_chk_requested_1'] = chr(response_frame[9]) template['lower_exit_requested_10'] = chr(response_frame[10]) template['lower_exit_requested_1'] = chr(response_frame[11]) template['upper_rejects_10'] = chr(response_frame[15]) template['upper_rejects_1'] = chr(response_frame[16]) template['upper_status'] = chr(response_frame[13]) template['lower_rejects_10'] = chr(response_frame[17]) template['lower_rejects_1'] = chr(response_frame[18]) template['lower_status'] = chr(response_frame[14]) return template
def __init__(self): self.log = Logger("main").logger() config = Config(main_cfg_path) config.cfg_load() self.port_name = config.cfg.get('Relay', 'port_name') self.port = None self.ser = None
def update(self, uid, token, refresh_token, appId=""): req = self.auth.update_token(uid, token, refresh_token, appId) Logger.info("code=%s, content=%s", req.status_code, req.json()) if not req.ok: #Logger.error("update token failed!uid=%s, token=%s, refreshToken=%s, content=%s", uid, token, refresh_token, req.content) print("update_token failed!%s" % req.json()) return None return req.json()
def login_test(self, mobile, pwd): # 尝试登录 rtn = self.login(mobile, pwd, app_id=1001) if rtn is None: Logger.error("login failed!user=%s, pwd=%s", mobile, pwd) return login_user = rtn Logger.info(rtn)
def verify_token(self, token): req = self.auth.query(token) Logger.info("code=%s, content=%s", req.status_code, req.content) if not req.ok: #Logger.error("verify user token failed!token=%s", token) print("query failed!%s" % req.json()) return False return True
def login(self, user_code, pwd, app_id=''): req = self.auth.login(user_code, pwd, app_id) Logger.info("code=%s, content=%s", req.status_code, req.json()) if not req.ok: #Logger.error("user login failed!user_code=%s,pwd=%s, msg=%s", user_code, pwd, req.content) print("login failed!%s" % req.json()) return None self.context.add_login_user(req.json()) return req.json()
class getPicList4HotMi: def __init__(self): self.logger = Logger(logger="getPicList4HotMi").getlog() def get_getPicList4HotMiURL(self,baseURL,URL,lang,timeStamp,clientVersionInfo,access_token): ''' :param baseURL: :param lang: :param timeStamp: :param clientVersionInfo: :param access_token: :return:热门推荐 ''' getPicList4HotMiURL = baseURL + URL + "?lang=%s&timeStamp=%s&clientVersionInfo=%s&access_token=%s" % (lang, timeStamp,clientVersionInfo,access_token) self.logger.info("url为:%s" %getPicList4HotMiURL) return getPicList4HotMiURL @retry(stop_max_attempt_number=5, wait_random_min=1000, wait_random_max=2000, retry_on_result=_result) def send_request_getPicList4HotMi(self,url,currentPage,pageSize,allNailSuitFlag=None): ''' :param url: :param currentPage: :param pageSize: :return: ''' headers = {"Content-Type": "application/json"} parameters = { "currentPage":currentPage, "pageSize":pageSize, "allNailSuitFlag": allNailSuitFlag } self.logger.info("请求的参数为:%s" %parameters) r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30) self.logger.info("返回的参数为:%s" % json.loads(r.text)) return json.loads(r.text) @retry(stop_max_attempt_number=5, wait_random_min=1000, wait_random_max=2000, retry_on_result=_result) def send_request_getPicList4HotMi_old(self,url,currentPage,pageSize): ''' :param url: :param currentPage: :param pageSize: :return: ''' headers = {"Content-Type": "application/json"} parameters = { "currentPage":currentPage, "pageSize":pageSize } self.logger.info("请求的参数为:%s" %parameters) r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30) self.logger.info("返回的参数为:%s" % json.loads(r.text)) return json.loads(r.text)
def logout(self, uid, token): req = self.auth.logout(token) Logger.info("code=%s, content=%s", req.status_code, req.json()) if not req.ok: #Logger.error("user logout failed!token=%s, msg=%s", token, req.content) print("login failed!%s" % req.json()) return None self.context.del_login_user(uid) return req.json()
def __init__(self): self.logger = Logger(self) self.required = ['features', 'targets', 'learning_rate'] self.checkbox = {} self.is_model_built = False self.is_data_built = False self.is_lr_changed = False for r in self.required: self.checkbox[r] = False
class KeypadApp: # pylint: disable=R0903 ## __slots__ allow us to explicitly declare data members __slots__ = ['_config_mgr', '_logger', '_log_store', '_state_object'] ## KeypadApp class constructor. # @param self The object pointer. def __init__(self): ## Instance of a configuration manager class. self._config_mgr = None self._logger = Logger() self._log_store = LogStore() self._logger.WriteToConsole = True self._logger.ExternalLogger = self self._logger.Initialise() ## Instance of the keypad state object. self._state_object = None ## Start the application, this will not exit until both the GUI and the # Twisted reactor have been destroyed. The only exception is if any # elements of the startup fail (e.g. loading the configuration). # @param self The object pointer. def start_app(self): self._config_mgr = ConfigurationManager() config = self._config_mgr.parse_config_file('configuration.json') if not config: self._logger.Log(LogType.Error, self._config_mgr.last_error_msg) return wx_app = wx.App() reactor.registerWxApp(wx_app) self._state_object = KeypadStateObject(config, self._logger) keypad_api_ctrl = KeypadApiController(config, self._state_object, self._log_store, self._logger) api_server = server.Site(keypad_api_ctrl) reactor.listenTCP(config.keypadController.networkPort, api_server) check_panel_loop = LoopingCall(self._state_object.check_panel) check_panel_loop.start(0.01, now=False) reactor.run() ## Stop the application. # @param self The object pointer. def stop_app(self): self._logger.Log(LogType.Info, 'Stopping keypad controller, cleaning up...') def add_log_event(self, current_time, log_level, msg): self._log_store.AddLogEvent(current_time, log_level, msg)
def verify_user(self, uid, token): req = self.auth.query_user(uid, token) Logger.info("code=%s, content=%s", req.status_code, req.json()) if not req.ok: #Logger.error("query user all token failed!uid=%s, token=%s, content=%s", uid, token, req.content) print("query_user failed!%s" % req.json()) return None return req.json()
def __init__(self): self.logger = Logger(self) self.is_clustering_node_by_name = False self.is_full_structure = False self.is_display_list_node_index = False self.is_save_avg_degree_connectivity = False self.clear_graph() self.hook_on_node = None self.all_avg_degree_con = {}
def __init__(self, fileName): ''' :param fileName: ''' self.logger = Logger(logger="FileParser").getlog() try: self.config = ConfigParser() self.config.read(fileName, encoding='utf-8') except: self.logger.exception('文件名不存在,请检查配置!')
def __init__(self, marketDataManager, orderManager, portfolioManager, exchangeDataListener): self.marketDataManager = marketDataManager self.orderManager = orderManager self.portfolioManager = portfolioManager self.exchangeDataListener = exchangeDataListener self.cretenExecDetlId = None self.log = Logger(logPrefix='', logForceDebug=False)
def command_dispense_several(self, cassets_info, cassets_dispense): logger = Logger() logger.debug('Dispenser_LCDM4000: Amount will be dispensed from several cassettes') # check limits upper_count = int(cassets_dispense.get(0,0)) m_upper_count = int(cassets_dispense.get(4,0)) m_lower_count = int(cassets_dispense.get(5,0)) lower_count = int(cassets_dispense.get(1,0)) logger.debug('Dispenser_LCDM4000: upper_count : %d' % upper_count) logger.debug('Dispenser_LCDM4000: m_upper_count : %d' % m_upper_count) logger.debug('Dispenser_LCDM4000: m_lower_count : %d' % m_lower_count) logger.debug('Dispenser_LCDM4000: lower_count : %d' % lower_count) ''' The number of bills to be dispensed from cassette + 0x20 ''' upper_count += 0x20 m_upper_count += 0x20 m_lower_count += 0x20 lower_count += 0x20 return [ 0x04,0x30,0x02,0x52,upper_count,m_upper_count,m_lower_count,lower_count,0x20,0x20,0x20,0x03, 0x04^0x30^0x02^0x52^upper_count^m_upper_count^m_lower_count^lower_count^0x20^0x20^0x20^0x03 ]
def __init__(self, endpoint): self._config_file = os.getenv('CENCON_CONFIG') self._curr_devices = None self.__db = os.getenv('CENCON_DB') self._device_mgr = None self._endpoint = endpoint self._event_manager = None self._log_store = LogStore() self._state_mgr = None self._worker_thread = None self._logger = Logger()
def __init__(self): ## Instance of a configuration manager class. self._config_mgr = None self._logger = Logger() self._log_store = LogStore() self._logger.WriteToConsole = True self._logger.ExternalLogger = self self._logger.Initialise() ## Instance of the keypad state object. self._state_object = None
def __init__(self, device, baudrate=9600, sleep_time=.5, timeout=0): self.device, self.timeout = device, timeout self.logger = Logger() if baudrate: self.baudrate = baudrate if sleep_time > 0: self.sleep_time = sleep_time Thread.__init__(self)
def __init__(self, appKey, tradeSrv): super(DemoModel, self).__init__(appKey, tradeSrv) self.i = 0 self.isBuy = True self.isOpen = True self.logger = Logger('demo', False) self.logger.info("INIT", self.appConfig) self.data = Data() self.tickList = self.data.getTickHistory('al', ['al1809'], '20180807 14:50:00', '20180807 15:00:00') self.logger.info("LIST", self.tickList)
class addDiyPic: def __init__(self): self.logger = Logger(logger="addDiyPic").getlog() def get_AddDiyPicURL(self,baseURL,URL,lang,timeStamp,clientVersionInfo,access_token): ''' :param baseURL: :param URL: :param lang: :param timeStamp: :param clientVersionInfo: :param access_token: :return: ''' AddDiyPicURL = baseURL + URL + "?lang=%s&timeStamp=%s&clientVersionInfo=%s&access_token=%s" % (lang, timeStamp, clientVersionInfo,access_token) self.logger.info("url为:%s" %AddDiyPicURL) return AddDiyPicURL @retry(stop_max_attempt_number=5, wait_random_min=1000, wait_random_max=2000, retry_on_result=_result) def send_request_addDiyPic(self,url,galleryName,galleryUrl,galleryThumbnailUrl,collectionType): ''' :param galleryName: :param galleryUrl: :param galleryThumbnailUrl: :param collectionType: :return: ''' headers = {"Content-Type": "application/json"} if collectionType == "社区图库": parameters = { "galleryName":galleryName, "galleryUrl":galleryUrl, "galleryThumbnailUrl":galleryThumbnailUrl, "collectionType":"2" } self.logger.info("请求的参数为:%s" %parameters) r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30) self.logger.info("返回的参数为:%s" % json.loads(r.text)) return json.loads(r.text) elif collectionType == "DIY图库并收藏": parameters = { "galleryName":galleryName, "galleryUrl":galleryUrl, "galleryThumbnailUrl":galleryThumbnailUrl, "collectionType":"3"} self.logger.info("请求的参数为:%s" %parameters) r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30) self.logger.info("返回的参数为:%s" % json.loads(r.text)) return json.loads(r.text)
def __init__(self, exchangeClient, marketRulesManager, strategyManager): self.exchangeClient = exchangeClient self.marketRulesManager = marketRulesManager self.strategyManager = strategyManager self.shapeNewOrders = True self.validateOrders = True self.preventImmediateLimitOrder = True self.liveOrderCache = {} self.liveTradeCache = {} self.log = Logger()
class single: def __init__(self): self.logger = Logger(logger="single").getlog() def get_singleURL(self, baseurl,url, lang, timeStamp, clientVersionInfo,access_token): ''' :param url: :param lang: :param timeStamp: :param clientVersionInfo: :return: ''' singleURL = baseurl+ url + "?lang=%s&timeStamp=%s&clientVersionInfo=%s&access_token=%s" % (lang, timeStamp, clientVersionInfo,access_token) self.logger.info("url为:%s" %singleURL) return singleURL def send_request_single(self,url,targetid,filename,filepath): ''' :param url: :param targetid: :param filename: :param filepath: :return: ''' proportion = False files = {"file":(filename,open(filepath,"rb"),"multipart/form-data",{})} if targetid == "社区": data = {"targetid":"48d1cd1ef8d846d98897cf68f12dba01", "sizes":"240x360", "proportion":proportion} elif targetid == "头像": data = {"targetid":"329ad03f9c6c4db59caffbbe3b02e1e6", "sizes":"240x360", "proportion":proportion} elif targetid =="甲面": data = {"targetid":"6e9800a33d364c298a9e515ac3a2a9bc", "sizes":"240x360", "proportion":proportion} elif targetid == "DIY": data = {"targetid":"cb8b8835e5f84249958f01d1b2f47b07", "sizes":"240x360", "proportion":proportion} elif targetid == "系统": data = {"targetid":"4305685b17aa11e9b53f005056ad4128", "sizes":"240x360", "proportion":proportion} else: self.logger.error("targetid不存在,请检查配置!") self.logger.info("请求的参数为:%s" % data) r = requests.request("post",url,data = data,files=files,timeout=30) re = r.text josnre = json.loads(re) self.logger.info("返回的参数为:%s" % json.loads(r.text)) pictureDict= { "galleryName" :josnre["data"]["pictureName"], "galleryThumbnailUrl" :josnre["data"]["thumbnailPictureUrl"], "galleryUrl" :josnre["data"]["pictureUrl"] } return pictureDict
def validate_status_response(self, status_frame): logger = Logger() logger.debug('Dispenser_LCDM1000: Validate status_frame %s. Len is %d' % (status_frame, len(status_frame))) # Pop ACK status_frame.pop(0) response = { 'status' : True, 'error_cause' : "%X" % status_frame[5] , 'sensor_0' : "%X" % status_frame[6], 'sensor_1' : "%X" % status_frame[7] } return response
def command_dispense_single(self, cassets_info, id_cash_box, count): logger = Logger() count_10 = min(int(count * 1. / 10), self.dispense_limit_single_10) count_1 = min(count - count_10 * 10, self.dispense_limit_single_1) logger.debug( 'Corrected counts: 10 (%d), 1 (%d)' % (count_10, count_1) ) count_10 = ord("%s" % count_10) count_1 = ord("%s" % count_1) return [ 0x04,0x50,0x02,0x45,count_10,count_1,0x03, 0x04^0x50^0x02^0x45^count_10^count_1^0x03 ]
def validate_status_response(self, status_frame): logger = Logger() logger.debug('Dispenser_LCDM2000: Validate status_frame %s. Len is %d' % (status_frame, len(status_frame))) # Pop ACK status_frame.pop(0) response = { 'status' : True, 'error_cause' : "%X" % status_frame[5] , 'sensor_0' : "%X" % status_frame[6], 'sensor_1' : "%X" % status_frame[7] } return response
def command_dispense_single(self, cassets_info, id_cash_box, count): logger = Logger() count_10 = min(int(count * 1. / 10), self.dispense_limit_single_10) count_1 = min(count - count_10 * 10, self.dispense_limit_single_1) logger.debug('Corrected counts: 10 (%d), 1 (%d)' % (count_10, count_1)) count_10 = ord("%s" % count_10) count_1 = ord("%s" % count_1) return [ 0x04, 0x50, 0x02, 0x45, count_10, count_1, 0x03, 0x04 ^ 0x50 ^ 0x02 ^ 0x45 ^ count_10 ^ count_1 ^ 0x03 ]
def __init__(self): # init loggging logger = Logger('dwgetd',2001, '127.0.0.1', True) logger.addStuff(self.__driver) dispatcher.connect(self.newSlave, signal = 'NEW_SLAVE', sender = 'masterMainThread') dispatcher.connect(self.delSlave, signal = 'DEL_SLAVE', sender = 'masterMainThread') dispatcher.connect(self.newDownload, signal = 'NEW_DOWNLOAD', sender = 'masterMainThread') dispatcher.connect(self.__reply, signal = 'REPLY_SOCKET', sender = 'masterMainThread') dispatcher.connect(self.listSlaves, signal = 'LIST_SLAVES', sender = 'masterMainThread') dispatcher.connect(self.listTasks, signal = 'LIST_TASKS', sender = 'masterMainThread') self.__thread = MainThread() self.__thread.start()
def validate_status_response(self, status_frame): logger = Logger() logger.debug('Dispenser_LCDM4000: Validate status_frame %s. Len is %d' % (status_frame, len(status_frame))) # Pop ACK status_frame.pop(0) response = { 'status' : True, 'error_cause' : "%X" % status_frame[5], 'sensor_0' : "%X" % status_frame[6], # Upper 'sensor_1' : "%X" % status_frame[9], # Middle upper 'sensor_2' : "%X" % status_frame[12], # Middle lower 'sensor_3' : "%X" % status_frame[15], # Lower } return response
def get_dispense(self, amount, cassets_info): self.logger = Logger() ''' Method calculates cash dispensing between cassets amount: Amount to dispense cassets_info: Cassets infrormation in format {id_cassete : {'command' : 0x45, 'denomination' : 0, 'charging' : 100, 'position' : 'upper'},...} return { 'to_dispense' : 5, 'cassets' : { 0 : {'amount' : 100, 'count' : 10, 'denomination' : 10}, 1 : {'amount' : 1000, 'count' : 10, 'denomination' : 100}, ... } } ''' dispense = {'to_dispense': amount, 'cassets': {}} # Dynamic cassets information cassets = ([cassete_info['denomination'] for cassete_info in cassets_info.values()]) cassets.sort() while dispense['to_dispense'] > 0 and len( cassets ): self.logger.debug('[DISPENSER]: Amount to dispense: %s' % dispense['to_dispense']) self.logger.debug('[DISPENSER]: Next cassets are available: %s' % cassets_info) # select max denomination denomination = cassets.pop() self.logger.debug( '[DISPENSER]: selected denomination: %s' % denomination ) id_cassete = self.get_cassete_by_denomination( cassets_info, denomination ) # if no available cassets if id_cassete == -1: self.logger.debug('[DISPENSER]: no more cassets are available to dispense amount %s' % dispense['to_dispense']) continue # check count of banknotes banknotes_count = min( int( dispense['to_dispense'] * 1. / denomination ), # Count of full-dispensing cassets_info[id_cassete]['charging'], # Count of available banknotes self.dispense_limit # Dispenser limit ) # If no more banknotes if not banknotes_count: self.logger.debug( '[DISPENSER]: no such banknotes in cassete #%d' % id_cassete ) continue self.logger.debug( '[DISPENSER]: from selected cassete #%d will exit %d banknotes with denomination %d' % (id_cassete, banknotes_count, denomination) ) dispense['cassets'][id_cassete] = banknotes_count dispense['to_dispense'] -= banknotes_count * denomination return dispense
class queryUserInfoList: def __init__(self): self.logger = Logger(logger="queryUserInfoList").getlog() self.base = baseUtils() def get_queryUserInfoListURL(self,env,access_token): ''' :param baseURL: :param lang: :param timeStamp: :param clientVersionInfo: :return: ''' URL = "/user/userInfo/queryUserInfoList" if env == "dev": baseurl = "https://oc-api-dev.nailtutu.com" elif env == "uat": baseurl = "https://oc-api-uat.nailtutu.com" elif env == "prod": baseurl = "https://oc-api.nailtutu.com" else: self.logger.info("你输入的参数有误,请检查配置") ReallyURL = baseurl + URL + "?access_token=%s&lang=zh&timeStamp=%s" % (access_token,self.base.getTimeStamp()) self.logger.info("url为:%s" %ReallyURL) return ReallyURL def send_request_queryUserInfoList(self,url,nickname): ''' 用户查询列表 :param url: :param nickname: :return: ''' headers = {"Content-Type": "application/json"} parameters = { "userType":2, "username": "", "nickname": nickname, "mobile": "", "email": "", "userStatus": "0", "currentPage": 1, "pageSize": "20" } self.logger.info("请求的参数为:%s" %parameters) r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30) self.logger.info("返回的参数为:%s" % json.loads(r.text)) return json.loads(r.text)
def __init__(self, exchangeClient, marketDataManager, marketRulesManager, portfolioManager, orderManager): self.exchangeClient = exchangeClient self.marketDataManager = marketDataManager self.marketRulesManager = marketRulesManager self.portfolioManager = portfolioManager self.orderManager = orderManager self.candleSubscriptions = [] self.candleListenerCallbackMap = {} self.callbackPortfolio = None self.callbackOrders = None self.cretenExecDetlId = None self.lock = RLock() self.log = Logger()
class StrategyExecutor(object): def __init__(self): self.strategies = [] self.log = Logger() def addStrategy(self, strategy): self.strategies.append(strategy) def getStrategies(self): return self.strategies def execute(self, candle): self.log.debug('Processing candle: ' + str(candle)) # TODO should catch exceptions otherwise one faulty strategy will break all the remaining ones for strategy in self.strategies: strategy.execute(candle)
def __init__(self): self.log = Logger("main").logger() self.ard = Arduino() self.process = DataProcess() self.r = Relay() self.keyword = ParseCSV('../testfile/testcase/{}_keyword.csv'.format( self.ard.project)) config = Config('../config/{}.ini'.format(self.ard.project)) config.cfg_load() self.led_num = config.cfg.getint('config', 'led') self.power_button = config.cfg.get('config', 'power_button') m_cfg = Config(main_cfg_path) m_cfg.cfg_load() self.led1_data = m_cfg.cfg.get('Data', 'led1') self.sound_data = m_cfg.cfg.get('Data', 'sound') if not self.r.init_relay(): self.log.error('Something is wrong with your relay!') sys.exit()
def validate_status_response(self, status_frame): logger = Logger() logger.debug( 'Dispenser_LCDM4000: Validate status_frame %s. Len is %d' % (status_frame, len(status_frame))) # Pop ACK status_frame.pop(0) response = { 'status': True, 'error_cause': "%X" % status_frame[5], 'sensor_0': "%X" % status_frame[6], # Upper 'sensor_1': "%X" % status_frame[9], # Middle upper 'sensor_2': "%X" % status_frame[12], # Middle lower 'sensor_3': "%X" % status_frame[15], # Lower } return response
def command_dispense_single(self, cassets_info, id_cash_box, count): logger = Logger() logger.debug('Dispenser_LCDM4000: Request to dispense will be converted from single to multi dispense') CASSETE_ID_UPPER = 0 CASSETE_ID_LOWER = 1 CASSETE_ID_MIDDLE_UPPER = 4 CASSETE_ID_MIDDLE_LOWER = 5 cassets_dispense = { CASSETE_ID_UPPER : 0, CASSETE_ID_LOWER : 0, CASSETE_ID_MIDDLE_UPPER : 0, CASSETE_ID_MIDDLE_LOWER : 0, } cassets_dispense[id_cash_box] = count return self.command_dispense_several(cassets_info, cassets_dispense)
class queryTagInfo: def __init__(self): self.logger = Logger(logger="queryTagInfo").getlog() self.base = baseUtils() def get_queryTagInfoURL(self,env,access_token): ''' :param baseURL: :param lang: :param timeStamp: :param clientVersionInfo: :return: ''' URL = "/oc/tOcTagInfo/queryTagInfo" if env == "dev": baseurl = "https://oc-api-dev.nailtutu.com" elif env == "uat": baseurl = "https://oc-api-uat.nailtutu.com" elif env == "prod": baseurl = "https://oc-api.nailtutu.com" else: self.logger.info("你输入的参数有误,请检查配置") ReallyURL = baseurl + URL + "?access_token=%s&lang=zh&timeStamp=%s" % (access_token,self.base.getTimeStamp()) self.logger.info("url为:%s" %ReallyURL) return ReallyURL def send_request_queryTagInfo(self,url,tagName,currentPage=1,pageSize=15): ''' 查询标签信息 :param url: :param tagName: :param tagDescribe: :param sortNumber: :return: ''' headers = {"Content-Type": "application/json"} parameters = { "tagName":tagName, "currentPage":1, "pageSize":100, "orderBy":"sort_number DESC,modify_time DESC", "beginDate":None, "endDate":None } self.logger.info("请求的参数为:%s" %parameters) r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30) self.logger.info("返回的参数为:%s" % json.loads(r.text)) return json.loads(r.text)
def __init__ (self, device, baudrate = 9600, sleep_time = .5, timeout = 0): self.device, self.timeout = device, timeout self.logger = Logger() if baudrate: self.baudrate = baudrate if sleep_time > 0: self.sleep_time = sleep_time Thread.__init__(self)
def validate_dispense_response(self, response_frame): logger = Logger() logger.debug('Dispenser_LCDM1000: validate "Dispense" response frame %s' % response_frame) template = { 'status' : False, 'error_cause' : 0, 'upper_chk_requested_10' : 0, 'upper_chk_requested_1' : 0, 'upper_exit_requested_10' : 0, 'upper_exit_requested_1' : 0, 'upper_rejects_10' : 0, 'upper_rejects_1' : 0, 'upper_status' : 0, 'lower_chk_requested_10' : 0, 'lower_chk_requested_1' : 0, 'lower_exit_requested_10' : 0, 'lower_exit_requested_1' : 0, 'lower_rejects_10' : 0, 'lower_rejects_1' : 0, 'lower_status' : 0 } # Hook response_frame[3] = int(response_frame[3]) # Error while dispensing if len(response_frame) == 7: logger.debug('Dispenser_LCDM1000: len(response_frame) == 7') return False if len(response_frame) == 21: return self.__validate_dispense_both_response(response_frame, template) if response_frame[3] in [0x45, 0x55]: return self.__validate_dispense_single_response(response_frame, template)
def __init__(self, dispenser_model, port=False, baudrate=False, timeout=0.6, parity=False): if dispenser_model not in self.DISPENSERS: raise DispenserError("%s is not supported. See DispenserController.DISPENSERS for available dispensers.") self.logger = Logger() self.dispenser = self.__import_class( self.DISPENSERS[dispenser_model]["path"], self.DISPENSERS[dispenser_model]["class"] )() # Set data if port: self.dispenser.port = port if baudrate: self.dispenser.baudrate = baudrate if timeout: self.dispenser.timeout = timeout if parity: self.dispenser.parity = parity
def createExtensionIndex(*args): socket.setdefaulttimeout(TIMEOUT) indexdir = args[0] product = args[1] START_WORDS = "{\n\"extension_index\":[\n" cur_time = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())) root_spe_dir = os.path.join(indexdir,"spe"+cur_time) root_log_dir = os.path.join(indexdir, LOG_DIR_NAME) try: os.mkdir(root_spe_dir) extLogger = Logger(os.path.join(root_log_dir,LOG_INFO),'extLogger') extLogger.info("CreateExtensionIndex script start ...") except IOError as e: raise IOError("IOError: Need permission to write in "+indexdir) index_for_extension = START_WORDS whole_product_name = getWholeProductName(product) extLogger.info("start to get repo data from github ...") ext_output_path = os.path.join(indexdir, RAW_INDEX_FILE) i=0 ok_repo_num = 0 try: githubApiInfo_obj = GithubApiInfoObj() for item in githubApiInfo_obj.item_list: i+=1 index_for_extension_item = INDENT+"{\n" index_for_extension_item += generateJSONStr(item) repo_name = item[githubApiInfo_obj.__class__.REPOSITORY].val extLogger.info(str(i)+" repo: "+repo_name) try: info_json = InfoJSONObj(repo_name) except ValueError as e: raise e except Exception as e: extLogger.warning(str(e)) continue index_for_extension_item += generateJSONStr(info_json.item_list) repo_software = info_json.item_list[info_json.__class__.SOFTWARE].val index_for_extension_item += INDENT*2 + "\"download_link\":" +"\"" + re.sub('repos_name', repo_name, SPE_DOWNLOAD_URL) +"\",\n" index_for_extension_item += INDENT*2 + "\"image_link\":" +"\"" + re.sub('repos_name', repo_name, IMG_DOWNLOAD_URL) +"\",\n" if repo_software != whole_product_name: extLogger.info("This is not a " + whole_product_name + " repo. Switch to next repo.") continue repo_spe_url = re.sub('repos_name', repo_name, SPE_DOWNLOAD_URL) spe_name = repo_name+".spe" spe_saving_path = os.path.join(root_spe_dir,repo_name) os.mkdir(spe_saving_path) try: urllib.request.urlretrieve(repo_spe_url, os.path.join(spe_saving_path,spe_name)) srcZip = zipfile.ZipFile(os.path.join(spe_saving_path,spe_name), "r", zipfile.ZIP_DEFLATED) except: extLogger.warning("This repo '"+repo_name+" does not have spe package. Please check! Switch to next repo.") continue for file in srcZip.namelist(): if not os.path.isdir(spe_saving_path): os.mkdir(spe_saving_path) if FILE_NAME in file: srcZip.extract(file, spe_saving_path) srcZip.close() meta_path = os.path.join(spe_saving_path, META_DIR, FILE_NAME) metaObj = MetaObj(meta_path) index_for_extension_item += metaObj.generateExtensionJSON() index_for_extension_item += INDENT + "},\n" index_for_extension += index_for_extension_item ok_repo_num += 1 extLogger.info("Successfully get data!") index_for_extension = index_for_extension[0:-2] index_for_extension += '\n]\n}' index_for_extension_fp = open(ext_output_path,'w', encoding='utf-8') index_for_extension_fp.write(index_for_extension) index_for_extension_fp.close() extLogger.info("CreateIndexForDownloadExtensiosn action succeeded!") extLogger.info("Extension index file has been saved in "+ext_output_path) except Exception as e: extLogger.error(str(e), e) extLogger.info("CreateIndexForDownloadExtensiosn action failed!") raise e finally: extLogger.info("Totally get "+str(ok_repo_num)+" repo data.") clear(root_spe_dir) if not os.path.exists(ext_output_path): raise Exception("Fail to create extension index file! Please contact github administrator!") return ext_output_path
def CreateIndex(*args): print("size"+str(len(args))) outdir = args[0] product = args[1] if product == "modeler": repos_set_uri = RAW_REPOS_SET_URI.format('modeler','modeler') index_key = RAW_INDEX_KEY.format('modeler') elif product == 'stats': # wrong spell of statistics repos_set_uri = RAW_REPOS_SET_URI.format('statisitcs','stats') index_key = RAW_INDEX_KEY.format('stats') try: lic_path = os.path.join(outdir,LICENSE_DIR) os.mkdir(lic_path) logger = Logger(os.path.join(lic_path,LOG_INFO)) logger.info("Script start ...") except IOError as e: raise IOError("IOError: Need permission to write in "+outdir) try: try: repos_set_json = json.loads(URILoader.loadURI(repos_set_uri, "index file")) except ValueError as e: raise Exception("ValueError: The {0} has an illegal format. Please check!\n\n".format("index file")) except Exception as e: raise e try: repos_set_json_index = repos_set_json[index_key] except Exception as e: raise e license_obj_list = [] for repo in repos_set_json_index: try: repo_name = repo["repository"] except Exception: raise Exception("At least one repository in index file does not have repo name. Please check!\n\n") repo_license_uri = RAW_LICENSE_URI.format(repo_name) try: repo_license_content = URILoader.loadURI(repo_license_uri, "license file") except Exception as e: raise e isExistedLicense = False for item in license_obj_list: if repo_license_content == item.getLicenseContent(): isExistedLicense = True item.addRepoName(repo_name) break if not isExistedLicense: addObj(repo_name, repo_license_content,license_obj_list) print("Start to read license...") index_content = "{\n"+INDENT+"\"license_index\": [\n"; for obj in license_obj_list: index_item_str = LicenseIndexItemStr.getItemStr(obj) index_content += index_item_str license_fp = open(os.path.join(lic_path,obj.getLicenseName()),'w') license_fp.write(obj.getLicenseContent()) license_fp.close() index_content = index_content[0:-2] index_content += '\n' + INDENT + "]\n}" print("Start to write license to text...") index_fp = open(os.path.join(lic_path,'license_index.json'),'w') index_fp.write(index_content) except Exception as e: logger.error(str(e))
def createLangIndex(*args): outdir = args[0] ext_path = args[1] index_key = RAW_INDEX_KEY langLogger = None try: lang_path = os.path.join(outdir,LANG_DIR) os.mkdir(lang_path) root_log_dir = os.path.join(outdir, LOG_DIR_NAME) langLogger = Logger(os.path.join(root_log_dir,LOG_INFO),'langLogger') langLogger.info("CreateLicenseIndex script start ...") langLogger.info("Get extension index ...") repos_set_json = loadExtJSONContent(ext_path) repos_set_json_index = repos_set_json[index_key] for lang_item in LANG_LIST: fp_content = LANG_INDEX_PRE langLogger.info("Start to get '"+lang_item+"' file") i=0 for repo in repos_set_json_index: try: repo_name = repo["repository"] i+=1 except Exception: raise Exception("At least one repository in index file does not have repo name. Please check!") repo_lang_uri = RAW_REPO_LANG_URI.format(repo_name, lang_item) try: repo_lang_content = URILoader.loadURI(repo_lang_uri, "language index file") lang_json_str = LangPropObj.convertToJSONStr(repo_name, repo_lang_content, lang_item) except Exception as e: if 'HTTPError' in str(e): # some repositories do not have lang file, by default use en file in index for extension file summary = "" if 'Summary' in repo[EXT_KEY].keys(): summary = repo[EXT_KEY]['Summary'] desc = "" if 'Description' in repo[EXT_KEY].keys(): desc = repo[EXT_KEY]['Description'] lang_json_str = LangPropObj.generateJSONStr(repo_name,summary,desc) else: raise e fp_content += lang_json_str try: fp_content = fp_content[0:-2]+'\n'+INDENT+']\n}' fp = open(os.path.join(lang_path, lang_item+'.json'), 'w', encoding='utf-8') fp.write(fp_content) fp.close() except Exception as e: raise e except Exception as e: if langLogger!=None: langLogger.error(str(e),e) langLogger.info("CreatelangIndex action failed!") raise e finally: if langLogger!=None: langLogger.close()
def validate_dispense_response(self, response_frame): logger = Logger() logger.debug('Dispenser_LCDM4000: validate "Dispense" response frame %s' % (["0x%02X" % x for x in response_frame])) template = { 'status' : False, 'error_cause' : response_frame[4], 'miss' : response_frame[5], 'upper_exit_requested_1' : response_frame[6] - 0x20, 'upper_exit_requested_10' : 0, 'upper_chk_requested_1' : response_frame[6] - 0x20, 'upper_chk_requested_10' : 0, 'upper_rejects_1' : chr(response_frame[7] - 0x20), 'upper_rejects_10' : 0, 'type_1' : chr(response_frame[8]), 'm_upper_exit_requested_1' : response_frame[9] - 0x20, 'm_upper_exit_requested_10' : 0, 'm_upper_chk_requested_1' : response_frame[9] - 0x20, 'm_upper_chk_requested_10' : 0, 'm_upper_rejects_1' : chr(response_frame[10] - 0x20), 'm_upper_rejects_10' : 0, 'type_2' : chr(response_frame[11]), 'm_lower_exit_requested_1' : response_frame[12] - 0x20, 'm_lower_exit_requested_10' : 0, 'm_lower_chk_requested_1' : response_frame[12] - 0x20, 'm_lower_chk_requested_10' : 0, 'm_lower_rejects_1' : chr(response_frame[13] - 0x20), 'm_lower_rejects_10' : 0, 'type_3' : chr(response_frame[14]), 'lower_exit_requested_1' : response_frame[15] - 0x20, 'lower_exit_requested_10' : 0, 'lower_chk_requested_1' : response_frame[15] - 0x20, 'lower_chk_requested_10' : 0, 'lower_rejects_1' : chr(response_frame[16] - 0x20), 'lower_rejects_10' : 0, 'type_4' : chr(response_frame[17]), 'rsv' : 0, 'etx' : 0, 'bcc' : 0 } for k,v in template.items(): logger.debug(' > %s => %s' % (k,v)) return template if len(response_frame) == 21: logger.debug('Allright. Len response_frame is 21') else: logger.debug('Allright. Len response_frame is %s. Frame is %s' % (len(response_frame), (["%02x" % x for x in response_frame]) ) ) for k, v in template.items(): logger.debug(" ]]] %s: %s" % (k, v)) return False # Error while dispensing if len(response_frame) == 7: logger.debug('Dispenser_LCDM4000: len(response_frame) == 7') return False if len(response_frame) == 21: return self.__validate_dispense_both_response(response_frame, template) if response_frame[3] in [0x45, 0x55]: return self.__validate_dispense_single_response(response_frame, template)
def createIndex(*args): indexdir = args[0] product = args[1] START_WORDS = '{\n"productname_extension_index":[\n' cur_time = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) root_spe_dir = os.path.join(indexdir, "spe" + cur_time) try: os.mkdir(root_spe_dir) logger = Logger(os.path.join(indexdir, LOG_INFO)) logger.info("Script start ...") except IOError as e: raise IOError("IOError: Need permission to write in " + indexdir) index_for_extension = re.sub("productname", product, START_WORDS) whole_product_name = getWholeProductName(product) print("start to get repo data from github ...") logger.info("start to get repo data from github ...") i = 0 ok_repo_num = 0 try: githubApiInfo_obj = GithubApiInfoObj() for item in githubApiInfo_obj.item_list: i += 1 print(i) index_for_extension_item = INDENT + "{\n" index_for_extension_item += generateJSONStr(item) repo_name = item[githubApiInfo_obj.__class__.REPOSITORY].val logger.info(str(i) + "th repo: " + repo_name) print(repo_name) try: info_json = InfoJSONObj(repo_name) except ValueError as e: raise e except Exception as e: print(str(e)) logger.warning(str(e)) continue index_for_extension_item += generateJSONStr(info_json.item_list) repo_software = info_json.item_list[info_json.__class__.SOFTWARE].val index_for_extension_item += ( INDENT * 2 + '"download_link":' + '"' + re.sub("repos_name", repo_name, SPE_DOWNLOAD_URL) + '",\n' ) index_for_extension_item += ( INDENT * 2 + '"image_link":' + '"' + re.sub("repos_name", repo_name, IMG_DOWNLOAD_URL) + '",\n' ) if repo_software != whole_product_name: print("This is not a " + whole_product_name + " repo.\nSwitch to next repo.\n\n\n") logger.info("This is not a " + whole_product_name + " repo.\nSwitch to next repo.") continue repo_spe_url = re.sub("repos_name", repo_name, SPE_DOWNLOAD_URL) spe_name = repo_name + ".spe" spe_saving_path = os.path.join(root_spe_dir, repo_name) os.mkdir(spe_saving_path) try: urllib.request.urlretrieve(repo_spe_url, os.path.join(spe_saving_path, spe_name)) srcZip = zipfile.ZipFile(os.path.join(spe_saving_path, spe_name), "r", zipfile.ZIP_DEFLATED) except: print( "This repo '" + repo_name + "' does not have spe package. Please check!" + "\nSwitch to next repo.\n\n\n" ) logger.warning( "This repo '" + repo_name + "' does not have spe package. Please check!" + "\nSwitch to next repo." ) continue for file in srcZip.namelist(): if not os.path.isdir(spe_saving_path): os.mkdir(spe_saving_path) if FILE_NAME in file: srcZip.extract(file, spe_saving_path) srcZip.close() meta_path = os.path.join(spe_saving_path, META_DIR, FILE_NAME) metaObj = MetaObj(meta_path) index_for_extension_item += metaObj.generateExtensionJSON() index_for_extension_item += INDENT + "},\n" index_for_extension += index_for_extension_item print("Successfully get data!\n\n") ok_repo_num += 1 logger.info("Successfully get data!\n") index_for_extension = index_for_extension[0:-2] index_for_extension += "\n]\n}" index_for_extension_fp = open(os.path.join(indexdir, INDEX_FILE), "w") index_for_extension_fp.write(index_for_extension) index_for_extension_fp.close() except Exception as e: print(str(e)) logger.error(str(e)) finally: print("Totally get " + str(ok_repo_num) + " repo data successfully!\n\n") logger.info("Totally get " + str(ok_repo_num) + " repo data successfully!") clear(root_spe_dir)
class Dispenser: ''' Configuration ''' port = '/dev/ttyUSB' baudrate = 9600 timeout = 1 data_bits = 8 # 8 bits stop_bits = 1 # 1 bit parity = serial.PARITY_NONE # No parity bps = 3.5 # Banknotes per second ''' Limits for dispensing ''' dispense_limit_single_10 = 6 dispense_limit_single_1 = 9 dispense_limit_both_10 = 6 dispense_limit_both_1 = 9 dispense_limit = 60 # Limit banknotes count for dispensing from 1 cassete ''' PROTOCOL > CONSTANTS ''' p_soh = 0x01 # Start of Header p_stx = 0x02 # Start of Text p_etx = 0x03 # End of Text p_eot = 0x04 # Start of Transmission p_ack = 0x06 # ACK p_nck = 0x15 # NCK p_id = 0x50 # Communication ID p_bcc = 0x00 # Block Check Character: BCC can be gotten through Exclusive-OR (XOR) from the start of each message to ETX @staticmethod def get_cassete_by_denomination(cassets, denomination): for id_cassete, cassete_info in cassets.items(): if cassete_info['denomination'] == denomination: return id_cassete return -1 def get_dispense(self, amount, cassets_info): self.logger = Logger() ''' Method calculates cash dispensing between cassets amount: Amount to dispense cassets_info: Cassets infrormation in format {id_cassete : {'command' : 0x45, 'denomination' : 0, 'charging' : 100, 'position' : 'upper'},...} return { 'to_dispense' : 5, 'cassets' : { 0 : {'amount' : 100, 'count' : 10, 'denomination' : 10}, 1 : {'amount' : 1000, 'count' : 10, 'denomination' : 100}, ... } } ''' dispense = {'to_dispense': amount, 'cassets': {}} # Dynamic cassets information cassets = ([cassete_info['denomination'] for cassete_info in cassets_info.values()]) cassets.sort() while dispense['to_dispense'] > 0 and len( cassets ): self.logger.debug('[DISPENSER]: Amount to dispense: %s' % dispense['to_dispense']) self.logger.debug('[DISPENSER]: Next cassets are available: %s' % cassets_info) # select max denomination denomination = cassets.pop() self.logger.debug( '[DISPENSER]: selected denomination: %s' % denomination ) id_cassete = self.get_cassete_by_denomination( cassets_info, denomination ) # if no available cassets if id_cassete == -1: self.logger.debug('[DISPENSER]: no more cassets are available to dispense amount %s' % dispense['to_dispense']) continue # check count of banknotes banknotes_count = min( int( dispense['to_dispense'] * 1. / denomination ), # Count of full-dispensing cassets_info[id_cassete]['charging'], # Count of available banknotes self.dispense_limit # Dispenser limit ) # If no more banknotes if not banknotes_count: self.logger.debug( '[DISPENSER]: no such banknotes in cassete #%d' % id_cassete ) continue self.logger.debug( '[DISPENSER]: from selected cassete #%d will exit %d banknotes with denomination %d' % (id_cassete, banknotes_count, denomination) ) dispense['cassets'][id_cassete] = banknotes_count dispense['to_dispense'] -= banknotes_count * denomination return dispense
def createLangIndex(*args): outdir = args[0] ext_path = args[1] # if product == "modeler": # index_key = RAW_INDEX_KEY.format('modeler') # elif product == 'stats': # index_key = RAW_INDEX_KEY.format('stats') index_key = RAW_INDEX_KEY langLogger = None try: lang_path = os.path.join(outdir, LANG_DIR) os.mkdir(lang_path) root_log_dir = os.path.join(outdir, LOG_DIR_NAME) langLogger = Logger(os.path.join(root_log_dir, LOG_INFO), "langLogger") langLogger.info("CreateLicenseIndex script start ...") langLogger.info("Get extension index ...") repos_set_json = loadExtJSONContent(ext_path) repos_set_json_index = repos_set_json[index_key] for lang_item in LANG_LIST: fp_content = LANG_INDEX_PRE langLogger.info("Start to get '" + lang_item + "' file") i = 0 for repo in repos_set_json_index: try: repo_name = repo["repository"] i += 1 langLogger.info(lang_item + ": " + str(i) + " repo " + repo_name) except Exception: raise Exception("At least one repository in index file does not have repo name. Please check!") repo_lang_uri = RAW_REPO_LANG_URI.format(repo_name, lang_item) try: repo_lang_content = URILoader.loadURI(repo_lang_uri, "language index file") lang_json_str = LangPropObj.convertToJSONStr(repo_name, repo_lang_content, lang_item) except Exception as e: if "HTTPError" in str(e): # some repositories do not have lang file, by default use en file in index for extension file lang_json_str = LangPropObj.generateJSONStr( repo_name, repo[EXT_KEY]["Summary"], repo[EXT_KEY]["Description"] ) else: raise e fp_content += lang_json_str try: fp_content = fp_content[0:-2] + "\n" + INDENT + "]\n}" fp = open(os.path.join(lang_path, lang_item + ".json"), "w", encoding="utf-8") fp.write(fp_content) fp.close() except Exception as e: raise e except Exception as e: if langLogger != None: langLogger.error(str(e), e) langLogger.info("CreatelangIndex action failed!") raise e finally: if langLogger != None: langLogger.close()
class Cashcode_T1500 (Thread): parity = 'N' stopbits = 1 bitesize = 8 baudrate = 9600 serial_timeout = .5 p_ack = 0x00 p_nck = 0xFF p_sync = 0x02 p_adr = 0x03 c_reset = 0x30 c_status = 0x31 c_security = 0x32 c_poll = 0x33 c_bill_types = 0x34 c_stack = 0x35 c_return = 0x36 c_ident = 0x37 c_hold = 0x38 c_barcode = 0x39 c_barcode_extract = 0x3A c_bill_table = 0x41 c_download = 0x50 c_crc32 = 0x51 c_stats = 0x60 r_power_up = 0x10 r_power_up_validator = 0x11 r_power_up_stacker = 0x12 r_initialize = 0x13 r_idling = 0x14 r_accepting = 0x15 r_stacking = 0x17 r_returning = 0x18 r_unit_disabled = 0x19 r_holding = 0x1A r_device_busy = 0x1B #generic reject codes rj_reject = 0x1C rj_drop_casset_full = 0x41 rj_drop_casset_out = 0x42 rj_validator_jammed = 0x43 rj_drop_casset_jammed = 0x44 rj_cheated = 0x45 rj_pause = 0x46 rf_failure = 0x47 #events re_escrow = 0x80 re_stacked = 0x81 re_returned = 0x82 # Errors e_insertation = 0x60 bill_types = { 2: 10, 3: 50, 4: 100, 5: 500, 6: 1000, 7: 5000 } CRC_TABLE = [ 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 ] __prefix = '[Cashcode_t1500]' last_action = 0 time_start = 0 timeout = 0 sleep_time = .5 running = False events = [] def __init__ (self, device, baudrate = 9600, sleep_time = .5, timeout = 0): self.device, self.timeout = device, timeout self.logger = Logger() if baudrate: self.baudrate = baudrate if sleep_time > 0: self.sleep_time = sleep_time Thread.__init__(self) def connect(self): self.running = True try: self.serial = serial.serial_for_url( self.device, self.baudrate, parity = self.parity, timeout = self.serial_timeout ) self.check_status() self.logger.debug("Okay. Adapter has been connected to CASHCODE SM with data %s:%s" % (self.device, self.baudrate)) except serial.SerialException as e: message = 'Error while connecting to bill acceptor' self.logger.warning(message) raise AcceptorError(message = message, code = 500) except Exception as e: message = 'Error while connecting to bill acceptor. Error details: %s' % e self.logger.warning(message) raise AcceptorError(message = message, code = 500) self.full_reset() def disconnect(self): self.running = False try: self.logger.debug('[Cashcode_T1500]: reset') self.full_reset() time.sleep(3) self.serial.close() except: self.logger.debug('[Cashcode_T1500]: stopping with error') pass self.logger.debug('[Cashcode_T1500]: serial port has been closed') def run(self): self.logger.debug('[Cashcode_T1500]: thread has ran') self.logger.debug('[Cashcode_T1500]: timeout is %s' % self.timeout) total_summ = 0 response = None self.last_action = time.time() self.enable_bill_types() self.check_status() while self._running(self.timeout): time.sleep(self.sleep_time) # Если родительский поток не забрал все сообщения if len( self.events ): continue try: response = self.wait( wait = [self.re_stacked], skip = [self.r_idling, self.r_initialize, self.r_accepting, self.r_stacking], timeout = self.timeout ) except AcceptorError as e: message = 'Error while waiting %s. Response is %s. Error is %s' % (self.re_stacked, response, str(e.args)) self.logger.debug(message) continue try: amount = self.bill_types[response[1]] total_summ += amount self.logger.debug('Response is %s' % response) self.logger.debug('Accepted amount is %d' % amount) self.send_ack() self.events.append({'id_trx': 0, 'count': 1, 'value': amount, 'total_amount': total_summ, 'sleep_time': self.sleep_time}) except: pass self.logger.debug('[Cashcode_T1500]: run stop operations') self.disconnect() def pop_message(self): if not len(self.events): return False return self.events.pop(0) def _running(self, timeout): timestamp = int(time.time()) if not self.running: self.logger.debug("Acceptor thread stopped by flag") return False if timeout > 0 and timestamp - self.last_action > timeout: self.logger.debug("Acceptor thread stopped by timeout") #print "timestamp: %s, last_action: %s, timeout: %s" % (timestamp, self.last_action, timeout) return False return True def __calc_crc(self, data): crc = 0; for i in data: crc = self.CRC_TABLE[ (crc ^ i) & 0xFF] ^ (crc >> 8); return crc; def _read_nbytes(self, length): return str2bytes(self.serial.read(length)) def _read_byte(self): return ord(self.serial.read(1)) #reads next 2 bytes (crc length) def _read_crc(self): return self._read_nbytes(2) #reads response packey, verify crc, check header(sync, adr) def _read_response(self): header = self._read_nbytes(3) try: message = 'Header error. Is Cashcode connected to %s? Header is %s' % (self.device, header) if (header[0] <> self.p_sync or header[1] <> self.p_adr): self.logger.debug( message ) raise AcceptorError( message = message, code = 500 ) except IndexError: message = 'Header error. Header is %s' % ( header ) self.logger.debug( message ) raise AcceptorError( message = message, code = 500 ) packet = self._read_nbytes( header[2] - 3 - 2 ) crc = self._read_crc() checkCrc = int2bytes( self.__calc_crc(header + packet) ) if crc != checkCrc: self.logger.debug('%s: _read_response. Crc not satisfied their=%s , my=%s' % (self.__prefix, crc, checkCrc)) # self.logger.debug('%s: _read_response. response(len=%d) dec=%s, hex=%s ' % (self.__prefix, len(packet), packet, ints2hex(packet) )) self.validate_statement(packet) return packet def free(self, t = 0.02): time.sleep(t) ''' ******* SEND COMMANDS ************ ''' def send_single_command(self, cmd, read_response = True): packet = [self.p_sync, self.p_adr, 0x06, cmd] packet = packet + int2bytes( self.__calc_crc(packet) ) self.serial.write( serial.to_bytes( packet ) ) if read_response: return self._read_response() return True def send_command(self, data, read_response = True): packet = [ self.p_sync, self.p_adr, 5 + len(data)] + data packet = packet+ int2bytes(self.__calc_crc(packet)) self.serial.write(serial.to_bytes(packet) ) if read_response: return self._read_response() return True def status(self): return self.check_status() ''' ******* EXACT COMMANDS ************ ''' def check_status(self): status_response = self.send_single_command( self.c_status, True ) self.logger.debug( '%s: check_status: Status is "%s"' % (self.__prefix, status_response)) self.send_ack() return status_response def poll(self): return self.send_single_command( self.c_poll ) def full_reset(self): self.logger.debug( '%s: full_reset' % (self.__prefix) ) return self.__is_ack( self.send_single_command(self.c_reset) ) ''' ******** ALIASES ************** ''' def init_bill_types(self, b1, b2, b3, b4, b5, b6): init_response = self.send_command([self.c_bill_types, b3, b2, b1, b6, b5, b4]) self.logger.debug( '%s: init_bill_types: Result is "%s"' % (self.__prefix, init_response)) self.free() self.logger.debug( '%s: init_bill_types: poll' % (self.__prefix)) self.poll() self.free() self.send_ack() self.wait( wait = [self.r_idling], skip = [self.r_initialize] ) return True def enable_bill_types(self): self.logger.debug('[Cashcode_t1500->enable_bill_types]: Enable bill types') bills = 0 for i in range(2,8): bills = bills | 1 << i return self.init_bill_types(bills,0,0,0,0,0) def disable_bill_types(self): return self.init_bills(0,0,0,0,0,0) def receive_start(self, timeout = 10): self.logger.debug('%s: Starting receive of banknotes.' % self.__prefix) self.last_action = time.time() if( not self.enable_bill_types() ): raise Exception('[Cashcode_t1500->receive_start]: Bill types was not setuped') while self._running( timeout ): response = self.wait( wait = [self.re_stacked], skip = [self.r_idling, self.r_initialize, self.r_accepting, self.r_stacking] ) try: amount = self.bill_types[ response[1] ] self.logger.debug('Response is %s' % response) self.logger.debug('Accepted amount is %d' % amount) self.send_ack() return amount except: pass return 0 def receive_commit(self): response = self.send_ack() self.logger.debug('%s: commit result is %s' % (self.__prefix, response) ) def receive_rollback(self): response = self.send_single_command(self.c_return, read_response = True) self.logger.debug('%s: eject result is %s' % (self.__prefix, response) ) def send_ack(self): return self.send_single_command(self.p_ack, False) def send_nck(self): return self.send_single_command(self.p_nck, False) def bill_table(self): response = self.send_single_command(self.c_bill_table) for i in range(0,23): bytes=response[i*5 : i*5+5] print 'bytes: %s, %s' % (bytes, byte2str(bytes[1:4])) def __is_ack(self, data): return len(data)==1 and data[0]==self.p_ack def __is_nck(self, data): return len(data)==1 and data[0]==self.p_nck def _stacked_handler(self): pass def _rejected_handler(self): pass def wait(self, wait=[], skip=[], timeout = 10): self.logger.debug('[Cashcode_t1500->wait] start waiting %s' % timeout) while self._running( timeout ): response = self.poll() if(response[0] in wait): self.logger.debug('Normal response waited') return response if(response[0] in skip): self.validate_statement( response ) continue message = "[Cashcode_t1500->wait(%s, %s, %s)] got=%s" % (wait, skip, timeout, response) self.logger.debug( message ) raise AcceptorError(message, response) self.free(.2) def validate_statement(self, packet): if packet == [self.r_power_up]: self.logger.debug('State is POWER_UP') return if packet == [self.r_accepting]: self.logger.debug('State is ACCEPTING') return if packet == [self.r_stacking]: self.logger.debug('State is STACKING') return if packet == [self.rj_reject, self.e_insertation]: self.logger.debug('State is Error. Details: [rj_reject, e_insertation]') return
class DispenserAdapter: DISPENSERS = { "PULOON-LCDM1000": {"class": "Dispenser_LCDM1000", "path": "services.dispenser.dispensers.puloon_lcdm1000"}, "PULOON-LCDM2000": {"class": "Dispenser_LCDM2000", "path": "services.dispenser.dispensers.puloon_lcdm2000"}, "PULOON-LCDM4000": {"class": "Dispenser_LCDM4000", "path": "services.dispenser.dispensers.puloon_lcdm4000"}, } serial = None # Serial Object dispenser = None # Dispenser model implementation def __init__(self, dispenser_model, port=False, baudrate=False, timeout=0.6, parity=False): if dispenser_model not in self.DISPENSERS: raise DispenserError("%s is not supported. See DispenserController.DISPENSERS for available dispensers.") self.logger = Logger() self.dispenser = self.__import_class( self.DISPENSERS[dispenser_model]["path"], self.DISPENSERS[dispenser_model]["class"] )() # Set data if port: self.dispenser.port = port if baudrate: self.dispenser.baudrate = baudrate if timeout: self.dispenser.timeout = timeout if parity: self.dispenser.parity = parity @staticmethod def __import_class(class_path, class_name): try: module = __import__(class_path, fromlist="*") return getattr(module, class_name) except Exception as e: message = "DispenserAdapter: Couldnt load class %s from path %s With error: %s" % ( class_name, class_path, str(e.args), ) if __debug__: print message raise ImportError(message) def connect(self): """ Connect to serial port """ self.logger.debug("DispenserAdapter: port is %s" % self.dispenser.port) self.logger.debug("DispenserAdapter: parity is %s" % self.dispenser.parity) self.logger.debug("DispenserAdapter: baudrate is %s" % self.dispenser.baudrate) self.logger.debug("DispenserAdapter: timeout is %s" % self.dispenser.timeout) try: self.serial = serial.serial_for_url( self.dispenser.port, self.dispenser.baudrate, parity=self.dispenser.parity, timeout=self.dispenser.timeout, ) except SerialException as e: raise DispenserError("Error while connecting to dispenser", 500) try: self.status() except: pass def status(self): self.logger.debug("DispenserAdapter: get_status command received") response = self.__send(command=self.dispenser.command_status, validator=self.dispenser.validate_status_response) self.__write([self.dispenser.p_ack]) if isinstance(self.dispenser, Dispenser_LCDM4000): """ Read the EOT for LCDM4000 """ try: self.__read(timeout=0.6) except Exception as e: self.logger.debug("DispenserAdapter::status [forr Puloon_LCDM4000] error catched. [%s]" % str(e.args)) if not response: return False if "status" in response: self.logger.debug("DispenserAdapter: [CMD STATUS] result: %s" % response["status"]) self.logger.debug("DispenserAdapter: [CMD STATUS] info : %s" % response) return response["status"] return False def init(self): self.logger.debug("DispenserAdapter: init command received") response = self.__send(command=self.dispenser.command_init, validator=self.dispenser.validate_init_response) self.__write([self.dispenser.p_ack]) if isinstance(self.dispenser, Dispenser_LCDM4000): """ Read the EOT for LCDM4000 """ time.sleep(2.1) # try: # self.__read( timeout = .7 ) # except Exception as e: # self.logger.debug('DispenserAdapter::init [for Puloon_LCDM4000] error catched. [%s]' % str(e.args)) self.logger.debug("DispenserAdapter: init finished with result %s" % bool(response)) if response: return True return False def purge(self): self.logger.debug("DispenserAdapter: purge command received") response = self.__send(command=self.dispenser.command_purge, validator=self.dispenser.validate_purge_response) self.__write([self.dispenser.p_ack]) if isinstance(self.dispenser, Dispenser_LCDM4000): """ Read the EOT for LCDM4000 """ try: self.__read(timeout=0.6) except Exception as e: self.logger.debug("DispenserAdapter::purge [for Puloon_LCDM4000] error catched. [%s]" % str(e.args)) if response: if "status" in response: self.logger.debug("DispenserAdapter: [CMD PURGE] result: %s" % response["status"]) self.logger.debug("DispenserAdapter: [CMD PURGE] info : %s" % response) return response["status"] return False def dispense(self, amount, cassets_info): """ Dispense the bills amount: amount to dispense cassets_info: Cassets infrormation in format {id_cassete : {'command' : 0x45, 'denomination' : 0, 'charging' : 100, 'position' : 'upper'},...} """ dispense_info = self.dispenser.get_dispense(amount, cassets_info) command = None self.logger.debug("DispenserAdapter: Starting dispense of amount %s" % amount) # Amount is not dispensable if dispense_info["to_dispense"] == amount: raise DispenserError("Amount is not dispensable", 500) if len(dispense_info["cassets"]) > 1: command = self.dispenser.command_dispense_several(cassets_info, dispense_info["cassets"]) else: id_cassete, banknotes_count = dispense_info["cassets"].popitem() command = self.dispenser.command_dispense_single(cassets_info, id_cassete, banknotes_count) response = self.__send(command=command, validator=self.dispenser.validate_dispense_response) if not response: raise DispenserError("Error while dispensing (response from dispenser is None)", 500) self.__write([self.dispenser.p_ack]) return response def __send(self, command, validator=False): if not self.serial: raise DispenserError("Serial port is not opened") self.logger.debug("DispenserAdapter: send command in hex %s" % (["%02X" % x for x in command])) """ Пишем, спим полсекундочки и читаем """ self.logger.debug(">> serial.write %s" % (["%02X" % x for x in command])) bytes_written = self.__write(command) self.logger.debug(">> serial.read") bytes_recd = self.__read(timeout=1) self.logger.debug(">> serial.read done") if bytes_recd == [self.dispenser.p_nck]: raise DispenserError("DispenserAdapter.__send: bytes_recd == NCK") if bytes_recd == [self.dispenser.p_ack]: self.logger.debug("DispenserAdapter.__send: bytes_recd == ACK") bytes_recd = self.__read(timeout=60) readed = ["%02X" % x for x in bytes_recd] else: if isinstance(self.dispenser, Dispenser_LCDM4000): self.logger.debug("Dispenser instance is Dispenser_LCDM4000. F**k this!") if validator: return validator(bytes_recd) readed = ["%02X" % x for x in bytes_recd] self.logger.debug("DispenserAdapter.__send [read from dispenser]: HEX is %s" % readed) raise DispenserError("Shit hap in HEX: %s" % readed) self.logger.debug(">> serial.read in HEX: %s" % readed) # if isinstance(self.dispenser, Dispenser_LCDM4000): # ''' Read the EOT for LCDM4000 ''' # try: # self.__read( timeout = .5 ) # except Exception as e: # self.logger.debug('DispenserAdapter::dispense [for Puloon_LCDM4000] error catched. [%s]' % str(e.args)) if validator: return validator(bytes_recd) self.logger.debug("DispenserAdapter: No validator presents. Return invalidated response.") return bytes_recd def __write(self, bytes): return self.serial.write(serial.to_bytes(bytes)) def __read(self, timeout=60): time_start = time.time() frame = [] data = "" byte = self.serial.read(1) data += byte try: first_byte = int(byte2hex(byte), 16) self.logger.debug("DispenserAdapter.__read: first byte is: 0x%02X" % first_byte) if first_byte == self.dispenser.p_nck: self.logger.debug("DispenserAdapter.__read: first byte is NCK") return [self.dispenser.p_nck] if first_byte == self.dispenser.p_ack: self.logger.debug("DispenserAdapter.__read: first byte is: ACK") return [self.dispenser.p_ack] byte = self.serial.read(1) data += byte self.logger.debug("DispenserAdapter.__read: Wrong first byte in response 0x%02X" % first_byte) self.logger.debug("DispenserAdapter.__read: Next byte in response is 0x%02X" % int(byte2hex(byte))) except Exception as e: self.logger.debug("DispenserAdapter.__read: %s" % str(e.args)) pass self.logger.debug("DispenserAdapter.__read: first byte is detected") while True: if time.time() - time_start > timeout: self.logger.debug("DispenserAdapter.__read: timeout to read. ") for _, i in enumerate(serial.to_bytes(data)): frame.append(int(byte2hex(i), 16)) self.logger.debug( "DispenserAdapter.__read: full dump of response: %s" % (["0x%02X" % x for x in frame]) ) raise DispenserError(message="Timeout to read", code=500) try: if int(byte2hex(byte), 16) == self.dispenser.p_etx: break except Exception as e: self.logger.debug("Error in read cycle: %s" % str(e.args)) time.sleep(0.01) byte = self.serial.read(1) data += byte self.logger.debug("DispenserAdapter.__read: cycle is complete") data += self.serial.read(1) for _, i in enumerate(serial.to_bytes(data)): frame.append(int(byte2hex(i), 16)) self.logger.debug("DispenserAdapter.__read: full dump of response: [%s]" % ([x for x in frame])) return frame
if ch.lower() != 'y': print("Please choose another folder.") exit(-1) else: try: os.system(r"C:\Windows\System32\attrib -r "+ savePath+"\*.* " + " /s /d") shutil.rmtree(savePath, ignore_errors = True) except: raise Exception("Cannot get administrator permission to delete "+savePath) # logPath = ../Package/log logPath = os.path.join(savePath,LOG_DIR_NAME) os.mkdir(savePath) os.mkdir(logPath) mainLogger = Logger(os.path.join(logPath,LOG_NAME),'mainLogger') try: mainLogger.info("Main Script start ... ") # create index for extension mainLogger.info("'CreateExtensionIndex' start...") ext_path = createExtensionIndex(savePath, productName) mainLogger.info("'CreateExtensionIndex' complete...") ''' Description: create two threads -- one aimed at creating license index; the other aimed at creating lang index ''' # create thread to get index for license mainLogger.info("'CreateLicenseIndex' thread start...") runCreateLicenseIndex = runScriptThread(createLicenseIndex, savePath, ext_path)
def createLicenseIndex(*args): outdir = args[0] ext_path = args[1] #if product.lower() == "modeler": #repos_set_uri = RAW_REPOS_SET_URI.format('modeler','modeler') #index_key = RAW_INDEX_KEY.format('modeler') #elif product.lower() == 'stats': # wrong spell of statistics #repos_set_uri = RAW_REPOS_SET_URI.format('statisitcs','stats') #index_key = RAW_INDEX_KEY.format('stats') index_key = RAW_INDEX_KEY licenseLogger = None try: license_obj_list = [] lic_path = os.path.join(outdir,LICENSE_DIR) os.mkdir(lic_path) root_log_dir = os.path.join(outdir, LOG_DIR_NAME) licenseLogger = Logger(os.path.join(root_log_dir,LOG_INFO),'licenseLogger') licenseLogger.info("CreateLicenseIndex script start ...") try: licenseLogger.info("Get extension list ...") repos_set_json = loadExtJSONContent(ext_path) repos_set_json_index = repos_set_json[index_key] except Exception as e: raise e repo_index = 0 licenseLogger.info("Start to get license content ...") for repo in repos_set_json_index: try: repo_name = repo["repository"] except Exception: raise Exception("At least one repository in index file does not have repo name. Please check!") repo_license_uri = RAW_LICENSE_URI.format(repo_name) try: repo_license_content = URILoader.loadURI(repo_license_uri, "license file") except Exception as e: raise e isExistedLicense = False repo_index += 1 for item in license_obj_list: if repo_license_content == item.getLicenseContent(): isExistedLicense = True item.addRepoName(repo_name) break if not isExistedLicense: addObj(repo_name, repo_license_content,license_obj_list) lic_index = 0 index_content = "{\n"+INDENT+"\"license_index\": [\n"; for obj in license_obj_list: index_item_str = LicenseIndexItemStr.getItemStr(obj) index_content += index_item_str lic_index += 1 licenseLogger.info(str(lic_index)+" license: save in file '"+obj.getLicenseName()+"'.") licenseLogger.info("Repos use this license: "+LicenseIndexItemStr.convertListToString(obj.getRepoNameList())) license_fp = open(os.path.join(lic_path,obj.getLicenseName()),'w',encoding = "utf-8") license_fp.write(obj.getLicenseContent()) license_fp.close() index_content = index_content[0:-2] index_content += '\n' + INDENT + "]\n}" index_fp = open(os.path.join(lic_path,LIC_INDEX_FILE),'w',encoding='utf-8') index_fp.write(index_content) licenseLogger.info("CreateLicenseIndex action succeeded!") except Exception as e: if licenseLogger!=None: licenseLogger.error(str(e),e) licenseLogger.info("CreateLicenseIndex action failed!") raise e finally: if licenseLogger!=None: licenseLogger.info("Totally get "+str(len(license_obj_list))+" type(s) of license from "+str(repo_index)+" repos!") licenseLogger.close()
def __validate_dispense_single_response(response_frame, template): logger = Logger() response = {} if response_frame[3] == 0x45: logger.debug('Dispenser_LCDM4000: upper cassete validator') chk_sensor_exit_10 = 'upper_chk_requested_10' chk_sensor_exit_1 = 'upper_chk_requested_1' exit_requested_10 = 'upper_exit_requested_10' exit_requested_1 = 'upper_exit_requested_1' rejects_10 = 'upper_rejects_10' rejects_1 = 'upper_rejects_1' status = 'upper_status' elif response_frame[3] == 0x55: logger.debug('Dispenser_LCDM4000: lower cassete validator') chk_sensor_exit_10 = 'lower_chk_requested_10' chk_sensor_exit_1 = 'lower_chk_requested_1' exit_requested_10 = 'lower_exit_requested_10' exit_requested_1 = 'lower_exit_requested_1' rejects_10 = 'lower_rejects_10' rejects_1 = 'lower_rejects_1' status = 'lower_status' else: logger.debug('Dispenser_LCDM4000: UNKNOWN cassete') logger.debug('Dispenser_LCDM4000: response_frame[3] is %s' % response_frame[3]) logger.debug('Dispenser_LCDM4000: response_frame[3] is %X' % response_frame[3]) template[chk_sensor_exit_10] = chr(response_frame[4]) template[chk_sensor_exit_1] = chr(response_frame[5]) template[exit_requested_10] = chr(response_frame[6]) template[exit_requested_1] = chr(response_frame[7]) template[rejects_10] = chr(response_frame[10]) template[rejects_1] = chr(response_frame[11]) template['error_cause'] = response_frame[8] template[status] = response_frame[9] logger.debug('Dispenser_LCDM4000: Validate response_frame to dispense_single : %s' % response_frame) return template