Exemplo n.º 1
0
def parse(searchTerms):
    subDict = scrape()

    i = 0
    postList = []

    # Iterate through all scraped titles
    while i < len(subDict['title']):
        _titl = subDict['title'][i]
        have, want = "", ""

        # Search for faction
        # TODO: No hardcoded faction, switch between buying/selling
        if "ORK" in _titl.upper():
            if "[W]" in _titl.upper():
                have, want = _titl.upper().split("[W]")
            elif "(W)" in _titl.upper():
                have, want = _titl.upper().split("(W)")
            else:
                print(_titl)

            if "ORK" in have.upper():
                postList.append(i)
        i += 1

    for itm in postList:
        if searchTerms[0].upper() != "END":
            for term in searchTerms:
                if term.upper() in subDict['body'][itm]:
                    # Send on post info to alert function
                    Alert.TestAlert(subDict['title'][itm], subDict['url'][itm])
        else:
            Alert.TestAlert(subDict['title'][itm], subDict['url'][itm])
Exemplo n.º 2
0
    def __init__(self, conn_d_id, _user='******'):
        self.conn_d_id = conn_d_id
        self.user = _user
        self.alert = Alert()
        """
            Read database to get full details of device with conn_d_id = self.conn_d_id
            Then assign the values appropriately below
        """
        self.getAppData()

        if self.boardID == 2:
            if self.appliance == "Motion Detector":
                GPIO.setup(int(self.pin), GPIO.IN)
            else:
                GPIO.setup(int(self.pin), GPIO.OUT)
Exemplo n.º 3
0
    def verify(self, h):
        """
        Attempt to verify the current file.
        """
        CrawlConfig.log("hsi(%d) attempting to verify %s" %
                        (h.pid(), self.path))
        rsp = h.hashverify(self.path)

        if "TIMEOUT" in rsp or "ERROR" in rsp:
            rval = "skipped"
            self.set('fails', self.fails + 1)
            CrawlConfig.log(
                "hashverify transfer incomplete on %s -- skipping" % self.path)
            h.quit()
        elif "%s: (md5) OK" % self.path in rsp:
            rval = "matched"
            CrawlConfig.log("hashverify matched on %s" % self.path)
        elif "no valid checksum found" in rsp:
            if self.addable(self.cos):
                rval = self.add_to_sample(h)
            else:
                self.set('checksum', 0)
                rval = "skipped"
                CrawlConfig.log("hashverify skipped %s" % self.path)
        else:
            rval = Alert.Alert("Checksum mismatch: %s" % rsp)
            CrawlConfig.log("hashverify generated 'Checksum mismatch' " +
                            "alert on %s" % self.path)
        return rval
Exemplo n.º 4
0
    def __init__(self):
        threading.Thread.__init__(self)
        
        self.MATRIX = [ [1,2,3,'A'],
                        [4,5,6,'B'],
                        [7,8,9,'C'],
                        ['*',0,'#','D'] ]
        self.ROW = [6,5,11,9]
        self.COL = [10,22,27,17]
        self.password = ""  # this will store current entered password
        self.authenticated = False
        self.GPIOPin = ""
        self.alert = Alert()
        self.command = "Enter password:"

        for j in range(4):
            GPIO.setup(self.COL[j], GPIO.OUT)
            GPIO.output(self.COL[j],1)

        for i in range(4):
            GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down = GPIO.PUD_UP)
Exemplo n.º 5
0
    def get(self, clientversion, year=None, month=None, day=None):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        try:
            if needschedule(year,month,day):
                self.response.out.write('#schedule {:%Y.%m.%d}\n'.format(date.today()))
                self.response.out.write(CalcSchedule.getSchedule(clientversion))
                self.response.out.write('#name ' + CurrentSchedule.schedulename + '\n')

            special = CalcSchedule.getSpecial(clientversion);
            if special:
                self.response.out.write('#special\n')
                self.response.out.write(special)

            if Alert.hasAlerts():
                self.response.out.write('#allalerts\n')
                for alert in Alert.allAlerts():
                    self.response.out.write(str(alert))
                self.response.out.write('__\n')
        except:
            AdminUtils.handleError()
        finally:
            self.response.out.write('#done\n')
Exemplo n.º 6
0
def _redParse(searchTerms):
    subDict = rdt.scrape()

    i = 0
    postList = []

    #Iterate through all scraped titles
    while i < len(subDict['title']):
        _titl = subDict['title'][i]

        #Search for faction
        #TODO: No hardcoded faction, switch between buying/selling
        if "CHAOS" in _titl.upper():
            postList.append(i)
        i += 1

    for itm in postList:
        if searchTerms[0].upper() != "END":
            for term in searchTerms:
                if term.upper() in subDict['body'][itm]:
                    #Send on post info to alert function
                    Alert.TestAlert(subDict['title'][itm], subDict['url'][itm])
        else:
            Alert.TestAlert(subDict['title'][itm], subDict['url'][itm])
def Init():
    global ScriptSettings
    ScriptSettings = Settings(SettingsFile)
    ScriptSettings.Save(SettingsFile)

    global BanWordReward
    BanWordReward = BanWord.BanWord(ScriptName, Parent,
                                    ScriptSettings.EnableDebug)

    global CountdownReward
    CountdownReward = Countdown.Countdown(ScriptName, Parent,
                                          ScriptSettings.EnableDebug)

    global AlertReward
    AlertReward = Alert.Alert(ScriptName, Parent, ScriptSettings.EnableDebug)

    return
Exemplo n.º 8
0
def lambda_handler(event, context):
    dataModel = event
    alert = Alert.Alert(dataModel)
    s3 = S3.S3()

    resultList = []

    if dataModel["config"]["initObject"]:
        resultList.append(alert.backgroundObjectRegister())

    backgroundEvent = s3.readJson("backgroundEvent.json")
    lastNotificationTimestamp = s3.readJson("lastNotificationTimestamp.json")
    result = alert.cameraCoveredDetect(lastNotificationTimestamp,
                                       backgroundEvent)
    if result is not None:
        resultList.append(result)
    backgroundObjectList = s3.readJson("backgroundObjectList.json")

    result = alert.cameraMovedDetect(lastNotificationTimestamp,
                                     backgroundEvent, backgroundObjectList)
    if result is not None:
        resultList.append(result)

    result = alert.backgroundObjectLostDetect(backgroundObjectList,
                                              backgroundEvent)
    if result is not None:
        resultList.append(result)

    result = alert.abnormalObjectStayDetect(backgroundObjectList,
                                            backgroundEvent)
    if result is not None:
        resultList.append(result)

    dataModel["result"] = resultList

    return dataModel
Exemplo n.º 9
0
def main(pathDB):
    countError = 0

    #	Make sure that database exists
    Database.InitDataBase(pathDB)

    ## Open db and read all devices from table Device
    conn = sqlite3.connect(pathDB)
    cur = conn.cursor()
    cur.execute("SELECT * FROM Device ORDER BY deviceId")
    devices = cur.fetchall()

    # if Device table is empty quit
    if len(devices) == 0:
        print("Devices table is empty!")
        return 0

    print("{0} devices found.".format(str(len(devices))))

    totalErrors = 0
    log = ""
    sendEmail = False
    timeNow = time.time()

    #	fetch time of last sent email
    cur.execute("SELECT mailSent FROM Log ORDER BY mailSent DESC")
    timeEmailSent = cur.fetchone()
    if timeEmailSent is None:
        timeEmailSent = 0
    else:
        timeEmailSent = timeEmailSent[0]

## Iterate through all devices
    for device in devices:
        print("Device: {0}\tName: {2}\tUpdated: {1}\tErr:{3}".format(*device))
        #	Check latest values from db
        if Alert.CheckDeviceValues(conn, device[0]) > 0:
            # If time from the last email is >1h and device error has been >1h
            if timeEmailSent + 3600 < timeNow and device[3] + 3600 < timeNow:
                log += "Log records for the device \'{0}\':\n".format(
                    device[2])
                log += ReadLog.GetLogOfDevice(conn, device[2], 10) + "\n"
                ReadLog.MarkSent(conn, device[2])
                totalErrors += 1
                sendEmail = True  # An email will be sent

##	Check if any errors occured and send an email
    if sendEmail:
        #	Generate message
        message = "{0} device(s) has issues!\n".format(totalErrors)
        message += log
        #	Send an email to the address defined in settings table

        cur.execute("SELECT email FROM Settings")
        address = cur.fetchone()
        if address is not None:
            address = address[0]
            smtp.SendMail(address, message)

        print("Send email to {0}:".format(address))
        print(message)
    conn.close()
Exemplo n.º 10
0
class MatrixKeypad(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        
        self.MATRIX = [ [1,2,3,'A'],
                        [4,5,6,'B'],
                        [7,8,9,'C'],
                        ['*',0,'#','D'] ]
        self.ROW = [6,5,11,9]
        self.COL = [10,22,27,17]
        self.password = ""  # this will store current entered password
        self.authenticated = False
        self.GPIOPin = ""
        self.alert = Alert()
        self.command = "Enter password:"******"C":  # press C for resetting a password
                                self.clear()
                            elif self.authenticated:
                                key = str(self.MATRIX[i][j])
                                if key not in("D","A","B","*","#"):
                                    self.GPIOPin = self.GPIOPin + key
                                    self.alert.display2(self.command, self.GPIOPin)
                                    self.portValid(self.GPIOPin)
                                elif key == "A":
                                    self.onAll()
                                elif key == "B":
                                    self.offAll()
                            else:
                                self.password = self.password + str(self.MATRIX[i][j])
                                passLen = "*"*len(self.password)
                                print(passLen)
                                self.alert.display2(self.command, passLen)
                                if len(self.password) == 4:
                                    self.authenticate()
                            time.sleep(0.1)
                            while GPIO.input(self.ROW[i]) == 0:
                                  pass
                    GPIO.output(self.COL[j], 1)
        except KeyboardInterrupt:
            GPIO.cleanup()

    def clear(self):
        self.password = ""
        self.GPIOPin = ""
        self.alert.display2(self.command, "")

    def requireAuth(self):
        self.authenticated = False
        self.command = "Enter password:"******""
        self.GPIOPin = ""
        self.alert.display1(self.command)
    
    def notFound(self):
        self.clear()
        self.alert.display2("Device", "Not found!")

    def onAll(self):
        conn = ConnectionDB()
        apps = conn.getAllLights()
        devices = []
        for app in apps:
            devices.append(app['conn_d_id'])
        macros = MacroCommand(devices, 'on')
        macros.execute()
        self.requireAuth()

    def offAll(self):
        conn = ConnectionDB()
        apps = conn.getAllLights()
        devices = []
        for app in apps:
            devices.append(app['conn_d_id'])
        macros = MacroCommand(devices, 'off')
        macros.execute()
        self.requireAuth()

    def beep(self):
        self.alert.beep()
    
    def portValid(self, conn_d_id):
        conn = ConnectionDB()
        data = conn.portValid(conn_d_id)
        if data:
            state = data['state']
            ap = Appliance(data['conn_d_id'])
            if state == 1:
                ap.off()
            else:
                ap.on()
            self.requireAuth()
        else:
            if len(conn_d_id) == 2:
                self.notFound()
    
    def authenticate(self):
        conn = ConnectionDB()
        response = conn.pinValid(self.password)
        if response == 1:
            print("PIN CORRECT")
            self.command = "Command:"
            self.alert.display1(self.command)
            self.authenticated = True
        else:
            print("PIN wrong.")
            self.alert.display1("PIN WRONG")
            self.command = "Enter password:"******"")
            self.clear()
Exemplo n.º 11
0
    print systemInfo.processInfo_mem


if __name__ == '__main__':
    # config setter
    config = Configure.Configure('./config.xml')

    # log file
    logFileName = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    logger = Loger.Loger('Monitor-' + logFileName + '.log')

    # system info get
    systemInfo = SystemInfo.SystemInfo(pids=None, processName=None)

    # alert center
    alertcenter = Alert.Alert()

    # process names
    processNames = []

    # email info
    mailInfo = None
    receiver = []

    # alert limit define
    # region

    # alert limit configure
    cpuAlertCount = int(systemInfo.cpu_wait_time)
    cpuAlertCounter = 0
Exemplo n.º 12
0
 def get(self):
     Alert.dailyCleanup()
Exemplo n.º 13
0
class Appliance:
    def __init__(self, conn_d_id, _user='******'):
        self.conn_d_id = conn_d_id
        self.user = _user
        self.alert = Alert()
        """
            Read database to get full details of device with conn_d_id = self.conn_d_id
            Then assign the values appropriately below
        """
        self.getAppData()

        if self.boardID == 2:
            if self.appliance == "Motion Detector":
                GPIO.setup(int(self.pin), GPIO.IN)
            else:
                GPIO.setup(int(self.pin), GPIO.OUT)

    def on(self):
        threading.Thread(target=self.alert.ledOn).start()
        if self.boardID == 2:  # Board is Raspberry Pi
            try:
                GPIO.output(int(self.pin), False)
                notify = "{}-{} On".format(self.appliance, self.device_name)
                notifyLCD = "{}".format(self.device_name)
                print(notify)
                self.updateState(1)
                self.alert.display2(notifyLCD, "On")
                return True
            except Exception as e:
                print("Process Raspberry Pi failed {}".format(str(e)))
                return False
        elif self.boardID == 1:  # Board is Arduino
            try:
                conn = SerialManager()
                a = ArduinoApi(conn)
                a.pinMode(int(self.pin), a.OUTPUT)
                a.digitalWrite(int(self.pin), a.LOW)
                notify = "{}-{} On".format(self.appliance, self.device_name)
                notifyLCD = "{}".format(self.device_name)
                print(notify)
                self.updateState(1)
                self.alert.display2(notifyLCD, "On")
                return True
            except Exception as e:
                print("Failed to connect to Arduino {}".format(str(e)))
                return False

    def off(self):
        threading.Thread(target=self.alert.ledOff).start()
        if self.boardID == 2:  # Board is Raspberry Pi
            try:
                GPIO.output(int(self.pin), True)
                notify = "{}-{} Off".format(self.appliance, self.device_name)
                notifyLCD = "{}".format(self.device_name)
                print(notify)
                self.updateState(0)
                self.alert.display2(notifyLCD, "Off")
                return True
            except Exception as e:
                print("Process Raspberry Pi failed {}".format(str(e)))
                return False
        elif self.boardID == 1:  # Board is Arduino
            try:
                conn = SerialManager()
                a = ArduinoApi(conn)
                a.pinMode(int(self.pin), a.OUTPUT)
                a.digitalWrite(int(self.pin), a.HIGH)
                notify = "{}-{} Off".format(self.appliance, self.device_name)
                notifyLCD = "{}".format(self.device_name)
                print(notify)
                self.updateState(0)
                self.alert.display2(notifyLCD, "Off")
                return True
            except Exception as e:
                print("Failed to connect to Arduino {}".format(str(e)))
                return False

    def getstatus(self):
        return self.dstatus

    def updateState(self, state):
        conn = ConnectionDB()
        conn.updateState(self.conn_d_id, state, self.user)

    def logOnDevice(self):
        conn = ConnectionDB()
        conn.logOnDevice(self.conn_d_id, self.user)

    def logOffDevice(self):
        conn = ConnectionDB()
        conn.logOffDevice(self.conn_d_id, self.user)

    def getAppData(self):
        conn = ConnectionDB()
        data = conn.getAppData(self.conn_d_id)

        self.device_id = data['appID']
        self.boardID = data['boardID']
        self.mode = data['modeID']
        self.appliance = data['appliance']
        self.location = data['location']
        self.device_name = data['device_name']
        self.watts = data['watts']
        self.board = data['board']
        self.pin = data['PIN']
        self.date_added = data['date_added']
        self.status = data['state']
        self.auto_time_on = data['auto_time_on']
        self.auto_time_off = data['auto_time_off']

    def buzzerState(self, conn_d_id, state):
        conn = ConnectionDB()
        conn.buzzerState(conn_d_id, state)