Example #1
0
def SplitData(data):
    sublist = []
    templist = []
    totalsize = 0
    count = 0
    i = 0

    #only one element?
    if (len(data) == 1):
        d = hexlify(tinypacks.pack(data))
        sublist.append(d)
        return sublist
    while (i < len(data)):
        #Try to serialize data
        size = len(hexlify(tinypacks.pack(data[i]))) / 2
        totalsize += size
        if totalsize <= MAX_BYTE_SIZE:
            templist.append(data[i])
            i += 1
        elif totalsize > MAX_BYTE_SIZE:
            totalsize = 0
            size = 0
            l = hexlify(tinypacks.pack(templist))
            sublist.append(l)
            templist = []
            #subtract one from i, since the element didn't get appended.
            i -= 1

        if (i == len(data)):
            l = hexlify(tinypacks.pack(templist))
            sublist.append(l)
            break
    return sublist
Example #2
0
def SplitData(data):
	sublist = []
	templist = []
	totalsize = 0
	count = 0;
	i = 0; 

	#only one element?
	if(len(data) == 1):
		d =  hexlify(tinypacks.pack(data))
		sublist.append(d)
		return sublist
	while(i < len(data)):
		#Try to serialize data
		size = len(hexlify(tinypacks.pack(data[i])))/2;
		totalsize += size;
		if totalsize <= MAX_BYTE_SIZE:
			templist.append(data[i]);
			i += 1;
		elif totalsize > MAX_BYTE_SIZE:
			totalsize = 0;
			size = 0
			l = hexlify(tinypacks.pack(templist));
			sublist.append(l);
			templist = [];
			#subtract one from i, since the element didn't get appended.
			i -= 1;

		if(i == len(data)):
			l = hexlify(tinypacks.pack(templist));
			sublist.append(l);
			break
	return sublist;
Example #3
0
    def send(self, method, token, path, has_payload=False, payload=None):
        if has_payload:
            frame = "%s%s%s%s" % (tinypacks.pack(method),
                                  tinypacks.pack(token), tinypacks.pack(path),
                                  tinypacks.pack(payload))
        else:
            frame = "%s%s%s" % (tinypacks.pack(method), tinypacks.pack(token),
                                tinypacks.pack(path))
        frame += struct.pack(">H", crc16.crc16str(frame))

        if self.debug:
            print "TX:",
            for c in frame:
                print "%X" % ord(c),
            print "[%i]" % len(frame)

        try:
            self.fd.write("\x7E")
            for byte in frame:
                if byte == "\x7E":
                    self.fd.write("\x7D\x5E")
                elif byte == "\x7D":
                    self.fd.write("\x7D\x5D")
                else:
                    self.fd.write(byte)
            self.fd.write("\x7E")
        except IOError as err:
            raise PostmanError("Frame sending failed: %s" % err)
Example #4
0
    def send(self, method, token, path, has_payload=False, payload=None):
        if has_payload:
            frame = "%s%s%s%s" % (tinypacks.pack(method), tinypacks.pack(token), tinypacks.pack(path), tinypacks.pack(payload))
        else:
            frame = "%s%s%s" % (tinypacks.pack(method), tinypacks.pack(token), tinypacks.pack(path))
        frame +=  struct.pack(">H", crc16.crc16str(frame))

        if self.debug:
            print "TX:",
            for c in frame:
                print "%X" % ord(c),
            print "[%i]" % len(frame)

        try:
            self.fd.write("\x7E")
            for byte in frame:
                if byte == "\x7E":
                    self.fd.write("\x7D\x5E")
                elif byte == "\x7D":
                    self.fd.write("\x7D\x5D")
                else:
                    self.fd.write(byte)
            self.fd.write("\x7E")
        except IOError as err:
            raise PostmanError("Frame sending failed: %s" % err)
Example #5
0
def pack_location_day_data(loc, s):
    packed = tinypacks.pack(len(s))
    for event in s:
        start_timestamp = event['start_time']
        end_timestamp = event['end_time']
        type_id = type_name_to_id(event['type'])
        speaker = ''
        if 'speaker_names' in event:
            speaker = event['speaker_names']
        packed += tinypacks.pack(loc)
        packed += tinypacks.pack(type_id)
        packed += tinypacks.pack(start_timestamp)
        packed += tinypacks.pack(end_timestamp)
        packed += tinypacks.pack(speaker)
        packed += tinypacks.pack(event['title'])
    return packed
Example #6
0
    forecast = forecasts[timeElement['index']]
    timestamp = timestamps[timeElement['index']]
    weatherType = int(forecast['W'])
    temperature = int(forecast['T'])
    windSpeed = int(forecast['S'])
    feelsLikeTemperature = int(forecast['F'])
    screenRelativeHumidity = int(forecast['H'])
    precipitationProbability = int(forecast['Pp'])
    logger.info("timestamp: %d - %s UTC", timestamp, datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'));
    logger.info("temperature: %d", temperature);
    logger.info("feelsLikeTemperature: %d", feelsLikeTemperature);
    logger.info("weatherType: %d", weatherType);
    logger.info("windSpeed: %d", windSpeed);
    logger.info("screenRelativeHumidity: %d", screenRelativeHumidity);
    logger.info("precipitationProbability: %d", precipitationProbability);
    packedForecasts += tinypacks.pack(timestamp);
    packedForecasts += tinypacks.pack(weatherType);
    packedForecasts += tinypacks.pack(temperature);
    packedForecasts += tinypacks.pack(feelsLikeTemperature);
    packedForecasts += tinypacks.pack(windSpeed);
    packedForecasts += tinypacks.pack(screenRelativeHumidity);
    packedForecasts += tinypacks.pack(precipitationProbability);


logger.info("Content length: %d", len(packedForecasts))

# Update content
logger.info("Sending content...")
params = dict( rid='40962' )
response = requests.post(url=config['mcpBroadcastEndpoint'], params=params, data=packedForecasts)
Example #7
0
    speaker = "";
    if 'speaker' in event:
        speaker = event['speaker']['full_public_name']

    if matches_day:
        talks.append({
            "location_id": location_id,
            "type_id": type_id,
            "start_timestamp": start_timestamp,
            "end_timestamp": end_timestamp,
            "speaker": speaker,
            "title": event['title'],
            "abstract": event['abstract']
        })

packed = tinypacks.pack(len(talks));
for talk in talks:
    packed += tinypacks.pack(talk['location_id']);
    packed += tinypacks.pack(talk['type_id']);
    packed += tinypacks.pack(talk['start_timestamp']);
    packed += tinypacks.pack(talk['end_timestamp']);
    packed += tinypacks.pack(talk['speaker']);
    packed += tinypacks.pack(talk['title']);

print binascii.hexlify(packed)
logger.info("Content length: %d", len(packed))

# Update content
logger.info("Sending content...")
params = dict( rid=rid )
response = requests.post(url=config['mcpBroadcastEndpoint'], params=params, data=packed)
Example #8
0
        speaker = "";
        if 'speaker' in event:
            speaker = event['speaker']

        talks.append({
            "stageId": stageId,
            "typeId": typeId,
            "start": startTimestamp,
            "end": endTimestamp,
            "speaker": speaker,
            "title": event['title'],
           # event['description'] Thiss is quite a lot of data. Leaving it out for now
        })

packed = tinypacks.pack(len(talks));
for talk in talks:
    packed += tinypacks.pack(talk['stageId']);
    packed += tinypacks.pack(talk['typeId']);
    packed += tinypacks.pack(talk['start']);
    packed += tinypacks.pack(talk['end']);
    packed += tinypacks.pack(talk['speaker']);
    packed += tinypacks.pack(talk['title']);

print binascii.hexlify(packed)
logger.info("Content length: %d", len(packed))

# Connect do db
logger.info("Connection to DB...")
conn = psycopg2.connect(config['dbConnectionString'])
cursor = conn.cursor()
Example #9
0
#!/usr/bin/python
#
# TinyPacks pack/unpack example
#

import tinypacks

data = {"text": "Hello world!", "status": True, "count": 123}
print("Data: " +  repr(data))

packed_data = tinypacks.pack(data)
print("Packed: " + repr(packed_data))

(unpacked_data, remaining_data) = tinypacks.unpack(packed_data)
print("Unpacked: " + repr(unpacked_data))
Example #10
0
config = json.load(open('../etc/config.json'))

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('dm')
## TODO: make this settable via CLI options:
rgb1 = (0, 0, 255)
rgb2 = (0, 255, 0)
sound = 1
typebyte = 0

badge = int(sys.argv[1])
msg = sys.argv[2]
##

packed = b""
packed += tinypacks.pack(rgb1[0])
packed += tinypacks.pack(rgb1[1])
packed += tinypacks.pack(rgb1[2])
packed += tinypacks.pack(rgb2[0])
packed += tinypacks.pack(rgb2[1])
packed += tinypacks.pack(rgb2[2])
packed += tinypacks.pack(sound)
packed += tinypacks.pack(typebyte)
packed += tinypacks.pack(msg)

logger.info("Sending content...")
url = config['dmMsgEndpoint']
response = requests.post(url=url, params={'badge': badge}, data=packed)

if (response.status_code == 200):
    logger.info("OK")
Example #11
0
#  Software is furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
#  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
#  DEALINGS IN THE SOFTWARE.

import sys
import json
import tinypacks

if len(sys.argv) < 3:
    print("\nUsage: %s <JSON file> <TinyPacks file>\n" % sys.argv[0])
    sys.exit()

source_file = open(sys.argv[1], "r")
destination_file = open(sys.argv[2], "w")

parsed_json = json.load(source_file)
packed_tinypacks = tinypacks.pack(parsed_json)
destination_file.write(packed_tinypacks)

source_file.close()
destination_file.close()
Example #12
0
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
# 
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
#  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
#  DEALINGS IN THE SOFTWARE.

import sys
import json
import tinypacks

if len(sys.argv) < 3:
    print("\nUsage: %s <JSON file> <TinyPacks file>\n" % sys.argv[0])
    sys.exit()

source_file = open(sys.argv[1], "r")
destination_file = open(sys.argv[2], "w")

parsed_json = json.load(source_file)
packed_tinypacks = tinypacks.pack(parsed_json)
destination_file.write(packed_tinypacks)

source_file.close()
destination_file.close()

Example #13
0
jsonToBePacked = []
packedForecasts = b""
for timeElement in times:
    forecast = forecasts[timeElement['index']]
    timestamp = int(round(time.time()))  # ToDo: Use real time from the API
    weatherType = int(forecast['W'])
    temperature = int(forecast['T'])
    windSpeed = int(forecast['S'])
    feelsLikeTemperature = int(forecast['F'])
    screenRelativeHumidity = int(forecast['H'])
    precipitationProbability = int(forecast['Pp'])
    logger.info("timestamp: %d", timestamp)
    logger.info("temperature: %d", temperature)
    logger.info("weatherType: %d", weatherType)
    packedForecasts += tinypacks.pack(timestamp)
    packedForecasts += tinypacks.pack(weatherType)
    packedForecasts += tinypacks.pack(temperature)
    packedForecasts += tinypacks.pack(feelsLikeTemperature)
    packedForecasts += tinypacks.pack(windSpeed)
    packedForecasts += tinypacks.pack(screenRelativeHumidity)
    packedForecasts += tinypacks.pack(precipitationProbability)

#print jsonToBePacked
##packedForecasts = tinypacks.pack(jsonToBePacked)

#result = tinypacks.unpack(packedForecasts)
print binascii.hexlify(packedForecasts)

logger.info("Content length: %d", len(packedForecasts))
Example #14
0
        speaker = ""
        if 'speaker' in event:
            speaker = event['speaker']

        talks.append({
            "stageId": stageId,
            "typeId": typeId,
            "start": startTimestamp,
            "end": endTimestamp,
            "speaker": speaker,
            "title": event['title'],
            # event['description'] Thiss is quite a lot of data. Leaving it out for now
        })

packed = tinypacks.pack(len(talks))
for talk in talks:
    packed += tinypacks.pack(talk['stageId'])
    packed += tinypacks.pack(talk['typeId'])
    packed += tinypacks.pack(talk['start'])
    packed += tinypacks.pack(talk['end'])
    packed += tinypacks.pack(talk['speaker'])
    packed += tinypacks.pack(talk['title'])

print binascii.hexlify(packed)
logger.info("Content length: %d", len(packed))

# Connect do db
logger.info("Connection to DB...")
conn = psycopg2.connect(config['dbConnectionString'])
cursor = conn.cursor()