Beispiel #1
0
def run_hologram_receive_data(args):

    global hologram
    hologram = HologramCloud(dict(), network='cellular')

    hologram.event.subscribe('message.received', popReceivedMessage)

    if not hologram.network.at_sockets_available:
        hologram.network.connect()

    hologram.openReceiveSocket()
    print('Ready to receive data on port %s' % hologram.receive_port)

    try:
        handle_polling(args['timeout'], popReceivedMessage, 1)
    except KeyboardInterrupt as e:
        print 'Closing socket...'
        hologram.closeReceiveSocket()

        if not hologram.network.at_sockets_available:
            hologram.network.disconnect()

        sys.exit(e)

    if not hologram.network.at_sockets_available:
        hologram.network.disconnect()
Beispiel #2
0
def send_alarm(fahr, h, message, logger):
    hologram = HologramCloud(dict(), network='cellular')  # connect to cellular

    result = hologram.network.connect()
    if result == False:
        logger.info('Failed to connect to cell network')
        hologram.network.disconnect()
        sys.exit(1)  # later will call textMessage function
    logger.info("Attempting to send to Hologram cloud...")
    logger.info("String to send is " + message)
    logger.info("attempting to send to holo cloud")
    # postData={"value1":fahr,"value2":h}
    postData = {
        "value1": '{0:0.1f}'.format(fahr),
        "value2": '{0:0.1f}'.format(h)
    }
    r = requests.post(url=IFTTTPostSite, data=postData)
    # r is the returned status code from the curl request
    logger.info("response code: '{0:0.3d}'.format(r.status_code)" +
                " reason: " + r.reason)
    hologram.network.disconnect()

    if (r.status_code != "200"):
        return 1  # error condition
    else:
        return 0  # got a "200 OK"
def sendPSK(args, data, is_sms=False):

    if not (args['devicekey']) and ('devicekey' in data):
        args['devicekey'] = data['devicekey']

    if not args['devicekey']:
        raise HologramError('Device key not specified')

    credentials = {'devicekey': args['devicekey']}

    recv = ''
    if not is_sms and (args['host'] is not None or args['port'] is not None):
        # we're using some custom cloud
        customCloud = CustomCloud(None,
                                  send_host=args['host'],
                                  send_port=args['port'])
        recv = customCloud.sendMessage(args['message'],
                                       timeout=args['timeout'])
        print(f'RESPONSE FROM CLOUD: {recv}')
    else:
        # host and port are default so use Hologram
        hologram = HologramCloud(credentials,
                                 authentication_type='csrpsk',
                                 network='cellular')
        send_message_helper(hologram, args, is_sms=is_sms)
Beispiel #4
0
    def test_invalid_sms_length(self):

        hologram = HologramCloud(credentials, enable_inbound = False)

        temp = '111111111234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
        with pytest.raises(Exception, message = 'SMS cannot be more than 160 characters long!'):
            hologram.sendSMS('+1234567890', temp)
Beispiel #5
0
def sendTOTP(args, data, is_sms=False):

    if not args['iccid'] and ('device_id' in data):
        args['iccid'] = data['device_id']

    if not args['imsi'] and ('private_key' in data):
        args['imsi'] = data['private_key']

    credentials = {'device_id': args['iccid'], 'private_key': args['imsi']}
    hologram = HologramCloud(credentials, enable_inbound=False,
                             authentication_type='totp',
                             network='cellular')

    modem = ''
    # Load the ICCID and IMSI values if modem is physically attached to machine
    if hologram.network.isModemAttached():
        modem = hologram.network.active_modem_interface
        hologram.credentials = {'device_id': hologram.network.iccid,
                                'private_key': hologram.network.imsi}
        hologram.initializeNetwork('cellular-' + str(modem).lower())

    if (hologram.credentials['device_id'] is None) or (hologram.credentials['private_key'] is None):
        raise HologramError('Device id or private key not specified or cannot be pulled from modem. Please specify them or rerun the program with a provided device key')

    result = hologram.network.connect()
    if result == False:
        raise HologramError('Failed to connect to cell network')

    send_message_helper(hologram, args, is_sms=is_sms)
    hologram.network.disconnect()
Beispiel #6
0
    def test_create(self):
        hologram = HologramCloud(credentials, enable_inbound = False)

        assert hologram.send_host == 'cloudsocket.hologram.io'
        assert hologram.send_port == 9999
        assert hologram.receive_host == '0.0.0.0'
        assert hologram.receive_port == 4010
def run_hologram_receive_data(args):

    global hologram
    hologram = HologramCloud(dict(), network='cellular')

    hologram.event.subscribe('message.received', popReceivedMessage)

    if not hologram.network.at_sockets_available:
        hologram.network.connect()

    try:
        hologram.openReceiveSocket()
    except Exception as e:
        print(f"Failed to open socket to listen for data: {e}")
        return

    print(f'Ready to receive data on port {hologram.receive_port}')

    try:
        handle_polling(args['timeout'], popReceivedMessage, 1)
    except KeyboardInterrupt as e:
        pass

    print('Closing socket...')
    hologram.closeReceiveSocket()

    if not hologram.network.at_sockets_available:
        hologram.network.disconnect()
Beispiel #8
0
def run_hologram_receive_sms(args):
    global hologram
    hologram = HologramCloud(dict(), network='cellular')
    print('Ready to receive sms')
    try:
        handle_polling(args['timeout'], popReceivedSMS, 1)
    except KeyboardInterrupt as e:
        sys.exit(e)
Beispiel #9
0
    def test_get_result_string(self):

        hologram = HologramCloud(credentials, enable_inbound = False)

        assert hologram.getResultString(0) == 'Message sent successfully'
        assert hologram.getResultString(1) == 'Connection was closed so we couldn\'t read the whole message'
        assert hologram.getResultString(2) == 'Failed to parse the message'
        assert hologram.getResultString(3) == 'Auth section of the message was invalid'
        assert hologram.getResultString(-1) == 'Unknown error'
        assert hologram.getResultString(7) == 'Unknown response code'
Beispiel #10
0
def run_hologram_receive_sms(args):

    global hologram
    hologram = HologramCloud(None,
                             enable_inbound=False,
                             network='cellular-iota')

    hologram.event.subscribe('sms.received', popReceivedSMS)
    hologram.enableSMS()

    handle_timeout(args['timeout'])

    hologram.disableSMS()
Beispiel #11
0
    def test_get_result_string(self):

        hologram = HologramCloud(credentials, enable_inbound = False)

        assert hologram.getResultString(-1) == 'Unknown error'
        assert hologram.getResultString(0) == 'Message sent successfully'
        assert hologram.getResultString(1) == 'Connection was closed so we couldn\'t read the whole message'
        assert hologram.getResultString(2) == 'Failed to parse the message'
        assert hologram.getResultString(3) == 'Auth section of the message was invalid'
        assert hologram.getResultString(4) == 'Payload type was invalid'
        assert hologram.getResultString(5) == 'Protocol type was invalid'
        assert hologram.getResultString(6) == 'Internal error in Hologram Cloud'
        assert hologram.getResultString(7) == 'Metadata was formatted incorrectly'
        assert hologram.getResultString(8) == 'Topic was formatted incorrectly'
Beispiel #12
0
def run_hologram_receive_data(args):

    global hologram
    hologram = HologramCloud(None,
                             enable_inbound=False,
                             network='cellular-' + str(args['modem']))

    hologram.event.subscribe('message.received', popReceivedMessage)
    result = hologram.network.connect()
    if result == False:
        print 'Failed to connect to cell network'

    print 'Listening to port ' + str(hologram.receive_port)
    hologram.initializeReceiveSocket()

    handle_timeout(args['timeout'])

    hologram.closeReceiveSocket()

    hologram.network.disconnect()
Beispiel #13
0
 def run(self):
     self.start_time = time.time() - 200
     self.hologram = HologramCloud({'devicekey': 'ujk{]5pX'},
                                   network='cellular')
     if self.hologram.network.getConnectionStatus() != 1:
         self.hologram.network.disconnect()
         time.sleep(1)
     try:
         result = self.hologram.network.connect()
         if result == False:
             sys.stderr.write("Failed to connect to cell network\n")
         else:
             self.hologram.openReceiveSocket()
             self.hologram.event.subscribe('message.received',
                                           self.receivedMessage)
     except:
         sys.stderr.write("connection error\n")
         pass
     while True:
         time.sleep(220 * self.multiplier)
         self.compressGps()
def run_hologram_spacebridge(args):
    global hologram
    hologram = HologramCloud(dict(), network='cellular')

    hologram.event.subscribe('message.received', popReceivedMessage)

    hologram.network.disable_at_sockets_mode(
    )  # Persistent cellular connection
    hologram.network.scope = NetworkScope.HOLOGRAM  # Default route NOT set to cellular
    hologram.network.connect()

    hologram.openReceiveSocket()
    print(f'Ready to receive data on port {hologram.receive_port}')

    try:
        handle_polling(args['timeout'], popReceivedMessage, 1)
    except KeyboardInterrupt as e:
        print('Closing socket...')
        hologram.closeReceiveSocket()
        sys.exit(e)
    finally:
        hologram.network.disconnect()
Beispiel #15
0
def connect_hologram():

    try:

        cred = {'devicekey':''}
        hologram = HologramCloud(cred, network='cellular')

        network = hologram.network.connect(timeout=120)

        if network == False:

            os.system('sudo hologram modem disconnect')
            time.sleep(30)

            hologram = connect_hologram()
            return hologram

        file = open('sequences.txt','a')
        file.write('Connection Successful at ' + time.strftime('%H:%M') + '\n')
        file.close()

        return hologram

    except RuntimeError:

        return 'Moo'

    except Exception as e:

        # Save error in file
        file = open('error_messages.txt','a')
        file.write('Error: ' + str(e.message) +  ' at ' + time.strftime('%Y-%m-%d %H:%M') + '\n')
        file.close()

        os.system('sudo hologram modem disconnect')
        time.sleep(30)

        hologram = connect_hologram()
        return hologram
Beispiel #16
0
def waterlevel(data):
    if data.startswith('<info> app: WL data:'):
        waterout = int(data[20:])
        percentfull = ((waterout) / 177)
        gallons = (5.5 * percentfull)
        return gallons


while (1):
    # Wait until there is data waiting in the serial buffer
    if (serialPort.in_waiting > 0):
        # Read data out of the buffer until a carraige return / new line is found
        serialString = serialPort.readline()
        message = (serialString.decode('Ascii'))

        # Print the contents of the serial data
        print(message)

        #Water logic if connected
        gallons = waterlevel(message)
        print('Gallons in Bucket:' + str(gallons))

        #Send information to the cloud
        hologram = HologramCloud(dict(), network='cellular')
        print('Cloud type: ' + str(hologram))
        payload = {"WaterLevel": gallons}
        recv = hologram.sendMessage(json.dumps(payload))

        time.sleep(30)
Beispiel #17
0
def network_connect():
    run("sudo hologram network connect", shell=True)
    credentials = {'devicekey': 'a_jbDNcZ'}
    return HologramCloud(
        credentials, network='cellular',
        authentication_type='csrpsk')  #return cloud routing credentials
Beispiel #18
0
sys.path.append("..")
sys.path.append("../..")

from Hologram.HologramCloud import HologramCloud

if __name__ == "__main__":
    print ""
    print ""
    print "Testing Hologram Cloud class..."
    print ""
    print "* Note: You can obtain device keys from the Devices page"
    print "* at https://dashboard.hologram.io"
    print ""

    logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")

    hologram = HologramCloud(dict(), authentication_type='sim-otp',
                             network='cellular')

    result = hologram.network.connect()
    if result == False:
        print 'Failed to connect to cell network'

    recv = hologram.sendMessage("one two three!",
                                topics = ["TOPIC1","TOPIC2"],
                                timeout = 3)

    print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv)

    hologram.network.disconnect()
Beispiel #19
0
#
# Part of the CSAD IoT Crop Care Project
# Aidan Taylor 28th December 2017

from Hologram.HologramCloud import HologramCloud
from time import sleep
import urllib2
from sensorReading import getSoilSensor1, getSoilSensor2, getSoilSensor3, reservoirLevel
from watering import waterPot1, waterPot2, waterPot3, end

# Hologram Setup
credentials = {
    'devicekey': 'xxxxxxxx'
}  # replace with your unique Sim device key
cloud = HologramCloud(credentials,
                      network='cellular',
                      authentication_type='csrpsk')

# Thingspeak Setup:
myAPI = "xxxxxxxxxxxxxxxx"  # replace with your ThingSpeak Write API Key

# Control variables:
# The following values set the soil moisture point that triggers a watering cycle
pot1SoilThresh = 30.0
pot2SoilThresh = 30.0
pot3SoilThresh = 30.0

cycleTime = 900  # this sets the refresh timer for the entire script - 900 for normal 15 minutes


def main():
Beispiel #20
0
from Hologram.HologramCloud import HologramCloud

if __name__ == "__main__":
    print ""
    print ""
    print "Testing Hologram Cloud class..."
    print ""
    print "* Note: You can obtain device keys from the Devices page"
    print "* at https://dashboard.hologram.io"
    print ""

    device_key = raw_input("What is your device key? ")

    credentials = {'devicekey': device_key}

    hologram = HologramCloud(credentials, enable_inbound=False)

    print 'Hologram SDK version:'
    print hologram.version

    print ''
    print 'Cloud type: ' + str(hologram)
    print ''
    print 'Network type: ' + hologram.network_type
    print ''

    print 'Sending a periodic message every 10 seconds...'
    recv = hologram.sendPeriodicMessage(10,
                                        'This is a periodic message',
                                        topics=['PERIODIC MESSAGES'],
                                        timeout=6)
Beispiel #21
0
from json import loads, dumps
from base64 import b64decode

import paho.mqtt.client as mqtt

from rsa import verify
from config import get_config
from time import sleep
from key_tools import get_pub_key

cfg = get_config()

credentials = {'devicekey': cfg['nova-device-key']}

hologram = HologramCloud(credentials, network='cellular')
hologram.enableSMS()

public_key = get_pub_key()

if not public_key:
    print('Unable to load public key')
    exit(1)


def handle_message():

    sms_obj = hologram.popReceivedSMS()

    if sms_obj:
        try:
from tensorflow_core import lite as tflite
import numpy as np

import psutil

disk = psutil.disk_usage('/')
disk_percent_used = disk.percent
disk_free = disk.free / 2**30

from Hologram.HologramCloud import HologramCloud
subprocess.run("sudo hologram network connect", shell=True)
credentials = {
    'devicekey': 'a_jbDNcZ'
}  #'6r)^]p]Q'} #Hologram device key from hologram.io
hologram = HologramCloud(
    credentials, network='cellular', authentication_type='csrpsk'
)  #Connect to Hologram CLoud, change network to cellular to connect to LTE

sum_RSSI = 0.0
sum_quality = 0.0
num_samples = 5

camera = PiCamera()

curr = datetime.datetime.now()
currDate = curr.strftime("%d_%m_%Y")
currTime = curr.strftime("%H_%M_%S")
camera.resolution = (2592, 1944)
#camera.rotation = 180
camera.capture('/home/pi/images/' + curr.strftime("%d_%m_%Y_%H_%M_%S") +
               '.jpg')
Beispiel #23
0
LED_PIN = 17  ## GPIO pin the LED is attached to
DHT_PIN = 21  ## GPIO pin the DHT sensor is attached to
LUX_MCP = 0  ## ADC pin the Photoresistor is attached to
BTN_PIN = 27  ## GPIO pin the button is attached to

## Exercise 04 - triggered by a button press
GPIO.setup(BTN_PIN, GPIO.IN,
           pull_up_down=GPIO.PUD_UP)  ## Setup GPIO pin as an input

## Exercise 05 - send data to Hologram's cloud through WiFi
with open('../credentials.json') as key_file:
    devicekey = json.load(key_file)
## hologram = HologramCloud(devicekey, enable_inbound=False)

## Exercise 06 - send data to Hologram's cloud through Cellular
hologram = HologramCloud(devicekey, network='cellular', enable_inbound=False)
hologram.network.connect()  ## connect from the cellular netowork

try:
    while True:
        if GPIO.input(BTN_PIN) == False:

            ## Exercise 05 - send data to Hologram's cloud through WiFi
            lightOn(LED_PIN)

            message = json.dumps({
                'h': getHum(DHT_PIN),
                't': getTemp(DHT_PIN),
                'l': getLux(LUX_MCP)
            })
            sent = hologram.sendMessage(message)
Beispiel #24
0
from Hologram.HologramCloud import HologramCloud

credentials = {'devicekey': '^hD8&#%H'}

if __name__ == "__main__":
    print ""
    print ""
    print "Testing Hologram Cloud class..."
    print ""
    print "* Note: You can obtain device keys from the Devices page"
    print "* at https://dashboard.hologram.io"
    print ""

    hologram = HologramCloud(credentials,
                             network='cellular',
                             authentication_type='csrpsk'
                             )  #HologramCloud(dict(), network='cellular')

    print 'Cloud type: ' + str(hologram)
    startMsg = hologram.sendSMS(
        "+34693608737",
        "Hello!! If you know Clemente, send him a Whatsapp! ;)")
    # enter your mobile number in the space above, area code required
    #sleep(60) # lets allow a little time for the cellular interface to restart
    print 'RESPONSE MESSAGE: ' + hologram.getResultString(startMsg)
    #recv = hologram.sendMessage('one two three!',
    #                           topics = ['TOPIC1','TOPIC2'],
    #                          timeout = 3)

    #print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv)
Beispiel #25
0
 def __init__(self):
     self.hologram = HologramCloud(dict(), network='cellular')
     self.connected = self.hologram.network.connect()
     if self.connected == False:
         print(' Failed to connect to cell network')
from Hologram.HologramCloud import HologramCloud

if __name__ == "__main__":
    print("")
    print("")
    print("Testing Hologram Cloud class...")
    print("")
    print("* Note: You can obtain device keys from the Devices page")
    print("* at https://dashboard.hologram.io")
    print("")

    device_key = input("What is your device key? ")

    credentials = {'devicekey': device_key}

    hologram = HologramCloud(credentials, authentication_type='csrpsk')

    print('Sending a periodic message every 30 seconds...')
    recv = hologram.sendPeriodicMessage(30,
                                        'This is a periodic message',
                                        topics=['PERIODICMESSAGES'],
                                        timeout=6)

    print('sleeping for 40 seconds...')
    time.sleep(40)
    print('waking up!')

    hologram.stopPeriodicMessage()

    print('')
    print('Testing complete.')
Beispiel #27
0
import json ## Import library to create and read JSON

GPIO.setmode(GPIO.BCM) ## Use broadcom pin numbering

LED_PIN = 17 ## GPIO pin the LED is attached to
DHT_PIN = 21 ## GPIO pin the DHT sensor is attached to
LUX_MCP = 0 ## ADC pin the Photoresistor is attached to
BTN_PIN = 27 ## GPIO pin the button is attached to

## Exercise 04 - triggered by a button press
GPIO.setup(BTN_PIN,GPIO.IN,pull_up_down=GPIO.PUD_UP) ## Setup GPIO pin as an input

## Exercise 05 - send data to Hologram's cloud through WiFi
with open('../credentials.json') as key_file:
    devicekey = json.load(key_file)
hologram = HologramCloud(devicekey, enable_inbound=False)

try:
    while True:
        if GPIO.input(BTN_PIN) == False:

            ## Exercise 05 - send data to Hologram's cloud through WiFi
            lightOn(LED_PIN)

            message = json.dumps({'h': getHum(DHT_PIN), 't': getTemp(DHT_PIN), 'l': getLux(LUX_MCP)})
            sent = hologram.sendMessage(message)

            lightOff(LED_PIN)

            if sent == 0:
                print 'Success! Message sent to the cloud.'
def run_hologram_activate(args):

    hologram = HologramCloud(dict(), network='cellular')
    sim = hologram.network.iccid

    if sim is None:
        raise HologramError('Failed to fetch SIM number from the modem')

    func_args = dict()

    if args['apikey'] is None:
        (username, password) = prompt_for_username_and_password()
        func_args['username'] = username
        func_args['password'] = password
    else:
        func_args['apikey'] = args['apikey']

    api = Api(**func_args)

    success, plans = api.getPlans()

    if success == False:
        raise HologramError('Failed to fetch plans')

    planIdToZonesDict = populate_valid_plans(plans)

    selected_plan, plan_name = prompt_for_plan(plans, planIdToZonesDict)
    selected_zone = prompt_for_zone(planIdToZonesDict[selected_plan])

    # preview
    success, response = api.activateSIM(sim=sim,
                                        plan=selected_plan,
                                        zone=selected_zone,
                                        preview=True)

    if success == False:
        print('Activation verification failed: %s' % response)
        return
    elif not confirm_activation(sim, plan_name, selected_plan, selected_zone,
                                response['total_cost']):
        return

    success, response = api.activateSIM(sim=sim,
                                        plan=selected_plan,
                                        zone=selected_zone)

    if success == True:
        print('Activating SIM... (this may take up to a few minutes)')
    else:
        print('Activation failed')
        return

    start_time = time.time()
    while time.time() < start_time + CHECK_LIVE_SIM_STATE_MAX_TIMEOUT:
        success, sim_state = api.getSIMState(sim)

        if sim_state == 'LIVE':
            break

        time.sleep(CHECK_LIVE_SIM_STATE_INTERVAL)

    if sim_state == 'LIVE':
        print('Activation successful!')
    else:
        print(
            'SIM is still not activated. Check status in a few minutes on Hologram Dashboard (https://dashboard.hologram.io/) or contact [email protected] with any further delays'
        )
if __name__ == "__main__":
    print ""
    print ""
    print "Testing Hologram Cloud class..."
    print ""
    print "* Note: You can obtain device keys from the Devices page"
    print "* at https://dashboard.hologram.io"
    print ""

    device_id = raw_input("What is your device id? ")
    private_key = raw_input("What is your private key? ")

    credentials = {'device_id': device_id, 'private_key': private_key}

    hologram = HologramCloud(credentials,
                             enable_inbound=False,
                             authentication_type='totp')

    print 'Hologram SDK version:'
    print hologram.version

    print ''
    print 'Cloud type: ' + str(hologram)
    print ''
    print 'Network type: ' + hologram.network_type
    print ''

    recv = hologram.sendMessage("YESYESYES!", topics=["YES"], timeout=6)

    print 'RESPONSE CODE RECEIVED: ' + str(recv)
    print 'RESPONSE MESSAGE: ' + hologram.getResultString(recv)
Beispiel #30
0
sys.path.append("..")
sys.path.append("../..")

from Hologram.HologramCloud import HologramCloud

if __name__ == "__main__":
    print ""
    print ""
    print "Testing Hologram Cloud class..."
    print ""
    print "* Note: You can obtain device keys from the Devices page"
    print "* at https://dashboard.hologram.io"
    print ""

    hologram = HologramCloud(None,
                             enable_inbound=False,
                             network='cellular-iota')

    sum_RSSI = 0.0
    sum_quality = 0.0
    num_samples = 5

    # Query for signal strength every 2 seconds...
    for i in range(num_samples):
        signal_strength = hologram.network.signal_strength
        print 'Signal strength: ' + signal_strength
        rssi, qual = signal_strength.split(',')
        sum_RSSI = sum_RSSI + int(rssi)
        sum_quality = sum_quality + int(qual)
        time.sleep(2)