示例#1
0
    def __init__(self):
        self.file = LogWriter.LogWriter('log.txt')

        graph = facebook.GraphAPI(
            '1415774871877416|jzA-PuQwDbOG2m1vPgUYlPJtpn8')
        resp = graph.get_object('me/friends')

        for page in resp['data']:
            print(page)

        pass
示例#2
0
#!/usr/bin/env python

from DroneSimulator import *
from IpController import *
from LogWriter import *
from TimerThread import *
from ZTEmodem import *

from traceback import format_exception
import signal, sys

closeServerApp = False  # Main loop control (True=stop this app)

customDir = "."

logWriter = LogWriter(customDir + "/logs/simulator")


def topExceptHook(type, value, traceback):
    global logWriter
    exceptMsg = format_exception(type, value, traceback)
    try:
        logWriter.noteEvent("MainThread: unhandled Exception ", str(exceptMsg))
    except:
        pass  #can't handle logWriter exceptions here

    print "MainThread: unhandled Exception "
    for line in format_exception(type, value, traceback):
        print line,

    endHandler(None, None)
示例#3
0
 def __init__(self):
     self.controller = SC.clientSock()
     self.log = logw.LogWriter()
from DroneControler import DroneController
from ControlData import *
import time
from LogWriter import *
import struct

RB2 = "/dev/ttyAMA0"
RB3 = "/dev/ttyS0"


def onReceiveUsart(debugData):
    print 'Recived:', str(debugData)


logWriter = LogWriter('logs')
droneControler = DroneController(RB2, 115200, logWriter)

droneControler.setOnReceiveEvent(onReceiveUsart)

# time parameters of test
duration = 15.0  # [s]
sendingFreq = 2.0  # [Hz]

i = 0
while i < sendingFreq * duration:
    i += 1
    droneControler.sendCommData(ControlData.SomeValidControlCommand())
    time.sleep(1 / sendingFreq)

i = 0
while i < sendingFreq * 1:
    print "ERROR: can't find log dir: " + str(logsDIR)
    sys.exit(1)

###########################################################################
## LOAD SETTINGS
###########################################################################
SETTINGS = Settings(configFileName)
if customPort:
    SETTINGS.PORT = customPort

###########################################################################
## INIT
###########################################################################
#TODO make log writer global

logWriter = LogWriter(customDIR + "/logs/")

modem = ZTEmodem()

##UART part
droneController = DroneController(SETTINGS.UARTDEVICE, SETTINGS.UARTBAUDRATE,
                                  logWriter)
##-------

##IP part
server_name = ""  # "localhost"
ipController = IpController((server_name, SETTINGS.PORT),
                            SETTINGS.TCPSIMULATOR, True, SETTINGS.BINDRETRYNUM,
                            logWriter)

##--
from IpController import *
from LogWriter import *

logWriter = LogWriter('logs/')

receiver = IpController('', True, False, 10, logWriter)


def onReveiveControlDataFromIP(controlData):
    print "MainThread: ", str(controlData)


receiver.setOnReceiveEvent(onReveiveControlDataFromIP)

print('MainThread: waiting for a connection')
receiver.acceptConnection()
while receiver.keepConnection():
    receiver.forwardIncomingPacket()
print('MainThread: connection closed')

logWriter.noteEvent("MainThread: endHandler")
receiver.close()
logWriter.close()

print "DONE"
示例#7
0
def LinePost():
    """  LINE からメッセージがポストされたとき  """
    logWriter       = LogWriter.LogWriter( STORAGE_NAME, STORAGE_KEY )

    logWriter.WriteLog( "***** メッセージが LINE から POST されました。 *****" )
    try:
        szText  = "";

        for szKey, szValue in request.headers.items():
            szText += str( szKey ) + " : " + str( szValue ) + "\r\n"
        #for
        szText += "\r\n"

        # get request body as text
        body = request.get_data( as_text = True )
        app.logger.info( "Request body: " + body )
        szText += body;
        logWriter.WriteLog(
            "HTTP の内容\r\n" + szText
        );

        logWriter.WriteLog( "ヘッダーから 'X-Line-Signature' 取得中……" );
        signature = request.headers[ 'X-Line-Signature' ]

        # parse webhook body
        logWriter.WriteLog( "webhook body を解析中……" );
        try:
            events = parser.parse( body, signature )
        except InvalidSignatureError as e:
            #WriteLog( "parser.parse() failed." + "\r\n" + e.message );
            logWriter.WriteLog( "X-Line-Signature と LINE_CHANNEL_SECRET が一致しません。" );
            abort(400)
        except:
            raise;
        #}try

        # if event is MessageEvent and message is TextMessage, then echo text
        logWriter.WriteLog( "events を解析……" );
        for event in events:
            #// MessageEvent 型ではない
            if not isinstance( event, MessageEvent ):
                continue

            logWriter.WriteLog( "ユーザー ID 取得中……" );
            szUserID    = "";
            szUserName  = "";
            try:
                if( event.source.type == "user" ):
                    szUserID    = event.source.user_id;
                    logWriter.WriteLog( "ユーザー名取得中……" );
                    pProfile    = line_bot_api.get_profile( szUserID );
                    szUserName  = pProfile.display_name + " さん";
                    logWriter.WriteLog( szUserName );
                #}if
            except Exception as e:
                logWriter.WriteLog( str( e ) );
            #}try

            if isinstance( event.message, TextMessage ):
                logWriter.WriteLog( "テキスト メッセージです。" );
                szMessage   = "{0}\r\n「{1}」の QR コードを作成しました。".format( szUserName, event.message.text );

                #logWriter.WriteLog( "QR コードを作成中です。" );
                #pQrBuffer   = MakeQRCode( event.message.text );
                #szFileName  = szUserID + "\\qr-" + str( uuid.uuid4() );

                ##// オリジナル画像をストレージに保存する
                #logWriter.WriteLog( "オリジナル画像を保存中です。" );
                #szTempFileName  = szFileName + ".jpg";
                #logWriter.WriteBlob( szTempFileName, pQrBuffer[ 0 ] );
                #szOrgUri    = logWriter.MakeBlobUri( szTempFileName );
                #logWriter.WriteLog( "場所 '{0}'".format( szOrgUri ) );

                ##// サムネイル画像をストレージに保存する
                #logWriter.WriteLog( "サムネイル画像を保存中です。" );
                #szTempFileName  = szFileName + "_s.jpg";
                #logWriter.WriteBlob( szTempFileName, pQrBuffer[ 1 ] );
                #szThumbUri  = logWriter.MakeBlobUri( szTempFileName );
                #logWriter.WriteLog( "場所 '{0}'".format( szThumbUri ) );

                ReplyMessage(
                    event,
                    [
                    TextSendMessage(
                        text = szMessage
                    ),
                    #ImageSendMessage(
                    #    original_content_url    = szOrgUri,
                    #    preview_image_url       = szThumbUri
                    #)
                    TextSendMessage(
                        text = "かと思ったら、ライブラリー内でエラーが発生するため頓挫しました。"
                    ),
                    ]
                )
            elif isinstance( event.message, ImageMessage ):
                logWriter.WriteLog( "画像 メッセージです。" );

                logWriter.WriteLog( "画像コンテンツを取得中……" );
                message_id      = event.message.id
                message_content = line_bot_api.get_message_content( message_id )

                szImageFileName = szUserID + "\\" + str( uuid.uuid4() ) + r".jpg";
                logWriter.WriteLog( "画像コンテンツをストレージに保存しています。(ファイル名:" + szImageFileName + ")" );
                logWriter.WriteBlob( szImageFileName, message_content.content );

                image = io.BytesIO( message_content.content )

                logWriter.WriteLog( "Azure Computer Vision にインスタンス作成。" );
                pRestApi    = AnalyzeImage.AnalyzeImage( COMPUTER_VISION_KEY );
                logWriter.WriteLog( "Azure Computer Vision にリクエスト送信。" );
                szJson      = pRestApi.Request( image );

                logWriter.WriteLog( szJson );

                pRoot   = json.loads( szJson );

                szReply     = "";
                szExplicit  = "";

                #//  とりあえず説明文を取得する
                pDesc   = pRoot[ "description" ];
                szCaption       = "";
                lfConfidence    = 0.0;

                for pCap in pDesc[ "captions" ]:
                    if( lfConfidence < pCap[ "confidence" ] ):
                        szCaption       = pCap[ "text" ];
                        lfConfidence    = pCap[ "confidence" ];
                    #}if
                #}for

                #// Explicit
                #"adult":{"isAdultContent":false,"isRacyContent":false,"adultScore":0.045499119907617569,"racyScore":0.034160565584897995}
                pAdult  = pRoot[ "adult" ];
                szExplicit  += "KENZEN ポイント: {0}pt.".format( int( pAdult[ "adultScore" ] * 100 ) );
                szExplicit  += "\r\n";
                szExplicit  += "判定: ";
                if( pAdult[ "isAdultContent" ] ):
                    szExplicit  += "けしからん";
                else:
                    szExplicit  += "健全";
                #}if
                szExplicit  += "\r\n";
                szExplicit  += "ギリギリポイント: {0}pt.".format( int( pAdult[ "racyScore" ] * 100 ) );
                szExplicit  += "\r\n";
                szExplicit  += "判定: ";
                if( pAdult[ "isRacyContent" ] ):
                    szExplicit  += "けしからん";
                else:
                    szExplicit  += "健全";
                #}if
                szExplicit  += "\r\n";

                if( 0 < len( szCaption ) ):
                    #// 英語の解説を日本語に変換
                    pTransApi   = TranslatorText.Translate( TRANSLATOR_TEXT_KEY );
                    logWriter.WriteLog( "英語を日本語に翻訳中。({0})".format( szCaption ) );
                    szJson      = pTransApi.Request( szCaption );
                    logWriter.WriteLog( szJson );
                    pRoot       = json.loads( szJson );
                    szTrans     = "";
                    for pTransRoot in pRoot:
                        #logWriter.WriteLog( str( pTransRoot ) );
                        for pTrans in pTransRoot[ "translations" ]:
                            logWriter.WriteLog( str( pTrans ) );
                            szTrans += pTrans[ "text" ];
                            #for pTextRoot in pTrans:
                            #    logWriter.WriteLog( str( pTextRoot ) );
                    #}for

                    szReply = szUserName + "、この絵は「" + szTrans  + "(" + szCaption + ")」"
                    if( 0.8 <= lfConfidence ):
                        szReply += "です。";
                    elif( 0.6 <= lfConfidence ):
                        szReply += "かと思います。";
                    elif( 0.4 <= lfConfidence ):
                        szReply += "かな。";
                    elif( 0.2 <= lfConfidence ):
                        szReply += "です。たぶん……";
                    else:
                        szReply += "だと思うけど違っていそうです。";
                    #}if
                    szReply += "(正確度:{0}%)".format( int( lfConfidence * 100 ) );
                else:
                    szReply = szUserName + "、申し訳ありませんが、何の絵か全くわかりません。";
                #}if

                pReplyList  = list();
                if( 0 < len( szReply ) ):
                    pReplyList.append(
                        TextSendMessage(
                            text = szReply
                        )
                    )
                #}if
                if( 0 < len( szExplicit ) ):
                    pReplyList.append(
                        TextSendMessage(
                            text = szExplicit
                        )
                    )
                #}if

                ReplyMessage(
                    event,
                    pReplyList
                )
            else:
                logWriter.WriteLog( "type:{0} のメッセージです。現在、サポートしていません。".format( type( event ) ) );
                ReplyMessage(
                    event,
                    TextSendMessage(
                        text = "Sorry, this input resource is not supported."
                    )
                );
            #}if
        #}for event in events:

        logWriter.WriteLog( "OK" );
    except Exception as e:
        #WriteLog( szProgress + "でエラー発生。" + "\r\n" + e.message );
        szMsg   = str( e ) + "\r\n" + "でエラー発生。";
        ReplyMessage(
            event,
            TextSendMessage(
                text = szMsg
            )
        );
        logWriter.WriteLog( szMsg + "\r\n" + traceback.format_exc() );
        abort(400)
    #}try

    logWriter.WriteLog( "Exit LinePost()." );

    return 'OK'
示例#8
0
def log_to_file(file='pyLog.log'):
    global LOG_TO_FILE
    LOG_TO_FILE = log.LogWriter(file)
    LOG_TO_FILE.open()