Exemplo n.º 1
0
    def test_send_payload(self, mock_requests=MagicMock()):
        with patch.dict(
                os.environ,
            {
                "WEB_CLIENT_LOG_FILE": "web_client.log",
                "LOG_DIRECTORY": self.temp_dir.path,
                "LAN_SERVER_HTTPS": "True",
                "LAN_SERVER_IP": "0.0.0.0",
                "LAN_PORT": "0",
            },
        ):
            with LogCapture() as capture:
                l_client = WebClient()

                payload = '{"key": "value" }'
                payload = json.loads(payload)

                l_client.send(payload)

                mock_requests.post.assert_called_with("https://0.0.0.0:0",
                                                      json=payload)
                capture.check(
                    ("WEB_CLIENT_LOG_FILE", "INFO",
                     "Pinging: https://0.0.0.0:0"),
                    ("WEB_CLIENT_LOG_FILE", "INFO", f"data: { payload }"),
                )
    def test_ping_server_raise_ex(self, mock_requests=MagicMock()):
        with patch.dict(
                os.environ,
            {
                "WEB_CLIENT_LOG_FILE": "web_client.log",
                "LOG_DIRECTORY": self.temp_dir.path,
                "LAN_SERVER_HTTPS": "True",
                "LAN_SERVER_IP": "0.0.0.0",
                "LAN_PORT": "0",
            },
        ):
            with LogCapture() as capture:
                l_client = WebClient()
                mock_requests.post.side_effect = Exception("Exception")

                payload = "{'key':'value'}"

                with self.assertRaises(Exception):
                    l_client.ping_lan_server(payload)

                mock_requests.post.assert_called_with("https://0.0.0.0:0",
                                                      data=payload)
                capture.check(
                    ("WEB_CLIENT_LOG_FILE", "INFO", "Pinging"),
                    ("WEB_CLIENT_LOG_FILE", "INFO", f"data: { payload }"),
                    ("WEB_CLIENT_LOG_FILE", "ERROR",
                     "error occurred: Exception"),
                )
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        if os.environ.get("ENABLE_RADIO_TRANSMISSION"):
            self.transceiver = Transceiver()

        if os.environ.get("ENABLE_INTERNET_TRANSMISSION"):
            apiUrl = os.environ.get("REMOTE_SERVER_API_ENDPOINT")
            self.web_client = WebClient(server_url=apiUrl)
        self.logging = get_logger("COMM_PI_LOG_FILE")
        super().__init__(*args, **kwargs)
Exemplo n.º 4
0
def handleLocal():
    """
    starts listening on the defined serial port and passing
    received data along to the web client when received
    """
    transceiver = Transceiver()
    url = os.environ.get("DJANGO_SERVER_API_ENDPOINT")
    if url:
        client = WebClient(server_url=url)
        while True:
            data = transceiver.listen()
            if data:
                print(data, type(data))
                payload = json.loads(data)
                client.send(payload)
    else:
        print("DJANGO_SERVER_API_ENDPOINT not set")
Exemplo n.º 5
0
class CommPi(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        if os.environ.get("ENABLE_RADIO_TRANSMISSION"):
            self.transceiver = Transceiver()

        if os.environ.get("ENABLE_INTERNET_TRANSMISSION"):
            apiUrl = os.environ.get("REMOTE_SERVER_API_ENDPOINT")
            self.web_client = WebClient(server_url=apiUrl)
        self.logging = get_logger("COMM_PI_LOG_FILE")
        super().__init__(*args, **kwargs)

    def _set_response(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):
        self._set_response()
        self.logging.info("GET request for {}".format(self.path).encode("utf-8"))
        self.wfile.write("GET request for {}".format(self.path).encode("utf-8"))

    def do_POST(self):
        content_length = int(self.headers["Content-Length"])
        post_data = self.rfile.read(content_length)

        self.send_data(str(post_data.decode("utf-8")))
        self._set_response()
        self.logging.info("POST request for {}".format(self.path).encode("utf-8"))

        self.wfile.write("POST request for {}".format(self.path).encode("utf-8"))

    def send_data(self, payload):
        self.logging.info("send_data called, payload: " + str(payload))
        try:
            if os.environ.get("ENABLE_INTERNET_TRANSMISSION"):
                self.logging.info("transmit via internet")
                payload = json.loads(payload)
                self.web_client.send(payload)
            if os.environ.get("ENABLE_RADIO_TRANSMISSION"):
                self.logging.info("transmit via radio")
                self.transceiver.send(payload)
        except Exception as err:
            self.logging.error("error occurred: {}".format(str(err)))
            raise
        return
Exemplo n.º 6
0
def handleSense():
    """
    Starts up the SensorPi runtime, begins listening for SenseHat input,
    establishing a connection to a local CommPi via LAN, and sending data
    for transmission to the CommPi
    """
    sensor_keys = get_sensor_keys()
    sensor_ids = {}
    sensor_ids[sensor_keys["TEMPERATURE"]] = 2
    sensor_ids[sensor_keys["PRESSURE"]] = 3
    sensor_ids[sensor_keys["HUMIDITY"]] = 4
    sensor_ids[sensor_keys["ACCELERATION"]] = 5
    sensor_ids[sensor_keys["ORIENTATION"]] = 6
    sensePi = SensePi(sensor_ids=sensor_ids)

    client = WebClient()

    while True:
        print("while true")
        temp = sensePi.get_temperature()
        pres = sensePi.get_pressure()
        hum = sensePi.get_humidity()
        acc = sensePi.get_acceleration()
        orie = sensePi.get_orientation()
        all = sensePi.get_all()

        dataArr = [temp, pres, hum, acc, orie, all]

        for payload in dataArr:
            payload = json.dumps(payload)
            payload = json.loads(payload)
            print(payload)
            try:
                client.send(payload)
            except Exception as err:
                print("error occurred: {}".format(str(err)))
                raise
            time.sleep(1)
Exemplo n.º 7
0
def handleGps():
    """
    Starts up the GPSPi runtime, begins listening for GPS Hat input,
    establishing a connection to a local CommPi via LAN, and sending data
    for transmission to the CommPi
    """
    gpsPi = GPSReader()
    client = WebClient()

    while True:
        print("gps loop")
        coords = gpsPi.get_geolocation()
        speed = gpsPi.get_speed_mph()
        if coords is not None:
            data = [coords, speed]
            for i in data:
                payload = json.loads(json.dumps(i))
                try:
                    client.send(payload)
                except Exception as err:
                    print("Error transmitting gps data: {}".format(str(err)))
                    raise
                time.sleep(1)
    def test_init_no_log_no_server_http(self):
        with patch.dict(
                os.environ,
            {
                "WEB_CLIENT_LOG_FILE": "web_client.log",
                "LOG_DIRECTORY": self.temp_dir.path,
                "LAN_SERVER_IP": "0.0.0.0",
                "LAN_PORT": "0",
            },
        ):
            l_client = WebClient()

            self.assertTrue(l_client.logging is not None)
            self.assertTrue(l_client.logging.name == "WEB_CLIENT_LOG_FILE")
            self.assertIsInstance(l_client.logging, Logger)

            self.assertEqual(l_client.url, "http://0.0.0.0:0")
Exemplo n.º 9
0
    def test_init_log_server(self):
        with patch.dict(
            os.environ,
            {
                "NEW_LOG_FILE": "web_client.log",
                "LOG_DIRECTORY": self.temp_dir.path,
                "LAN_SERVER_HTTPS": "True",
                "LAN_SERVER_IP": "0.0.0.0",
                "LAN_PORT": "0",
            },
        ):
            l_client = WebClient(log_file_name="NEW_LOG_FILE", server_url="/url")

            self.assertTrue(l_client.logging is not None)
            self.assertTrue(l_client.logging.name == "NEW_LOG_FILE")
            self.assertIsInstance(l_client.logging, Logger)

            self.assertEqual(l_client.url, "/url")
Exemplo n.º 10
0
    def test_ping_server_raise_http_ex(self, mock_requests=MagicMock()):
        with patch.dict(
                os.environ,
            {
                "WEB_CLIENT_LOG_FILE": "web_client.log",
                "LOG_DIRECTORY": self.temp_dir.path,
                "LAN_SERVER_HTTPS": "True",
                "LAN_SERVER_IP": "0.0.0.0",
                "LAN_PORT": "0",
            },
        ):
            with LogCapture() as capture:
                l_client = WebClient()
                mock_requests.post.side_effect = HTTPError("HTTPError")

                payload = '{"key": "value" }'
                payloadJson = json.loads(payload)

                with self.assertRaises(HTTPError):
                    l_client.send(payloadJson)

                mock_requests.post.assert_called_with("https://0.0.0.0:0",
                                                      json=payloadJson)

                with self.assertRaises(HTTPError):
                    l_client.send(payload, is_json=False)

                mock_requests.post.assert_called_with("https://0.0.0.0:0",
                                                      data=payload)

                capture.check(
                    ("WEB_CLIENT_LOG_FILE", "INFO",
                     "Pinging: https://0.0.0.0:0"),
                    ("WEB_CLIENT_LOG_FILE", "INFO", f"data: { payloadJson }"),
                    ("WEB_CLIENT_LOG_FILE", "ERROR",
                     "HTTP error occurred: HTTPError"),
                    ("WEB_CLIENT_LOG_FILE", "INFO",
                     "Pinging: https://0.0.0.0:0"),
                    ("WEB_CLIENT_LOG_FILE", "INFO", f"data: { payload }"),
                    ("WEB_CLIENT_LOG_FILE", "ERROR",
                     "HTTP error occurred: HTTPError"),
                )
if os.environ["HARDWARE_TYPE"] == "commPi":
    print("CommunicationsPi")
    runServer(handler_class=CommPi)
elif os.environ["HARDWARE_TYPE"] == "sensePi":
    print("SensePi")
    sensor_keys = get_sensor_keys()
    sensor_ids = {}
    sensor_ids[sensor_keys["TEMPERATURE"]] = 2
    sensor_ids[sensor_keys["PRESSURE"]] = 3
    sensor_ids[sensor_keys["HUMIDITY"]] = 4
    sensor_ids[sensor_keys["ACCELERATION"]] = 5
    sensor_ids[sensor_keys["ORIENTATION"]] = 6
    sensePi = SensePi(sensor_ids=sensor_ids)
    gpsPi = GPSReader()
    client = WebClient()

    while True:
        print("while true")
        temp = sensePi.get_temperature()
        pres = sensePi.get_pressure()
        hum = sensePi.get_humidity()
        acc = sensePi.get_acceleration()
        orie = sensePi.get_orientation()
        all = sensePi.get_all()
        coords = gpsPi.get_geolocation()

        if coords is not None:
            data = [temp, pres, hum, acc, orie, coords, all]
        else:
            data = [temp, pres, hum, acc, orie, all]