Minicap数据解析(python)

Banner.py

import os

class Banner:
    
    def __init__(self):
        self.Version = 0 # 版本信息
        self.Length = 0 # banner长度
        self.Pid = 0 # 进程ID
        self.RealWidth = 0 # 设备的真实宽度                
        self.RealHeight = 0 # 设备的真实高度
        self.VirtualWidth = 0 # 设备的虚拟宽度
        self.VirtualHeight = 0 #设备的虚拟高度
        self.Orientation = 0  # 设备方向
        self.Quirks = 0  # 设备信息获取策略
        
    def toString(self):
        message = "Banner [Version=" + str(self.Version) + ", length=" + str(self.Length) + ", Pid=" + str(self.Pid) + ", realWidth=" +  str(self.RealWidth) + ", realHeight=" +  str(self.RealHeight) + ", virtualWidth=" +  str(self.VirtualWidth) + ", virtualHeight=" +  str(self.VirtualHeight) + ", orientation=" +  str(self.Orientation) +", quirks=" +  str(self.Quirks) + "]"
        return message


#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Created on 2016年12月29日

@author: fengbo
'''

from Banner import Banner
import socket
import threading
from itsdangerous import bytes_to_int
from Queue import Queue

Main.py

class MinicapStream:

    __instance = None
    __mutex = threading.Lock()
    def __init__(self):
        self.IP = "127.0.0.1" # 定义IP
        self.PORT = 1313 # 监听的端口
        self.Pid = 0 # 进程ID    
        self.banner = Banner() # 用于存放banner头信息       
#         self.minicapSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)   
        self.minicapSocket=None     
        self.ReadImageStreamTask = None        
        self.push = None
        self.picture = Queue()
    
    @staticmethod
    def getBuilder():
        """Return a single instance of TestBuilder object """
        if (MinicapStream.__instance == None):
            MinicapStream.__mutex.acquire()
            if (MinicapStream.__instance == None):
                MinicapStream.__instance = MinicapStream()
            MinicapStream.__mutex.release()
        return MinicapStream.__instance
    
    def get_d(self):
        print self.picture.qsize()
    def run(self):
        #开始执行
        #启动socket连接
        self.minicapSocket= socket.socket(socket.AF_INET,socket.SOCK_STREAM)   #定义socket类型,网络通信,TCP
        self.minicapSocket.connect((self.IP,self.PORT))       
#         return self.ReadImageStream()
        self.ReadImageStreamTask = threading.Thread(target=self.ReadImageStream).start()
    
    
    
    def ReadImageStream(self):
        #读取图片流到队列
        
        readBannerBytes = 0
        bannerLength = 2
        readFrameBytes = 0
        frameBodylength = 0
        dataBody = ""
        while True:          
            reallen=self.minicapSocket.recv(4096)         
            length = len(reallen)     
            if not length:
                continue      
            cursor = 0
            while cursor < length:
                #just do it            
                if readBannerBytes < bannerLength:
                    if readBannerBytes==0:
                        self.banner.Version = bytes_to_int(reallen[cursor])                        
                    elif readBannerBytes==1:
                        bannerLength = bytes_to_int(reallen[cursor])             
                        self.banner.Length = bannerLength
                    elif readBannerBytes in [2,3,4,5]:
                        self.banner.Pid += (bytes_to_int(reallen[cursor]) << ((readBannerBytes - 2) * 8)) >> 0;
                    elif readBannerBytes in [6,7,8,9]:
                        self.banner.RealWidth += (bytes_to_int(reallen[cursor]) << ((readBannerBytes - 6) * 8)) >> 0;
                    elif readBannerBytes in [10,11,12,13]:
                        self.banner.RealHeight += (bytes_to_int(reallen[cursor]) << ((readBannerBytes - 10) * 8)) >> 0;
                    elif readBannerBytes in [14,15,16,17]:
                        self.banner.VirtualWidth += (bytes_to_int(reallen[cursor]) << ((readBannerBytes - 14) * 8)) >> 0;
                    elif readBannerBytes in [18,19,20,21]:
                        self.banner.VirtualHeight += (bytes_to_int(reallen[cursor]) << ((readBannerBytes - 18) * 8)) >> 0;
                    elif readBannerBytes == 22:
                        self.banner.Orientation = bytes_to_int(reallen[cursor])*90
                    elif readBannerBytes == 23:
                        self.banner.Quirks = bytes_to_int(reallen[cursor])
                    cursor += 1
                    readBannerBytes += 1
                    if readBannerBytes == bannerLength:
                        print self.banner.toString()                                                    
                elif readFrameBytes < 4:
                    frameBodylength =frameBodylength+ ((bytes_to_int(reallen[cursor])<<(readFrameBytes*8)) >> 0)
                    cursor += 1
                    readFrameBytes += 1
                else:                                                
                    if length - cursor >= frameBodylength:                        
                        dataBody = dataBody + reallen[cursor:(cursor+frameBodylength)]
                        if bytes_to_int(dataBody[0])!=0xFF or bytes_to_int(dataBody[1])!=0xD8:
                            return  
                        self.picture.put(dataBody)  
#                         self.save_file('d:/pic.png', dataBody)         
                        cursor += frameBodylength
                        frameBodylength = 0
                        readFrameBytes = 0
                        dataBody = ""                    
                    else:
                        dataBody = dataBody + reallen[cursor:length]                         
                        frameBodylength -= length - cursor;
                        readFrameBytes += length - cursor;
                        cursor = length;

            
# adb shell LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -P 1200x1920@1200x1920/0
#             adb forward tcp:1313 localabstract:minicap
        
    
    def save_file(self,file_name, data):  
        file=open(file_name, "wb")  
        file.write(data)   
        file.flush()  
        file.close()  


   

if __name__ == '__main__':
    a = MinicapStream.getBuilder()
    print id(a)
    a.run()
#     print a.picture

pyqt.py
#!/usr/bin/env python

#############################################################################
##
## Copyright (C) 2010 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
##   * Redistributions of source code must retain the above copyright
##     notice, this list of conditions and the following disclaimer.
##   * Redistributions in binary form must reproduce the above copyright
##     notice, this list of conditions and the following disclaimer in
##     the documentation and/or other materials provided with the
##     distribution.
##   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
##     the names of its contributors may be used to endorse or promote
##     products derived from this software without specific prior written
##     permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################


from PyQt4 import QtCore, QtGui
from MinicapStream import MinicapStream
import threading
from time import sleep


        
class Screenshot(QtGui.QWidget):
    def __init__(self):
        super(Screenshot, self).__init__()        
        self.obje = MinicapStream.getBuilder()
        self.inst()
        self.picture = self.obje.picture
        self.screenshotLabel = QtGui.QLabel()
        self.screenshotLabel.setSizePolicy(QtGui.QSizePolicy.Expanding,
                QtGui.QSizePolicy.Expanding)
        self.screenshotLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.screenshotLabel.setScaledContents(True)
        self.screenshotLabel.setMinimumSize(400, 640)

        self.createOptionsGroupBox()
        self.createButtonsLayout()

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.screenshotLabel)
        mainLayout.addWidget(self.optionsGroupBox)
        mainLayout.addLayout(self.buttonsLayout)
        self.setLayout(mainLayout)
        
        self.shootScreen()
        self.delaySpinBox.setValue(5)

        self.setWindowTitle("Screenshot")
        self.resize(480,640)
        

#     def resizeEvent(self, event):
#         scaledSize = self.originalPixmap.size()
#         scaledSize.scale(self.screenshotLabel.size(), QtCore.Qt.KeepAspectRatio)
#         if not self.screenshotLabel.pixmap() or scaledSize != self.screenshotLabel.pixmap().size():
#             self.updateScreenshotLabel()
    def inst(self):
        t= threading.Thread(target=self.obje.run)
        t.start()
    
    def newScreenshot(self):        
        while True:
            if not self.picture.empty():
                sleep(0.1)
                self.shootScreen()
            else:
                sleep(0.2)
    

#         if self.hideThisWindowCheckBox.isChecked():
#             self.hide()
#         self.newScreenshotButton.setDisabled(True)
# 
#         QtCore.QTimer.singleShot(self.delaySpinBox.value() * 1000,
#                 self.shootScreen)

    def saveScreenshot(self):
        format = 'png'
        initialPath = QtCore.QDir.currentPath() + "/untitled." + format

        fileName = QtGui.QFileDialog.getSaveFileName(self, "Save As",
                initialPath,
                "%s Files (*.%s);;All Files (*)" % (format.upper(), format))
#         if fileName:
#             self.originalPixmap.save(fileName, format)
    
        
    def shootScreen(self):
        if self.delaySpinBox.value() != 0:
            QtGui.qApp.beep()

        # Garbage collect any existing image first.
        self.originalPixmap = None
#         self.originalPixmap = QtGui.QPixmap.grabWindow(QtGui.QApplication.desktop().winId())
#         self.updateScreenshotLabel()
        pixmap=QtGui.QPixmap()
        pixmap.loadFromData(self.picture.get())
        self.screenshotLabel.setPixmap(pixmap);
        self.newScreenshotButton.setDisabled(False)
        if self.hideThisWindowCheckBox.isChecked():
            self.show()

    def updateCheckBox(self):
        if self.delaySpinBox.value() == 0:
            self.hideThisWindowCheckBox.setDisabled(True)
        else:
            self.hideThisWindowCheckBox.setDisabled(False)

    def createOptionsGroupBox(self):
        self.optionsGroupBox = QtGui.QGroupBox("Options")

        self.delaySpinBox = QtGui.QSpinBox()
        self.delaySpinBox.setSuffix(" s")
        self.delaySpinBox.setMaximum(60)
        self.delaySpinBox.valueChanged.connect(self.updateCheckBox)

        self.delaySpinBoxLabel = QtGui.QLabel("Screenshot Delay:")

        self.hideThisWindowCheckBox = QtGui.QCheckBox("Hide This Window")

        optionsGroupBoxLayout = QtGui.QGridLayout()
        optionsGroupBoxLayout.addWidget(self.delaySpinBoxLabel, 0, 0)
        optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1)
        optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0, 1, 2)
        self.optionsGroupBox.setLayout(optionsGroupBoxLayout)

    def createButtonsLayout(self):
        self.newScreenshotButton = self.createButton("New Screenshot",
                    self.newScreenshot)

        self.saveScreenshotButton = self.createButton("Save Screenshot",
                self.saveScreenshot)

        self.quitScreenshotButton = self.createButton("Quit", self.close)

        self.buttonsLayout = QtGui.QHBoxLayout()
        self.buttonsLayout.addStretch()
        self.buttonsLayout.addWidget(self.newScreenshotButton)
        self.buttonsLayout.addWidget(self.saveScreenshotButton)
        self.buttonsLayout.addWidget(self.quitScreenshotButton)

    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

    def updateScreenshotLabel(self):
        self.screenshotLabel.setPixmap(self.originalPixmap.scaled(
                self.screenshotLabel.size(), QtCore.Qt.KeepAspectRatio,
                QtCore.Qt.SmoothTransformation))
        

        

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)

    screenshot = Screenshot()
    screenshot.show()
    sys.exit(app.exec_())
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,200评论 4 16
  • 本节内容 Python介绍 发展史 Python 2 or 3? 安装 Hello World程序 变量 用户输入...
    小小不懂11阅读 3,390评论 2 30
  • 1. Python的hello-world: print ("Hello, Python!")、 完了 摇就完事儿...
    LunarShade阅读 1,348评论 0 0
  • 近年来, 我国正经历着伟大的民族振兴时期,全国人民努力实现现代化,综合国力有了很大的增强。但是我国与世界经济强国...
    杨琴金山阅读 495评论 1 11
  • 秋之始 夏之末 年之中 万物最后的蓄积、生长、爆发之时 雨一场场下 霜一层层降 越下越凉 越降越重 惹眼的绿色一点...
    清茶咖啡阅读 196评论 0 1