Example #1
0
def doDeposit(sessionType, validAccounts, accountsPendingCreation,
              accountsPendingDeletion):
    if sessionType == session.loggedOutSessionType:
        print messages.getMessage("txErrNotLoggedIn")
        return False, None, None, None
    else:
        # Get the acct name and number
        result, accountNumber = getAcctNumber()

        if False == result:
            # There was an error getting the account info from the user
            return False, None, None, None

        # Validate that the account isn't a new or deleted account
        if False == validateNewDeleted("deposit", accountNumber,
                                       accountsPendingCreation,
                                       accountsPendingDeletion):
            return False, None, None, None

        # Check if the account actually exists
        if accountNumber not in validAccounts:
            print messages.getMessage("accountDoesntExist", accountNumber)
            return False, None, None, None

        result, dollarAmount = getDollarAmount(sessionType)

        if False == result:
            # There was an error getting the dollar amount from the user
            return False, None, None, None

        transaction = makeTxDeposit(accountNumber, dollarAmount)

        return True, transaction, accountNumber, dollarAmount
Example #2
0
 def __SendCommandToHosts(self, action):
     # get action command and send it to members
     cmd = action["command"]
     print "Sending Command to hosts: ", cmd
     print "Hosts: ", self.hosts
     if int(cmd) == PLAYER_START_FILENUMBER:
         msgData = messages.getMessage(int(cmd),args=["-i", str(action['file_number'])])
     else:
         msgData = messages.getMessage(int(cmd))
     udpbroadcaster.sendMessageToHosts(msgData, self.hosts)
Example #3
0
def validateNewDeleted(action, accountNumber, accountsPendingCreation,
                       accountsPendingDeletion):
    if accountNumber in accountsPendingDeletion:
        print messages.getMessage("pendingDeletion", [action, accountNumber])
        return False
    elif accountNumber in accountsPendingCreation:
        print messages.getMessage("pendingCreation", [action, accountNumber])
        return False
    else:
        return True
Example #4
0
 def __SendCommandToHosts(self, action):
     # get action command and send it to members
     cmd = action["command"]
     print "Sending Command to hosts: ", cmd
     print "Hosts: ", self.hosts
     if int(cmd) == PLAYER_START_FILENUMBER:
         msgData = messages.getMessage(
             int(cmd), args=["-i", str(action['file_number'])])
     else:
         msgData = messages.getMessage(int(cmd))
     udpbroadcaster.sendMessageToHosts(msgData, self.hosts)
Example #5
0
def getAcctNumber(s=""):
    accountNumber = raw_input(
        messages.getMessage("pleaseEnter", "account number" + s) + "> ")

    if len(accountNumber) != 7 or accountNumber.startswith(
            " ") or accountNumber.endswith(" ") or accountNumber.startswith(
                "0") or not qbUtil.isInt(accountNumber):
        print messages.getMessage("invalidCustom",
                                  ["account number", accountNumber])
        return False, None

    return True, accountNumber
Example #6
0
def main():
    data = None
    flag = -1

    if len(sys.argv) > 3:
        flag = int(sys.argv[2])
        args = sys.argv[3:]
        data = messages.getMessage(flag, args)
    elif len(sys.argv) == 3:
        flag = int(sys.argv[2])
        data = messages.getMessage(flag)

    if data and not flag == -1:
        sendMessage(data)
Example #7
0
def main():
	data = None
	flag = -1

	if len(sys.argv) > 3:
		flag = int(sys.argv[2])
		args = sys.argv[3:]
		data = messages.getMessage(flag, args)
	elif len(sys.argv) == 3:
		flag = int(sys.argv[2])
		data = messages.getMessage(flag)

	if data and not flag == -1:
		sendMessage(data)
Example #8
0
 def HandleGroupMemberRequest(self, reqGroupName, masterIP):
     if not self.groupMaster and reqGroupName == self.groupName:
         self.masterHost = masterIP
         # member of requested group --> send acknowledge
         byRequest = "1"
         msgData = messages.getMessage(GROUP_MEMBER_ACKNOWLEDGE, ["-s", str(self.groupName), "-i", byRequest])
         udpbroadcaster.sendMessage(msgData, self.masterHost)
Example #9
0
 def GroupMasterRoutine(self):
     # add localhost to host list to receive commands on master player as well
     self.memberHosts.append('127.0.0.1')
     self.actionHandler.AddHost('127.0.0.1', True)
     # send member request broadcast
     msgData = messages.getMessage(GROUP_MEMBER_REQUEST, ["-s", str(self.groupName)])
     udpbroadcaster.sendBroadcast(msgData, True)
Example #10
0
 def GroupMasterRoutine(self):
     # add localhost to host list to receive commands on master player as well
     self.memberHosts.append('127.0.0.1')
     self.actionHandler.AddHost('127.0.0.1', True)
     # send member request broadcast
     msgData = messages.getMessage(GROUP_MEMBER_REQUEST,
                                   ["-s", str(self.groupName)])
     udpbroadcaster.sendBroadcast(msgData, True)
Example #11
0
def getDollarAmount(sessionType):

    centsAmount = raw_input(
        messages.getMessage("pleaseEnter", "an amount of money in cents") +
        "> ")

    if not qbUtil.isInt(centsAmount):
        print messages.getMessage(
            "invalidCustom",
            ["monetary amount",
             qbUtil.centsToDollars(centsAmount)])
        return False, None

    centsAmountInt = int(centsAmount)

    if centsAmountInt <= 0 or (sessionType == session.privilegedSessionType
                               and centsAmount > 99999999):
        print messages.getMessage(
            "invalidCustom",
            ["monetary amount",
             qbUtil.centsToDollars(centsAmount)])
        return False, None
    elif centsAmountInt > 100000:
        print messages.getMessage("mustBeAgent",
                                  "execute transactions over $1000")
        return False, None

    return True, centsAmountInt
Example #12
0
def getAcctNameNumber():
    result, accountNumber = getAcctNumber()

    if False == result:
        print messages.getMessage("invalidCustom",
                                  ["account number", accountNumber])
        return False, None, None

    accountName = raw_input(
        messages.getMessage("pleaseEnter", "account name") + "> ")

    if len(accountName) < 3 or len(accountName) > 30 or accountName.startswith(
            " ") or accountName.endswith(" "):
        print messages.getMessage("invalidCustom",
                                  ["account name", accountName])
        return False, None, None

    return True, accountName, accountNumber
Example #13
0
 def HandleGroupMemberRequest(self, reqGroupName, masterIP):
     if not self.groupMaster and reqGroupName == self.groupName:
         self.masterHost = masterIP
         # member of requested group --> send acknowledge
         byRequest = "1"
         msgData = messages.getMessage(
             GROUP_MEMBER_ACKNOWLEDGE,
             ["-s", str(self.groupName), "-i", byRequest])
         udpbroadcaster.sendMessage(msgData, self.masterHost)
Example #14
0
def main():
	global sock
	data = None
	flag = -1

	if len(sys.argv) > 3:
		flag = int(sys.argv[2])
		args = sys.argv[3:]
		data = messages.getMessage(flag, args)
	elif len(sys.argv) == 3:
		flag = int(sys.argv[2])
		data = messages.getMessage(flag)

	host = '<broadcast>'
	port = 60005


	# if valid message data and flag present --> send it
	if data and not flag == -1:
		print "Creating socket..."
		# SOCK_DGRAM is the socket type to use for UDP sockets
		print "Starting broadcast response listening thread..."
		rcv_thread = threading.Thread(target=udpbroadcastlistener.startListening)
		rcv_thread.daemon = True
		rcv_thread.start()
		time.sleep(1)
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,1)
		#ip = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
		#print "Local IP: ", ip
		print "Sending message..."
		sent = False
		while not sent:
			print "Trying to send..."
			sent = sock.sendto(data + "\n", (host, port))
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,0)
		print "Message sent!"
		#data, addr = sock.recvfrom(6)
		#print "Response from ", addr
		sock.close()

	#udpbroadcastlistener.startListening()
	time.sleep(2)
	cleanExit()
Example #15
0
def doCreateAcct(sessionType, validAccounts, accountsPendingCreation,
                 accountsPendingDeletion):

    if sessionType == session.loggedOutSessionType:
        print messages.getMessage("txErrNotLoggedIn")
        return False, None, None
    elif sessionType != session.privilegedSessionType:
        print messages.getMessage("mustBeAgent", "create an account")
        return False, None, None
    else:

        # Get the acct name and number
        result, accountName, accountNumber = getAcctNameNumber()

        if False == result:
            # There was an error getting the account info from the user
            return False, None, None

        # Validate that the account isn't a new or deleted account
        if False == validateNewDeleted("create account", accountNumber,
                                       accountsPendingCreation,
                                       accountsPendingDeletion):
            return False, None, None

        if accountNumber in validAccounts:
            print messages.getMessage("accountAlreadyExists", accountNumber)
            return False, None, None

        # I think we're good to make the transaction at this point
        transaction = makeTxCreate(accountNumber, accountName)

        return True, transaction, accountNumber
Example #16
0
def doTransfer(sessionType, validAccounts, accountsPendingCreation,
               accountsPendingDeletion):
    if sessionType == session.loggedOutSessionType:
        print messages.getMessage("txErrNotLoggedIn")
        return False, None, None, None
    else:
        # Get the acct name and number
        result, accountNumberFrom = getAcctNumber(" to transfer from")

        # Validate that the account isn't a new or deleted account
        if False == validateNewDeleted("transfer", accountNumberFrom,
                                       accountsPendingCreation,
                                       accountsPendingDeletion):
            return False, None, None, None

        # Check if the account actually exists
        if accountNumberFrom not in validAccounts:
            print messages.getMessage("accountDoesntExist", accountNumberFrom)
            return False, None, None, None

        # Get the acct name and number
        result, accountNumberTo = getAcctNumber(" to transfer to")

        # Validate that the account isn't a new or deleted account
        if False == validateNewDeleted("transfer", accountNumberTo,
                                       accountsPendingCreation,
                                       accountsPendingDeletion):
            return False, None, None, None

        # Check if the account actually exists
        if accountNumberTo not in validAccounts:
            print messages.getMessage("accountDoesntExist", accountNumberTo)
            return False, None, None, None

        # Check if "from" and "to" accounts are the same
        if accountNumberFrom == accountNumberTo:
            print messages.getMessage("transferSameAccountError")
            return False, None, None, None

        result, dollarAmount = getDollarAmount(sessionType)

        if False == result:
            # There was an error getting the dollar amount from the user
            return False, None, None, None

        transaction = makeTxTransfer(accountNumberFrom, accountNumberTo,
                                     dollarAmount)

        return True, transaction, accountNumberTo, dollarAmount
Example #17
0
    def handle(self):
        data = self.request[0]
        inData = self.request[0].strip()
        cSocket = self.request[1]
        curThread = threading.current_thread()
        result, msg = interpreter.interpret(data)

        if result == SERVER_REQUEST:
            print "{} on {} wrote:".format(self.client_address[0], curThread.name)
            print "\nServer request received - sending response...\n"
            responseData = messages.getMessage(SERVER_REQUEST_ACKNOWLEDGE, ["-i", str(TYPE_RASPMEDIA_PLAYER), "-i", "0","-s", str(configtool.readConfig()['player_name'])])
            addr = (self.client_address[0], UDP_PORT)
            #print "Response delay..."
            #time.sleep(1)
            print "Sending response to:"
            print (addr)
            if cSocket.sendto(responseData, addr):
                print "Response sent!"
            else:
                print "Sending response failed!"
        elif result == FILELIST_REQUEST:
            files = mediaplayer.getMediaFileList()
            print files
            args = ['-i', str(len(files))]
            for file in files:
                args.append('-s')
                args.append(file)
            responseData = messages.getMessage(FILELIST_RESPONSE,args)
            if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)):
                print "Filelist sent!"
        elif result == CONFIG_REQUEST:
            responseData = messages.getConfigMessage()
            if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)):
                print "Config sent!"
        elif result == PLAYER_UPDATE_ERROR:
            responseData = messages.getMessage(PLAYER_UPDATE_ERROR, ["-s", str(msg)])
            cSocket.sendto(responseData, (self.client_address[0], UDP_PORT))
Example #18
0
 def updateContract(self, data=None):
     try:
         self.updateLastMethodCall("updateContract")
         self.myLog("--updateContract --")
         if (data == None): data = self.CallgetDataContract()
         self.myLog("updateContract : data %s" % (data))
         self.checkDataContract(data)
         self.myLog("updateContract(2) : data %s" % (data))
         self._contract = self.analyseValueContract(data)
     except Exception as inst:
         if (inst.args[:2] == ("call", "error")):
             message = "%s - %s" % (messages.getMessage(
                 inst.args[2]), self.getLastAnswer())
             self.updateErrorLastCall(message)
             raise Exception(inst)
         else:
             raise Exception(inst)
Example #19
0
    def _format_warning(message, category, filename, lineno, line=None):
        """Replace the default warnings.formatwarning

        This allows the warnings being called using a simple mnemonic
        string. The full message is then found from the message module.
        """
        import messages
        message = messages.getMessage(message)
        message = """..

pyFormex Warning
================
%s

`Called from:` %s `line:` %s
""" % (message, filename, lineno)
        if line:
            message += "%s\n" % line
        return message
Example #20
0
    def _format_warning(message,category,filename,lineno,line=None):
        """Replace the default warnings.formatwarning

        This allows the warnings being called using a simple mnemonic
        string. The full message is then found from the message module.
        """
        import messages
        message = messages.getMessage(message)
        message = """..

pyFormex Warning
================
%s

`Called from:` %s `line:` %s
""" % (message,filename,lineno)
        if line:
            message += "%s\n" % line
        return message
Example #21
0
    def __init__(self, config):
        self.groupName = config["group"]
        self.memberCount = 0
        self.groupMasterName = config["group_master_name"]
        self.groupMaster = config["group_master"] == 1
        self.actions = config["actions"]
        self.memberHosts = []

        self.masterHost = ""

        if self.groupMaster:
            print "INITIALIZING GroupActionHandler WITH ACTIONS: ", self.actions
            # init action handler thread
            self.actionHandler = GroupActionHandler(self.actions)
            self.actionHandler.daemon = True
            self.actionHandler.start()
            self.GroupMasterRoutine()
        else:
            # player is a group member --> broadcast acknowledge with request flag set to false in case master is already online
            byRequest = "0"
            msgData = messages.getMessage(GROUP_MEMBER_ACKNOWLEDGE, ["-s", str(self.groupName), "-i", byRequest])
            udpbroadcaster.sendBroadcast(msgData)
Example #22
0
    def __init__(self, config):
        self.groupName = config["group"]
        self.memberCount = 0
        self.groupMasterName = config["group_master_name"]
        self.groupMaster = config["group_master"] == 1
        self.actions = config["actions"]
        self.memberHosts = []

        self.masterHost = ""

        if self.groupMaster:
            print "INITIALIZING GroupActionHandler WITH ACTIONS: ", self.actions
            # init action handler thread
            self.actionHandler = GroupActionHandler(self.actions)
            self.actionHandler.daemon = True
            self.actionHandler.start()
            self.GroupMasterRoutine()
        else:
            # player is a group member --> broadcast acknowledge with request flag set to false in case master is already online
            byRequest = "0"
            msgData = messages.getMessage(
                GROUP_MEMBER_ACKNOWLEDGE,
                ["-s", str(self.groupName), "-i", byRequest])
            udpbroadcaster.sendBroadcast(msgData)
Example #23
0
def doWithdraw(sessionType, validAccounts, accountsPendingCreation,
               accountsPendingDeletion, accountsWithdrawalDict):
    if sessionType == session.loggedOutSessionType:
        print messages.getMessage("txErrNotLoggedIn")
        return False, None, None, None
    else:
        # Get the acct name and number
        result, accountNumber = getAcctNumber()

        if False == result:
            # There was an error getting the account info from the user
            return False, None, None, None

        # Validate that the account isn't a new or deleted account
        if False == validateNewDeleted("withdraw", accountNumber,
                                       accountsPendingCreation,
                                       accountsPendingDeletion):
            return False, None, None, None

        # Check if the account actually exists
        if accountNumber not in validAccounts:
            print messages.getMessage("accountDoesntExist", accountNumber)
            return False, None, None, None

        result, dollarAmount = getDollarAmount(sessionType)

        if False == result:
            # There was an error getting the dollar amount from the user
            return False, None, None, None

        #check to see if we would hit a withdrawal limit
        if sessionType != session.privilegedSessionType:
            if accountNumber in accountsWithdrawalDict:
                if (accountsWithdrawalDict[accountNumber] +
                        int(dollarAmount)) > 100000:
                    #We can't go over $1000 in a session
                    print messages.getMessage("withdrawLimitErr",
                                              accountNumber)
                    return False, None, None, None

        transaction = makeTxWithdraw(accountNumber, dollarAmount)

        return True, transaction, accountNumber, dollarAmount
Example #24
0
def doLogin(currentSession):
    if currentSession in validSessionTypes:
        # If the current session is in the valid list, then we don't need
        # to do anything
        print messages.getMessage("alreadyLoggedIn")
    else:
        print messages.getMessage("pleaseEnter", "session type")
        sessionType = raw_input("> ")

        if sessionType in validSessionTypes:
            # If the loginParam is valid, then we return it
            # This will log the user in
            return True, sessionType
        else:
            # If the login param is invalid, print an error and return
            # the current session type (logged out)
            print messages.getMessage("invalidSess", sessionType)

    # We return the current session type (for invalid login types and
    # when the user is already logged in)
    return False, currentSession
Example #25
0
        print('First ', users.index(u))
    print(u)

# list / tuple / dictionary

print(users[1])
print(users[1:3])

# modify the value
users[1] = 'Adams'
# remove a value from the list
del users[0]
print(users[0:-1])
# tuple
usersTuple = ('Chang', 'Chow', 'Missi')
# iterate on tuple
for u in usersTuple:
    print(u)
# will throw an error here , tuple is read only
# usersTuple[0] = 'Munchow'
# print(usersTuple[0])

from messages import getMessage, test

print(getMessage('Hey!'))
test()

from utils.mathutils import add as mAdd

print(mAdd(100, 253))
Example #26
0
def doLogout(currentSession):
    if currentSession in validSessionTypes:
        return loggedOutSessionType
    else:
        print messages.getMessage("alreadyLoggedOut")
Example #27
0
    def handle(self):
        data = self.request[0]
        inData = self.request[0].strip()
        cSocket = self.request[1]
        curThread = threading.current_thread()
        if not self.client_address[0] in netutil.ip4_addresses():
            result, msg = interpreter.interpret(data, self.client_address[0])

            if result == SERVER_REQUEST:
                freeSpace = self.FreeDiskSpace()
                responseData = messages.getMessage(
                    SERVER_REQUEST_ACKNOWLEDGE, [
                        "-i",
                        str(TYPE_RASPMEDIA_PLAYER), "-i", "0", "-s",
                        str(configtool.readConfig()['player_name']), "-i",
                        str(freeSpace[0]), "-i",
                        str(freeSpace[1])
                    ])
                addr = (self.client_address[0], UDP_PORT)
                print "Sending response to client:"
                print(addr)
                if cSocket.sendto(responseData, addr):
                    print "Response sent!"
                else:
                    print "Sending response failed!"
            elif result == FILELIST_REQUEST:
                files = mediaplayer.getMediaFileList()
                args = ['-i', str(len(files))]
                for file in files:
                    args.append('-s')
                    args.append(file)
                responseData = messages.getMessage(FILELIST_RESPONSE, args)
                if cSocket.sendto(responseData,
                                  (self.client_address[0], UDP_PORT)):
                    print "Filelist sent!"
            elif result == CONFIG_REQUEST:
                responseData = messages.getConfigMessage()
                if cSocket.sendto(responseData,
                                  (self.client_address[0], UDP_PORT)):
                    print "Config sent!"
            elif result == GROUP_CONFIG_REQUEST:
                response = messages.getGroupConfigMessage()
                if cSocket.sendto(response,
                                  (self.client_address[0], UDP_PORT)):
                    print "Group Config sent!"
            elif result == GROUP_CONFIG_ADD_ACTION:
                configtool.addGroupAction(msg)
                gConf = configtool.readGroupConfig()
                response = messages.getMessage(GROUP_CONFIG_ADD_ACTION)
                if cSocket.sendto(response,
                                  (self.client_address[0], UDP_PORT)):
                    print "Action saved confirmation sent!"
                GroupManager.ReInitGroupManager(gConf)
            elif result == GROUP_CONFIG_ACTION_DELETE:
                configtool.deleteGroupAction(msg)
                gConf = configtool.readGroupConfig()
                response = messages.getMessage(GROUP_CONFIG_ACTION_DELETE)
                if cSocket.sendto(response,
                                  (self.client_address[0], UDP_PORT)):
                    print "Action deleted confirmation sent!"
                GroupManager.ReInitGroupManager(gConf)
            elif result == PLAYER_UPDATE_ERROR:
                responseData = messages.getMessage(PLAYER_UPDATE_ERROR,
                                                   ["-s", str(msg)])
                cSocket.sendto(responseData,
                               (self.client_address[0], UDP_PORT))
            elif result == FILE_DATA_REQUEST:
                # send images from player over tcp to host in separate thread to not block other udp handling
                t = threading.Thread(target=self.SendImagesOverTCP,
                                     args=[self.client_address[0]])
                t.daemon = True
                t.start()
            elif result == DISK_INFO_REQUEST:
                freeSpace = self.FreeDiskSpace()
                responseData = messages.getMessage(
                    DISK_INFO_REQUEST,
                    ["-i", str(freeSpace[0]), "-i",
                     str(freeSpace[1])])
                addr = (self.client_address[0], UDP_PORT)
                if cSocket.sendto(responseData, addr):
                    print "Disk Info sent!"
                else:
                    print "Sending disk info failed!"
        else:
            print "Received own broadcast... ignored."
Example #28
0
    def update(self):
        log.info("myEnedis ...new update ??")

        if (self.getContract().getValue() != None):
            if self.getCallPossible():
                try:
                    log.error("myEnedis ...%s update lancé, status precedent : %s, lastCall :%s" \
                                      % (self.getContract().get_PDL_ID(), self.getStatusLastCall(), self.getLastMethodCallError()))
                    self.updateGitVersion()
                    self.updateErrorLastCall("")
                    self.updateLastMethodCall("")
                    self.setUpdateRealise(True)
                    if (self.isConsommation()):
                        self._niemeAppel += 1
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateYesterday"):
                            self.updateYesterday()
                        try:
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateCurrentWeek"):
                                self.updateCurrentWeek()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateLastWeek"):
                                self.updateLastWeek()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateLast7Days"):
                                self.updateLast7Days()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateDataYesterdayHCHP"):
                                self.updateDataYesterdayHCHP()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateLast7DaysDetails"):
                                self.updateLast7DaysDetails()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateCurrentMonth"):
                                self.updateCurrentMonth()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateLastMonth"):
                                self.updateLastMonth()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateLastMonthLastYear"):
                                self.updateLastMonthLastYear()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateCurrentYear"):
                                self.updateCurrentYear()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateLastYear"):
                                self.updateLastYear()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateYesterdayLastYear"):
                                self.updateYesterdayLastYear()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateCurrentWeekLastYear"):
                                self.updateCurrentWeekLastYear()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateYesterdayConsumptionMaxPower"):
                                self.updateYesterdayConsumptionMaxPower()
                            if (self.getStatusLastCall()
                                    or self.getLastMethodCallError()
                                    == "updateCurrentMonthLastYear"):
                                self.updateCurrentMonthLastYear()

                            self.updateTimeLastCall()
                            self.updateStatusLastCall(True)
                            log.info("mise à jour effectuee")
                        except Exception as inst:
                            if (
                                    inst.args[:2] == ("call", "error")
                            ):  # gestion que c'est pas une erreur de contrat trop recent ?
                                log.error(
                                    "%s - Erreur call ERROR %s" %
                                    (self.getContract().get_PDL_ID(), inst))
                                # Erreur lors du call...
                                self.updateTimeLastCall()
                                self.updateStatusLastCall(False)
                                self.updateErrorLastCall(
                                    "%s - %s" %
                                    (messages.getMessage(inst.args[2]),
                                     myCalli.getLastAnswer()))
                                log.error("%s - last call : %s" %
                                          (self.getContract().get_PDL_ID(),
                                           self.getLastMethodCall()))
                            else:
                                raise Exception(inst)

                    if (self.isProduction()):
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateProductionYesterday"):
                            self.updateYesterdayProduction()
                        self.updateTimeLastCall()
                        self.updateStatusLastCall(True)

                except Exception as inst:
                    if (inst.args == ("call", None)):
                        log.error("*" * 60)
                        log.error("%s - Erreur call" %
                                  (self.getContract().get_PDL_ID(), ))
                        self.updateTimeLastCall()
                        self.updateStatusLastCall(False)
                        message = "%s - %s" % (messages.getMessage(
                            inst.args[2]), myCalli.getLastAnswer())
                        self.updateErrorLastCall(message)
                        log.error("%s - %s" % (self.getContract().get_PDL_ID(),
                                               self.getLastMethodCall()))
                    else:
                        log.error("-" * 60)
                        log.error("Erreur inconnue call ERROR %s" % (inst))
                        log.error("Erreur last answer %s" % (inst))
                        log.error("Erreur last call %s" %
                                  (self.getLastMethodCall()))
                        log.error(traceback.format_exc())
                        log.error("-" * 60)
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        log.warning(sys.exc_info())
                        self.updateStatusLastCall(False)
                        self.updateTimeLastCall()
                        self.updateErrorLastCall("%s" % (inst))
                        log.error("LastMethodCall : %s" %
                                  (self.getLastMethodCall()))
            else:
                self.setUpdateRealise(False)
                log.info("%s pas d'update trop tot !!!" %
                         (self.getContract().get_PDL_ID()))
        else:
            self.setUpdateRealise(False)
            log.info("%s update impossible contrat non trouve!!!" %
                     (self.getContract().get_PDL_ID()))
        self.updateLastUpdate()
Example #29
0
    def update(self):

        if ((self.getTimeLastCall() == None)
                or (self.getStatusLastCall() == False)
                or (self.getDelaiIsGood())):
            try:
                self.myLogWarning( "myEnedis ...%s update lancé, status precedent : %s, lastCall :%s" \
                                   % (self.get_PDL_ID(), self.getStatusLastCall(), self.getLastMethodCallError()))
                self.updateErrorLastCall("")
                self.updateLastMethodCall("")
                self.setUpdateRealise(True)
                if (self.isConsommation()):
                    self._niemeAppel += 1
                    if (self.getStatusLastCall()
                            or self.getLastMethodCallError()
                            == "updateYesterday"):
                        self.updateYesterday()
                    try:
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateCurrentWeek"):
                            self.updateCurrentWeek()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateLastWeek"):
                            self.updateLastWeek()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateLast7Days"):
                            self.updateLast7Days()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateCurrentMonth"):
                            self.updateCurrentMonth()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateLastMonth"):
                            self.updateLastMonth()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateCurrentYear"):
                            self.updateCurrentYear()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateDataYesterdayHCHP"):
                            try:
                                self.updateDataYesterdayHCHP()
                            except Exception as inst:
                                #print("inst :", inst)
                                if (
                                        inst.args[:3] == ('call', 'error',
                                                          'no_data_found')
                                ):  # gestion que c'est pas une erreur de contrat trop recent ?
                                    # si le service ne repond pas, l'erreur pas grave, c'est que pas encore remonté
                                    self.updateErrorLastCall(
                                        "%s" % (messages.getMessage(
                                            inst.args[2]), " pour hier"))
                                    pass
                                else:
                                    raise Exception(inst)
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateLastYear"):
                            self.updateLastYear()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateLastMonthLastYear"):
                            self.updateLastMonthLastYear()
                        if (self.getStatusLastCall()
                                or self.getLastMethodCallError()
                                == "updateLast7DaysDetails"):
                            self.updateLast7DaysDetails()
                        self.updateTimeLastCall()
                        self.updateStatusLastCall(True)
                        self.myLogWarning("mise à jour effectuee")
                    except Exception as inst:
                        if (
                                inst.args[:2] == ("call", "error")
                        ):  # gestion que c'est pas une erreur de contrat trop recent ?
                            self.myLogWarning("%s - Erreur call ERROR %s" %
                                              (self.get_PDL_ID(), inst))
                            # Erreur lors du call...
                            self.updateTimeLastCall()
                            self.updateStatusLastCall(False)
                            self.updateErrorLastCall(
                                "%s - %s" % (messages.getMessage(
                                    inst.args[2]), self.getLastAnswer()))
                            self.myLogWarning(
                                "%s - last call : %s" %
                                (self.get_PDL_ID(), self.getLastMethodCall()))
                        else:
                            raise Exception(inst)
                elif (self.isProduction()):
                    if (self.getStatusLastCall()
                            or self.getLastMethodCallError()
                            == "updateProductionYesterday"):
                        self.updateProductionYesterday()
                    self.updateTimeLastCall()
                    self.updateStatusLastCall(True)

            except Exception as inst:
                if (inst.args == ("call", None)):
                    self.myLogWarning("%s - Erreur call" %
                                      (self.get_PDL_ID(), ))
                    # Erreur lors du call...
                    # Erreur lors du call...
                    self.updateTimeLastCall()
                    self.updateStatusLastCall(False)
                    self.updateErrorLastCall("%s - %s" % (messages.getMessage(
                        inst.args[2]), self.getLastAnswer()))
                    self.myLogWarning(
                        "%s - %s" %
                        (self.get_PDL_ID(), self.getLastMethodCall()))
                else:
                    self.myLogWarning("-" * 60)
                    self.myLogWarning("Erreur inconnue call ERROR %s" % (inst))
                    self.myLogWarning("Erreur last answer %s" % (inst))
                    self.myLogWarning("Erreur last call %s" %
                                      (self.getLastMethodCall()))
                    self.myLogWarning("-" * 60)
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    self.myLogWarning(sys.exc_info())
                    self.updateStatusLastCall(False)
                    self.updateTimeLastCall()
                    self.updateErrorLastCall("%s" % (inst))
                    self.myLogWarning("LastMethodCall : %s" %
                                      (self.getLastMethodCall()))

        else:
            self.setUpdateRealise(False)
            self.myLogWarning("%s pas d'update trop tot !!!" %
                              (self.get_PDL_ID()))
        self.updateLastUpdate()
Example #30
0
    def handle(self):
        data = self.request[0]
        inData = self.request[0].strip()
        cSocket = self.request[1]
        curThread = threading.current_thread()
        if not self.client_address[0] in netutil.ip4_addresses():
            result, msg = interpreter.interpret(data, self.client_address[0])


            if result == SERVER_REQUEST:
                freeSpace = self.FreeDiskSpace()
                responseData = messages.getMessage(SERVER_REQUEST_ACKNOWLEDGE, ["-i", str(TYPE_RASPMEDIA_PLAYER), "-i", "0","-s", str(configtool.readConfig()['player_name']), "-i", str(freeSpace[0]), "-i", str(freeSpace[1])])
                addr = (self.client_address[0], UDP_PORT)
                print "Sending response to client:"
                print (addr)
                if cSocket.sendto(responseData, addr):
                    print "Response sent!"
                else:
                    print "Sending response failed!"
            elif result == FILELIST_REQUEST:
                files = mediaplayer.getMediaFileList()
                args = ['-i', str(len(files))]
                for file in files:
                    args.append('-s')
                    args.append(file)
                responseData = messages.getMessage(FILELIST_RESPONSE,args)
                if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)):
                    print "Filelist sent!"
            elif result == CONFIG_REQUEST:
                responseData = messages.getConfigMessage()
                if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)):
                    print "Config sent!"
            elif result == GROUP_CONFIG_REQUEST:
                response = messages.getGroupConfigMessage()
                if cSocket.sendto(response, (self.client_address[0], UDP_PORT)):
                    print "Group Config sent!"
            elif result == GROUP_CONFIG_ADD_ACTION:
                    configtool.addGroupAction(msg)
                    gConf = configtool.readGroupConfig()
                    response = messages.getMessage(GROUP_CONFIG_ADD_ACTION)
                    if cSocket.sendto(response, (self.client_address[0], UDP_PORT)):
                        print "Action saved confirmation sent!"
                    GroupManager.ReInitGroupManager(gConf)
            elif result == GROUP_CONFIG_ACTION_DELETE:
                    configtool.deleteGroupAction(msg)
                    gConf = configtool.readGroupConfig()
                    response = messages.getMessage(GROUP_CONFIG_ACTION_DELETE)
                    if cSocket.sendto(response, (self.client_address[0], UDP_PORT)):
                        print "Action deleted confirmation sent!"
                    GroupManager.ReInitGroupManager(gConf)
            elif result == PLAYER_UPDATE_ERROR:
                responseData = messages.getMessage(PLAYER_UPDATE_ERROR, ["-s", str(msg)])
                cSocket.sendto(responseData, (self.client_address[0], UDP_PORT))
            elif result == FILE_DATA_REQUEST:
                # send images from player over tcp to host in separate thread to not block other udp handling
                t = threading.Thread(target=self.SendImagesOverTCP, args=[self.client_address[0]])
                t.daemon = True
                t.start()
            elif result == DISK_INFO_REQUEST:
                freeSpace = self.FreeDiskSpace()
                responseData = messages.getMessage(DISK_INFO_REQUEST, ["-i", str(freeSpace[0]), "-i", str(freeSpace[1])])
                addr = (self.client_address[0], UDP_PORT)
                if cSocket.sendto(responseData, addr):
                    print "Disk Info sent!"
                else:
                    print "Sending disk info failed!"
        else:
            print "Received own broadcast... ignored."