Beispiel #1
0
def test_function_call(hammock):
    spark = SparkCloud("myToken", spark_api=hammock)
    assert 1 == spark.T1000.digitalwrite('D7', 'HIGH')
    hammock.v1.devices("53ff6e066667574845411267")("digitalwrite").POST.assert_called_once_with(
        params={"access_token": "myToken"},
        data={"params": "D7,HIGH"}
    )
Beispiel #2
0
def test_target_device_accessed_by_dictionnary(hammock):
    spark = SparkCloud("myToken", spark_api=hammock)
    assert spark.devices["T1000"].connected == True
    hammock.v1.devices.GET.assert_called_once_with(
        params={"access_token": "myToken"}
    )
    assert hammock.v1.devices("53ff6e066667574845411267").GET.call_count == 1
Beispiel #3
0
def test_target_device_accessed_by_name(hammock):
    """Access the spark device using its name as an attribute of the SparkCloud object"""
    spark = SparkCloud("myToken", spark_api=hammock)
    assert spark.T1000.connected == True
    hammock.v1.devices.GET.assert_called_once_with(
        params={"access_token": "myToken"}, timeout=30)
    print(hammock.v1.devices("53ff6e066667574845411267").GET.call_count == 1)
Beispiel #4
0
def test_login_password(hammock):
    """When login with user/password, SparkCloud fetches a token"""
    spark = SparkCloud("myLogin", "myPassword", spark_api=hammock)
    hammock.oauth.token.POST.assert_called_once_with(
        auth=('spark', 'spark'),
        data={"username": "******", "password": "******", "grant_type": "password"}
    )
    assert spark.access_token == "254406f79c1999af65a7df4388971354f85cfee9"
Beispiel #5
0
def checkout(request):

    spark = SparkCloud(SP_USERNAME,SP_PASSWORD)

    """
    " Alternative:
    "spark = SparkCloud(SP_ACCESS_TOKEN)
    """

    if (spark.<YOUR_CORE_NAME>.connected):

        nonce=request.POST.get("payment_method_nonce")

        """
        " Finishing the transaction adn getting the result.
        """

        result=braintree.Transaction.sale({
            "amount":"1.00",
            "payment_method_nonce":nonce
        })

        transaction_id=result.transaction.id

        name = request.POST.get("twitterName")
        if name != "":

            """
            " Calling to Spark Core to show the tweet message at the tft
            """
            spark.<YOUR_CORE_NAME>.twitter(name)

            api = tweetpony.API(
                    consumer_key = TP_CONSUMER_KEY,
                    consumer_secret = TP_CONSUMER_SECRET,
                    access_token = TP_ACCESS_TOKEN,
                    access_token_secret = TP_ACCESS_TOKEN_SECRET
                    )
            try:
                text = "Hi @"+name+". This is your transaction ID:"+transaction_id+". Please, grab your candies!"
                api.update_status(text)
            except tweetpony.APIError as err:
                print "Oops, something went wrong! Twitter returned error #%i and said: %s" % (err.code, err.description)
            else:
                print "Yay! Your tweet has been sent!"

        """
        " Calling to Spark Core to move the motor

        """
        spark.<YOUR_CORE_NAME>.candy(transaction_id)

    else:

        textMessage = "ERROR: Device not connected"


    return render_to_response("checkout.html",locals())
Beispiel #6
0
 def login(self, username, password):
     try:
         print 'trying to connect to the cloud...'
         # Though Spark is now Particle, this python API still use Spark here.
         self.Particle = SparkCloud(username, password)
     except Exception as er:
         print er
         self.Particle = None
         print('\nLog in failed, please check your credentials!')
Beispiel #7
0
def test_target_devices_caching(hammock):
    spark = SparkCloud("myToken", spark_api=hammock)
    assert spark.devices["T1000"].connected == True
    assert hammock.v1.devices("53ff6e066667574845411267").GET.call_count == 1
    hammock.v1.devices("53ff6e066667574845411267").GET.reset_mock()
    assert spark.devices["T1000"].connected == True
    assert hammock.v1.devices("53ff6e066667574845411267").GET.call_count == 0
    time.sleep(10)
    assert spark.devices["T1000"].connected == True
    assert hammock.v1.devices("53ff6e066667574845411267").GET.call_count == 1
Beispiel #8
0
    def __init__(self, devf="/root/runtime/homelib/.temperature.oak"):
        with open(devf) as f:
            self.name, self.token = f.readline()[:-1].split(":")

            SparkCloud.__init__(self, self.token)
Beispiel #9
0
#
import logging
import json
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
from spyrk import SparkCloud
# PARTICLE_DEVICE_ID = 'YOUR_DEVICE_ID_HERE'
# PARTICLE_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN_HERE'
# PARTICLE_NODE_MAIN = YOUR_MAIN_NODE_ID
# or
from config import PARTICLE_DEVICE_ID, PARTICLE_ACCESS_TOKEN, PARTICLE_NODE_MAIN, PARTICLE_NODE_KM
from colormaker import name2wrgb

app = Flask(__name__)
ask = Ask(app, "/")
spark = SparkCloud(PARTICLE_ACCESS_TOKEN)
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
sparkDevice = spark.devices[PARTICLE_DEVICE_ID]


@ask.launch
def hello():
    logging.info("Hello Xlight")
    if sparkDevice.connected:
        speech_text = render_template('hello')
        return question(speech_text).reprompt(speech_text).simple_card(
            'HelloXlight', speech_text)
    else:
        speech_text = render_template('device_offline')
        return question(speech_text).reprompt(speech_text).simple_card(
            'HelloXlight', speech_text)
Beispiel #10
0
import time
import calendar
from spyrk import SparkCloud

ACCESS_TOKEN = '' # access token redacted for security reasons
time_good = 0

response = requests.get('http://spacexstats.com')
soup = BeautifulSoup(response.text)
countdown_text = soup.find('time').string
# example of countdown_text is "10 Feb 2015 23:04:46 UTC"
print "Countdown Text: " + countdown_text

try: 
	countdown_time = time.strptime(countdown_text, "%d %b %Y %H:%M:%S %Z")
	time_good = 1
except ValueError:
	print "Error decoding the date and time"

if (time_good == 0):
	try:
		countdown_time = time.strptime(countdown_text, "%d %b %Y %Z")
		time_good = 2
	except ValueError:
		print "Error decoding just the date."
		
if (time_good != 0):
	countdown_time_unix = calendar.timegm(countdown_time)
	spark = SparkCloud(ACCESS_TOKEN)
	spark.TimeKeeper.setTZero(str(countdown_time_unix))
Beispiel #11
0
def handle_non_discovery_v3(request):
    request_namespace = request["directive"]["header"]["namespace"]
    request_name = request["directive"]["header"]["name"]
    access_token = request["directive"]["endpoint"]["scope"]["token"]
    particle_device = get_directive_deviceid(request)
    particle_node = get_directive_nodeid(request)
    particle_model = get_directive_model(request)

    spark = SparkCloud(access_token)
    sparkDevice = spark.devices[particle_device]
    if request_namespace == "Alexa.PowerController":
        if request_name == "TurnOn":
            value = "ON"
        else:
            value = "OFF"

        if sparkDevice.connected:
            # Call cloud function
            if particle_model == "Smart Switch":
                cmd_obj = dict(cmd=8, nd=particle_node, msg=1, ack=1, tag=65 if value == 'ON' else 66, pl="1")
            else:
                cmd_obj = dict(cmd=1, nd=particle_node, state=1 if value == 'ON' else 0)
            cmd_string = json.dumps(cmd_obj)
            sparkDevice.JSONCommand(cmd_string)

        response = {
            "context": {
                "properties": [
                    {
                        "namespace": "Alexa.PowerController",
                        "name": "powerState",
                        "value": value,
                        "timeOfSample": get_utc_timestamp(),
                        "uncertaintyInMilliseconds": 500
                    }
                ]
            },
            "event": {
                "header": {
                    "namespace": "Alexa",
                    "name": "Response",
                    "payloadVersion": "3",
                    "messageId": get_uuid(),
                    "correlationToken": request["directive"]["header"]["correlationToken"]
                },
                "endpoint": {
                    "scope": {
                        "type": "BearerToken",
                        "token": "access-token-from-Amazon"
                    },
                    "endpointId": request["directive"]["endpoint"]["endpointId"]
                },
                "payload": {}
            }
        }
        return response

    elif request_namespace == "Alexa.BrightnessController":
        if request_name == "SetBrightness":
            brightness = request["directive"]["payload"]["brightness"]
            if sparkDevice.connected:
                # Call cloud function
                cmd_obj = dict(cmd=3, nd=particle_node, value=brightness)
                cmd_string = json.dumps(cmd_obj)
                sparkDevice.JSONCommand(cmd_string)

            response = {
                "context": {
                    "properties": [
                        {
                            "namespace": "Alexa.BrightnessController",
                            "name": "brightness",
                            "value": brightness,
                            "timeOfSample": get_utc_timestamp(),
                            "uncertaintyInMilliseconds": 500
                        }
                    ]
                },
                "event": {
                    "header": {
                        "namespace": "Alexa",
                        "name": "Response",
                        "payloadVersion": "3",
                        "messageId": get_uuid(),
                        "correlationToken": request["directive"]["header"]["correlationToken"]
                    },
                    "endpoint": {
                        "scope": {
                            "type": "BearerToken",
                            "token": "access-token-from-Amazon"
                        },
                        "endpointId": request["directive"]["endpoint"]["endpointId"]
                    },
                    "payload": {}
                }
            }
            return response
        elif request_name == "AdjustBrightness":
            brightness = request["directive"]["payload"]["brightnessDelta"]
            # ToDo:... need new cloud interface
            response = {
                "context": {
                    "properties": [
                        {
                            "namespace": "Alexa.BrightnessController",
                            "name": "brightness",
                            "value": brightness,
                            "timeOfSample": get_utc_timestamp(),
                            "uncertaintyInMilliseconds": 500
                        }
                    ]
                },
                "event": {
                    "header": {
                        "namespace": "Alexa",
                        "name": "Response",
                        "payloadVersion": "3",
                        "messageId": get_uuid(),
                        "correlationToken": request["directive"]["header"]["correlationToken"]
                    },
                    "endpoint": {
                        "scope": {
                            "type": "BearerToken",
                            "token": "access-token-from-Amazon"
                        },
                        "endpointId": request["directive"]["endpoint"]["endpointId"]
                    },
                    "payload": {}
                }
            }
            return response

    elif request_namespace == "Alexa.ColorTemperatureController":
        # should retrieve from status change report
        cct = 5000
        if request_name == "SetColorTemperature":
            cct = request["directive"]["payload"]["colorTemperatureInKelvin"]
        elif request_name == "DecreaseColorTemperature":
            cct = cct - 200
            if cct < 3000:
                cct = 3000
        elif request_name == "IncreaseColorTemperature":
            cct = cct + 200
            if cct > 6500:
                cct = 6500

        if sparkDevice.connected:
            # Call cloud function
            cmd_obj = dict(cmd=5, nd=particle_node, value=cct)
            cmd_string = json.dumps(cmd_obj)
            sparkDevice.JSONCommand(cmd_string)

        response = {
            "context": {
                "properties": [
                    {
                        "namespace": "Alexa.ColorTemperatureController",
                        "name": "colorTemperatureInKelvin",
                        "value": cct,
                        "timeOfSample": get_utc_timestamp(),
                        "uncertaintyInMilliseconds": 500
                    }
                ]
            },
            "event": {
                "header": {
                    "namespace": "Alexa",
                    "name": "Response",
                    "payloadVersion": "3",
                    "messageId": get_uuid(),
                    "correlationToken": request["directive"]["header"]["correlationToken"]
                },
                "endpoint": {
                    "scope": {
                        "type": "BearerToken",
                        "token": "access-token-from-Amazon"
                    },
                    "endpointId": request["directive"]["endpoint"]["endpointId"]
                },
                "payload": {}
            }
        }
        return response

    elif request_namespace == "Alexa.ColorController":
        if request_name == "SetColor":
            # HSV to RGB
            rgb_color = [0, 255, 0, 0]
            hsv_color = request["directive"]["payload"]["color"]
            #rgb_color = colorsys.hsv_to_rgb(hsv_color)

            if sparkDevice.connected:
                # Call cloud function
                cmd_obj = dict(cmd=2, nd=particle_node)
                cmd_obj['ring'] = [0, 1, 80] + rgb_color
                cmd_string = json.dumps(cmd_obj)
                sparkDevice.JSONCommand(cmd_string)

            response = {
                "context": {
                    "properties": [
                        {
                            "namespace": "Alexa.ColorController",
                            "name": "color",
                            "value": hsv_color,
                            "timeOfSample": get_utc_timestamp(),
                            "uncertaintyInMilliseconds": 500
                        }
                    ]
                },
                "event": {
                    "header": {
                        "namespace": "Alexa",
                        "name": "Response",
                        "payloadVersion": "3",
                        "messageId": get_uuid(),
                        "correlationToken": request["directive"]["header"]["correlationToken"]
                    },
                    "endpoint": {
                        "scope": {
                            "type": "BearerToken",
                            "token": "access-token-from-Amazon"
                        },
                        "endpointId": request["directive"]["endpoint"]["endpointId"]
                    },
                    "payload": {}
                }
            }
            return response

    elif request_namespace == "Alexa.Authorization":
        if request_name == "AcceptGrant":
            response = {
                "event": {
                    "header": {
                        "namespace": "Alexa.Authorization",
                        "name": "AcceptGrant.Response",
                        "payloadVersion": "3",
                        "messageId": "5f8a426e-01e4-4cc9-8b79-65f8bd0fd8a4"
                    },
                    "payload": {}
                }
            }
            return response
Beispiel #12
0
def handle_non_discovery(request):
    request_name = request["header"]["name"]
    access_token = request["payload"]["accessToken"]
    particle_device = get_directive_deviceid(request)
    particle_node = get_directive_nodeid(request)
    particle_model = get_directive_model(request)

    spark = SparkCloud(access_token)
    sparkDevice = spark.devices[particle_device]

    if request_name == "TurnOnRequest":
        header = {
            "namespace": "Alexa.ConnectedHome.Control",
            "name": "TurnOnConfirmation",
            "payloadVersion": "2",
            "messageId": get_uuid()
        }
        if sparkDevice.connected:
            # Call cloud function
            if particle_model == "Smart Switch":
                cmd_obj = dict(cmd=8, nd=particle_node, msg=1, ack=1, tag=65, pl="1")
            else:
                cmd_obj = dict(cmd=1, nd=particle_node, state=1)
            cmd_string = json.dumps(cmd_obj)
            sparkDevice.JSONCommand(cmd_string)
    elif request_name == "TurnOffRequest":
        header = {
            "namespace": "Alexa.ConnectedHome.Control",
            "name": "TurnOffConfirmation",
            "payloadVersion": "2",
            "messageId": get_uuid()
        }
        if sparkDevice.connected:
            # Call cloud function
            if particle_model == "Smart Switch":
                cmd_obj = dict(cmd=8, nd=particle_node, msg=1, ack=1, tag=66, pl="1")
            else:
                cmd_obj = dict(cmd=1, nd=particle_node, state=0)
            cmd_string = json.dumps(cmd_obj)
            sparkDevice.JSONCommand(cmd_string)
    elif request_name == "SetPercentageRequest":
        header = {
            "namespace": "Alexa.ConnectedHome.Control",
            "name": "SetPercentageConfirmation",
            "payloadVersion": "2",
            "messageId": get_uuid()
        }
        if sparkDevice.connected:
            # Call cloud function
            brightness = request["payload"]["percentageState"]["value"]
            cmd_obj = dict(cmd=3, nd=particle_node, value=brightness)
            cmd_string = json.dumps(cmd_obj)
            sparkDevice.JSONCommand(cmd_string)

    # other handlers omitted in this example
    payload = {}
    response = {
        "header": header,
        "payload": payload
    }
    return response
Beispiel #13
0
def test_variable_fetch(hammock):
    spark = SparkCloud("myToken", spark_api=hammock)
    assert spark.T1000.game_state == "state"
    hammock.v1.devices("53ff6e066667574845411267")("game_state").GET.assert_called_once_with(
        params={"access_token": "myToken"}
    )
Beispiel #14
0
def test_variable_list(hammock):
    spark = SparkCloud("myToken", spark_api=hammock)
    device = spark.T1000
    assert 'game_state' in device.variables
    assert 'string' in device.variables["game_state"]
Beispiel #15
0
def test_function_list(hammock):
    spark = SparkCloud("myToken", spark_api=hammock)
    device = spark.T1000
    assert 'digitalwrite' in device.functions
Beispiel #16
0
def test_login_token(hammock):
    """When login with an access token, the oauth token request is not used"""
    spark = SparkCloud("myToken", spark_api=hammock)
    assert spark.access_token == "myToken"