Пример #1
0
    def DoGet(self, aRequest):
        Header = THeader()

        R    = None 
        Code = 200
        Content = aRequest.get('content', '{}')

        Path = aRequest.get('path')
        Func = Api.Load(Path)
        if (Func):
            try:
                Content = json.loads(Content)
                try:
                    R = Func(Content)
                    if (R is None):
                        R = {}
                    R = json.dumps(R)
                except Exception as e:
                    Code = 400
                    R = Log.Print(1, self.__class__.__name__, 'DoGet()', e)
            except:
                Code = 400
                R = Log.Print(1, self.__class__.__name__, 'DoGet()', 'json error %s' % Content)
        else:
            Code = 404
            R = 'Error: %s %s' % (Header.Codes.get(Code), Path)

        self.Timer.Init()
        print('In:', Path, Content, 'Out:', R)

        Header.AddCode(Code)
        Header.AddData(R)
        return str(Header)
Пример #2
0
def Api(aData):
    gc.collect()

    Url = aData.get('url')
    R = Update(Url)
    Log.Print(1, 'Api', 'Update()', R)
    return {'result': R, 'ID': Conf.Get('ID'), 'hint': 'Reset ?'}
Пример #3
0
def Api(aData):
    i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
    try:
        Obj = SHT31(i2c)
        R = Obj.get_temp_humi()
    except Exception as e:
        Log.Print(1, 'Err: dev_sht3x', 'Api()', e)
        R = [None, None]
    return {'temperature': R[0], 'humidity': R[1]}
Пример #4
0
def Api(aData):
    i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=10000)
    try:
        bme = BME280(i2c=i2c)
        t, p, h = bme.read_compensated_data()
        R = [t, h, p]
    except Exception as e:
        Log.Print(1, 'Err: DevBME280', 'Api()', e)
        R = [None, None, None]
    return {'temperature': R[0], 'humidity': R[1], 'preasure': R[2]}
Пример #5
0
def Exec(aValue):
    #aValue = 'result = (2+3)*2'
    Vars = {}
    try:
        exec(aValue, globals(), Vars)
        R = Vars.get('result')
    except Exception as e:
        Log.Print(0, 'Exec()', e)
        R = e
    return R
Пример #6
0
def Api(aData):
    #i2c = machine.I2C(scl= machine.Pin(5), sda= machine.Pin(4))
    i2c = machine.I2C(1)
    try:
        Obj = AM2320(i2c)
        #Obj.measure()
        #R = [Obj.temperature(), Obj.humidity()]
        R = [Obj.temperature, Obj.relative_humidity]
    except Exception as e:
        Log.Print(1, 'Err: dev_am2320', 'Api()', e)
        R = [None, None]
    return {'temperature': R[0], 'humidity': R[1]}
Пример #7
0
def Exec():
    Configure()
    ConnectWan()

    gc.collect()
    print('mem_free', gc.mem_free())

    #Log.AddEcho(THost('192.168.2.11', 8008))
    Log.Print(1, 'Run', 'Exec()', 'Start')

    App1 = App.TApp()
    App1.Connect(80, Conf.Get('SockTimeOut', 0.1))
    #try:
    App1.Run()
Пример #8
0
def Get(aPin):
    #Pin = machine.Pin(aPin, machine.Pin.IN, machine.Pin.PULL_UP)
    Pin = machine.Pin(aPin)
    Obj = dht.DHT22(Pin)

    try:
        time.sleep_ms(250)
        Obj.measure()
        time.sleep_ms(250)
        T = Obj.temperature()
        H = Obj.humidity()
        R = [T, H]
    except Exception as e:
        Log.Print(1, 'Err: DevDHT22', 'Get()', e)
        R = [None, None]
    return R
Пример #9
0
def Get(aPin=0):
    try:
        MQ2 = TMQ2(pinData=aPin, baseVoltage=3.3)
        print("Calibrating")
        MQ2.calibrate()

        print("smoke")
        S = MQ2.readSmoke()
        print("lpg")
        L = MQ2.readLPG()
        print("methane")
        M = MQ2.readMethane()
        print("hydrogen")
        H = MQ2.readHydrogen()
        R = [S, L, M, H]
    except Exception as e:
        Log.Print(1, 'dev_mq2', 'Get()', e)
        R = [None, None, None, None]
    return R
Пример #10
0
    def DoTimeOut(self):
        if (self.Cnt > 0 and self.Cnt % 10 == 0):
            try:
                import _sys_unget
                _sys_unget.Api({})
            except Exception as E:
                print('DoTimeOut', E)

        cFL = Conf.Get('FlashLed')
        if (cFL):
            Pin.SetPinInv(cFL)

        cWH = Conf.Get('WatchHost')
        if (cWH):
            if (Net.SendData(cWH, 80)):
                self.WatchHostErr = 0
            else:
                self.WatchHostErr += 1
                if (self.WatchHostErr >= Conf.Get('WatchHostErr', 30)): 
                    Log.Print(1, self.__class__.__name__, 'OnTimer()', 'WatchHost reboot...')
                    time.sleep(5)
                    machine.reset()
Пример #11
0
class TestEngine:
    def __init__(self, config, sku):
        self.config = config
        self.sequence = self.config.Get('TestSequence')
        self.dut_name = self.config.Get('DUT_Name')
        self.eventManager = EventManager()
        self.log = Log()
        port = self.config.Get('port')
        print self.config.Get('port')
        self.comm = Comm232(self.config, self.log, self.eventManager, port)
        #self.comm.UnsetVerbose()
        #print "*********************", self.comm.verboseFlag
        #self.comm.setTimeout(3)
        self.testItems = []
        self.testItemResults = []
        self.BuildTestItems()
        self.testResult = ''
        self.PrepareForInit()
        self.powerdown = PowerDown(self.config, self.eventManager, self.log, \
             self.comm, 2, True)
        self.shopFloorPass = ShopFloorPass(self.config)
        self.shopFloorFail = ShopFloorFail(self.config)

    def PrepareForInit(self):
        cmdStr = '/bin/hostname'
        lsopenfile = subprocess.Popen(cmdStr, shell=True, \
                                      stdout=subprocess.PIPE, \
                                      stderr=subprocess.PIPE)
        lsopenfile.wait()
        self.hostname = lsopenfile.communicate()[0]
        self.testDate = datetime.now().strftime("%Y/%m/%d")

    def PrepareForEachTest(self):
        self.log_filename = self.config.Get('CanisterSN') + \
      '-' + datetime.now().strftime("%Y%m%d%H%M%S") + '.log'
        #self.log_filename2 = self.config.Get('CanisterSN') + \
        #     '-' + datetime.now().strftime("%Y%m%d%H%M%S") + '-boot.log'
        #self.config.Put('BootLogFileName', self.log_filename2)
        print self.log_filename
        #print self.log_filename2
        home_dir = self.config.Get('HOME_DIR')
        self.log.Open(home_dir + '/FTLog/TMP/' + self.log_filename)
        #self.log.Open2(home_dir + '/FTLog/TMP/' + self.log_filename2)
        self.log.PrintNoTime('                                ')
        self.log.PrintNoTime('                                ')

#self.log.PrintNoTime('Station : ' + self.hostname)
#self.log.PrintNoTime('Date    : ' + self.testDate)
#self.log.PrintNoTime('Version : ' + self.config.Get('Version'))
#############################################3333
# No need to print the below item in log, Because there information already print by GetBarcode
#############################################3333
#self.log.PrintNoTime('PN      : ' + self.config.Get('PN'))
#self.log.PrintNoTime('SN      : ' + self.config.Get('SN'))
#self.log.PrintNoTime('BMC_MAC1: ' + self.config.Get('BMC_MAC1'))
#self.log.PrintNoTime('BMC_MAC2: ' + self.config.Get('BMC_MAC2'))
#self.log.PrintNoTime('ETH_MAC1: ' + self.config.Get('ETH_MAC1'))
#self.log.PrintNoTime('ETH_MAC2: ' + self.config.Get('ETH_MAC2'))
#self.log.PrintNoTime('ETH_MAC3: ' + self.config.Get('ETH_MAC3'))
#self.log.PrintNoTime('SAS_EXP : ' + self.config.Get('WWW_SAS_Exp'))
#self.log.PrintNoTime('SAS_Ctl : ' + self.config.Get('WWW_SAS_Contr'))

    def BuildTestItems(self):
        self.testItems = []
        home_dir = self.config.Get('HOME_DIR')
        f = open(home_dir + '/TestConfig/' + self.sequence, 'r')
        lines = f.readlines()
        for line in lines:
            if line[0] == '#':
                continue
        #print line
        #self.testItems.append(eval(line))
        #************************************
        #Date:2014-07-14
        #Author:Yong Tan
        #this following code will let the testscript  import the model automotally, we not need to update the TestEngine.py file(import the New test Item),when there are same new test item added.
        #we split the Class Name and Pramater, And Then import the Class Name(the Class Name must same as the Model Name) and to create a new object with the Class Name, and Paramter.
        #************************************
            print line
            modelPatt = "(?P<ClassName>^\w+)(?P<Parameter>\([\w\W]*\)$)"
            patternModel = re.compile(modelPatt)
            m = patternModel.search(line)
            className = m.group('ClassName')
            if className == "GetBarcode":
                className = "FFGetUnitInfo"
            if className == "ShopFloorQuery":
                continue

            parameter = m.group('Parameter')
            m_import = __import__(className)
            m_testItem = getattr(m_import, className)
            #eval("m_testItem%s" %parameter)
            print m_testItem
            self.testItems.append(eval("m_testItem%s" % parameter))

    def Run(self):
        self.PrepareForEachTest()
        self.errorCodeList = ''
        flexflow_group = []
        self.config.Put('StartTime',
                        datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        for test_oo in self.testItems:
            #print "=====================", self.comm.verboseFlag
            #flexflow_tmp = ['start','duration','name','']
            flexflow_tmp = ['', '', '', '']
            self.log.Print(
                '##############################################################'
            )

            testItemResult = TestItem()
            testItemResult.testName = test_oo.section_str
            self.testResult = test_oo.Start()
            if self.testResult[0:4] == 'FAIL':
                flexflow_tmp[0] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                flexflow_tmp[1] = str(
                    (datetime.now() -
                     datetime.strptime(flexflow_tmp[0],
                                       ("%Y-%m-%d %H:%M:%S"))).seconds)
                flexflow_tmp[2] = test_oo.section_str
                flexflow_tmp[3] = self.testResult[15:20]
                testItemResult.testResult = "FAIL"
                self.config.Put('Sati_ErrorCode', self.testResult[-5:])
                self.log.Print("Test Fail: %s" % test_oo.section_str)
                self.config.Put('Sati_TestResult', 'Failed')
                #self.errorCodeList = self.errorCodeList + self.testResult[-5:] + ', '
                self.errorCodeList = self.errorCodeList + self.testResult[-5:]
                #self.ffSaveResult.Start()
                testItemResult.errorCode = self.testResult[-5:]
                self.testItemResults.append(testItemResult)
                flexflow_group.append(flexflow_tmp)
                self.config.Put('flexflow_group', flexflow_group)
                self.config.Put('TestResult', "Failed")
                return self.testResult
            elif self.testResult == 'PASS':
                self.config.Put('TestResult', "Passed")
                testItemResult.testResult = "PASS"
                self.testItemResults.append(testItemResult)
                pass
            else:
                self.config.Put('TestResult', "Failed")
                self.log.Print("Test result unknow: %s" % test_oo.section_str)
                return 'FAIL'

        #recorde the test result in test log
        if self.errorCodeList == '':
            self.config.Put('Sati_ErrorCode', '00000')
            self.config.Put('Sati_TestResult', 'Passed')
            #self.config.Put('Sati_TestResult', 'Passed')
            return 'PASS'
        else:
            return 'FAIL ErrorCode=%s' % self.errorCodeList

    def End(self):
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        print self.config.Get('Sati_ErrorCode')[:-2]
        self.config.Put('EndTime',
                        datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        if self.config.Get('Sati_ErrorCode')[:-2] == '050':
            pass
        elif self.config.Get('Sati_ErrorCode')[:-2] != '000':
            InvokeYesNoButton("Report Fail to Shop Floor?")
            try:
                open("REPLY_NO")
            except IOError:
                #self.shopFloorFail.Start()
                #f = FFSaveResult(self.config, self.log).Start()
                #if f[15:20] == '030':
                #    InvokeMessagePopup('FlexFlow: SaveResult Error, please check network!', 'Proceed')
                pass

        else:
            #self.shopFloorPass.Start()
            #f = FFSaveResult(self.config, self.log).Start()
            #if f[15:20] == '030':
            #    InvokeMessagePopup('FlexFlow: SaveResult Error, please check network!', 'Proceed')

            pass
        if self.config.Get('Sati_ErrorCode')[:-2] == '050':
            pass
        elif self.config.Get('Sati_ErrorCode')[:-2] != '100' and \
           self.config.Get('Sati_ErrorCode')[:-2] != '190' and \
           self.config.Get('Sati_ErrorCode')[:-2] != '000':
            self.DoPowerOFF()
        else:
            try:
                pass
            #self.powerdown.TurnOff()
            except:
                pass
        #print "Power off"
        #self.powerdown.TurnOff()
        #header_complete_str = 'LS BFT: '  + self.testResult
        #self.log.AddHeader(header_complete_str)
        #to create header in test log
        header_complete_str = ""
        header_complete_str += ('Station    : ' + self.hostname + "\n")
        header_complete_str += ('Date       : ' + self.testDate + "\n")
        header_complete_str += (
            ('Version    : ' + self.config.Get('Version')) + "\n")
        header_complete_str += ('Test Result: %s\n' % (self.testResult))
        header_complete_str += "\n****************************************************************************************\n"
        for ti in self.testItemResults:
            str_testResults = ti.testName.ljust(70) + ti.testResult.rjust(
                10) + "\n"
            header_complete_str = header_complete_str + str_testResults
        header_complete_str += "****************************************************************************************\n"
        self.log.AddHeader_Long(header_complete_str,
                                home_dir + '/FTLog/TMP/' + self.log_filename)
        self.log.Close()
        #self.log.Close2()
        #self.comm.close()

        moveTRIAL1 = 'mv ' + home_dir + '/FTLog/TMP/' + self.log_filename + \
                   ' ' + home_dir + '/FTLog/TRIAL/' + self.log_filename
        #moveTRIAL2 = 'mv ' + home_dir + '/FTLog/TMP/' + self.log_filename2 + \
        #           ' ' + home_dir + '/FTLog/TRIAL/' + self.log_filename2
        movePASS1 = 'mv ' + home_dir + '/FTLog/TMP/' + self.log_filename + \
                   ' ' + home_dir + '/FTLog/PASS/' + self.log_filename
        #movePASS2 = 'mv ' + home_dir + '/FTLog/TMP/' + self.log_filename2 + \
        #           ' ' + home_dir + '/FTLog/PASS/' + self.log_filename2
        moveFAIL1 = 'mv ' + home_dir + '/FTLog/TMP/' + self.log_filename + \
                   ' ' + home_dir + '/FTLog/FAIL/' + self.log_filename
        #moveFAIL2 = 'mv ' + home_dir + '/FTLog/TMP/' + self.log_filename2 + \
        #           ' ' + home_dir + '/FTLog/FAIL/' + self.log_filename2
        if self.config.Get('RUN_STATE') == 'TrialRun':
            print moveTRIAL1
            os.system(moveTRIAL1)
            #print moveTRIAL2
            #os.system(moveTRIAL2)
        elif self.testResult == 'PASS':
            print movePASS1
            os.system(movePASS1)
            #print movePASS2
            #os.system(movePASS2)
        elif self.testResult[0:4] == 'FAIL':
            print moveFAIL1
            os.system(moveFAIL1)
            #print moveFAIL2
            #os.system(moveFAIL2)

    def DoPowerOFF(self):
        InvokeYesNoButton("Click YES to start shutting down SATI")
        try:
            open("REPLY_NO")
        except IOError:
            self.powerdown.TurnOff()
        else:
            pass
Пример #12
0
def Api(aData):
    Msg   = aData.get('msg')
    Level = aData.get('level', 1)
    R = Log.Print(Level, Msg)
    return {'result': R}