Ejemplo n.º 1
0
def notify(serial_number,zone_name):
    global _LAST_NOTIFY
    print("Time since last notification: ")
    print(int(time.time()) - _LAST_NOTIFY)
    if ((int(time.time()) - _LAST_NOTIFY) >= MOTION_ALERT_PAUSE_TIME):

        ts = str(time.time()).split(".")[0] + "000"
        #snaptime = (datetime.datetime.now() - datetime.timedelta(seconds=5)).isoformat().split(".")[0] + "-06:00"
        #print(snaptime)
        
        posturl = 'https://dashboard.meraki.com/api/v0/networks/{0}/cameras/{1}/snapshot'.format(NETWORK_ID, serial_number)
        headers = {
            'x-cisco-meraki-api-key': format(str(MERAKI_API_KEY)),
            'Content-Type': 'application/json'
        }
        postdata = {
            #'timestamp': format(str(snaptime))	
        }

        dashboard = requests.post(posturl, data=json.dumps(postdata), headers=headers)
        djson = json.loads(dashboard.text)
        file = format(str(djson['url']))
                
        videolink = merakiapi.getmvvideolink(MERAKI_API_KEY, NETWORK_ID, serial_number, ts)
        camera = merakiapi.getdevicedetail(MERAKI_API_KEY, NETWORK_ID, serial_number)
    
        msg = "**New People Detection!** <br> **Camera:** {} ({}) <br> **Zone:** {} <br> **Total detections:** {}  <br> **Video Link:** {}".format(camera['name'], serial_number, zone_name, MOTION_ALERT_PEOPLE_COUNT_THRESHOLD, videolink['url'])
        time.sleep(3)
        result = sent_notification(msg,files=file)
        
        _LAST_NOTIFY = int(time.time())
    else:
        print("Skipping Notification, too soon")
Ejemplo n.º 2
0
def replaceForm():
    form = ReplaceDevice()
    if form.validate_on_submit():
        message = []

        postNetwork = form.networkField.data
        netname = merakiapi.getnetworkdetail(apikey, postNetwork)
        oldMX = form.oldMX.data
        newMX = form.newMX.data
        oldSwitch = form.oldSwitch.data
        newSwitch = form.newSwitch.data
        oldAP = form.oldAP.data
        newAP = form.newAP.data

        if oldMX is not '':
            oldconfig = merakiapi.getdevicedetail(apikey, postNetwork, oldMX)
            merakiapi.updatedevice(apikey,
                                   postNetwork,
                                   newMX,
                                   name=oldconfig['name'],
                                   tags=oldconfig['tags'],
                                   lat=oldconfig['lat'],
                                   lng=oldconfig['lng'],
                                   address=oldconfig['address'],
                                   move='true')
            result = merakiapi.removedevfromnet(apikey, postNetwork, oldMX)
            if result == None:
                message = Markup(
                    'MX with serial <strong>{}</strong> successfully deleted from Network: <strong>{}</strong>'
                    .format(oldMX, netname['name']))
            merakiapi.claim(apikey, organizationid, serial=newMX)
            result = merakiapi.adddevtonet(apikey, postNetwork, newMX)
            if result == None:
                message = Markup(
                    'MX with serial <strong>{}</strong> successfully added to Network: <strong>{}</strong>'
                    .format(newMX, netname['name']))

        if oldSwitch is not '':
            #ADD NEW SWITCH TO NETWORK
            merakiapi.claim(apikey, organizationid, serial=newSwitch)
            result = merakiapi.adddevtonet(apikey, postNetwork, newSwitch)
            oldconfig = merakiapi.getdevicedetail(apikey, postNetwork,
                                                  oldSwitch)
            merakiapi.updatedevice(apikey,
                                   postNetwork,
                                   newSwitch,
                                   name=oldconfig['name'],
                                   tags=oldconfig['tags'],
                                   lat=oldconfig['lat'],
                                   lng=oldconfig['lng'],
                                   address=oldconfig['address'],
                                   move='true')
            if result == None:
                message = Markup(
                    'Switch with serial <strong>{}</strong> successfully added to Network: <strong>{}</strong>'
                    .format(newSwitch, netname['name']))
                #CLONE L2 PORT CONFIGS
                if '24' in oldconfig['model']:
                    numports = 30
                elif '48' in oldconfig['model']:
                    numports = 54
                elif '16' in oldconfig['model']:
                    numports = 22
                elif '32' in oldconfig['model']:
                    numports = 38
                for port in range(1, numports):
                    config = merakiapi.getswitchportdetail(
                        apikey, oldSwitch, port)
                    print(config)
                    # Clone corresponding new switch
                    # Tags needed to be input as a list
                    #if config['tags'] is not '':
                    #    tags = config['tags'].split()
                    #else:
                    tags = []

                    # Access type port
                    if config['type'] == 'access':
                        merakiapi.updateswitchport(
                            apikey,
                            newSwitch,
                            port,
                            name=config['name'],
                            tags=tags,
                            enabled=config['enabled'],
                            porttype=config['type'],
                            vlan=config['vlan'],
                            voicevlan=config['voiceVlan'],
                            poe='true',
                            isolation=config['isolationEnabled'],
                            rstp=config['rstpEnabled'],
                            stpguard=config['stpGuard'],
                            accesspolicynum=config['accessPolicyNumber'])

# Trunk type port
                    elif config['type'] == 'trunk':
                        merakiapi.updateswitchport(
                            apikey,
                            newSwitch,
                            port,
                            name=config['name'],
                            tags=tags,
                            enabled=config['enabled'],
                            porttype=config['type'],
                            vlan=config['vlan'],
                            allowedvlans=config['allowedVlans'],
                            poe='true',
                            isolation=config['isolationEnabled'],
                            rstp=config['rstpEnabled'],
                            stpguard=config['stpGuard'])
            #404 MESSAGE FOR INVALID SERIAL IS BLANK, POPULATE ERROR MESSAGE MANUALLY
            elif result == 'noserial':
                message = Markup(
                    'Invalid serial <strong>{}</strong>'.format(serial))
            else:
                message = result
            #REMOVE OLD SWITCH FROM NETWORK
            merakiapi.removedevfromnet(apikey, postNetwork, oldSwitch)

        if oldAP is not '':
            oldconfig = merakiapi.getdevicedetail(apikey, postNetwork, oldAP)
            merakiapi.updatedevice(apikey,
                                   postNetwork,
                                   newAP,
                                   name=oldconfig['name'],
                                   tags=oldconfig['tags'],
                                   lat=oldconfig['lat'],
                                   lng=oldconfig['lng'],
                                   address=oldconfig['address'],
                                   move='true')
            result = merakiapi.removedevfromnet(apikey, postNetwork, oldAP)
            if result == None:
                message = Markup(
                    'AP with serial <strong>{}</strong> successfully deleted from Network: <strong>{}</strong>'
                    .format(oldMX, netname['name']))
            merakiapi.claim(apikey, organizationid, serial=newAP)
            result = merakiapi.adddevtonet(apikey, postNetwork, newAP)
            if result == None:
                message = Markup(
                    'AP with serial <strong>{}</strong> successfully added to Network: <strong>{}</strong>'
                    .format(newMX, netname['name']))

        #SEND MESSAGE TO SUBMIT PAGE
        flash(message)
        return redirect('/submit')
    return render_template('replace.html',
                           title='Meraki Device Provisioning',
                           form=form)
Ejemplo n.º 3
0
def notify(serial_number, detection_type, zone_id):
    global _LAST_PEOPLE_NOTIFY, _LAST_VEHICLE_NOTIFY
    if detection_type == 'vehicle':
        print("Time since last vehicle notification: ")
        print(int(time.time()) - _LAST_VEHICLE_NOTIFY)
    if detection_type == 'people':
        print("Time since last people notification: ")
        print(int(time.time()) - _LAST_PEOPLE_NOTIFY)
    if (((detection_type == 'people') and
         (int(time.time()) - _LAST_PEOPLE_NOTIFY) >= MOTION_ALERT_PAUSE_TIME)
            or
        ((detection_type == 'vehicle') and
         (int(time.time()) - _LAST_VEHICLE_NOTIFY) >= MOTION_ALERT_PAUSE_TIME)
        ):

        ts = str(time.time()).split(".")[0] + "000"
        #snaptime = (datetime.datetime.now() - datetime.timedelta(seconds=5)).isoformat().split(".")[0] + "-06:00"
        #print(snaptime)

        if config.DEBUG:
            print("SNAPSHOT API CALL")

        posturl = 'https://dashboard.meraki.com/api/v0/networks/{0}/cameras/{1}/snapshot'.format(
            NETWORK_ID, serial_number)
        headers = {
            'x-cisco-meraki-api-key': format(str(MERAKI_API_KEY)),
            'Content-Type': 'application/json'
        }
        postdata = {
            #'timestamp': format(str(snaptime))
        }

        dashboard = requests.post(posturl,
                                  data=json.dumps(postdata),
                                  headers=headers)
        djson = json.loads(dashboard.text)
        file = format(str(djson['url']))
        if config.DEBUG:
            print("URL: {}".format(file))

        # WAIT FOR SNAPSHOT IMAGE
        if config.DEBUG:
            print("PAUSING TO WAIT FOR SNAPSHOT IMAGE")
        time.sleep(4)

        if config.DEBUG:
            print("GETTING ZONE NAME")
        zones = merakiapi.getmvzones(MERAKI_API_KEY, serial_number)
        for zone in zones:
            if zone['zoneId'] == zone_id:
                zone_name = zone['label']
                break
        if config.DEBUG:
            print("ZONE NAME: %s" % zone_name)

        videolink = merakiapi.getmvvideolink(MERAKI_API_KEY, NETWORK_ID,
                                             serial_number, ts)
        if config.DEBUG:
            print("VIDEO LINK: %s" % videolink)

        camera = merakiapi.getdevicedetail(MERAKI_API_KEY, NETWORK_ID,
                                           serial_number)
        if config.DEBUG:
            print("CAMERA: %s" % camera)

        if config.DEBUG:
            print("DOWNLOADING SNAPSHOT FROM CAMERA")

        image = requests.get(file, allow_redirects=True)
        open('photo.jpg', 'wb').write(image.content)
        if config.DEBUG:
            print("SNAPSHOT SUCCESSFULLY DOWNLOADED")

            msg = ""

            if detection_type == 'vehicle':

                with open('photo.jpg', 'rb') as image_file:
                    image_base64 = base64.b64encode(image_file.read())

                    if config.DEBUG:
                        print("SNAPSHOT SUCCESSFULLY ENCODED")

                    msg += "*New Vehicle Detection!* <br>"
                    if config.lpr:
                        if config.DEBUG:
                            print("STARTING OPENALPR")
                        posturl = 'https://api.openalpr.com/v2/recognize_bytes?recognize_vehicle=1&country=us&secret_key=%s' % (
                            openalprsecret)
                        try:
                            plateresult = requests.post(posturl,
                                                        data=image_base64)
                        except requests.exceptions.RequestException as e:  # This is the correct syntax
                            print("OPENALPR API FAILED!")
                            print(e)
                        print("OPENALPR RETURNED")
                        plates = json.loads(plateresult.text)

                        if config.DEBUG:
                            print(json.dumps(plateresult.json(), indent=2))

                        for result in plates['results']:
                            for key, value in result.items():
                                if key == 'plate':
                                    v_plate = value
                                    print("PLATE: %s" % value)
                                if key == 'vehicle':
                                    v_color = value['color'][0]['name']
                                    v_make = value['make'][0]['name']
                                    #v_body = value['body_type'][0]['name']
                                    v_year = value['year'][0]['name']
                                    print("COLOR: %s" %
                                          value['color'][0]['name'])
                                    print("MAKE: %s" %
                                          value['make'][0]['name'])
                                    #print("BODY TYPE: %s" % value['body_type'][0]['name'])
                                    print("YEAR: %s" %
                                          value['year'][0]['name'])
                        """
                  #DUMMY DATA FOR TESTING
                  v_plate = "123ABC"
                  v_color = "GREEN"
                  v_make = "DODGE"
                  v_body = "SUV"
                  v_year = "1999"
                  """

                        msg += "*License Plate:* {} <br> *Vehicle Color:* {} <br> *Make:* {} <br> *Year:* {} <br>".format(
                            v_plate, v_color.capitalize(), v_make.capitalize(),
                            v_year)

                    #else:
                    #  msg = "*New Vehicle Detection!* <br> *Camera:* {} ({}) <br> *Zone:* {} <br> *Total detections:* {}  <br> *Video Link:* {}".format(camera['name'], serial_number, zone_name, MOTION_ALERT_VEHICLE_COUNT_THRESHOLD, videolink['url'])
            if detection_type == 'people':

                msg += "*New People Detection!*  \n"

                if config.image_detect:
                    if config.DEBUG:
                        print("STARTING MICROSOFT IMAGE PROCESSING")

                    image_data = open('photo.jpg', "rb").read()

                    #MICROSOFT IMAGE DETECTION
                    posturl = "{}/vision/v2.0/analyze".format(
                        config.computervision_endpoint)
                    headers = {
                        'Ocp-Apim-Subscription-Key':
                        format(str(microsoftapikey)),
                        'Content-Type': 'application/octet-stream'
                    }
                    postdata = {
                        #'url': 'https://spn16.meraki.com/stream/jpeg/snapshot/a9a675d665f5ba49VHODA3OThkMDY1Y2I3YWJiYjUzNzQzYWYyYTA4MDEyYjJmNzQ2NmQwYzkxZDA0MzZkNmI4YjZhOWEzNDRhZDRjManEcZLzQhsSgIvXY1Rrp64ynNWUCq3vFDmwbpm0DB2LjAJUOrVIu0_kDw1IKX3O-83oX4W43if8heYm8groFojxrDempDPdBZPmRhoMwLM7Znqbfn0jlPcClaoRPSzTZy02j0YE0OmX70-RmPIraZh9tPssnnlsWHfGNDS7ZKkbf4qHI-fXp39TEd6lZ6QOtz_gFYofETwniPWNwu54TiE'
                        'url': file
                    }
                    #postdata = json.dumps(postdata)
                    params = {'visualFeatures': 'Categories,Tags,Color'}

                    try:
                        imageresult = requests.post(posturl,
                                                    headers=headers,
                                                    params=params,
                                                    data=image_data)
                    except requests.exceptions.RequestException as e:  # This is the correct syntax
                        print("MICROSOFT VISION API FAILED!")
                        print(e)

                    cog = json.loads(imageresult.text)
                    if config.DEBUG:
                        print("MICROSOFT IMAGE ANALYSIS RESULT JSON: %s" % cog)

                    tagstring = "*Detected Tags:* <br>"
                    for tag in cog['tags']:
                        if tag['confidence'] >= 0.8:
                            tagstring += "&nbsp;&nbsp;&nbsp;&nbsp;{} <br>".format(
                                tag['name'].capitalize())
                            print(tag['name'].capitalize())

                    msg += tagstring

                if config.face_detect:
                    if config.DEBUG:
                        print("STARTING MICROSOFT FACE PROCESSING")
                    #MICROSOFT FACE DETECTION

                    image_data1 = open('photo.jpg', "rb").read()

                    faceurl = "{}/detect".format(config.face_endpoint)
                    headers = {
                        'Ocp-Apim-Subscription-Key': microsoftfaceapikey,
                        'Content-Type': 'application/octet-stream'
                    }
                    params = {
                        'returnFaceId':
                        'true',
                        'returnFaceLandmarks':
                        'false',
                        'returnFaceAttributes':
                        'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
                    }

                    #image_url = 'https://spn16.meraki.com/stream/jpeg/snapshot/a9a675d665f5ba49VHODA3OThkMDY1Y2I3YWJiYjUzNzQzYWYyYTA4MDEyYjJmNzQ2NmQwYzkxZDA0MzZkNmI4YjZhOWEzNDRhZDRjManEcZLzQhsSgIvXY1Rrp64ynNWUCq3vFDmwbpm0DB2LjAJUOrVIu0_kDw1IKX3O-83oX4W43if8heYm8groFojxrDempDPdBZPmRhoMwLM7Znqbfn0jlPcClaoRPSzTZy02j0YE0OmX70-RmPIraZh9tPssnnlsWHfGNDS7ZKkbf4qHI-fXp39TEd6lZ6QOtz_gFYofETwniPWNwu54TiE'
                    image_url = file

                    try:
                        response = requests.post(faceurl,
                                                 headers=headers,
                                                 params=params,
                                                 data=image_data1)
                    except requests.exceptions.RequestException as e:  # This is the correct syntax
                        print("MICROSOFT FACE API FAILED!")
                        print(e)
                    rstr = json.dumps(response.json())
                    faces = json.loads(rstr)
                    if config.DEBUG:
                        print("FACES JSON: %s" % rstr)

                    facecount = 0
                    facestring = ""

                    for face in faces:
                        facecount += 1
                        facestring += "*Face {}:* <br>".format(facecount)
                        print("FACE %s: " % facecount)
                        for k, v in face['faceAttributes'].items():
                            if k == 'age':
                                facestring += "&nbsp;&nbsp;&nbsp;&nbsp;Age: {} <br>".format(
                                    v)
                                print("AGE: {}".format(v))
                            if k == 'gender':
                                facestring += "&nbsp;&nbsp;&nbsp;&nbsp;Gender: {} <br>".format(
                                    v.capitalize())
                                print("GENDER: {}".format(v.capitalize()))
                            if k == 'emotion':
                                for key in v:
                                    if v[key] >= 0.5:
                                        facestring += "&nbsp;&nbsp;&nbsp;&nbsp;Emotion: {} <br>".format(
                                            key.capitalize())
                                        print("EMOTION: {}".format(key))
                            if k == 'glasses':
                                facestring += "&nbsp;&nbsp;&nbsp;&nbsp;Glasses: {} <br>".format(
                                    v)
                                print("GLASSES: {}".format(v))

                    msg += "*Total Faces Detected:* {} <br> {} <br>".format(
                        facecount, facestring)

        if config.DEBUG:
            print("ANALYTICS (IF ENABLED) COMPLETE")

        msg += "*Camera:* {} ({})  \n *Zone:* {}  \n *Video Link:* [Click Here]({})".format(
            camera['name'], serial_number, zone_name.capitalize(),
            videolink['url'])
        print("MESSAGE: %s" % msg)

        if config.notify_telegram:
            print("Preparing Telegram Notification")

            print("Sending Telegram Photo")
            bot.send_photo(chat_id=config.telegramroom, photo=image_file)

            print("Sending Telegram Message")
            bot.send_message(chat_id=config.telegramroom,
                             text=msg,
                             parse_mode=telegram.ParseMode.MARKDOWN)

        if config.notify_webex:
            print("PREPARING WEBEX NOTIFICATION")
            webex_notify(msg)

        if detection_type == 'people':
            _LAST_PEOPLE_NOTIFY = int(time.time())
        elif detection_type == 'vehicle':
            _LAST_VEHICLE_NOTIFY = int(time.time())
    else:
        print("Skipping Notification, too soon")