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)
class HologramSender: 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') def __del__(self): self.hologram.network.disconnect() def foundPerson(self, name, ID, location, phone): payload = self.formatPayload(name, ID, location, phone) return self.sendAlert() def formatPayload(self, name, ID, location, phone): payloadDict = {} payloadDict['name'] = name payloadDict['ID'] = ID payloadDict['phoneNumber'] = phone payloadDict['location'] = location payloadDict['datetime'] = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") jsonPayload = json.dumps(payloadDict) self.payload = jsonPayload def sendAlert(self): self.responseCode = self.hologram.sendMessage(self.payload, topics=["waldo-edge"]) return self.hologram.getResultString(self.responseCode)
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()
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 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)
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 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)
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'
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 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'
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()
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()
class HologramAPI: def __init__(self): self.client = HologramCloud(dict(), network='cellular', authentication_type='csrpsk') def send_sms(self, to_num, msg): try: response = self.client.sendSMS(to_num, msg) print(response) except: print( "FAIL: Unable to send SMS via Hologram. (Modem disconnected?)")
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()
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
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()
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()
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)
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
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()
# # 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():
import random import string from time import sleep def randomString(stringLength): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) credentials = { 'devicekey': '^hD8&#%H' } # replace with your unique Sim device key cloud = HologramCloud(credentials, network='cellular', authentication_type='csrpsk') clave = randomString(5) mensaje_instruccion = "Bienvenido al programa de seguridad. Para activar el programa, envie primero la clave aleatoria. Su clave es: " + str( clave) print mensaje_instruccion recv = cloud.sendSMS("+14439044822", mensaje_instruccion) while True: sms_obj = cloud.popReceivedSMS() if sms_obj == None: print 'U' else: if sms_obj.message == clave: print "Great!"
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')
from Hologram.HologramCloud import HologramCloud hologram = HologramCloud(dict(), network='cellular') result = hologram.network.connect() if result == False: print ' Failed to connect to cell network' hologram.openReceiveSocket() time.sleep(20) # sleep for 20 seconds hologram.closeReceiveSocket() recv = hologram.popReceivedMessage() print 'Receive buffer: ' + str(recv) hologram.network.disconnect()
from Hologram.HologramCloud import HologramCloud hologram = HologramCloud(dict(), network='cellular') result = hologram.network.connect() if result == False: print ' Failed to connect to cell network' response_code = hologram.sendMessage("hello, world 1!") print hologram.getResultString( response_code) # Prints 'Message sent successfully'. response_code = hologram.sendMessage("hello, world 2!", topics=["example-topic"]) hologram.network.disconnect()
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)
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 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.event.broadcast('network.disconnected') recv = hologram.sendMessage("one!", topics = ["TWO MORE TIMES","TOPIC TOPIC"]) # Send advanced message print "RESPONSE CODE RECEIVED: " + str(recv) recv = hologram.sendMessage("two!", topics = ["TWO MORE TIMES","TOPIC TOPIC"]) # Send advanced message print "RESPONSE CODE RECEIVED: " + str(recv) recv = hologram.sendMessage("three!", topics = ["TWO MORE TIMES","TOPIC TOPIC"]) # Send advanced message print "RESPONSE CODE RECEIVED: " + str(recv) hologram.event.broadcast('network.connected')
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, os os.system("sh /home/pi/rpifiles/vedirect/updatevars.sh") sys.path.insert(0, '/home/pi/rpifiles/RPI_SSD1306/') import sigpower from Hologram.HologramCloud import HologramCloud hologram = HologramCloud(dict(), network='cellular') var_vpv = sigpower.var_vpv var_batt = sigpower.var_batt var_bars = sigpower.var_bars var_op = sigpower.var_op result = hologram.network.connect() if result == False: print ' Failed to connect to cell network' response_code = hologram.sendMessage("Panel is " + str(var_vpv) + " - Batt is " + str(var_batt) + " - Network is " + str(var_op) + " with " + str(var_bars) + " bars of signal", topics=["Gulch"], timeout=10) print hologram.getResultString(response_code) hologram.network.disconnect()
try: from Hologram.HologramCloud import HologramCloud # Create Hologram class network object hologram = HologramCloud(dict(), network='cellular') # Connect to the Hologram Global Network result = hologram.network.connect() except: print("Hologram network error")