Last active
December 16, 2015 03:09
-
-
Save DarylWM/5367737 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Continuously read the serial port and process IO data received from a remote XBee. | |
from xbee import ZigBee | |
import serial | |
import struct | |
from array import array | |
import boto | |
import boto.s3 | |
from datetime import datetime, date, time | |
import sys | |
from boto.s3.key import Key | |
AWS_ACCESS_KEY_ID = <your access key here> | |
bucketName = AWS_ACCESS_KEY_ID.lower() + '-farmcam-bucket' | |
conn = boto.connect_s3() | |
bucket = conn.lookup(bucketName) | |
if bucket is None: | |
bucket = conn.create_bucket(bucketName, location=boto.s3.connection.Location.APSoutheast2) | |
def ByteToHex(byteStr): | |
# Convert a byte string to it's hex string representation e.g. for output. | |
return ''.join( [ "%02X" % ord( x ) for x in byteStr ] ).strip() | |
def percent_cb(complete, total): | |
sys.stdout.write('.') | |
sys.stdout.flush() | |
ser = serial.Serial('/dev/tty.usbserial-A901JYV9', 57600) | |
xbee = ZigBee(ser, escaped=True) | |
imageBytes = array('B') | |
byteCount = 0 | |
# Continuously read and print packets | |
print 'Continuously read and print packets' | |
while True: | |
try: | |
response = xbee.wait_read_frame() | |
msgType = struct.unpack("B", response['rf_data'][0])[0] | |
if msgType == 0xf3: | |
print 'info received from ' + ByteToHex(response['source_addr_long']) + ': ' + response['rf_data'][1:] | |
elif msgType == 0xf4: | |
bytesRemaining = struct.unpack("H", response['rf_data'][1:3][::-1])[0] | |
numberOfBytesRxd = struct.unpack("B", response['rf_data'][3])[0] | |
byteCount += numberOfBytesRxd | |
for i in range(numberOfBytesRxd): | |
imageBytes.append(struct.unpack("B", response['rf_data'][4+i])[0]) | |
if bytesRemaining <= 0: | |
# Write the image to a file | |
dt = datetime.now() | |
fileName = ByteToHex(response['source_addr_long']) + '-' + dt.strftime("%Y-%m-%d-%H-%M-%S-%f") + '.jpg' | |
output_file = open('../' + fileName, 'wb') | |
imageBytes.tofile(output_file) | |
output_file.close() | |
# Write the file to S3 | |
print 'Uploading %s to Amazon S3 bucket %s' % (fileName, bucketName) | |
k = Key(bucket) | |
k.key = fileName | |
k.set_contents_from_filename('../' + fileName, cb=percent_cb, num_cb=10) | |
# reset for the next one | |
imageBytes = array('B') | |
byteCount = 0 | |
else: | |
print 'not a recognised message type.' | |
except KeyboardInterrupt: | |
break | |
ser.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment