Esempio n. 1
0
from flask import Flask, jsonify
from flask.config import Config
from flask_restful import Api
from flask_jwt import JWT
from security import authenticate, identity as identity_function
from user import UserRegister
from app_logging import AppLogger
from config_manager import ConfigManager
from connection.db import DbInit
from item import Item, ItemList
from datetime import timedelta
import os

DEFAULT_PORT = 5050
logger = AppLogger.get_logger(__name__)

app = Flask(__name__)
app.secret_key = os.environ.get("JWT_SECRET",
                                ConfigManager.get("jwt_secret", "jose"))

api = Api(app)
app.config["JWT_EXPIRATION_DELTA"] = timedelta(
    seconds=3600)  # 1 hour expiration time

# config JWT auth key name to be 'email' instead of default 'username'
app.config["JWT_AUTH_USERNAME_KEY"] = "email"

jwt = JWT(app, authenticate, identity_function)  # new endpont '/auth'
# Requires Authorization header
#   JWT <token>
Esempio n. 2
0
    import traceback
    import argparse
    import os
    import time
    import json
    import zlib

    from app_logging import AppLogger

except Exception as ex:
    cs.CSClient().log('cpu_usage.py', 'Import failure: {}'.format(ex))
    cs.CSClient().log('cpu_usage.py',
                      'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)

log = AppLogger()


def start_app():
    """ Add functionality to execute when the app is started. """
    try:
        log.info('start_app()')

        create_folder()
        create_csv()
        get_usage()

    except Exception as e:
        log.error('Exception during start_app()! exception: {}'.format(e))
        raise
Esempio n. 3
0
    import cs
    import sys
    import traceback

    from http.server import BaseHTTPRequestHandler
    from app_logging import AppLogger

except Exception as ex:
    # Output DEBUG logs indicating what import failed. Use the logging in the
    # CSClient since app_logging may not be loaded.
    cs.CSClient().log('getsignal.py', 'Import failure: {}'.format(ex))
    cs.CSClient().log('getsignal.py', 'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)

# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()
log.debug('Started webserver.py')


class GetHandler(BaseHTTPRequestHandler):

    def do_GET(self):

        # serve the index.html file
        if self.path == '/':
            try:
                f = open('index.html','rb')

                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
Esempio n. 4
0
    use of this file is subject to the Cradlepoint Software License Agreement
    distributed with this file. Unauthorized reproduction or distribution of
    this file is subject to civil and criminal penalties.

    Desc:
        Determine "fastest" wireless wan connection by loading both SIMs,
        running speedtest. Disable the not-fastest SIM.
"""

import cs
import time
import settings
from app_logging import AppLogger

# Create an AppLogger for logging to NCOS syslog.
log = AppLogger()


class Boot1Exception(Exception):
    pass


class Timeout(Boot1Exception):
    pass


class SocketLost(Boot1Exception):
    pass


class OneModem(Boot1Exception):
Esempio n. 5
0
"""
A reference application to access GNSS on the IBR1700.
See the readme.txt for more details.

"""

import time
import socket
import settings

from inetline import ReadLine
from app_logging import AppLogger

# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()

try:
    log.debug('Starting {}'.format(settings.APP_NAME))
    gnss_addr = ("127.0.0.1", 17488)

    gnssd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    log.debug("Attempting sock.connect({})".format(gnss_addr))
    gnssd_sock.connect(gnss_addr)

    # Turns on ALL messages. Only way to turn off is to close the socket.
    log.debug("Attempting sock.send(b'ALL\\r\\n')")
    gnssd_sock.sendall(b'ALL\r\n')

    # Enable IMU messages
    log.debug("Attempting sock.send(b'IMU yes\\r\\n')")
    gnssd_sock.sendall(b'IMU yes\n\r')
Esempio n. 6
0
    import ssl
    import paho.mqtt.client as mqtt
    import paho.mqtt.publish as publish

    from app_logging import AppLogger
    from threading import Thread

except Exception as e:
    # Output logs indicating what import failed.
    cs.CSClient().log('ibr1700_obdII.py', 'Import failure: {}'.format(e))
    cs.CSClient().log('ibr1700_obdII.py',
                      'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)

# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()

# The mqtt_client for publishing to the broker
mqtt_client = None

# Topics for all OBD-II PIDs with QOS
topics = [(settings.VEHICLE_SPEED, 0), (settings.ENGINE_SPEED, 0),
          (settings.THROTTLE_POSITION, 0), (settings.ODOMETER, 0),
          (settings.FUEL_LEVEL, 0), (settings.ENGINE_COOLANT_TEMPERATURE, 0),
          (settings.IGNITION_STATUS, 0), (settings.MIL_STATUS, 0),
          (settings.FUEL_RATE, 0), (settings.PTO_STATUS, 0),
          (settings.SEATBELT_FASTENED, 0), (settings.MISFIRE_MONITOR, 0),
          (settings.FUEL_SYSTEM_MONITOR, 0),
          (settings.COMPREHENSIVE_COMPONENT_MONITOR, 0),
          (settings.CATALYST_MONITOR, 0),
          (settings.HEATED_CATALYST_MONITOR, 0),
Esempio n. 7
0
    import ssl
    import paho.mqtt.client as mqtt
    import paho.mqtt.publish as publish

    from app_logging import AppLogger
    from threading import Thread

except Exception as e:
    # Output logs indicating what import failed.
    cs.CSClient().log('mqtt_app.py', 'Import failure: {}'.format(e))
    cs.CSClient().log('mqtt_app.py',
                      'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)

# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()

# The mqtt_client for publishing to the broker
mqtt_client = None


# Called when the broker responds to our connection request.
def on_connect(client, userdata, flags, rc):
    log.debug("MQTT Client connection results: {}".format(
        mqtt.connack_string(rc)))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    # QOS 0: The broker will deliver the message once, with no confirmation.
    # QOS 1: The broker will deliver the message at least once, with confirmation required.
    # QOS 2: The broker will deliver the message exactly once by using a four step handshake.
import os, sys

currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
# Import parent libs
from app_logging import AppLogger
from config_manager import ConfigManager
import logging
from user import User

logger = AppLogger.get_logger(__name__,
                              level=logging.INFO,
                              log_file="test.log")

if __name__ == "__main__":
    logger.info("info statement")
    logger.debug("debug statement")

    jwt_secret = ConfigManager.get("jwt_secret", "jose")

    logger.info(f"jwt_secret: {jwt_secret}")
    user = User.find_by_username("douglas")
    logger.info(f"user: {user}")

    currentdir = os.path.dirname(os.path.realpath(__file__))
    parentdir = os.path.dirname(currentdir)
    logger.info(f"currentdir: {currentdir}, parentdir: {parentdir}")
Esempio n. 9
0
    use of this file is subject to the Cradlepoint Software License Agreement
    distributed with this file. Unauthorized reproduction or distribution of
    this file is subject to civil and criminal penalties.

    Desc:
        Determine "fastest" wireless wan connection by loading both SIMs,
        running speedtest. Disable the not-fastest SIM.
"""

import cs
import time
import settings
from app_logging import AppLogger

# Create an AppLogger for logging to NCOS syslog.
log = AppLogger()


class Boot1Exception(Exception):
    pass


class Timeout(Boot1Exception):
    pass


class SocketLost(Boot1Exception):
    pass


class OneModem(Boot1Exception):
Esempio n. 10
0
    import sys
    import traceback
    import argparse

    from app_logging import AppLogger

except Exception as ex:
    # Output DEBUG logs indicating what import failed. Use the logging in the
    # CSClient since app_logging may not be loaded.
    cs.CSClient().log('app_template.py', 'Import failure: {}'.format(ex))
    cs.CSClient().log('app_template.py', 'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)


# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()


# Add functionality to execute when the app is started
def start_app():
    try:
        log.debug('start_app()')

    except Exception as e:
        log.error('Exception during start_app()! exception: {}'.format(e))
        raise


# Add functionality to execute when the app is stopped
def stop_app():
    try:
Esempio n. 11
0
    https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/iot-hub/iot-hub-mqtt-support.md

Refer to section 'Using the MQTT protocol directly'.
"""

import cs
import os
import ssl
import urllib.parse

from app_logging import AppLogger
from paho.mqtt import client as mqtt


# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()

# Path to the TLS certificates file. The certificates were copied from the certs.c file
# located here: https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c
path_to_root_cert = os.path.join(os.getcwd(), 'certs.cer')

# MS Azure IoT Hub name
iot_hub_name = ''

# Device name in MS Azure IoT Hub
device_id = ''

# SAS token for the device id. This can be generated using the Device Explorer Tool.
# The format of the token should be similar to:
# 'SharedAccessSignature sr={your hub name}.azure-devices.net%2Fdevices%2FMyDevice01%2Fapi-version%3D2016-11-14&sig=vSgHBMUG.....Ntg%3d&se=1456481802'
sas_token = ''
Esempio n. 12
0
"""
A reference application to access GNSS on the IBR1700.
See the readme.txt for more details.

"""

import time
import socket
import settings

from inetline import ReadLine
from app_logging import AppLogger


# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()


try:
    log.debug('Starting {}'.format(settings.APP_NAME))
    gnss_addr = ("127.0.0.1", 17488)

    gnssd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    log.debug("Attempting sock.connect({})".format(gnss_addr))
    gnssd_sock.connect(gnss_addr)

    # Turns on ALL messages. Only way to turn off is to close the socket.
    log.debug("Attempting sock.send(b'ALL\\r\\n')")
    gnssd_sock.sendall(b'ALL\r\n')

    # Enable IMU messages
    import platform
    import collections
    import traceback

    from app_logging import AppLogger
    from importlib import util

except Exception as ex:
    # Output logs indicating what import failed.
    cs.CSClient().log('python_module_list.py', 'Import failure: {}'.format(ex))
    cs.CSClient().log('python_module_list.py', 'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)


# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()


def log_module_list():
    # name this file (module)
    this_module_name = os.path.basename(__file__).rsplit('.')[0]

    # dict for loaders with their modules
    loaders = collections.OrderedDict()

    # names of build-in modules
    for module_name in sys.builtin_module_names:

        # find an information about a module by name
        module_info = util.find_spec(module_name)
Esempio n. 14
0
based on the sample from here:
    https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/iot-hub/iot-hub-mqtt-support.md

Refer to section 'Using the MQTT protocol directly'.
"""

import cs
import os
import ssl
import urllib.parse

from app_logging import AppLogger
from paho.mqtt import client as mqtt

# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()

# Path to the TLS certificates file. The certificates were copied from the certs.c file
# located here: https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c
path_to_root_cert = os.path.join(os.getcwd(), 'certs.cer')

# MS Azure IoT Hub name
iot_hub_name = ''

# Device name in MS Azure IoT Hub
device_id = ''

# SAS token for the device id. This can be generated using the Device Explorer Tool.
# The format of the token should be similar to:
# 'SharedAccessSignature sr={your hub name}.azure-devices.net%2Fdevices%2FMyDevice01%2Fapi-version%3D2016-11-14&sig=vSgHBMUG.....Ntg%3d&se=1456481802'
sas_token = ''
Esempio n. 15
0
    import ssl
    import paho.mqtt.client as mqtt
    import paho.mqtt.publish as publish

    from app_logging import AppLogger
    from threading import Thread

except Exception as e:
    # Output logs indicating what import failed.
    cs.CSClient().log('ibr1700_obdII.py', 'Import failure: {}'.format(e))
    cs.CSClient().log('ibr1700_obdII.py', 'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)


# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()

# The mqtt_client for publishing to the broker
mqtt_client = None

# Topics for all OBD-II PIDs with QOS
topics = [(settings.VEHICLE_SPEED, 0),
          (settings.ENGINE_SPEED, 0),
          (settings.THROTTLE_POSITION, 0),
          (settings.ODOMETER, 0),
          (settings.FUEL_LEVEL, 0),
          (settings.ENGINE_COOLANT_TEMPERATURE, 0),
          (settings.IGNITION_STATUS, 0),
          (settings.MIL_STATUS, 0),
          (settings.FUEL_RATE, 0),
          (settings.PTO_STATUS, 0),
    import traceback
    import os.path
    import json
    import time

    from app_logging import AppLogger

except Exception as ex:
    # Output DEBUG logs indicating what import failed. Use the logging in the
    # CSClient since app_logging may not be loaded.
    cs.CSClient().log('getsignal.py', 'Import failure: {}'.format(ex))
    cs.CSClient().log('getsignal.py', 'Traceback: {}'.format(traceback.format_exc()))
    sys.exit(-1)

# Create an AppLogger for logging to syslog in NCOS.
log = AppLogger()
log.debug('Started getsignal.py')

# initialize rssi and sinr lists
rssi = []
sinr = []

# js block
js_block = """
var values = %s;
var ctx = document.getElementById("%sChart").getContext('2d');
var scatterChart = new Chart(ctx, {
    type: 'scatter',
    data: {
        datasets: [{
            label: '%s',