예제 #1
0
 def receiveImage(self, packet):
     """
      Receives an image from tracker.
      Sends it to the observer server, when totally received.
     """
     log.error('Image receiving...')
     log.info('[IS NOT IMPLEMENTED]')
예제 #2
0
 def sendAcknowledgement(self, packet):
     """
      Sends acknowledgement to the socket
     """
     buf = self.getAckPacket(packet.crc)
     log.info("Send acknowledgement, crc = %d" % packet.crc)
     return self.send(buf)
예제 #3
0
    def processProtocolPacket(self, protocolPacket):
        """
         Process ATrack packet.
         @type protocolPacket: packets.Packet
         @param protocolPacket: ATrack protocol packet
        """
        if isinstance(protocolPacket, packets.PacketKeepAlive):
            self.uid = protocolPacket.unitId
            log.debug("Keep alive packet received. UnitId = %s" % self.uid)

        # sends the acknowledgment
        self.sendAcknowledgement(protocolPacket)

        if not isinstance(protocolPacket, packets.PacketData):
            return

        if not self.uid:
            self.uid = protocolPacket.unitId
            log.debug("Data packet received. UnitId = %s" % self.uid)

        observerPackets = self.translate(protocolPacket)
        if len(observerPackets) == 0:
            log.info("Location packet not found. Exiting...")
            return

        log.info(observerPackets)
        self.store(observerPackets)
예제 #4
0
파일: tr151.py 프로젝트: gitter-badger/Pipe
    def processDataBuffer(self, buffer, format = 'report'):
        """
         Processing of data from socket / storage.
         @param buffer: Data from socket
         @param format: Source of data format ('report' or 'sms')
        """
        # let's work with text data
        data = buffer.decode()
        rc = self.re_compiled[format]
        position = 0

        log.debug("Data received:\n%s", data)
        m = rc.search(data, position)
        if not m:
            self.processError(data)

        while m:
            # - OK. we found it, let's see for checksum
            log.debug("Raw match found.")
            data_device = m.groupdict()
            packetObserver = self.translate(data_device)
            log.info(packetObserver)
            self.uid = packetObserver['uid']
            self.store([packetObserver])
            position += len(m.group(0))
            m = rc.search(data, position)
예제 #5
0
파일: handler.py 프로젝트: maprox/pipe
 def sendImages(self, images):
     """
      Sends image to the observer
      @param images: dict() of binary data like {'camera1': b'....'}
     """
     if not self.uid:
         log.error('[%s] Cant send an image - self.uid is not defined!',
             self.handlerId)
         return
     imagesList = []
     for image in images:
         image['content'] = base64.b64encode(image['content']).decode()
         imagesList.append(image)
     observerPacket = {
       'uid': self.uid,
       'time': datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f'),
       'images': imagesList
     }
     result = self.store(observerPacket)
     if result.isSuccess():
         log.info('[%s] sendImages(): Images have been sent.',
           self.handlerId)
     else:
         # ? Error messages should be converted into readable format
         log.error('[%s] sendImages():\n %s',
           self.handlerId, result.getErrorsList())
예제 #6
0
파일: handler.py 프로젝트: maprox/pipe
    def processData(self, data):
        """
         Processing of data from socket / storage.
         Might be overridden in child classes
         @param data: Data from socket
        """
        if self._packetsFactory:
            try:
                if self._buffer is None:
                    self._buffer = b''
                self._buffer += data
                protocolPackets = (
                    self._packetsFactory.getPacketsFromBuffer(self._buffer)
                )
                for protocolPacket in protocolPackets:
                    self.processProtocolPacket(protocolPacket)
                self._buffer = None
            except NeedMoreDataException as E:
                log.info('[%s] Need more data...', self.handlerId)
                return
            except Exception as E:
                log.error("[%s] processData error: %s", self.handlerId, E)

        log.debug('[%s] Checking handler commands', self.handlerId)
        if not self.needProcessCommands():
            return self
        log.debug('[%s] Ok we can process commands!', self.handlerId)

        self.processCommands()
        return self
예제 #7
0
 def sendAcknowledgement(self, packet):
     """
      Sends acknowledgement to the socket
      @param packet: a L{packets.BasePacket} subclass
     """
     buf = self.getAckPacket(packet)
     log.info("Send acknowledgement: h" + binascii.hexlify(buf).decode())
     return self.send(buf)
예제 #8
0
파일: tr151.py 프로젝트: gitter-badger/Pipe
 def sendAcknowledgement(self, packet):
     """
      Sends acknowledgement to the socket
      @param packet: a L{packets.Packet} subclass
     """
     buf = self.getAckPacket(packet)
     log.info("Send acknowledgement, crc = %d" % packet.crc)
     return self.send(buf)
예제 #9
0
 def sendAcknowledgement(self, packet):
     """
      Sends acknowledgement to the socket
      @param packet: a L{packets.Packet} subclass
     """
     buf = self.getAckPacket(packet)
     log.info("[%s] Send acknowledgement", self.handlerId)
     return self.send(buf)
예제 #10
0
 def run(self):
     """
      Method wich starts TCP-server
     """
     log.debug("Server::run()")
     self.server_thread = Thread(target = self.server.serve_forever)
     self.server_thread.setDaemon(False)
     self.server_thread.start()
     log.info("Server is started on port %s", self.port)
예제 #11
0
파일: server.py 프로젝트: maprox/pipe
 def run(self):
     """
      Method which starts TCP-server
     """
     log.debug("Server::run()")
     if not HandlerClass:
         log.critical('No protocol handlers specified! (use --handler)')
         return
     server_thread = Thread(target=self.server.serve_forever)
     server_thread.setDaemon(False)
     server_thread.start()
     log.info("Server is started on port %s", self.port)
예제 #12
0
 def sendInternalCommand(self, command):
     """
      Sends command to the tracker
      @param command: Command string
     """
     log.info('Sending "' + command + '"...')
     packet = packets.Packet()
     packet.header = 1
     packet.addTag(0x03, self.headpack['uid'])
     packet.addTag(0x04, self.headpack['uid2'])
     packet.addTag(0xE0, self.__commands_num_seq)
     packet.addTag(0xE1, command)
     self.send(packet.rawData)
     # save sended command in local dict
     self.__commands[self.__commands_num_seq] = packet
     self.__commands_num_seq += 1 # increase command number sequence
예제 #13
0
 def delete(self, item, port, timestamp):
     """
      Removes item from storage, puts in trash
      @param item: Item we want to remove
      @param port: Device port
      @param timestamp: Start timestamp
     """
     try:
         uidName = item['name']
         filename = os.path.join(conf.pathStorage, port, uidName)
         newName = os.path.join(conf.pathTrash, timestamp, port, uidName)
         log.info('Delete data for %s', uidName)
         log.info('fileName = %s, newName = %s', filename, newName)
         newDir = os.path.dirname(newName)
         if not os.path.exists(newDir):
             os.makedirs(newDir)
         os.rename(filename, newName)
     except Exception as E:
         log.error(E)
예제 #14
0
    def processProtocolPacket(self, protocolPacket):
        """
         Process Ime packet.
         @type protocolPacket: packets.Packet
         @param protocolPacket: Ime protocol packet
        """

        self.sendAcknowledgement(protocolPacket)

        self.isHeadPacket = False
        if isinstance(protocolPacket, packets.ImePacketLogin):
            log.info('[%s] Header is stored.', self.handlerId)
            self.uid = protocolPacket.deviceImei
            self.isHeadPacket = True

        if not isinstance(protocolPacket, packets.ImePacketData):
            return

        if not self.__headPacketRawData:
            self.__headPacketRawData = b''

        observerPackets = self.translate(protocolPacket)
        if len(observerPackets) == 0:
            log.info('[%s] Location packet not found. Exiting...',
                     self.handlerId)
            return

        log.info(observerPackets)
        self.store(observerPackets)
예제 #15
0
    def processProtocolPacket(self, protocolPacket):
        """
         Process teltonika packet.
         @type protocolPacket: packets.Packet
         @param protocolPacket: Teltonika protocol packet
        """
        if not self.__headPacketRawData:
            self.__headPacketRawData = b''

        if isinstance(protocolPacket, packets.PacketHead):
            log.info('HeadPack is stored.')
            self.__headPacketRawData = protocolPacket.rawData
            self.uid = protocolPacket.deviceImei

        if not self.uid:
            return log.error('HeadPack is not found!')

        # try to configure this tracker
        if self.configure():
            return

        # sends the acknowledgment
        self.sendAcknowledgement(protocolPacket)

        if isinstance(protocolPacket, packets.PacketHead):
            return

        observerPackets = self.translate(protocolPacket)
        if len(observerPackets) == 0:
            log.info('Location packet not found. Exiting...')
            return

        log.info(observerPackets)
        self.store(observerPackets)
예제 #16
0
    def processProtocolPacket(self, protocolPacket):
        """
         Process naviset packet.
         @type protocolPacket: packets.Packet
         @param protocolPacket: Naviset protocol packet
        """

        self.sendAcknowledgement(protocolPacket)
        self.receiveImage(protocolPacket)

        self.isHeadPacket = False
        log.info('[%s] processProtocolPacket... isHead = %s',
            self.handlerId, self.isHeadPacket)
        if isinstance(protocolPacket, packets.PacketHead):
            log.info('[%s] HeadPack is stored.', self.handlerId)
            self.__headPacketRawData = protocolPacket.rawData
            self.uid = protocolPacket.deviceImei
            self.isHeadPacket = True

        if isinstance(protocolPacket, packets.PacketAnswer):
            log.info("[%s] Storing command answer packet: %s",
                self.handlerId, protocolPacket.__class__)
            broker.sendAmqpAnswer(self, protocolPacket)
            return

        if not isinstance(protocolPacket, packets.PacketData):
            return

        if not self.__headPacketRawData:
            self.__headPacketRawData = b''

        observerPackets = self.translate(protocolPacket)
        if len(observerPackets) == 0:
            log.info('[%s] Location packet not found. Exiting...',
                self.handlerId)
            return

        log.info(observerPackets)
        self.store(observerPackets)
예제 #17
0
    def receiveImage(self, packet):
        """
         Receives an image from tracker.
         Sends it to the observer server, when totally received.
        """
        if (packet == None) or (packet.body == None) or (len(packet.body) == 0):
            log.error('Empty image packet. Transfer aborted!')
            return

        config = self.__imageReceivingConfig
        partnum = packet.body[0]
        if self.__imageReceivingConfig is None:
            self.__imageReceivingConfig = {
              'imageParts': {}
            }
            config = self.__imageReceivingConfig
            log.info('Image transfer is started.')
        else:
            if len(packet.body) > 1:
                log.debug('Image transfer in progress...')
                log.debug('Size of chunk is %d bytes', len(packet.body) - 1)
            else:
                imageData = b''
                imageParts = self.__imageReceivingConfig['imageParts']
                for num in sorted(imageParts.keys()):
                    imageData += imageParts[num]
                self.sendImages([{
                  'mime': 'image/jpeg',
                  'content': imageData
                }])
                self.__imageReceivingConfig = None
                log.debug('Transfer complete.')
                return

        imageData = packet.body[1:]
        config['imageParts'][partnum] = imageData
예제 #18
0
    def processProtocolPacket(self, protocolPacket):
        """
         Process galileo packet.
         @param protocolPacket: Galileo protocol packet
        """
        #if (self.__packNum == 1) and (self.__imageReceivingConfig is None):
        #    self.__packNum += 1
        #    self.sendInternalCommand("Makephoto 1")

        observerPackets = self.translate(protocolPacket)
        self.sendAcknowledgement(protocolPacket)
        if not self.__headPacketRawData:
            self.__headPacketRawData = b''

        if protocolPacket.header == 1:
            self.__headPacketRawData = protocolPacket.rawData

        if protocolPacket.hasTag(0xE1):
            log.info('Device answer is "' +
                protocolPacket.getTag(0xE1).getValue() + '".')

        if len(observerPackets) > 0:
            if 'uid' in observerPackets[0]:
                self.headpack = observerPackets[0]
                self.uid = self.headpack['uid']
                log.info('HeadPack is stored.')
                if 'time' not in self.headpack:
                    observerPackets.remove(self.headpack)

        if protocolPacket.header == 4:
            return self.receiveImage(protocolPacket)

        if len(observerPackets) == 0: return
        log.info('Location packet found. Sending...')

        # MainPack
        for packet in observerPackets:
            packet.update(self.headpack)

        log.info(observerPackets)
        self.store(observerPackets)
예제 #19
0
    def getEmails(self):
        """
         Retrieves emails from IMAP connection
         @return: List of email bodies
        """
        list = []

        host = conf.get("imap", "host")
        port = conf.get("imap", "port")
        username = conf.get("imap", "username")
        password = conf.get("imap", "password")
        filter = conf.get("imap", "filter")

        if not host:
            log.error('IMAP / No host specified! Exiting')
            return list

        log.info('IMAP / Connecting to %s:%s', host, port)
        M = imaplib.IMAP4_SSL(host, port)
        M.login(username, password)
        log.debug("IMAP / Logged in as %s", username)

        try:
            M.select('INBOX', readonly=False) # select INBOX mailbox
            res, data = M.uid('search', filter or '(unseen)')
            nums = data[0].split()

            if len(nums) > 0:
                log.info('IMAP / There are %s new message(s)', len(nums))
            else:
                log.info('IMAP / There are no new messages')

            for num in nums:
                res, data = M.uid('fetch', num, '(RFC822)')
                raw_email = data[0][1]

                msg = email.message_from_bytes(raw_email)
                list.append(msg)
        finally:
            try:
                M.close()
            except:
                pass
            M.logout()

        return list
예제 #20
0
파일: list.py 프로젝트: gitter-badger/Pipe
# -*- coding: utf8 -*-
"""
@project   Maprox <http://www.maprox.net>
@info      Protocol handlers list
@copyright 2009-2013, Maprox LLC
"""

from kernel.logger import log
from kernel.config import conf

# Load modules
HandlerClass = None
handlerName = conf.get("settings", "handler")
handlerClassPath = "lib.handlers." + handlerName
try:
    pkg = __import__(handlerClassPath, globals(), locals(), ["Handler"])
    if hasattr(pkg, "Handler"):
        HandlerClass = getattr(pkg, "Handler")
        HandlerClass.initAmqpThread(handlerName)
        log.info("Protocol is loaded: " + HandlerClass.__doc__)
    else:
        log.error("Class 'Handler' in not found in module %s", handlerClassPath)
except Exception as E:
    log.error("Protocol '%s' loading error: %s", handlerClassPath, E)
예제 #21
0
    def receiveImage(self, packet):
        """
         Receives an image from tracker.
         Sends it to the observer server, when totally received.
        """
        if self.__imageReceivingConfig is None:
            self.__imageReceivingConfig = {
                'bytesReceived': 0,
                'lastChunkReceivedTime': datetime.now(),
                'imageParts': {}
            }

        # Automatic image request each 5 minutes
        #diff = datetime.now() - \
        #    self.__imageReceivingConfig['lastChunkReceivedTime']
        #if diff.seconds > 60 * 5: # 5 minutes
        #    self.__imageReceivingConfig = None
        #    self.sendCommand(packets.CommandGetImage({
        #        "type": commands.IMAGE_RESOLUTION_640x480
        #    }))

        if not isinstance(packet, packets.PacketAnswerCommandGetImage):
            return

        config = self.__imageReceivingConfig
        if packet.code == packets.IMAGE_ANSWER_CODE_SIZE:
            log.info('Image transfer is started.')
            log.info('Size of image is %d bytes', packet.imageSize)
            config['imageSize'] = packet.imageSize
            config['bytesReceived'] = 0
            config['imageParts'] = {}
        elif packet.code == packets.IMAGE_ANSWER_CODE_DATA:
            log.debug('Image transfer in progress...')
            chunkLength = len(packet.chunkData)
            if chunkLength == 0:
                log.debug('Chunk #%d (%d bytes). Null chunk - skip it...',
                    packet.chunkNumber, chunkLength)
            else:
                config['bytesReceived'] += chunkLength
                config['imageParts'][packet.chunkNumber] = packet.chunkData
                log.debug('Chunk #%d (%d bytes). %d of %d bytes received.',
                    packet.chunkNumber, chunkLength,
                    config['bytesReceived'], config['imageSize'])
            if config['bytesReceived'] >= config['imageSize']:
                imageData = b''
                imageParts = self.__imageReceivingConfig['imageParts']
                for num in sorted(imageParts.keys()):
                    imageData += imageParts[num]
                log.debug('Transfer complete. Sending to the server...')
                self.sendImages([{
                    'mime': 'image/jpeg',
                    'content': imageData
                }])
                self.__imageReceivingConfig = None

        # remember time of last chunk to re-request image
        # if connection breaks down
        config['lastChunkReceivedTime'] = datetime.now()
        # send confirmation
        self.sendCommand(commands.NavisetCommandGetImage({
            "type": commands.IMAGE_PACKET_CONFIRM_OK
        }))