예제 #1
0
def alert(request):
    if request.method == 'POST':
        try:
            alert = Alert(user=BaseUser.objects.get(user=request.user),
                          posX=request.POST["lat"],
                          posY=request.POST["lng"])
            alert.save()

            tokens = [i for i in Token.objects.all()]

            filtered_tokens = list(
                filter(
                    lambda x: dist(x.vendor.lat, x.vendor.lng, request.POST[
                        "lat"], request.POST["lng"]) <= 50, tokens))
            registration_ids = [i.token for i in filtered_tokens]
            print(registration_ids)
            message_title = "Beau-Chef"
            message_body = "Vienen los Carabineros"
            push_service.notify_multiple_devices(
                registration_ids=registration_ids,
                message_title=message_title,
                message_body=message_body,
                message_icon='/static/img/Notificacion.png')
            return JsonResponse({})
        except:
            return render(request, 'app/index.html')
예제 #2
0
def alert_add():
    form = AlertForm()
    if request.method == 'POST' and form.validate():
        user = User.objects(email=current_user.email).first()

        if not form.currency.data in supported_currencies(
                exchange=form.exchange.data):
            flash("{} doesn\\'t support {}".format(form.exchange.data,
                                                   form.currency.data))
            return redirect(url_for('index'))

        if not form.cryptocurrency.data in supported_cryptocurrencies(
                exchange=form.exchange.data):
            flash("{} doesn\\'t support {}".format(form.exchange.data,
                                                   form.cryptocurrency.data))
            return redirect(url_for('index'))

        alert = Alert(
            user=user,
            method=form.method.data,
            method_data=form.method_data.data,
            cryptocurrency=form.cryptocurrency.data,
            price_direction=form.price_direction.data,
            price=form.price.data,
            currency=form.currency.data,
            exchange=form.exchange.data,
            note=form.note.data,
            resend_after=resend_after_to_seconds(form.resend_after.data),
            notify_only_once=form.notify_only_once.data,
        )

        if alert_meets_price_criteria(alert):
            flash(
                "{} price ${} {} is already {} ${} {} on {}, retry with new parameters"
                .format(
                    alert.cryptocurrency,
                    get_current_price(alert.exchange, alert.currency,
                                      alert.cryptocurrency), alert.currency,
                    alert.price_direction, alert.price, alert.currency,
                    alert.exchange))
            return redirect(url_for('index'))

        if not alert_meets_max_emails_criteria(alert):
            flash("Max amount of active alerts reached: {}".format(
                app.config['APP_MAX_ALERTS_PER_MONTH']))
            return redirect(url_for('terms_of_service'))

        alert.save()
        flash("Alert added successfully!")
        return redirect(url_for('alerts'))

    flash_form_errors(form)
    return redirect(url_for('index'))
예제 #3
0
def ticker_alerts():
    with app.app_context():
        app.logger.debug("Processing Alerts ...")
        for alert in Alert.objects(active=True):
            app.logger.debug("Processing Alert: {}".format(alert.id))
            if alert_meets_price_criteria(alert):
                alert_trigger(alert)
예제 #4
0
def initdata(user_count=50,
             post_count=1000,
             tag_count=20,
             comment_count=800,
             alert_count=10):

    users = []
    for i in range(user_count):
        profile = fake.simple_profile()
        user = User(
            name=profile['name'],
            username=profile['username'],
            created_at=fake.past_datetime(),
        )
        users.append(user)
    db.session.add_all(users)
    db.session.commit()

    tags = []
    for i in range(tag_count):
        tag = Tag(name=fake.word())
        tags.append(tag)
    db.session.add_all(tags)
    db.session.commit()

    posts = []
    for i in range(post_count):
        post = Post(
            title=fake.sentence(),
            tags=list(
                set([
                    Tag.query.get(random.randrange(1, Tag.query.count())),
                    Tag.query.get(random.randrange(1, Tag.query.count())),
                    Tag.query.get(random.randrange(1, Tag.query.count()))
                ])),
            user_id=random.randrange(1, User.query.count()),
            created_at=fake.date_time_between(start_date='-365d'))
        posts.append(post)
    db.session.add_all(posts)
    db.session.commit()

    comments = []
    for i in range(comment_count):
        comment = Comment(
            content=fake.sentence(),
            user_id=random.randrange(1, User.query.count()),
            post_id=random.randrange(1, Post.query.count()),
            created_at=fake.date_time_between(start_date='-365d'))
        comments.append(comment)
    db.session.add_all(comments)
    db.session.commit()

    alerts = []
    for i in range(alert_count):
        alert = Alert(title=fake.sentence(),
                      content=fake.sentence(),
                      created_at=fake.past_datetime())
        alerts.append(alert)
    db.session.add_all(alerts)
    db.session.commit()
예제 #5
0
def alert_edit(hash):
    alert = Alert.objects(hash=hash).first()
    if not alert:
        flash("Such alert doesn' exists")
        return redirect(url_for('alerts'))

    form = AlertForm()
    if request.method == 'POST' and form.validate():
        if not form.currency.data in supported_currencies(
                exchange=form.exchange.data):
            flash("{} doesn\\'t support {}".format(form.exchange.data,
                                                   form.currency.data))
            return redirect(url_for('alert_edit', hash=hash))

        if not form.cryptocurrency.data in supported_cryptocurrencies(
                exchange=form.exchange.data):
            flash("{} doesn\\'t support {}".format(form.exchange.data,
                                                   form.cryptocurrency.data))
            return redirect(url_for('alert_edit', hash=hash))

        alert.method = form.method.data
        alert.method_data = form.method_data.data
        alert.cryptocurrency = form.cryptocurrency.data
        alert.price_direction = form.price_direction.data
        alert.price = form.price.data
        alert.currency = form.currency.data
        alert.exchange = form.exchange.data
        alert.note = form.note.data
        alert.resend_after = resend_after_to_seconds(form.resend_after.data)
        alert.notify_only_once = form.notify_only_once.data

        if alert_meets_price_criteria(alert):
            flash(
                "{} price ${} {} is already {} ${} {} on {}, retry with new parameters"
                .format(
                    alert.cryptocurrency,
                    get_current_price(alert.exchange, alert.currency,
                                      alert.cryptocurrency), alert.currency,
                    alert.price_direction, alert.price, alert.currency,
                    alert.exchange))
            return redirect(url_for('alert_edit', hash=hash))

        alert.save()
        flash('Changes saved!')
        return redirect(url_for('alerts'))

    forms = alert_forms()
    forms['alert'].method.data = alert.method
    forms['alert'].method_data.data = alert.method_data
    forms['alert'].cryptocurrency.data = alert.cryptocurrency
    forms['alert'].price_direction.data = alert.price_direction
    forms['alert'].price.data = alert.price
    forms['alert'].currency.data = alert.currency
    forms['alert'].exchange.data = alert.exchange
    forms['alert'].note.data = alert.note
    forms['alert'].resend_after.data = seconds_to_resend_after(
        alert.resend_after)
    forms['alert'].notify_only_once.data = alert.notify_only_once

    return render_template("alert.edit.html.j2", forms=forms, hash=hash)
예제 #6
0
def alert_meets_max_emails_criteria(alert):
    if len(Alert.objects(
            user=alert.user,
            active=True)) >= app.config['APP_MAX_ALERTS_PER_MONTH']:
        if not alert.user.is_mod():
            return False

    return True
예제 #7
0
def alert_delete(hash):
    alert = Alert.objects(hash=hash).first()
    if not alert:
        flash("Such alert doesn' exists")
        return redirect(url_for('alerts'))

    alert.delete()
    flash('Alert deleted sucessfully')
    return redirect(url_for('alerts'))
예제 #8
0
파일: routes.py 프로젝트: bl195/quitIT-1
def handle_alert_message(message):
    """
    Handles alert message comming from RaspberryPi.
    Processes the alert, logs the location to t database
    and then forwards an SMS alert to the user's phone
    """
    # get the time and create Alert Entry
    time = datetime.utcnow()

    sid = request.sid
    user_context = sessions.get(sid)
    Alert(time=time, coordinates=user_context["location"])
예제 #9
0
def alert_toggle_state(hash):
    alert = Alert.objects(hash=hash).first()
    if not alert:
        flash("Such alert doesn' exists")
        return redirect(url_for('alerts'))

    if not alert.active and not alert_meets_max_emails_criteria(alert):
        flash("Max amount of active alerts reached: {}".format(
            app.config['APP_MAX_ALERTS_PER_MONTH']))
        return redirect(url_for('terms_of_service'))

    alert.active = not alert.active
    alert.save(clean=False)
    return redirect(url_for('alerts'))
예제 #10
0
def alert_report(hash):
    alert = Alert.objects(hash=hash).first()
    if not alert:
        flash("Such alert doesn' exists")
        return redirect(url_for('index'))

    alert.active = False
    alert.user.spam_strikes += 1
    if alert.user.spam_strikes == app.config['APP_MAX_ALERTS_SPAM_STRIKES']:
        alert.user.suspend()
    alert.save()
    flash(
        "The reported alert has been disabled and the infractor notified, sorry for the inconvience!"
    )
    return redirect(url_for('index'))
예제 #11
0
    def alert(self, alert_id, alert_msg):
        """
        This is where we process incoming message stanzas
        """

        # Save the alert to the db
        a = Alert(id=alert_id, content=json.dumps(alert_msg))
        with self.app.app_context():
            try:
                db.session.add(a)
                db.session.commit()
            except:
                self.app.logger.info("DB CONNECTION FAILURE")
                db.session.rollback()

        # Alert the clients that we have a new alert
        socketio.emit('a911_alarm', \
                      {'type': 'alarm', 'id': alert_id}, \
                      namespace='/afd')
예제 #12
0
def raise_alert():
    try:
        source = request.headers.get('Source', '')
        if not source:
            source = 'System'

        patient = request.headers.get('Patient', '')
        if not patient:
            system_logging('Patient not provided', exception=True)

        status = Alert(patient=patient, creator=source).save()
        if status:
            system_logging(
                f'Unable to raise alert raised by {source} for patient {patient}',
                exception=True)

        user = User.query.filter(User.user_id == patient).first()
        user.launch_task('send_alert_communication',
                         'Sending alert communication', patient)
        return jsonify({'message': 'done'})
    except Exception as err:
        print(err)
        system_logging(f"Error raising alert {err}", exception=True)
        return ''
예제 #13
0
def dashboard():
    """Dashboard."""
    if current_user.role == 'admin':
        # Admin user, show register form
        form = RegisterForm()
        form_error = False
        deleted_user = session.pop('deleted_user', False)
        if request.method == 'POST' and form.validate_on_submit():
            user = User(
                email=form.email.data,
                password=form.password.data,
                phone_number=form.phone_number.data,
                other=form.other.data,
                shelter=form.shelter.data,
                food=form.food.data,
                clothes=form.clothes.data,
                role=form.role.data
            )
            user.save()
            verify_email(user.email)
            flash('User registered succesfully', 'success')
            return redirect(url_for('dashboard'))
        elif request.method == 'POST' and not form.validate_on_submit():
            form_error = True
        return render_template('dashboard/admin.html', 
            form=form, 
            form_error=form_error,
            users=User.get_users(),
            alerts=Alert.get_alerts(),
            delete_user_form=DeleteUserForm(),
            deleted_user=deleted_user)
    elif current_user.role == 'advocate':
        # Advocate user, show alert form
        form = AlertForm()
        if request.method == 'POST' and form.validate_on_submit():
            alert = Alert(
                description=form.description.data,
                other=form.other.data,
                shelter=form.shelter.data,
                food=form.food.data,
                clothes=form.clothes.data,
                gender=form.gender.data,
                age=form.age.data,
                user=current_user
            )
            alert.save()
            users_to_notify = User.get_provider(alert.food, alert.clothes, alert.shelter, alert.other)
            for user in users_to_notify:
                print("found user to notify {}".format(user))
                body = "There is a new 15th night alert. Go to " + \
                       HOST_NAME + \
                       "/respond_to/" + \
                       str(alert.id) + " to respond."
                send_sms(to_number=user.phone_number, body=body)
                send_email(user.email, '15th Night Alert', body)
            flash('Alert sent successfully', 'success')
            return redirect(url_for('dashboard'))

        return render_template('dashboard/advocate.html', form=form)
    else:
        # Provider user, show alerts
        return render_template(
                'dashboard/provider.html',
                user=current_user,
                alerts=Alert.get_active_alerts_for_provider(current_user)
        )
예제 #14
0
파일: views.py 프로젝트: strawwj/my_code
def data(did, sid):
    print(type(request.json), request.json)
    device = g.current_user.devices.filter_by(id=did).first()
    if device is None:
        return jsonify({'status': 404, 'info': '找不到你的设备'})

    sensor = device.sensors.filter_by(id=sid).first()
    if sensor is None:
        return jsonify({'status': 404, 'info': '找不到你的传感器'})
    print(request.json)
    if request.json is None:
        return jsonify({'status': 404, 'info': '找不到你的数据'})

    if 'data' not in request.json.keys():
        return jsonify({'status': 404, 'info': '找不到你的数据'})

    # 判断报警

    data = Data()
    data.data = request.json.get('data')
    data.sensor_id = sid
    db.session.add(data)
    db.session.commit()
    if data.data > sensor.max:
        alert = Alert()
        alert.sensor_id = sensor.id
        alert.reason = '超出最大值'
        alert.data_id = data.id
        alert.current_max = sensor.max
        alert.current_min = sensor.min
        db.session.add(alert)
        db.session.commit()
    if data.data < sensor.max:
        alert = Alert()
        alert.sensor_id = sensor.id
        alert.reason = '低于最小值'
        alert.data_id = data.id
        alert.current_max = sensor.max
        alert.current_min = sensor.min
        db.session.add(alert)
        db.session.commit()
    return jsonify({'status': 200})
예제 #15
0
def sget_sensor_parms(device_id):
    device = Device.query.filter_by(id=device_id).first_or_404()
    i = Indicator()
    
    temp_inside = request.args.get('temp_inside', default = -1, type = float)
    temp_outside_first = request.args.get('temp_outside_first', default = -1, type = float)
    temp_outside_second = request.args.get('temp_outside_second', default = -1, type = float)
    temp_outside_third = request.args.get('temp_outside_third', default = -1, type = float)
    if (temp_outside_second == 0):
        temp_outside_second = round((temp_outside_first+temp_outside_third)/2,1)
    temp_outside_fourth = request.args.get('temp_outside_fourth', default = -1, type = float)
    distance = request.args.get('distance', default = -1, type = float)
    power = request.args.get('power', default = -1, type = float)
    pressure = request.args.get('pressure', default = -1, type = float)
    if pressure != -1:
        pressure = int(float(pressure)) / 100
    else:
        pressure = pressure
    speed = request.args.get('speed', default = -1, type = float)
    temp_in = request.args.get('temp_in', default = -1, type = float)
    temp_out = request.args.get('temp_out', default = -1, type = float)
    temp_all = request.args.get('temp_all', default = -1, type = float)
    
    i.temp_inside = temp_inside
    i.temp_outside_first = temp_outside_first
    i.temp_outside_second = temp_outside_second
    i.temp_outside_third = temp_outside_third
    i.temp_outside_fourth = temp_outside_fourth
    i.distance = distance
    i.power = power
    i.pressure = pressure
    i.speed = speed
    i.temp_in = temp_in
    i.temp_out = temp_out
    i.temp_all = temp_all
    
    i.device_id = device_id
    
    #получаеми хэшрейты
    i.hashrate_poolbtccom = 0
    if (not device.apikey_poolbtccom is None and device.apikey_poolbtccom != ""):
        r = requests.get("https://eu-pool.api.btc.com/v1/realtime/hashrate?access_key="+device.apikey_poolbtccom+"&puid="+device.puid_poolbtccom)
        if r.status_code == 200:
            print(r.text)
            r = r.json()
            if (r["err_no"] == 0):
                i.hashrate_poolbtccom = float(r["data"]["shares_15m"])
            

    

    #antpool
    i.hashrate_antpool = 0
    if (not device.apikey_antpool is None and device.apikey_antpool != ""):
        nonce=int(time.time()*1000)
        msgs=device.userid_antpool+device.apikey_antpool+str(nonce)
        api_sign=[]
        api_sign.append(hmac.new(device.secret_antpool.encode(encoding="utf-8"), msg=msgs.encode(encoding="utf-8"), digestmod=hashlib.sha256).hexdigest().upper())
        api_sign.append(nonce)

        post_data = {'key': device.apikey_antpool, 'nonce': api_sign[1],'signature': api_sign[0],'coin': device.coin_antpool}
        r = requests.post("https://antpool.com/api/hashrate.htm", data=post_data)

        if r.status_code == 200:
            r = r.json()
            if r["code"] == 0:
                try:
                    i.hashrate_antpool = int(r["data"]["last10m"])
                except:
                    pass

    i.hashrate_viabtc = 0

    i.hashrate_f2pool = 0
    if (not device.apikey_f2pool is None and device.apikey_f2pool != ""):
        r = requests.get("http://api.f2pool.com/bitcoin/"+device.apikey_f2pool)
        if r.status_code == 200:
            r = r.json()
            try:
                i.hashrate_f2pool = int(r["hashrate"])
            except:
                pass   

    i.hashrate_slushpool = 0

    if (not device.apikey_slushpool is None and device.apikey_slushpool != ""):
        r = requests.get("https://slushpool.com/accounts/profile/json/"+device.apikey_slushpool)
        if r.status_code == 200 and r.text != "Invalid token":
            r = r.json()
            try:
                i.hashrate_slushpool = int(r["workers"][r["username"] + "." + device.worker_slushpool]["hashrate"])
            except:
                pass

    i.hashrate_total = i.hashrate_poolbtccom + i.hashrate_antpool + i.hashrate_viabtc + i.hashrate_f2pool + i.hashrate_slushpool 
    device.hash_rate = i.hashrate_total

    db.session.add(i)
    db.session.commit()

    # Некоторое количество говнокода
    a = Alert()
    if float(i.temp_inside) > 75.0:
        a.text = "Внутренняя температура превышает пороговое значение в 75 градусов на " + str(float(temp_inside)-75.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Внутренняя температура превышает пороговое значение в 75 градусов на " + str(float('temp_inside)-75.0) + "градусов")
    if float(i.temp_outside_first) > 70.0:
        a.text = "Температура первого датчика превышает пороговое значение в 70 градусов на " + str(float(temp_outside_first)-70.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура первого датчика превышает пороговое значение в 70 градусов на " + str(float('temp_outside_first)-70.0) + "градусов")
    if float(i.temp_outside_second) > 65.0:
        a.text = "Температура второго датчика превышает пороговое значение в 65 градусов на " + str(float(temp_outside_second)-65.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура второго датчика превышает пороговое значение в 65 градусов на " + str(float(temp_outside_second)-65.0) + "градусов")
    if float(i.temp_outside_third) > 60.0:
        a.text = "Температура третьего датчика превышает пороговое значение в 60 градусов на " + str(float(temp_outside_third)-60.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура третьего датчика превышает пороговое значение в 60 градусов на " + str(float(temp_outside_third)-60.0) + "градусов")
    if float(i.temp_outside_fourth) > 60.0:
        a.text = "Температура четвёртого датчика превышает пороговое значение в 60 градусов на " + str(float(temp_outside_fourth)-60.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура четвёртого датчика превышает пороговое значение в 60 градусов на " + str(float(temp_outside_fourth)-60.0) + "градусов")
    if float(i.distance) > 199.0:
        a.text = "Расстояние до жидкости превышает пороговое значение 199 на " + str(float(distance)-199.0)
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Расстояние до жидкости!', '*****@*****.**', ['*****@*****.**'], "Расстояние до жидкости превышает пороговое значение 199 на " + str(float(distance)-199.0))
    if float(i.power) > 100.0:
        a.text = "Мощность превышает пороговое значение 100 на" + str(float(power)-100.0)
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Мощность!', '*****@*****.**', ['*****@*****.**'], "Мощность превышает пороговое значение 100 на" + str(float(power)-100.0))
    if float(i.pressure) > 200000.0:
        a.text = "Давление превышает пороговое значение 200000 на " + str(float(pressure)-200000.0)
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        #send_email('Превышение давления!', '*****@*****.**', ['*****@*****.**'], "Давление превышает пороговое значение 200000 на " + str(float(pressure)-200000.0))
        
    indicator = i.query.filter_by(device_id=1).first()
    return render_template('json_show.html', data=indicator.timestamp)
예제 #16
0
def show_json(device_id):
    device = Device.query.filter_by(id=device_id).first_or_404()

    i = Indicator()
    r = requests.get(device.url_sensor_device)
    if r.status_code == 200:
        r = r.json()
        i.temp_inside = r['temp_inside']
        i.temp_outside_first = r['temp_outside_first']
        i.temp_outside_second = r['temp_outside_second']
        i.temp_outside_third = r['temp_outside_third']
        i.temp_outside_fourth = r['temp_outside_fourth']
        i.distance = r['distance']
        i.power = r['power']
        i.pressure = int(float(r['pressure_bmp180'])) / 100
        i.speed = r['speed']
        i.temp_in = r['temp_in']
        i.temp_out = r['temp_out']
        i.temp_all = r['temp_all']
    else:
        i.temp_inside = -1
        i.temp_outside_first = -1
        i.temp_outside_second = -1
        i.temp_outside_third = -1
        i.temp_outside_fourth = -1 
        i.distance =-1
        i.power = -1
        i.pressure = -1
        i.speed = -1
        i.temp_in = -1
        i.temp_out = -1
        i.temp_all = -1   

    i.device_id = device_id

    r = requests.get(device.url_relay_device)
    if r.status_code == 200:
        #TODO: костыль из-за старой версии прошивки реле
        r = r.text
        r = r.replace('"relay 6": 0 "sensor 1"', '"relay 6": 0, "sensor 1"').replace('"relay 6": 1 "sensor 1"', '"relay 6": 1, "sensor 1"')
        r = json.loads(r)

        i.relay1_state = False if r['relay 1'] == 1 else True
        i.relay2_state = False if r['relay 2'] == 1 else True
        i.relay3_state = False if r['relay 3'] == 1 else True
        i.relay4_state = False if r['relay 4'] == 1 else True
        i.relay5_state = False if r['relay 5'] == 1 else True
        i.relay6_state = False if r['relay 6'] == 1 else True

        current_mult =  1.0 / 1024 * 30 / 2 * 1.2 #5.0 / 1024.0 * 0.707 / 66 * 1000

        i.relay1_current = 0 if float(r['sensor 1']) <= 120 else float(r['sensor 1']) * current_mult
        i.relay2_current = 0 if float(r['sensor 2']) <= 120 else float(r['sensor 2']) * current_mult
        i.relay3_current = 0 if float(r['sensor 3']) <= 120 else float(r['sensor 3']) * current_mult
        i.relay4_current = 0 if float(r['sensor 4']) <= 120 else float(r['sensor 4']) * current_mult
        i.relay5_current = 0 if float(r['sensor 5']) <= 120 else float(r['sensor 5']) * current_mult
        i.relay6_current = 0 if float(r['sensor 6']) <= 120 else float(r['sensor 6']) * current_mult
    else:
        i.relay1_state = False
        i.relay2_state = False
        i.relay3_state = False
        i.relay4_state = False 
        i.relay5_state = False 
        i.relay6_state = False  

        i.relay1_current = 0 
        i.relay2_current = 0
        i.relay3_current = 0
        i.relay4_current = 0 
        i.relay5_current = 0 
        i.relay6_current = 0 

    if device.relay1_state is None:
        device.relay1_state =  i.relay1_state

    if device.relay2_state is None:
        device.relay2_state =  i.relay2_state

    if device.relay3_state is None:
        device.relay3_state =  i.relay3_state

    if device.relay4_state is None:
        device.relay4_state =  i.relay4_state

    if device.relay5_state is None:
        device.relay5_state =  i.relay5_state

    if device.relay6_state is None:
        device.relay6_state =  i.relay6_state

    device.status = True if device.relay1_state or device.relay2_state or device.relay3_state or device.relay4_state or device.relay5_state or device.relay6_state else False


    if (device.relay1_state != i.relay1_state):
        if (device.relay1_state):
            requests.get(device.url_relay_device + 'relay1on')    
        else:
            requests.get(device.url_relay_device + 'relay1off')

    if (device.relay2_state != i.relay2_state):
        if (device.relay2_state):
            requests.get(device.url_relay_device + 'relay2on')    
        else:
            requests.get(device.url_relay_device + 'relay2off')

    if (device.relay3_state != i.relay3_state):
        if (device.relay3_state):
            requests.get(device.url_relay_device + 'relay3on')    
        else:
            requests.get(device.url_relay_device + 'relay3off')

    if (device.relay4_state != i.relay4_state):
        if (device.relay4_state):
            requests.get(device.url_relay_device + 'relay4on')    
        else:
            requests.get(device.url_relay_device + 'relay4off')

    if (device.relay5_state != i.relay5_state):
        if (device.relay5_state):
            requests.get(device.url_relay_device + 'relay5on')    
        else:
            requests.get(device.url_relay_device + 'relay5off')

    if (device.relay6_state != i.relay6_state):
        if (device.relay6_state):
            requests.get(device.url_relay_device + 'relay6on')    
        else:
            requests.get(device.url_relay_device + 'relay6off')

    #получаеми хэшрейты
    i.hashrate_poolbtccom = 0
    if (not device.apikey_poolbtccom is None and device.apikey_poolbtccom != ""):
        r = requests.get("https://eu-pool.api.btc.com/v1/realtime/hashrate?access_key="+device.apikey_poolbtccom+"&puid="+device.puid_poolbtccom)
        if r.status_code == 200:
            print(r.text)
            r = r.json()
            if (r["err_no"] == 0):
                i.hashrate_poolbtccom = float(r["data"]["shares_15m"])
            

    

    #antpool
    i.hashrate_antpool = 0
    if (not device.apikey_antpool is None and device.apikey_antpool != ""):
        nonce=int(time.time()*1000)
        msgs=device.userid_antpool+device.apikey_antpool+str(nonce)
        api_sign=[]
        api_sign.append(hmac.new(device.secret_antpool.encode(encoding="utf-8"), msg=msgs.encode(encoding="utf-8"), digestmod=hashlib.sha256).hexdigest().upper())
        api_sign.append(nonce)

        post_data = {'key': device.apikey_antpool, 'nonce': api_sign[1],'signature': api_sign[0],'coin': device.coin_antpool}
        r = requests.post("https://antpool.com/api/hashrate.htm", data=post_data)

        if r.status_code == 200:
            r = r.json()
            if r["code"] == 0:
                try:
                    i.hashrate_antpool = int(r["data"]["last10m"])
                except:
                    pass

    i.hashrate_viabtc = 0

    i.hashrate_f2pool = 0
    if (not device.apikey_f2pool is None and device.apikey_f2pool != ""):
        r = requests.get("http://api.f2pool.com/bitcoin/"+device.apikey_f2pool)
        if r.status_code == 200:
            r = r.json()
            try:
                i.hashrate_f2pool = int(r["hashrate"])
            except:
                pass   

    i.hashrate_slushpool = 0

    if (not device.apikey_slushpool is None and device.apikey_slushpool != ""):
        r = requests.get("https://slushpool.com/accounts/profile/json/"+device.apikey_slushpool)
        if r.status_code == 200 and r.text != "Invalid token":
            r = r.json()
            try:
                i.hashrate_slushpool = int(r["workers"][r["username"] + "." + device.worker_slushpool]["hashrate"])
            except:
                pass

    i.hashrate_total = i.hashrate_poolbtccom + i.hashrate_antpool + i.hashrate_viabtc + i.hashrate_f2pool + i.hashrate_slushpool 
    device.hash_rate = i.hashrate_total

    db.session.add(i)
    db.session.commit()

    # Некоторое количество говнокода
    a = Alert()
    if float(i.temp_inside) > 75.0:
        a.text = "Внутренняя температура превышает пороговое значение в 75 градусов на " + str(float(r['temp_inside'])-75.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Внутренняя температура превышает пороговое значение в 75 градусов на " + str(float(r['temp_inside'])-75.0) + "градусов")
    if float(i.temp_outside_first) > 70.0:
        a.text = "Температура первого датчика превышает пороговое значение в 70 градусов на " + str(float(r['temp_outside_first'])-70.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура первого датчика превышает пороговое значение в 70 градусов на " + str(float(r['temp_outside_first'])-70.0) + "градусов")
    if float(i.temp_outside_second) > 65.0:
        a.text = "Температура второго датчика превышает пороговое значение в 65 градусов на " + str(float(r['temp_outside_second'])-65.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура второго датчика превышает пороговое значение в 65 градусов на " + str(float(r['temp_outside_second'])-65.0) + "градусов")
    if float(i.temp_outside_third) > 60.0:
        a.text = "Температура третьего датчика превышает пороговое значение в 60 градусов на " + str(float(r['temp_outside_third'])-60.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура третьего датчика превышает пороговое значение в 60 градусов на " + str(float(r['temp_outside_third'])-60.0) + "градусов")
    if float(i.temp_outside_fourth) > 60.0:
        a.text = "Температура четвёртого датчика превышает пороговое значение в 60 градусов на " + str(float(r['temp_outside_fourth'])-60.0) + "градусов"
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Превышение температуры!', '*****@*****.**', ['*****@*****.**'], "Температура четвёртого датчика превышает пороговое значение в 60 градусов на " + str(float(r['temp_outside_fourth'])-60.0) + "градусов")
    if float(i.distance) > 199.0:
        a.text = "Расстояние до жидкости превышает пороговое значение 199 на " + str(float(r['distance'])-199.0)
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Расстояние до жидкости!', '*****@*****.**', ['*****@*****.**'], "Расстояние до жидкости превышает пороговое значение 199 на " + str(float(r['distance'])-199.0))
    if float(i.power) > 100.0:
        a.text = "Мощность превышает пороговое значение 100 на" + str(float(r['power'])-100.0)
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Мощность!', '*****@*****.**', ['*****@*****.**'], "Мощность превышает пороговое значение 100 на" + str(float(r['power'])-100.0))
    if float(i.pressure) > 200000.0:
        a.text = "Давление превышает пороговое значение 200000 на " + str(float(r['pressure'])-200000.0)
        a.device_id = i.device_id
        db.session.add(a)
        db.session.commit()
        send_email('Превышение давления!', '*****@*****.**', ['*****@*****.**'], "Давление превышает пороговое значение 200000 на " + str(float(r['pressure'])-200000.0))
    #if float(r['speed']) > 0.0:
    #    a.text = "Скорость превышает пороговое значение в 0 на " + str(float(r['temp_outside_fourth'])-0.0)
    #    a.device_id = i.device_id
    #    db.session.add(a)
     #   db.session.commit()
    #if float(r['temp_in']) > 0.0:
    #    a.text = "Температура внутри превышает пороговое значение в 0 градусов на " + str(float(r['temp_in'])-0.0) + "градусов"
    #    a.device_id = i.device_id
    #    db.session.add(a)
    #    db.session.commit()
    #if float(r['temp_out']) > 0.0:
    #    a.text = "Температура снаружи превышает пороговое значение в 0 градусов на " + str(float(r['temp_out'])-0.0) + "градусов"
    #    a.device_id = i.device_id
    #    db.session.add(a)
    #    db.session.commit()
    #if float(r['temp_all']) > 0.0:
    #    a.text = "Температура общая превышает пороговое значение в 0 градусов на " + str(float(r['temp_all'])-0.0) + "градусов"
    #    a.device_id = i.device_id
    #    db.session.add(a)
    #    db.session.commit()
    
    indicator = i.query.filter_by(device_id=1).first()
    return render_template('json_show.html', data=indicator.timestamp)
예제 #17
0
파일: ddos.py 프로젝트: nadhirfr/rf-ids
 def save_alert(self, params):
     alert = Alert(
         ip_source=params['ip_source'], ip_destination=params['ip_destination'], port=params['port'], agent=params['agent'], datasource=params['datasource'])
     alert.save()