From c25b3a7c94ce425daeec37bed51f641ccece8473 Mon Sep 17 00:00:00 2001 From: Marc Teichtahl Date: Sun, 27 Aug 2017 18:13:57 +1000 Subject: [PATCH 01/11] initial --- bin/config/pokey.cfg | 15 +++++ src/common/configmanager/configmanager.h | 2 + .../mappingConfigManager.cpp | 2 +- src/libs/plugins/common/simhubdeviceplugin.h | 1 + src/libs/plugins/pokey/main.cpp | 48 ++++++++++++++- src/libs/plugins/pokey/main.h | 1 + src/libs/plugins/pokey/pokeyDevice.cpp | 60 +++++++++++++++++++ src/libs/plugins/pokey/pokeyDevice.h | 21 +++++++ 8 files changed, 148 insertions(+), 2 deletions(-) diff --git a/bin/config/pokey.cfg b/bin/config/pokey.cfg index d50896c..821eef4 100644 --- a/bin/config/pokey.cfg +++ b/bin/config/pokey.cfg @@ -293,6 +293,21 @@ configuration = type = "DIGITAL_OUTPUT" } ) + }, + { + serialNumber="26766", + name = "test PWM", + pins = (), + pwm= ( + { + channel =0, + name = "G_OH_EGT", + decription = "APU Exhaust Gas Temp", + units = "degrees", + dutyCycle = 1.00, + period = 20 # milliseconds + } + ) } ) diff --git a/src/common/configmanager/configmanager.h b/src/common/configmanager/configmanager.h index b3c414b..522ff14 100644 --- a/src/common/configmanager/configmanager.h +++ b/src/common/configmanager/configmanager.h @@ -19,8 +19,10 @@ #include "aws/aws.h" #endif +#include "common/support/threadmanager.h" #include "log/clog.h" #include "mappingConfigManager/mappingConfigManager.h" + #include "simhub.h" #ifndef RETURN_OK diff --git a/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp b/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp index b8292ab..55c498a 100644 --- a/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp +++ b/src/common/configmanager/mappingConfigManager/mappingConfigManager.cpp @@ -91,7 +91,7 @@ int MappingConfigManager::init(void) } else { _mapping[source] = std::make_pair(source, target); - logger.log(LOG_INFO, " - adding %s", target.c_str()); + // logger.log(LOG_INFO, " - adding %s", target.c_str()); } if (sustain > 0 && !mapContains(_sustainMap, source)) { diff --git a/src/libs/plugins/common/simhubdeviceplugin.h b/src/libs/plugins/common/simhubdeviceplugin.h index a0d2bfe..c24a638 100644 --- a/src/libs/plugins/common/simhubdeviceplugin.h +++ b/src/libs/plugins/common/simhubdeviceplugin.h @@ -31,6 +31,7 @@ typedef union { int bool_value; operator bool() const { return bool_value; } operator int() const { return int_value; } + operator float() const { return float_value; } } VariantUnion; typedef struct { diff --git a/src/libs/plugins/pokey/main.cpp b/src/libs/plugins/pokey/main.cpp index 79ae8b3..f0cad35 100644 --- a/src/libs/plugins/pokey/main.cpp +++ b/src/libs/plugins/pokey/main.cpp @@ -95,6 +95,9 @@ int PokeyDevicePluginStateManager::deliverValue(GenericTLV *data) else if (data->type == ConfigType::CONFIG_INT) { device->targetValue(data->name, (int)data->value); } + else if (data->type == ConfigType::CONFIG_FLOAT) { + device->targetValue(data->name, (float)data->value); + } } return 0; @@ -210,6 +213,45 @@ bool PokeyDevicePluginStateManager::deviceConfiguration(libconfig::SettingIterat return retVal; } +bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *pwm, std::shared_ptr pokeyDevice) +{ + bool retVal = true; + + int PWMLength = pwm->getLength(); + + if (PWMLength > 0) { + + _logger(LOG_INFO, " [%s] - Found %i PWM Channels", pokeyDevice->name().c_str(), PWMLength); + + for (libconfig::SettingIterator iter = pwm->begin(); iter != pwm->end(); iter++) { + int channel = 0; + std::string name = ""; + std::string description = ""; + std::string units = ""; + float dutyCycle = 1.5; // percent + uint32_t period = 20; // milliseconds + + try { + iter->lookupValue("channel", channel); + iter->lookupValue("name", name); + iter->lookupValue("description", description); + iter->lookupValue("units", units); + iter->lookupValue("dutyCycle", dutyCycle); + iter->lookupValue("period", period); + } + catch (const libconfig::SettingNotFoundException &nfex) { + _logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath()); + } + + if (addTargetToDeviceTargetList(name, pokeyDevice)) { + pokeyDevice->addPWM(channel, name, description, units, dutyCycle, period); + _logger(LOG_INFO, " - Added PWM channel %i - %s", channel, name.c_str()); + } + } + } + return retVal; +} + bool PokeyDevicePluginStateManager::devicePinsConfiguration(libconfig::Setting *pins, std::shared_ptr pokeyDevice) { /** pin = 4, @@ -445,7 +487,8 @@ int PokeyDevicePluginStateManager::preflightComplete(void) continue; } - devicePinsConfiguration(&iter->lookup("pins"), pokeyDevice); + if (iter->exists("pins")) + devicePinsConfiguration(&iter->lookup("pins"), pokeyDevice); // check if there is an encoder section in the config if (iter->exists("encoders")) @@ -455,6 +498,9 @@ int PokeyDevicePluginStateManager::preflightComplete(void) if (iter->exists("displays")) deviceDisplaysConfiguration(&iter->lookup("displays"), pokeyDevice); + if (iter->exists("pwm")) + devicePWMConfiguration(&iter->lookup("pwm"), pokeyDevice); + pokeyDevice->startPolling(); } diff --git a/src/libs/plugins/pokey/main.h b/src/libs/plugins/pokey/main.h index 8dd672a..bc3d56c 100644 --- a/src/libs/plugins/pokey/main.h +++ b/src/libs/plugins/pokey/main.h @@ -35,6 +35,7 @@ class PokeyDevicePluginStateManager : public PluginStateManager bool deviceEncodersConfiguration(libconfig::Setting *encoders, std::shared_ptr pokeyDevice); bool deviceDisplaysConfiguration(libconfig::Setting *displays, std::shared_ptr pokeyDevice); int deviceDisplaysGroupsConfiguration(libconfig::Setting *displayGroups, int id, std::shared_ptr pokeyDevice, std::string type); + bool devicePWMConfiguration(libconfig::Setting *pwm, std::shared_ptr pokeyDevice); bool addTargetToDeviceTargetList(std::string, std::shared_ptr device); std::shared_ptr targetFromDeviceTargetList(std::string); void enumerateDevices(void); diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index 4300543..4291b0f 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -150,6 +150,31 @@ void PokeyDevice::addPin(std::string pinName, int pinNumber, std::string pinType _pins[portNumber].value = defaultValue; _pins[portNumber].description = description; } +void PokeyDevice::addPWM(uint8_t channel, std::string name, std::string description, std::string units, uint32_t dutyCycle, uint32_t period) +{ + + _pwmChannels[channel] = true; + float ms = _pokey->info.PWMinternalFrequency / 1000; + + PK_PWMConfigurationGet(_pokey); + + _pokey->PWM.PWMperiod = (ms * period); + _pokey->PWM.PWMduty[channel] = (ms * dutyCycle); + _pokey->PWM.PWMenabledChannels[channel] = true; + + int ret = PK_PWMConfigurationSet(_pokey); + + printf("---> ret %i\n", ret); + + PK_PWMUpdate(_pokey); + + mapNameToPWM(name.c_str(), channel); + _pwm[channel].name = name; + _pwm[channel].description = description; + _pwm[channel].units = units; + _pwm[channel].dutyCycle = dutyCycle; + _pwm[channel].period = period; +} void PokeyDevice::startPolling() { @@ -356,6 +381,24 @@ uint32_t PokeyDevice::targetValue(std::string targetName, int value) return 0; } +uint32_t PokeyDevice::targetValue(std::string targetName, float value) +{ + uint8_t channel = PWMFromName(targetName); + uint32_t ms = _pokey->info.PWMinternalFrequency / 1000; + + uint32_t duty = 0.0056 * value; + + _pokey->PWM.PWMduty[channel] = duty; + _pokey->PWM.PWMenabledChannels[channel] = true; + + int ret = PK_PWMConfigurationSet(_pokey); + + printf("---> ret %0.00f \n", value); + + PK_PWMUpdate(_pokey); + return 0; +} + uint32_t PokeyDevice::targetValue(std::string targetName, bool value) { uint32_t retValue = -1; @@ -478,11 +521,28 @@ int PokeyDevice::pinFromName(std::string targetName) return -1; } +uint8_t PokeyDevice::PWMFromName(std::string targetName) +{ + std::map::iterator it; + it = _pwmMap.find(targetName); + + if (it != _pwmMap.end()) { + return it->second; + } + else + return -1; +} + void PokeyDevice::mapNameToPin(std::string name, int pin) { _pinMap.emplace(name, pin); } +void PokeyDevice::mapNameToPWM(std::string name, int pin) +{ + _pwmMap.emplace(name, pin); +} + void PokeyDevice::mapNameToEncoder(std::string name, int encoderNumber) { _encoderMap.emplace(name, encoderNumber); diff --git a/src/libs/plugins/pokey/pokeyDevice.h b/src/libs/plugins/pokey/pokeyDevice.h index cf648b4..4f56b83 100644 --- a/src/libs/plugins/pokey/pokeyDevice.h +++ b/src/libs/plugins/pokey/pokeyDevice.h @@ -28,6 +28,7 @@ #define MAX_MATRIX_LEDS 2 #define MAX_MATRIX_LED_GROUPS 8 #define MAX_DIGITS 10 +#define MAX_PWM_CHANNELS 6 typedef struct { std::string pinName; @@ -68,6 +69,16 @@ typedef struct { device_matrixLED_group_t group[MAX_MATRIX_LED_GROUPS]; } device_matrixLED_t; +typedef struct { + uint8_t id; + std::string units; + std::string name; + std::string description; + uint8_t pin; + float dutyCycle; + uint32_t period; +} device_pwm_t; + class PokeyDevice { private: @@ -88,13 +99,18 @@ class PokeyDevice std::map _pinMap; std::map _encoderMap; std::map _displayMap; + std::map _pwmMap; sPoKeysDevice *_pokey; void *_callbackArg; SPHANDLE _pluginInstance; + device_port_t _pins[MAX_PINS]; device_encoder_t _encoders[MAX_ENCODERS]; device_matrixLED_t _matrixLED[MAX_MATRIX_LEDS]; + device_pwm_t _pwm[MAX_PWM_CHANNELS]; + uint8_t _pwmChannels[6]; + uint8_t _intToDisplayRow[MAX_DIGITS]; EnqueueEventHandler _enqueueCallback; @@ -103,6 +119,7 @@ class PokeyDevice uv_timer_t _pollTimer; int pinFromName(std::string targetName); + uint8_t PWMFromName(std::string targetName); uint8_t displayFromName(std::string targetName); uint8_t displayNumber(uint8_t displayNumwber, std::string targetName, int value); @@ -114,12 +131,15 @@ class PokeyDevice bool validatePinCapability(int, std::string); bool validateEncoder(int encoderNumber); + void mapNameToPin(std::string name, int pin); void mapNameToEncoder(std::string name, int encoderNumber); void mapNameToMatrixLED(std::string name, int id); + void mapNameToPWM(std::string name, int pin); uint32_t targetValue(std::string targetName, bool value); uint32_t targetValue(std::string targetName, int value); + uint32_t targetValue(std::string targetName, float value); uint32_t inputPin(uint8_t pin); uint32_t outputPin(uint8_t pin); int32_t name(std::string name); @@ -155,6 +175,7 @@ class PokeyDevice bool isPinDigitalInput(uint8_t pin); bool isEncoderCapable(int pin); void addPin(std::string name, int pinNumber, std::string pinType, int defaultValue = 0, std::string description = "None"); + void addPWM(uint8_t pinNumber, std::string name, std::string description, std::string units, uint32_t dutyCycle, uint32_t period); void addEncoder(int encoderNumber, uint32_t defaultValue, std::string name = DEFAULT_ENCODER_NAME, std::string description = DEFAULT_ENCODER_DESCRIPTION, int min = DEFAULT_ENCODER_MIN, int max = DEFAULT_ENCODER_MAX, int step = DEFAULT_ENCODER_STEP, int invertDirection = DEFAULT_ENCODER_DIRECTION, std::string units = ""); From 72bfe7648d66fc60cc543add00a86a8f5463fcdd Mon Sep 17 00:00:00 2001 From: Marc Teichtahl Date: Mon, 28 Aug 2017 16:29:47 +1000 Subject: [PATCH 02/11] confusing --- src/app/simhub.cpp | 19 +++++++++++-------- src/app/simhub.h | 17 +++++++++++------ src/libs/plugins/pokey/pokeyDevice.cpp | 14 +++++++++----- 3 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/app/simhub.cpp b/src/app/simhub.cpp index 16ef049..421561c 100644 --- a/src/app/simhub.cpp +++ b/src/app/simhub.cpp @@ -1,6 +1,6 @@ #include -#include #include +#include #include "common/configmanager/configmanager.h" #include "log/clog.h" @@ -45,7 +45,7 @@ SimHubEventController::~SimHubEventController(void) if (_awsHelper.polly()) { _awsHelper.polly()->shutdown(); } - + if (_awsHelper.kinesis()) { _awsHelper.kinesis()->shutdown(); } @@ -54,12 +54,9 @@ SimHubEventController::~SimHubEventController(void) #endif } +#if defined(_AWS_SDK) void SimHubEventController::startSustainThread(void) { -#if defined(_AWS_SDK) - _awsHelper.polly()->say("Simulator is ready."); -#endif - std::shared_ptr sustainThread = std::make_shared([=] { _sustainThreadManager.setThreadRunning(true); while (!_sustainThreadManager.threadCanceled()) { @@ -71,7 +68,7 @@ void SimHubEventController::startSustainThread(void) std::chrono::milliseconds now = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); - for (std::pair entry: _sustainValues) { + for (std::pair entry : _sustainValues) { std::chrono::milliseconds sustain = entry.second.first; std::chrono::milliseconds ts = entry.second.second->timestamp(); @@ -93,7 +90,6 @@ void SimHubEventController::ceaseSustainThread(void) _sustainThreadManager.shutdownThread(); } -#if defined(_AWS_SDK) void SimHubEventController::deliverKinesisValue(std::shared_ptr value) { std::string name = value->name(); @@ -159,12 +155,14 @@ bool SimHubEventController::deliverValue(std::shared_ptr value) bool retVal = false; +#if defined(_AWS_SDK) if (mapContains(_configManager->mapManager()->sustainMap(), value->name())) { // update the sustain value map entry std::lock_guard sustainGuard(_sustainValuesMutex); _sustainValues[value->name()].second = value; _sustainValues[value->name()].first = std::chrono::milliseconds(_configManager->mapManager()->sustainMap()[value->name()]); } +#endif // determine value destination from the source - very simple at the moment // (just deliver to whatever instance is not the source) - may want more @@ -175,10 +173,12 @@ bool SimHubEventController::deliverValue(std::shared_ptr value) } else if (value->ownerPlugin() == _prepare3dMethods.plugin_instance) { +#if defined(_AWS_SDK) if (value->name() == "N_ELEC_PANEL_LOWER_LEFT") { if (c_value >= 0) _awsHelper.polly()->say("dc volts %i", c_value->value); } +#endif retVal = !_pokeyMethods.simplug_deliver_value(_pokeyMethods.plugin_instance, c_value); } @@ -308,7 +308,10 @@ void SimHubEventController::terminate(void) { assert(_running); +#if defined(_AWS_SDK) ceaseSustainThread(); +#endif + shutdownPlugin(_prepare3dMethods); shutdownPlugin(_pokeyMethods); _running = false; diff --git a/src/app/simhub.h b/src/app/simhub.h index 38856f2..3f4d6b1 100644 --- a/src/app/simhub.h +++ b/src/app/simhub.h @@ -3,11 +3,9 @@ #include #include +#include #include #include -#include -#include - #include "appsupport.h" #include "elements/attributes/attribute.h" @@ -16,6 +14,7 @@ #if defined(_AWS_SDK) #include "aws/aws.h" +#include "common/support/threadmanager.h" #endif class ConfigManager; // forward reference @@ -30,8 +29,8 @@ class ConfigManager; // forward reference * void * to 'this' that was passed to the plugin when it registered * the callback stub, to call into the proper 'eventCallback' member */ - - typedef std::pair> SustainMapEntry; + +typedef std::pair> SustainMapEntry; class SimHubEventController { @@ -46,17 +45,21 @@ class SimHubEventController simplug_vtable loadPlugin(std::string dylibName, libconfig::Config *pluginConfigs, EnqueueEventHandler eventCallback); void terminate(void); void shutdownPlugin(simplug_vtable &pluginMethods); +#if defined(_AWS_SDK) void startSustainThread(void); void ceaseSustainThread(void); +#endif ConcurrentQueue> _eventQueue; simplug_vtable _prepare3dMethods; simplug_vtable _pokeyMethods; ConfigManager *_configManager; +#if defined(_AWS_SDK) CancelableThreadManager _sustainThreadManager; std::map _sustainValues; std::mutex _sustainValuesMutex; +#endif bool _running; @@ -77,7 +80,7 @@ class SimHubEventController assert(prepare3dConfig != NULL); _prepare3dDeviceConfig = prepare3dConfig; }; - + void setPokeyConfig(libconfig::Config *pokeyConfig) { assert(pokeyConfig != NULL); @@ -112,7 +115,9 @@ template void SimHubEventController::runEventLoop(F &&eventProcessorFu _running = true; +#if defined(_AWS_SDK) startSustainThread(); +#endif while (!breakLoop) { try { diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index 4291b0f..0a3c431 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -1,4 +1,6 @@ +#include #include +#include #include "elements/attributes/attribute.h" #include "pokeyDevice.h" @@ -381,21 +383,23 @@ uint32_t PokeyDevice::targetValue(std::string targetName, int value) return 0; } +using namespace std::chrono_literals; + uint32_t PokeyDevice::targetValue(std::string targetName, float value) { uint8_t channel = PWMFromName(targetName); uint32_t ms = _pokey->info.PWMinternalFrequency / 1000; - uint32_t duty = 0.0056 * value; + uint32_t duty = (3 * value) / 700; + duty *= ms; - _pokey->PWM.PWMduty[channel] = duty; _pokey->PWM.PWMenabledChannels[channel] = true; + // int ret = PK_PWMConfigurationSet(_pokey); - int ret = PK_PWMConfigurationSet(_pokey); - - printf("---> ret %0.00f \n", value); + printf("---> duty %d, ret %.3f \n", duty, value); PK_PWMUpdate(_pokey); + return 0; } From 507a4a5425fd488c52d8121246ff5d352ef333da Mon Sep 17 00:00:00 2001 From: Marc Teichtahl Date: Tue, 29 Aug 2017 22:30:04 +1000 Subject: [PATCH 03/11] adding cfn for dynamo - all create, delete and update are now region aware --- tools/aws/cfn/stacks/dynamo/config | 3 ++ tools/aws/cfn/stacks/dynamo/create.sh | 18 ++++++++ tools/aws/cfn/stacks/dynamo/delete.sh | 12 +++++ tools/aws/cfn/stacks/dynamo/stack.json | 58 +++++++++++++++++++++++++ tools/aws/cfn/stacks/dynamo/update.sh | 9 ++++ tools/aws/cfn/stacks/kinesis/stack.json | 37 ++++++++++++++++ 6 files changed, 137 insertions(+) create mode 100644 tools/aws/cfn/stacks/dynamo/config create mode 100755 tools/aws/cfn/stacks/dynamo/create.sh create mode 100755 tools/aws/cfn/stacks/dynamo/delete.sh create mode 100644 tools/aws/cfn/stacks/dynamo/stack.json create mode 100755 tools/aws/cfn/stacks/dynamo/update.sh diff --git a/tools/aws/cfn/stacks/dynamo/config b/tools/aws/cfn/stacks/dynamo/config new file mode 100644 index 0000000..3931300 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/config @@ -0,0 +1,3 @@ +STACK_NAME=simhubDynamo +S3_BUCKET=s3://teichtah-lambda-functions +REGION=us-east-1 \ No newline at end of file diff --git a/tools/aws/cfn/stacks/dynamo/create.sh b/tools/aws/cfn/stacks/dynamo/create.sh new file mode 100755 index 0000000..9227244 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/create.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +. config + + +echo "Creating Dynamo Table(s)" +aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION + +if [ $? -eq 0 ] +then + echo " - waiting for Dynamo creation to complete" + aws cloudformation wait stack-create-complete --stack-name $STACK_NAME --region $REGION + echo "Dynamo creation completed." + aws cloudformation describe-stacks --stack-name $STACK_NAME --region $REGION --output json | jq '.[][0].Outputs' + +else + echo "Dynam creation failed" +fi diff --git a/tools/aws/cfn/stacks/dynamo/delete.sh b/tools/aws/cfn/stacks/dynamo/delete.sh new file mode 100755 index 0000000..58944c5 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/delete.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +. config + +echo "Deleting cloudformation stack "$STACK_NAME +aws cloudformation delete-stack --stack-name $STACK_NAME --region $REGION + +if [ $? -eq 0 ] +then + echo " - waiting for deletion to complete" + aws cloudformation wait stack-delete-complete --stack-name $STACK_NAME --region $REGION +fi diff --git a/tools/aws/cfn/stacks/dynamo/stack.json b/tools/aws/cfn/stacks/dynamo/stack.json new file mode 100644 index 0000000..79ce328 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/stack.json @@ -0,0 +1,58 @@ +{ + "AWSTemplateFormatVersion": "2010-09-09", + "Parameters": { + "EnvironmentName": { + "Description": "The string that will be prefixed to each instance name", + "Type": "String", + "MinLength": "3", + "MaxLength": "16", + "Default": "simhub", + "AllowedPattern": "[a-zA-Z0-9]*", + "ConstraintDescription": "Environment names must be 3-16 characters and contain only a-z and 0-9." + }, + "DynamoTableName": { + "Description": "DynamoDB", + "Type": "String", + "MinLength": "3", + "MaxLength": "16", + "Default": "simhub", + "AllowedPattern": "[a-zA-Z0-9]*", + "ConstraintDescription": "dynamo db names must be 3-16 characters and contain only a-z and 0-9." + } + }, + "Resources": { + "DynamoTable": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [{ + "AttributeName": "source", + "AttributeType": "S" + }], + "KeySchema": [{ + "AttributeName": "source", + "KeyType": "HASH" + }], + "ProvisionedThroughput": { + "ReadCapacityUnits": "10", + "WriteCapacityUnits": "10" + }, + "TableName": { + "Ref": "DynamoTableName" + } + } + } + }, + "Outputs": { + "DynamoARN": { + "Value": { + "Fn::GetAtt": ["DynamoTable", "Arn"] + }, + "Description": "DynamoTable ARN", + "Export": { + "Name": { + "Fn::Sub": "${AWS::StackName}-DynamoTable-ARN" + } + } + } + } +} \ No newline at end of file diff --git a/tools/aws/cfn/stacks/dynamo/update.sh b/tools/aws/cfn/stacks/dynamo/update.sh new file mode 100755 index 0000000..8fc56c4 --- /dev/null +++ b/tools/aws/cfn/stacks/dynamo/update.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +. config + +echo "Updating Dynamo" + +aws cloudformation update-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION +echo " - waiting for dynamo update to complete. This may take some time" +aws cloudformation wait stack-update-complete --stack-name $STACK_NAME --region $REGION diff --git a/tools/aws/cfn/stacks/kinesis/stack.json b/tools/aws/cfn/stacks/kinesis/stack.json index f6841f1..a5aa5f2 100644 --- a/tools/aws/cfn/stacks/kinesis/stack.json +++ b/tools/aws/cfn/stacks/kinesis/stack.json @@ -18,6 +18,15 @@ "Default": "simhubStream", "AllowedPattern": "[a-zA-Z0-9]*", "ConstraintDescription": "Environment names must be 3-16 characters and contain only a-z and 0-9." + }, + "DynamoTable": { + "Description": "DynamoDB", + "Type": "String", + "MinLength": "3", + "MaxLength": "16", + "Default": "simhub", + "AllowedPattern": "[a-zA-Z0-9]*", + "ConstraintDescription": "dynamo db names must be 3-16 characters and contain only a-z and 0-9." } }, "Resources": { @@ -30,6 +39,34 @@ "RetentionPeriodHours": 24, "ShardCount": 1 } + }, + "DynamoTable": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [{ + "AttributeName": "source", + "AttributeType": "S" + }, + { + "AttributeName": "description", + "AttributeType": "S" + }, + { + "AttributeName": "units", + "AttributeType": "S" + }, { + "AttributeName": "value", + "AttributeType": "S" + } + ], + "ProvisionedThroughput": { + "ReadCapacityUnits": "10", + "WriteCapacityUnits": "10" + }, + "TableName": { + "Ref": "DynamoTable" + } + } } }, "Outputs": { From 69a4c8dbfd3028a3f46d21a6cce812f98a3df8d0 Mon Sep 17 00:00:00 2001 From: Marc Teichtahl Date: Wed, 30 Aug 2017 15:55:54 +1000 Subject: [PATCH 04/11] updating --- tools/aws/cfn/create.sh | 5 ++- tools/aws/cfn/stacks/kinesis/create.sh | 6 ++-- tools/aws/cfn/stacks/kinesis/stack.json | 33 +++---------------- .../functions/processKinesis/handler.js | 6 ++-- .../functions/processKinesis/stack.json | 27 ++++++++++++--- 5 files changed, 37 insertions(+), 40 deletions(-) diff --git a/tools/aws/cfn/create.sh b/tools/aws/cfn/create.sh index 16335b3..8717275 100755 --- a/tools/aws/cfn/create.sh +++ b/tools/aws/cfn/create.sh @@ -2,7 +2,10 @@ echo "Creating simhub environment" -cd stacks/kinesis +cd stacks/dynamo +./create.sh + +cd ../kinesis ./create.sh cd ../lambda diff --git a/tools/aws/cfn/stacks/kinesis/create.sh b/tools/aws/cfn/stacks/kinesis/create.sh index 1e34783..351efb0 100755 --- a/tools/aws/cfn/stacks/kinesis/create.sh +++ b/tools/aws/cfn/stacks/kinesis/create.sh @@ -4,15 +4,15 @@ echo "Creating Kinesis Stream" -aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json +aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION if [ $? -eq 0 ] then echo " - waiting for Kinesis Stream creation to complete" - aws cloudformation wait stack-create-complete --stack-name $STACK_NAME + aws cloudformation wait stack-create-complete --stack-name $STACK_NAME --region $REGION aws s3 rm $S3_BUCKET/$S3_KEY echo "Kinesis Stream creation completed." - aws cloudformation describe-stacks --stack-name $STACK_NAME --output json | jq '.[][0].Outputs' + aws cloudformation describe-stacks --stack-name $STACK_NAME --region $REGION --output json | jq '.[][0].Outputs' else echo "Kinesis Stream creation failed" diff --git a/tools/aws/cfn/stacks/kinesis/stack.json b/tools/aws/cfn/stacks/kinesis/stack.json index a5aa5f2..54f13b0 100644 --- a/tools/aws/cfn/stacks/kinesis/stack.json +++ b/tools/aws/cfn/stacks/kinesis/stack.json @@ -39,40 +39,15 @@ "RetentionPeriodHours": 24, "ShardCount": 1 } - }, - "DynamoTable": { - "Type": "AWS::DynamoDB::Table", - "Properties": { - "AttributeDefinitions": [{ - "AttributeName": "source", - "AttributeType": "S" - }, - { - "AttributeName": "description", - "AttributeType": "S" - }, - { - "AttributeName": "units", - "AttributeType": "S" - }, { - "AttributeName": "value", - "AttributeType": "S" - } - ], - "ProvisionedThroughput": { - "ReadCapacityUnits": "10", - "WriteCapacityUnits": "10" - }, - "TableName": { - "Ref": "DynamoTable" - } - } } }, "Outputs": { "KinesisStreamARN": { "Value": { - "Fn::GetAtt": ["KinesisStream", "Arn"] + "Fn::GetAtt": [ + "KinesisStream", + "Arn" + ] }, "Description": "Kinesis Stream", "Export": { diff --git a/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js b/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js index 81b4d25..0ccd52b 100644 --- a/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js +++ b/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js @@ -5,8 +5,8 @@ var AWS = require('aws-sdk'); var s3 = new AWS.S3(); var cloudwatch = new AWS.CloudWatch(); -var dynamodb = new AWS.DynamoDB(); - +var dynamodb = new AWS.DynamoDB({region: process.env.dynamoRegion}); +var dynamoTable = process.env.dynamoRegion /** * cleanJSONString * @@ -36,7 +36,7 @@ function writeToDynamo(name, value, units, description) { 'description': {S: description} }, ReturnConsumedCapacity: 'TOTAL', - TableName: 'simhub' + TableName: dynamoTable }; dynamodb.putItem(params, function(err, data) { diff --git a/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json b/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json index c40c5d5..4e79157 100644 --- a/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json +++ b/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json @@ -19,6 +19,16 @@ "Type": "String", "Default": "teichtah-lambda-functions", "Description": "Lambda function bucket" + }, + "DynamoRegion": { + "Type": "String", + "Default": "us-east-1", + "Description": "AWS region of the dynamoDB table" + }, + "DynamoTable": { + "Type": "String", + "Default": "simhub", + "Description": "Name of the dynamoDB table" } }, "Resources": { @@ -49,7 +59,16 @@ "Ref": "ProcessKinesisFunctionKey" } }, - "Environment": {}, + "Environment": { + "Variables": { + "dynamoRegion": { + "Ref": "DynamoRegion" + }, + "dynamoTable": { + "Ref": "DynamoTable" + } + } + }, "Runtime": "nodejs6.10", "Timeout": "120", "MemorySize": "1024", @@ -72,9 +91,9 @@ "Arn" ] }, - "StartingPosition": "TRIM_HORIZON" - }, - "BatchSize": 10 + "StartingPosition": "LATEST", + "BatchSize": 5 + } }, "LambdaPermission": { "Type": "AWS::Lambda::Permission", From 3876942e7ace093a3e225760f685d8b0400e4049 Mon Sep 17 00:00:00 2001 From: Marc Teichtahl Date: Wed, 27 Sep 2017 09:29:28 +1000 Subject: [PATCH 05/11] Updated CFN Stack --- tools/aws/cfn/stacks/dynamo/create.sh | 6 +- tools/aws/cfn/stacks/dynamo/delete.sh | 4 +- tools/aws/cfn/stacks/dynamo/stack.json | 4 +- .../functions/processKinesis/handler.js | 60 +++++++++++-------- .../functions/processKinesis/stack.json | 8 +-- 5 files changed, 46 insertions(+), 36 deletions(-) diff --git a/tools/aws/cfn/stacks/dynamo/create.sh b/tools/aws/cfn/stacks/dynamo/create.sh index 9227244..46099c9 100755 --- a/tools/aws/cfn/stacks/dynamo/create.sh +++ b/tools/aws/cfn/stacks/dynamo/create.sh @@ -4,14 +4,14 @@ echo "Creating Dynamo Table(s)" -aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION +/Users/teichtah/Library/Python/2.7/bin/aws cloudformation create-stack --stack-name $STACK_NAME --template-body file://stack.json --region $REGION if [ $? -eq 0 ] then echo " - waiting for Dynamo creation to complete" - aws cloudformation wait stack-create-complete --stack-name $STACK_NAME --region $REGION + /Users/teichtah/Library/Python/2.7/bin/aws cloudformation wait stack-create-complete --stack-name $STACK_NAME --region $REGION echo "Dynamo creation completed." - aws cloudformation describe-stacks --stack-name $STACK_NAME --region $REGION --output json | jq '.[][0].Outputs' + /Users/teichtah/Library/Python/2.7/bin/aws cloudformation describe-stacks --stack-name $STACK_NAME --region $REGION --output json | jq '.[][0].Outputs' else echo "Dynam creation failed" diff --git a/tools/aws/cfn/stacks/dynamo/delete.sh b/tools/aws/cfn/stacks/dynamo/delete.sh index 58944c5..c20e92d 100755 --- a/tools/aws/cfn/stacks/dynamo/delete.sh +++ b/tools/aws/cfn/stacks/dynamo/delete.sh @@ -3,10 +3,10 @@ . config echo "Deleting cloudformation stack "$STACK_NAME -aws cloudformation delete-stack --stack-name $STACK_NAME --region $REGION +/Users/teichtah/Library/Python/2.7/bin/aws cloudformation delete-stack --stack-name $STACK_NAME --region $REGION if [ $? -eq 0 ] then echo " - waiting for deletion to complete" - aws cloudformation wait stack-delete-complete --stack-name $STACK_NAME --region $REGION + /Users/teichtah/Library/Python/2.7/bin/aws cloudformation wait stack-delete-complete --stack-name $STACK_NAME --region $REGION fi diff --git a/tools/aws/cfn/stacks/dynamo/stack.json b/tools/aws/cfn/stacks/dynamo/stack.json index 79ce328..56a8adf 100644 --- a/tools/aws/cfn/stacks/dynamo/stack.json +++ b/tools/aws/cfn/stacks/dynamo/stack.json @@ -15,8 +15,8 @@ "Type": "String", "MinLength": "3", "MaxLength": "16", - "Default": "simhub", - "AllowedPattern": "[a-zA-Z0-9]*", + "Default": "simhub-KeyVal", + "AllowedPattern": "[a-zA-Z0-9-]*", "ConstraintDescription": "dynamo db names must be 3-16 characters and contain only a-z and 0-9." } }, diff --git a/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js b/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js index 0ccd52b..cd845be 100644 --- a/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js +++ b/tools/aws/cfn/stacks/lambda/functions/processKinesis/handler.js @@ -5,8 +5,10 @@ var AWS = require('aws-sdk'); var s3 = new AWS.S3(); var cloudwatch = new AWS.CloudWatch(); -var dynamodb = new AWS.DynamoDB({region: process.env.dynamoRegion}); -var dynamoTable = process.env.dynamoRegion +var dynamodb = new AWS.DynamoDB({ + region: process.env.dynamoRegion +}); +var dynamoTable = process.env.dynamoTable /** * cleanJSONString * @@ -16,34 +18,43 @@ var dynamoTable = process.env.dynamoRegion function cleanJSONString(string) { // preserve newlines, etc - use valid JSON string = string.replace(/\\n/g, '\\n') - .replace(/\\'/g, '\\\'') - .replace(/\\"/g, '\\"') - .replace(/\\&/g, '\\&') - .replace(/\\r/g, '\\r') - .replace(/\\t/g, '\\t') - .replace(/\\b/g, '\\b') - .replace(/\\f/g, '\\f'); + .replace(/\\'/g, '\\\'') + .replace(/\\"/g, '\\"') + .replace(/\\&/g, '\\&') + .replace(/\\r/g, '\\r') + .replace(/\\t/g, '\\t') + .replace(/\\b/g, '\\b') + .replace(/\\f/g, '\\f'); // remove non-printable and other non-valid JSON chars return string.replace(/[\u0000-\u0019]+/g, ''); } function writeToDynamo(name, value, units, description) { + var params = { Item: { - 'source': {S: name}, - 'value': {S: value}, - 'units': {S: units}, - 'description': {S: description} + 'source': { + S: name + }, + 'value': { + S: value + }, + 'units': { + S: units + }, + 'title': { + S: description + } }, ReturnConsumedCapacity: 'TOTAL', TableName: dynamoTable }; - dynamodb.putItem(params, function(err, data) { + dynamodb.putItem(params, function (err, data) { if (err) - console.log(err, err.stack, params); // an error occurred + console.log(err, err.stack, params); // an error occurred else - console.log(data); // successful response + console.log(data); // successful response }); } @@ -53,9 +64,10 @@ function putCloudwatchMetric(metricName, dimName, dimValue, ts, value) { /* required */ { MetricName: metricName, - Dimensions: [ - {Name: dimName, Value: dimValue}, - ], + Dimensions: [{ + Name: dimName, + Value: dimValue + }, ], StorageResolution: 1, Timestamp: new Date(ts).toISOString(), Unit: 'None', @@ -66,18 +78,18 @@ function putCloudwatchMetric(metricName, dimName, dimValue, ts, value) { Namespace: 'simhub' /* required */ }; - cloudwatch.putMetricData(params, function(err, data) { + cloudwatch.putMetricData(params, function (err, data) { if (err) - console.log(err, err.stack); // an error occurred + console.log(err, err.stack); // an error occurred else - console.log(data); // successful response + console.log(data); // successful response }); } /** * Main lambda handler and entry point */ -exports.index = function(event, context, callback) { +exports.index = function (event, context, callback) { // find the number of records being given to us by kinesis var recordCount = event.Records.length; @@ -98,4 +110,4 @@ exports.index = function(event, context, callback) { callback(null, 'Complete'); -} +} \ No newline at end of file diff --git a/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json b/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json index 4e79157..adab728 100644 --- a/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json +++ b/tools/aws/cfn/stacks/lambda/functions/processKinesis/stack.json @@ -27,7 +27,7 @@ }, "DynamoTable": { "Type": "String", - "Default": "simhub", + "Default": "simhub-KeyVal", "Description": "Name of the dynamoDB table" } }, @@ -35,8 +35,7 @@ "ProcessKinesisFunction": { "Type": "AWS::Lambda::Function", "Properties": { - "Tags": [ - { + "Tags": [{ "Key": "Environment", "Value": { "Ref": "EnvironmentName" @@ -108,8 +107,7 @@ "Principal": "apigateway.amazonaws.com", "SourceArn": { "Fn::Join": [ - "", - [ + "", [ "arn:aws:execute-api:", { "Ref": "AWS::Region" From 4a875e5790a165d3c4656519a6455dd434b410fa Mon Sep 17 00:00:00 2001 From: Marc Teichtahl Date: Mon, 23 Oct 2017 13:30:44 +1100 Subject: [PATCH 06/11] Added experimental PWM code to this branch - will pick up work on my laptop --- lib/pokey/PoKeysLibCore.c | 1269 ++++++++++++------------ lib/pokey/PoKeysLibCoreSockets.c | 1259 ++++++++++++----------- src/libs/plugins/pokey/pokeyDevice.cpp | 97 +- src/libs/plugins/pokey/pokeyDevice.h | 7 + 4 files changed, 1334 insertions(+), 1298 deletions(-) diff --git a/lib/pokey/PoKeysLibCore.c b/lib/pokey/PoKeysLibCore.c index 5916199..4a1a79d 100755 --- a/lib/pokey/PoKeysLibCore.c +++ b/lib/pokey/PoKeysLibCore.c @@ -1,6 +1,6 @@ /* -Copyright (C) 2013 Matevž Bošnak (matevz@poscope.com) +Copyright (C) 2013 Matev� Bo�nak (matevz@poscope.com) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -14,794 +14,753 @@ Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#include -#include "PoKeysLib.h" #include "PoKeysLibCore.h" +#include "PoKeysLib.h" #include "PoKeysLibCoreSockets.h" -#include "string.h" #include "stdio.h" +#include "string.h" +#include + //#define PK_COM_DEBUG -int32_t PKI_CheckInterface(struct hid_device_info * devInfo) -{ - if (devInfo->interface_number == 1) - return 1; +int32_t PKI_CheckInterface(struct hid_device_info *devInfo) { + if (devInfo->interface_number == 1) + return 1; - return 0; + return 0; } // Connection specific commands -int32_t PK_EnumerateUSBDevices() -{ - int32_t numDevices = 0; - struct hid_device_info *devs, *cur_dev; - - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; - - while (cur_dev) - { - /*printf("Device Found\n"); - printf(" Serial: %ls\n", cur_dev->serial_number); - printf(" Product: %ls\n", cur_dev->product_string); - printf(" Interface: %d\n", cur_dev->interface_number); - printf("\n");*/ - - if (PKI_CheckInterface(cur_dev)) - { - numDevices++; - } - - cur_dev = cur_dev->next; - } - hid_free_enumeration(devs); - - devs = hid_enumerate(0x1DC3, 0x1002); - cur_dev = devs; - - while (cur_dev) - { - /*printf("Device Found\n"); - printf(" Serial: %ls\n", cur_dev->serial_number); - printf(" Product: %ls\n", cur_dev->product_string); - printf(" Interface: %d\n", cur_dev->interface_number); - printf("\n");*/ - if (cur_dev->interface_number == -1) numDevices++; - cur_dev = cur_dev->next; +int32_t PK_EnumerateUSBDevices() { + int32_t numDevices = 0; + struct hid_device_info *devs, *cur_dev; + + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; + + while (cur_dev) { + /*printf("Device Found\n"); + printf(" Serial: %ls\n", cur_dev->serial_number); + printf(" Product: %ls\n", cur_dev->product_string); + printf(" Interface: %d\n", cur_dev->interface_number); + printf("\n");*/ + + if (PKI_CheckInterface(cur_dev)) { + numDevices++; } - hid_free_enumeration(devs); + + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); + + devs = hid_enumerate(0x1DC3, 0x1002); + cur_dev = devs; + + while (cur_dev) { + /*printf("Device Found\n"); + printf(" Serial: %ls\n", cur_dev->serial_number); + printf(" Product: %ls\n", cur_dev->product_string); + printf(" Interface: %d\n", cur_dev->interface_number); + printf("\n");*/ + if (cur_dev->interface_number == -1) + numDevices++; + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); #ifdef POKEYSLIB_USE_LIBUSB - numDevices += PK_EnumerateFastUSBDevices(); + numDevices += PK_EnumerateFastUSBDevices(); #endif - return numDevices; + return numDevices; } -int32_t PK_GetCurrentDeviceConnectionType(sPoKeysDevice* device) -{ - return device->connectionType; +int32_t PK_GetCurrentDeviceConnectionType(sPoKeysDevice *device) { + return device->connectionType; } -void InitializeNewDevice(sPoKeysDevice* device) -{ - uint32_t i; - memset(&device->info, 0, sizeof(sPoKeysDevice_Info)); - memset(&device->DeviceData, 0, sizeof(sPoKeysDevice_Data)); - - device->netDeviceData = 0; - - memset(&device->matrixKB, 0, sizeof(sMatrixKeyboard)); - memset(&device->PWM, 0, sizeof(sPoKeysPWM)); - memset(&device->LCD, 0, sizeof(sPoKeysLCD)); - +void InitializeNewDevice(sPoKeysDevice *device) { + uint32_t i; + memset(&device->info, 0, sizeof(sPoKeysDevice_Info)); + memset(&device->DeviceData, 0, sizeof(sPoKeysDevice_Data)); - device->FastEncodersConfiguration = 0; - device->FastEncodersOptions = 0; - device->UltraFastEncoderConfiguration = 0; - device->UltraFastEncoderOptions = 0; + device->netDeviceData = 0; - device->UltraFastEncoderFilter = 0; + memset(&device->matrixKB, 0, sizeof(sMatrixKeyboard)); + memset(&device->PWM, 0, sizeof(sPoKeysPWM)); + memset(&device->LCD, 0, sizeof(sPoKeysLCD)); - memset(device->request, 0, 64); - memset(device->response, 0, 64); + device->FastEncodersConfiguration = 0; + device->FastEncodersOptions = 0; + device->UltraFastEncoderConfiguration = 0; + device->UltraFastEncoderOptions = 0; - device->sendRetries = 3; - device->readRetries = 10; - device->socketTimeout = 100; + device->UltraFastEncoderFilter = 0; - PK_DeviceDataGet(device); + memset(device->request, 0, 64); + memset(device->response, 0, 64); - device->Pins = (sPoKeysPinData*)malloc(sizeof(sPoKeysPinData) * device->info.iPinCount); - memset(device->Pins, 0, sizeof(sPoKeysPinData) * device->info.iPinCount); + device->sendRetries = 3; + device->readRetries = 10; + device->socketTimeout = 100; + PK_DeviceDataGet(device); - for (i = 0; i < device->info.iPinCount; i++) - { - if (PK_IsCounterAvailable(device, i)) - { - device->Pins[i].DigitalCounterAvailable = 1; - } else - { - device->Pins[i].DigitalCounterAvailable = 0; - } - } + device->Pins = + (sPoKeysPinData *)malloc(sizeof(sPoKeysPinData) * device->info.iPinCount); + memset(device->Pins, 0, sizeof(sPoKeysPinData) * device->info.iPinCount); - device->Encoders = (sPoKeysEncoder*)malloc(sizeof(sPoKeysEncoder) * device->info.iEncodersCount); - memset(device->Encoders, 0, sizeof(sPoKeysEncoder) * device->info.iEncodersCount); - - if (device->info.iEasySensors) - { - device->EasySensors = (sPoKeysEasySensor*)malloc(sizeof(sPoKeysEasySensor) * device->info.iEasySensors); - memset(device->EasySensors, 0, sizeof(sPoKeysEasySensor) * device->info.iEasySensors); - } else - { - device->EasySensors = NULL; + for (i = 0; i < device->info.iPinCount; i++) { + if (PK_IsCounterAvailable(device, i)) { + device->Pins[i].DigitalCounterAvailable = 1; + } else { + device->Pins[i].DigitalCounterAvailable = 0; } - - device->PWM.PWMduty = (uint32_t*)malloc(sizeof(uint32_t) * device->info.iPWMCount); - memset(device->PWM.PWMduty, 0, sizeof(uint32_t) * device->info.iPWMCount); - - device->PWM.PWMenabledChannels = (unsigned char*)malloc(sizeof(unsigned char) * device->info.iPWMCount); - memset(device->PWM.PWMenabledChannels, 0, sizeof(unsigned char) * device->info.iPWMCount); - device->PWM.PWMpinIDs = (unsigned char*)malloc(sizeof(unsigned char) * device->info.iPWMCount); - memset(device->PWM.PWMpinIDs, 0, sizeof(unsigned char) * device->info.iPWMCount); - - PK_FillPWMPinNumbers(device); - - device->PoExtBusData = (unsigned char*)malloc(sizeof(unsigned char) * device->info.iPoExtBus); - - device->MatrixLED = (sPoKeysMatrixLED*)malloc(sizeof(sPoKeysMatrixLED) * device->info.iMatrixLED); - memset(device->MatrixLED, 0, sizeof(sPoKeysMatrixLED) * device->info.iMatrixLED); - - memset(&device->PEv2, 0, sizeof(sPoKeysPEv2)); - - device-> multiPartBuffer = malloc(512); - if (device->multiPartBuffer <= 0) device->multiPartBuffer = 0; + } + + device->Encoders = (sPoKeysEncoder *)malloc(sizeof(sPoKeysEncoder) * + device->info.iEncodersCount); + memset(device->Encoders, 0, + sizeof(sPoKeysEncoder) * device->info.iEncodersCount); + + if (device->info.iEasySensors) { + device->EasySensors = (sPoKeysEasySensor *)malloc( + sizeof(sPoKeysEasySensor) * device->info.iEasySensors); + memset(device->EasySensors, 0, + sizeof(sPoKeysEasySensor) * device->info.iEasySensors); + } else { + device->EasySensors = NULL; + } + + device->PWM.PWMduty = + (uint32_t *)malloc(sizeof(uint32_t) * device->info.iPWMCount); + memset(device->PWM.PWMduty, 0, sizeof(uint32_t) * device->info.iPWMCount); + + device->PWM.PWMenabledChannels = + (unsigned char *)malloc(sizeof(unsigned char) * device->info.iPWMCount); + memset(device->PWM.PWMenabledChannels, 0, + sizeof(unsigned char) * device->info.iPWMCount); + device->PWM.PWMpinIDs = + (unsigned char *)malloc(sizeof(unsigned char) * device->info.iPWMCount); + memset(device->PWM.PWMpinIDs, 0, + sizeof(unsigned char) * device->info.iPWMCount); + + PK_FillPWMPinNumbers(device); + + device->PoExtBusData = + (unsigned char *)malloc(sizeof(unsigned char) * device->info.iPoExtBus); + + device->MatrixLED = (sPoKeysMatrixLED *)malloc(sizeof(sPoKeysMatrixLED) * + device->info.iMatrixLED); + memset(device->MatrixLED, 0, + sizeof(sPoKeysMatrixLED) * device->info.iMatrixLED); + + memset(&device->PEv2, 0, sizeof(sPoKeysPEv2)); + + device->multiPartBuffer = malloc(512); + if (device->multiPartBuffer <= 0) + device->multiPartBuffer = 0; #ifdef USE_ALIGN_TEST - device->alignTest1 = 1; - device->alignTest2 = 2; - device->alignTest3 = 3; - device->alignTest4 = 4; - device->alignTest5 = 5; - device->alignTest6 = 6; - device->alignTest7 = 7; - device->alignTest8 = 8; - device->alignTest9 = 9; - device->alignTest10 = 10; - device->alignTest11 = 11; + device->alignTest1 = 1; + device->alignTest2 = 2; + device->alignTest3 = 3; + device->alignTest4 = 4; + device->alignTest5 = 5; + device->alignTest6 = 6; + device->alignTest7 = 7; + device->alignTest8 = 8; + device->alignTest9 = 9; + device->alignTest10 = 10; + device->alignTest11 = 11; #endif } -void CleanDevice(sPoKeysDevice* device) -{ - free(device->Pins); - device->Pins = NULL; - free(device->Encoders); - device->Encoders = NULL; - free(device->PWM.PWMduty); - device->PWM.PWMduty = NULL; - free(device->PWM.PWMenabledChannels); - device->PWM.PWMenabledChannels = NULL; - free(device->PWM.PWMpinIDs); - device->PWM.PWMpinIDs = NULL; - free(device->PoExtBusData); - device->PoExtBusData = NULL; - free(device->MatrixLED); - device->MatrixLED = NULL; - - if (device->multiPartBuffer != NULL) - { - free(device->multiPartBuffer); - device->multiPartBuffer = NULL; - } - - if (device->EasySensors != NULL) - { - free(device->EasySensors); - device->EasySensors = NULL; - } - - if (device->netDeviceData != NULL) - { - free(device->netDeviceData); - device->netDeviceData = NULL; - } +void CleanDevice(sPoKeysDevice *device) { + free(device->Pins); + device->Pins = NULL; + free(device->Encoders); + device->Encoders = NULL; + free(device->PWM.PWMduty); + device->PWM.PWMduty = NULL; + free(device->PWM.PWMenabledChannels); + device->PWM.PWMenabledChannels = NULL; + free(device->PWM.PWMpinIDs); + device->PWM.PWMpinIDs = NULL; + free(device->PoExtBusData); + device->PoExtBusData = NULL; + free(device->MatrixLED); + device->MatrixLED = NULL; + + if (device->multiPartBuffer != NULL) { + free(device->multiPartBuffer); + device->multiPartBuffer = NULL; + } + + if (device->EasySensors != NULL) { + free(device->EasySensors); + device->EasySensors = NULL; + } + + if (device->netDeviceData != NULL) { + free(device->netDeviceData); + device->netDeviceData = NULL; + } } -void PK_ReleaseDeviceStructure(sPoKeysDevice* device) -{ - CleanDevice(device); +void PK_ReleaseDeviceStructure(sPoKeysDevice *device) { CleanDevice(device); } + +void PK_CloneDeviceStructure(sPoKeysDevice *original, + sPoKeysDevice *destination) { + // Reserve memory... + destination->Pins = (sPoKeysPinData *)malloc(sizeof(sPoKeysPinData) * + original->info.iPinCount); + destination->Encoders = (sPoKeysEncoder *)malloc( + sizeof(sPoKeysEncoder) * original->info.iEncodersCount); + destination->PWM.PWMduty = + (uint32_t *)malloc(sizeof(uint32_t) * original->info.iPWMCount); + destination->PWM.PWMenabledChannels = + (unsigned char *)malloc(sizeof(unsigned char) * original->info.iPWMCount); + destination->PWM.PWMpinIDs = + (unsigned char *)malloc(sizeof(unsigned char) * original->info.iPWMCount); + destination->MatrixLED = (sPoKeysMatrixLED *)malloc( + sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); + + if (original->info.iEasySensors) { + destination->EasySensors = (sPoKeysEasySensor *)malloc( + sizeof(sPoKeysEasySensor) * original->info.iEasySensors); + } else { + destination->EasySensors = 0; + } + + // Network device information structure... + if (original->netDeviceData != 0) { + destination->netDeviceData = + (sPoKeysNetworkDeviceInfo *)malloc(sizeof(sPoKeysNetworkDeviceInfo)); + memcpy(destination->netDeviceData, original->netDeviceData, + sizeof(sPoKeysNetworkDeviceInfo)); + } else { + destination->netDeviceData = 0; + } + destination->PoExtBusData = + (unsigned char *)malloc(sizeof(unsigned char) * original->info.iPoExtBus); + + // Copy data + destination->devHandle = original->devHandle; + destination->devHandle2 = original->devHandle2; + + destination->info = original->info; + destination->DeviceData = original->DeviceData; + + memcpy(&destination->Pins[0], &original->Pins[0], + original->info.iPinCount * sizeof(sPoKeysPinData)); + memcpy(&destination->Encoders[0], &original->Encoders[0], + original->info.iEncodersCount * sizeof(sPoKeysEncoder)); + + if (original->info.iEasySensors) { + memcpy(&destination->EasySensors[0], &original->EasySensors[0], + original->info.iEasySensors * sizeof(sPoKeysEasySensor)); + } + + destination->matrixKB = original->matrixKB; + + destination->PWM.PWMperiod = original->PWM.PWMperiod; + memcpy(destination->PWM.PWMduty, original->PWM.PWMduty, + sizeof(uint32_t) * original->info.iPWMCount); + memcpy(destination->PWM.PWMenabledChannels, original->PWM.PWMenabledChannels, + sizeof(unsigned char) * original->info.iPWMCount); + memcpy(destination->PWM.PWMpinIDs, original->PWM.PWMpinIDs, + sizeof(unsigned char) * original->info.iPWMCount); + + memcpy(destination->MatrixLED, original->MatrixLED, + sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); + + destination->LCD = original->LCD; + + destination->PoNETmodule = original->PoNETmodule; + destination->PoIL = original->PoIL; + destination->RTC = original->RTC; + + destination->FastEncodersConfiguration = original->FastEncodersConfiguration; + destination->FastEncodersOptions = original->FastEncodersOptions; + destination->UltraFastEncoderConfiguration = + original->UltraFastEncoderConfiguration; + destination->UltraFastEncoderOptions = original->UltraFastEncoderOptions; + destination->UltraFastEncoderFilter = original->UltraFastEncoderFilter; + + memcpy(destination->PoExtBusData, original->PoExtBusData, + sizeof(unsigned char) * original->info.iPoExtBus); + + destination->connectionType = original->connectionType; + destination->requestID = original->requestID; } -void PK_CloneDeviceStructure(sPoKeysDevice* original, sPoKeysDevice *destination) -{ - // Reserve memory... - destination->Pins = (sPoKeysPinData*)malloc(sizeof(sPoKeysPinData) * original->info.iPinCount); - destination->Encoders = (sPoKeysEncoder*)malloc(sizeof(sPoKeysEncoder) * original->info.iEncodersCount); - destination->PWM.PWMduty = (uint32_t*)malloc(sizeof(uint32_t) * original->info.iPWMCount); - destination->PWM.PWMenabledChannels = (unsigned char*)malloc(sizeof(unsigned char) * original->info.iPWMCount); - destination->PWM.PWMpinIDs = (unsigned char*)malloc(sizeof(unsigned char) * original->info.iPWMCount); - destination->MatrixLED = (sPoKeysMatrixLED*)malloc(sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); - - if (original->info.iEasySensors) - { - destination->EasySensors = (sPoKeysEasySensor*)malloc(sizeof(sPoKeysEasySensor) * original->info.iEasySensors); - } else - { - destination->EasySensors = 0; - } - - // Network device information structure... - if (original->netDeviceData != 0) - { - destination->netDeviceData = (sPoKeysNetworkDeviceInfo *)malloc(sizeof(sPoKeysNetworkDeviceInfo)); - memcpy(destination->netDeviceData, original->netDeviceData, sizeof(sPoKeysNetworkDeviceInfo)); - } else - { - destination->netDeviceData = 0; - } - destination->PoExtBusData = (unsigned char*)malloc(sizeof(unsigned char) * original->info.iPoExtBus); - - - // Copy data - destination->devHandle = original->devHandle; - destination->devHandle2 = original->devHandle2; - - destination->info = original->info; - destination->DeviceData = original->DeviceData; - - memcpy(&destination->Pins[0], &original->Pins[0], - original->info.iPinCount * sizeof(sPoKeysPinData)); - memcpy(&destination->Encoders[0], &original->Encoders[0], - original->info.iEncodersCount * sizeof(sPoKeysEncoder)); - - - if (original->info.iEasySensors) - { - memcpy(&destination->EasySensors[0], &original->EasySensors[0], - original->info.iEasySensors * sizeof(sPoKeysEasySensor)); - } - - destination->matrixKB = original->matrixKB; - - destination->PWM.PWMperiod = original->PWM.PWMperiod; - memcpy(destination->PWM.PWMduty, original->PWM.PWMduty, - sizeof(uint32_t) * original->info.iPWMCount); - memcpy(destination->PWM.PWMenabledChannels, original->PWM.PWMenabledChannels, - sizeof(unsigned char) * original->info.iPWMCount); - memcpy(destination->PWM.PWMpinIDs, original->PWM.PWMpinIDs, - sizeof(unsigned char) * original->info.iPWMCount); +void *PK_FastUSBConnectToDevice(uint32_t deviceIndex); - memcpy(destination->MatrixLED, original->MatrixLED, - sizeof(sPoKeysMatrixLED) * original->info.iMatrixLED); +sPoKeysDevice *PK_ConnectToDevice(uint32_t deviceIndex) { + int32_t numDevices = 0; + struct hid_device_info *devs, *cur_dev; + sPoKeysDevice *tmpDevice; + void *devData; - destination->LCD = original->LCD; + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; - destination->PoNETmodule = original->PoNETmodule; - destination->PoIL = original->PoIL; - destination->RTC = original->RTC; + while (cur_dev) { + if (cur_dev->interface_number == 1) { + if (numDevices == deviceIndex) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); - destination->FastEncodersConfiguration = original->FastEncodersConfiguration; - destination->FastEncodersOptions = original->FastEncodersOptions; - destination->UltraFastEncoderConfiguration =original->UltraFastEncoderConfiguration; - destination->UltraFastEncoderOptions = original->UltraFastEncoderOptions; - destination->UltraFastEncoderFilter = original->UltraFastEncoderFilter; + // printf("Connect to this device..."); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = NULL; - memcpy(destination->PoExtBusData, original->PoExtBusData, sizeof(unsigned char) * original->info.iPoExtBus); + tmpDevice->connectionType = PK_DeviceType_USBDevice; - destination->connectionType = original->connectionType; - destination->requestID = original->requestID; - -} - -void * PK_FastUSBConnectToDevice(uint32_t deviceIndex); - -sPoKeysDevice* PK_ConnectToDevice(uint32_t deviceIndex) -{ - int32_t numDevices = 0; - struct hid_device_info *devs, *cur_dev; - sPoKeysDevice* tmpDevice; - void * devData; - - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; - - while (cur_dev) - { - if (cur_dev->interface_number == 1) - { - if (numDevices == deviceIndex) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - //printf("Connect to this device..."); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = NULL; - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - - - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - } - //hid_set_nonblocking(devHandle); - hid_free_enumeration(devs); - return tmpDevice; - } - numDevices++; + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; } - cur_dev = cur_dev->next; + // hid_set_nonblocking(devHandle); + hid_free_enumeration(devs); + return tmpDevice; + } + numDevices++; } - hid_free_enumeration(devs); - - // Continue with 0x1002 devices - devs = hid_enumerate(0x1DC3, 0x1002); - cur_dev = devs; - - while (cur_dev) - { - if (cur_dev->interface_number == -1) - { - if (numDevices == deviceIndex) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - //printf("Connect to this device..."); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = NULL; - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - } - //hid_set_nonblocking(devHandle); - hid_free_enumeration(devs); - return tmpDevice; - } - numDevices++; + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); + + // Continue with 0x1002 devices + devs = hid_enumerate(0x1DC3, 0x1002); + cur_dev = devs; + + while (cur_dev) { + if (cur_dev->interface_number == -1) { + if (numDevices == deviceIndex) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + + // printf("Connect to this device..."); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = NULL; + + tmpDevice->connectionType = PK_DeviceType_USBDevice; + + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; } - cur_dev = cur_dev->next; + // hid_set_nonblocking(devHandle); + hid_free_enumeration(devs); + return tmpDevice; + } + numDevices++; } - hid_free_enumeration(devs); + cur_dev = cur_dev->next; + } + hid_free_enumeration(devs); #ifdef POKEYSLIB_USE_LIBUSB - // Try connecting to the bulk interface of the PoKeys device... - devData = PK_FastUSBConnectToDevice(deviceIndex - numDevices); + // Try connecting to the bulk interface of the PoKeys device... + devData = PK_FastUSBConnectToDevice(deviceIndex - numDevices); - //void * devData = ConnectToFastUSBInterface(serialNumber); - if (devData != NULL) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); + // void * devData = ConnectToFastUSBInterface(serialNumber); + if (devData != NULL) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); - tmpDevice->devHandle = NULL; - tmpDevice->devHandle2 = devData; + tmpDevice->devHandle = NULL; + tmpDevice->devHandle2 = devData; - tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; - InitializeNewDevice(tmpDevice); - return tmpDevice; - } + tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; + InitializeNewDevice(tmpDevice); + return tmpDevice; + } #endif - return NULL; + return NULL; } // Flags: // bits 7-1: deviceType specifier (2 - PoKeys56, 3 - PoKeys58, 4 - PoKeys16) // bit 0: use UDP -sPoKeysDevice* PK_ConnectToPoKeysDevice(uint32_t serialNumber, uint32_t checkForNetworkDevicesAndTimeout, uint32_t flags) -{ - int32_t numDevices = 0; - struct hid_device_info *devs, *cur_dev; - int32_t k; - sPoKeysDevice* tmpDevice; - uint8_t serialSearch[8]; - //uint8_t serialSearch58[8]; - - sPoKeysNetworkDeviceSummary * devices; - int32_t iNet; - - int devRange = 0; - uint8_t deviceTypeRequested = (flags >> 1) & 0x7F; - - +sPoKeysDevice * +PK_ConnectToPoKeysDevice(uint32_t serialNumber, + uint32_t checkForNetworkDevicesAndTimeout, + uint32_t flags) { + int32_t numDevices = 0; + struct hid_device_info *devs, *cur_dev; + int32_t k; + sPoKeysDevice *tmpDevice; + uint8_t serialSearch[8]; + // uint8_t serialSearch58[8]; + + sPoKeysNetworkDeviceSummary *devices; + int32_t iNet; + + int devRange = 0; + uint8_t deviceTypeRequested = (flags >> 1) & 0x7F; #ifdef POKEYSLIB_USE_LIBUSB - // Try connecting to fast USB interface first - void * devData = ConnectToFastUSBInterface(serialNumber); - if (devData != NULL) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - tmpDevice->devHandle = NULL; - tmpDevice->devHandle2 = devData; - - tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; - InitializeNewDevice(tmpDevice); - return tmpDevice; - } + // Try connecting to fast USB interface first + void *devData = ConnectToFastUSBInterface(serialNumber); + if (devData != NULL) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + + tmpDevice->devHandle = NULL; + tmpDevice->devHandle2 = devData; + + tmpDevice->connectionType = PK_DeviceType_FastUSBDevice; + InitializeNewDevice(tmpDevice); + return tmpDevice; + } #endif - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; - sprintf((char*)serialSearch, "x.%05u", serialNumber % 100000); - //sprintf(serialSearch58, "3.%05u", serialNumber % 100000); + sprintf((char *)serialSearch, "x.%05u", serialNumber % 100000); + // sprintf(serialSearch58, "3.%05u", serialNumber % 100000); - while (cur_dev) - { - if ((cur_dev->interface_number == 1 && devRange == 0) || - (cur_dev->interface_number == 0 && devRange == 1)) - { - if (cur_dev->serial_number != 0 && cur_dev->serial_number[0] != 'P') - { - // Check the serial number first - for (k = 1; k < 8 && cur_dev->serial_number[k] != 0; k++) - { - if (cur_dev->serial_number[k] != serialSearch[k]) break; - } - - if (deviceTypeRequested == 2 && cur_dev->serial_number[0] != '2') k = 0; - if (deviceTypeRequested == 3 && cur_dev->serial_number[0] != '3') k = 0; - if (deviceTypeRequested == 4 && cur_dev->serial_number[0] != '4') k = 0; - - /* - for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) - { - if (cur_dev->serial_number[k] != serialSearch[k]) break; - } - - if (k != 7) - { - for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) - { - if (cur_dev->serial_number[k] != serialSearch58[k]) break; - } - }*/ - - if (k == 7) - { - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - - //printf("Connect to this device..."); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = 0; - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - } - //hid_set_nonblocking(devHandle); - hid_free_enumeration(devs); - return tmpDevice; - } - } else - { - // Old, PoKeys55 device - we must to connect and read the serial number... - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - tmpDevice->devHandle = (void*)hid_open_path(cur_dev->path); - tmpDevice->devHandle2 = 0; - - if (tmpDevice->devHandle != NULL) - { - InitializeNewDevice(tmpDevice); - } else - { - free(tmpDevice); - tmpDevice = NULL; - hid_free_enumeration(devs); - return NULL; - } - - tmpDevice->connectionType = PK_DeviceType_USBDevice; - if (tmpDevice->DeviceData.SerialNumber == serialNumber) - { - hid_free_enumeration(devs); - return tmpDevice; - } else - { - CleanDevice(tmpDevice); - free(tmpDevice); - } - } + while (cur_dev) { + if ((cur_dev->interface_number == 1 && devRange == 0) || + (cur_dev->interface_number == 0 && devRange == 1)) { + if (cur_dev->serial_number != 0 && cur_dev->serial_number[0] != 'P') { + // Check the serial number first + for (k = 1; k < 8 && cur_dev->serial_number[k] != 0; k++) { + if (cur_dev->serial_number[k] != serialSearch[k]) + break; + } - numDevices++; + if (deviceTypeRequested == 2 && cur_dev->serial_number[0] != '2') + k = 0; + if (deviceTypeRequested == 3 && cur_dev->serial_number[0] != '3') + k = 0; + if (deviceTypeRequested == 4 && cur_dev->serial_number[0] != '4') + k = 0; + + /* + for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) + { + if (cur_dev->serial_number[k] != serialSearch[k]) break; } - cur_dev = cur_dev->next; - if (cur_dev == NULL) + if (k != 7) { - devRange++; - switch (devRange) + for (k = 0; k < 8 && cur_dev->serial_number[k] != 0; k++) { - case 1: - hid_free_enumeration(devs); - devs = hid_enumerate(0x1DC3, 0x1001); - cur_dev = devs; - break; + if (cur_dev->serial_number[k] != serialSearch58[k]) break; } + }*/ + + if (k == 7) { + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + + // printf("Connect to this device..."); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = 0; + + tmpDevice->connectionType = PK_DeviceType_USBDevice; + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; + } + // hid_set_nonblocking(devHandle); + hid_free_enumeration(devs); + return tmpDevice; + } + } else { + // Old, PoKeys55 device - we must to connect and read the serial + // number... + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + tmpDevice->devHandle = (void *)hid_open_path(cur_dev->path); + tmpDevice->devHandle2 = 0; + + if (tmpDevice->devHandle != NULL) { + InitializeNewDevice(tmpDevice); + } else { + free(tmpDevice); + tmpDevice = NULL; + hid_free_enumeration(devs); + return NULL; } - } - hid_free_enumeration(devs); - - if (checkForNetworkDevicesAndTimeout) - { - devices = (sPoKeysNetworkDeviceSummary*)malloc(sizeof(sPoKeysNetworkDeviceSummary) * 16); - iNet = PK_SearchNetworkDevices(devices, checkForNetworkDevicesAndTimeout, serialNumber); - if (iNet > 16) iNet = 16; + tmpDevice->connectionType = PK_DeviceType_USBDevice; + if (tmpDevice->DeviceData.SerialNumber == serialNumber) { + hid_free_enumeration(devs); + return tmpDevice; + } else { + CleanDevice(tmpDevice); + free(tmpDevice); + } + } - for (k = 0; k < iNet; k++) - { - //printf("\nNetwork device found, serial = %lu at %u.%u.%u.%u", devices[k].SerialNumber, devices[k].IPaddress[0], devices[k].IPaddress[1], devices[k].IPaddress[2], devices[k].IPaddress[3]); - if (devices[k].SerialNumber == serialNumber) - { - if (flags & 1) devices[k].useUDP = 1; - tmpDevice = PK_ConnectToNetworkDevice(&devices[k]); - if (tmpDevice == NULL) - { - //CleanDevice(tmpDevice); - free(tmpDevice); - //printf("\nProblem connecting to the device..."); - } else - { - free(devices); - InitializeNewDevice(tmpDevice); - return tmpDevice; - } - } + numDevices++; + } + cur_dev = cur_dev->next; + + if (cur_dev == NULL) { + devRange++; + switch (devRange) { + case 1: + hid_free_enumeration(devs); + devs = hid_enumerate(0x1DC3, 0x1001); + cur_dev = devs; + break; + } + } + } + hid_free_enumeration(devs); + + if (checkForNetworkDevicesAndTimeout) { + devices = (sPoKeysNetworkDeviceSummary *)malloc( + sizeof(sPoKeysNetworkDeviceSummary) * 16); + iNet = PK_SearchNetworkDevices(devices, checkForNetworkDevicesAndTimeout, + serialNumber); + + if (iNet > 16) + iNet = 16; + + for (k = 0; k < iNet; k++) { + // printf("\nNetwork device found, serial = %lu at %u.%u.%u.%u", + // devices[k].SerialNumber, devices[k].IPaddress[0], + // devices[k].IPaddress[1], devices[k].IPaddress[2], + // devices[k].IPaddress[3]); + if (devices[k].SerialNumber == serialNumber) { + if (flags & 1) + devices[k].useUDP = 1; + tmpDevice = PK_ConnectToNetworkDevice(&devices[k]); + if (tmpDevice == NULL) { + // CleanDevice(tmpDevice); + free(tmpDevice); + // printf("\nProblem connecting to the device..."); + } else { + free(devices); + InitializeNewDevice(tmpDevice); + return tmpDevice; } - free(devices); + } } + free(devices); + } - return NULL; + return NULL; } - -sPoKeysDevice* PK_ConnectToDeviceWSerial(uint32_t serialNumber, uint32_t checkForNetworkDevicesAndTimeout) -{ - return PK_ConnectToPoKeysDevice(serialNumber, checkForNetworkDevicesAndTimeout, 0); +sPoKeysDevice * +PK_ConnectToDeviceWSerial(uint32_t serialNumber, + uint32_t checkForNetworkDevicesAndTimeout) { + return PK_ConnectToPoKeysDevice(serialNumber, + checkForNetworkDevicesAndTimeout, 0); } -sPoKeysDevice* PK_ConnectToDeviceWSerial_UDP(uint32_t serialNumber, uint32_t checkForNetworkDevicesAndTimeout) -{ - return PK_ConnectToPoKeysDevice(serialNumber, checkForNetworkDevicesAndTimeout, 1); +sPoKeysDevice * +PK_ConnectToDeviceWSerial_UDP(uint32_t serialNumber, + uint32_t checkForNetworkDevicesAndTimeout) { + return PK_ConnectToPoKeysDevice(serialNumber, + checkForNetworkDevicesAndTimeout, 1); } -void PK_DisconnectDevice(sPoKeysDevice* device) -{ - if (device != NULL) - { - if (device->connectionType == PK_DeviceType_NetworkDevice) - { - PK_DisconnectNetworkDevice(device); - } else - { +void PK_DisconnectDevice(sPoKeysDevice *device) { + if (device != NULL) { + if (device->connectionType == PK_DeviceType_NetworkDevice) { + PK_DisconnectNetworkDevice(device); + } else { #ifdef POKEYSLIB_USE_LIBUSB - // Disconnect the fast USB interface... - DisconnectFromFastUSBInterface(device->devHandle2); - device->devHandle2 = NULL; + // Disconnect the fast USB interface... + DisconnectFromFastUSBInterface(device->devHandle2); + device->devHandle2 = NULL; #endif - if ((hid_device*)device->devHandle != NULL) - { - hid_close((hid_device*)device->devHandle); - } - } - - CleanDevice(device); - free(device); + if ((hid_device *)device->devHandle != NULL) { + hid_close((hid_device *)device->devHandle); + } } + + CleanDevice(device); + free(device); + } } -int32_t CreateRequest(unsigned char * request, unsigned char type, unsigned char param1, unsigned char param2, unsigned char param3, unsigned char param4) -{ - if (request == NULL) return PK_ERR_NOT_CONNECTED; +int32_t CreateRequest(unsigned char *request, unsigned char type, + unsigned char param1, unsigned char param2, + unsigned char param3, unsigned char param4) { + if (request == NULL) + return PK_ERR_NOT_CONNECTED; - memset(request, 0, 64); + memset(request, 0, 64); - request[1] = type; - request[2] = param1; - request[3] = param2; - request[4] = param3; - request[5] = param4; + request[1] = type; + request[2] = param1; + request[3] = param2; + request[4] = param3; + request[5] = param4; - return PK_OK; + return PK_OK; } -int32_t PK_CustomRequest(sPoKeysDevice* device, unsigned char type, unsigned char param1, unsigned char param2, unsigned char param3, unsigned char param4) -{ - device->request[1] = type; - device->request[2] = param1; - device->request[3] = param2; - device->request[4] = param3; - device->request[5] = param4; +int32_t PK_CustomRequest(sPoKeysDevice *device, unsigned char type, + unsigned char param1, unsigned char param2, + unsigned char param3, unsigned char param4) { + device->request[1] = type; + device->request[2] = param1; + device->request[3] = param2; + device->request[4] = param3; + device->request[5] = param4; - return SendRequest(device); + return SendRequest(device); } -uint8_t getChecksum(uint8_t * data) -{ - uint8_t temp = 0; - uint32_t i; +uint8_t getChecksum(uint8_t *data) { + uint8_t temp = 0; + uint32_t i; - for (i = 0; i < 7; i++) - { - temp += data[i]; - } - return temp; + for (i = 0; i < 7; i++) { + temp += data[i]; + } + return temp; } int32_t LastRetryCount = 0; int32_t LastWaitCount = 0; - //#define PK_COM_DEBUG -int32_t SendRequest_multiPart(sPoKeysDevice* device) -{ - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType == PK_DeviceType_NetworkDevice) - { - return SendEthRequestBig(device); - //return SendEthRequest(device); - //return PK_ERR_TRANSFER; - } +int32_t SendRequest_multiPart(sPoKeysDevice *device) { + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType == PK_DeviceType_NetworkDevice) { + return SendEthRequestBig(device); + // return SendEthRequest(device); + // return PK_ERR_TRANSFER; + } #ifdef POKEYSLIB_USE_LIBUSB - if (device->connectionType == PK_DeviceType_FastUSBDevice) - return SendRequestFastUSB_multiPart(device); - else - return PK_ERR_TRANSFER; -#else + if (device->connectionType == PK_DeviceType_FastUSBDevice) + return SendRequestFastUSB_multiPart(device); + else return PK_ERR_TRANSFER; +#else + return PK_ERR_TRANSFER; #endif } - //#define PK_COM_DEBUG -int32_t SendRequest(sPoKeysDevice* device) -{ - // Initialize variables - uint32_t waits = 0; - uint32_t retries = 0; - int32_t result = 0; - uint8_t bufferOut[65] = {0}; - - #ifdef PK_COM_DEBUG - int i; - #endif - - hid_device * devHandle; - - - - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType == PK_DeviceType_NetworkDevice) - { - return SendEthRequest(device); - } +int32_t SendRequest(sPoKeysDevice *device) { + // Initialize variables + uint32_t waits = 0; + uint32_t retries = 0; + int32_t result = 0; + uint8_t bufferOut[65] = {0}; + + // #ifdef PK_COM_DEBUG + int i; + // #endif + + hid_device *devHandle; + + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType == PK_DeviceType_NetworkDevice) { + return SendEthRequest(device); + } #ifdef POKEYSLIB_USE_LIBUSB - if (device->connectionType == PK_DeviceType_FastUSBDevice) - return SendRequestFastUSB(device); + if (device->connectionType == PK_DeviceType_FastUSBDevice) + return SendRequestFastUSB(device); #endif - devHandle = (hid_device*)device->devHandle; + devHandle = (hid_device *)device->devHandle; + if (devHandle == NULL) + return PK_ERR_GENERIC; - if (devHandle == NULL) return PK_ERR_GENERIC; + // Request sending loop + while (retries++ < 2) { + device->request[0] = 0xBB; + device->request[6] = ++device->requestID; + device->request[7] = getChecksum(device->request); - // Request sending loop - while (retries++ < 2) - { - device->request[0] = 0xBB; - device->request[6] = ++device->requestID; - device->request[7] = getChecksum(device->request); - - memcpy(bufferOut + 1, device->request, 64); - - #ifdef PK_COM_DEBUG - printf("\n * SEND "); - for (i = 0; i < 10; i++) - { - printf("%X ", bufferOut[i]); - } - #endif - - result = hid_write(devHandle, bufferOut, 65); - - // In case of an error, try sending again - if (result < 0) - { - //printf(" ERR %u", result); - retries++; - continue; - } + memcpy(bufferOut + 1, device->request, 64); - waits = 0; + // #ifdef PK_COM_DEBUG + printf("\n * SEND "); + for (i = 0; i < 10; i++) { + printf("%X ", bufferOut[i]); + } + // #endif - // Request receiving loop - while (waits++ < 50) - { - result = hid_read(devHandle, device->response, 65); + result = hid_write(devHandle, bufferOut, 65); - // Error is not an option - if (result < 0) - { - //printf(" Receive ERR %u", result); - break; - } + // In case of an error, try sending again + if (result < 0) { + // printf(" ERR %u", result); + retries++; + continue; + } -#ifdef PK_COM_DEBUG - printf("\n * RECV "); - for (i = 0; i < 10; i++) - { - printf("%X ", device->response[i]); + waits = 0; + + // Request receiving loop + while (waits++ < 50) { + result = hid_read(devHandle, device->response, 65); + + // Error is not an option + if (result < 0) { + // printf(" Receive ERR %u", result); + break; + } + + // #ifdef PK_COM_DEBUG + printf("\n * RECV "); + for (i = 0; i < 10; i++) { + printf("%X ", device->response[i]); + } + + printf(" (request ID: %X ?= %X", device->response[6], device->requestID); + // #endif + + // Check the header and the request ID + if (device->response[0] == 0xAA && + device->response[6] == device->requestID) { + if (device->response[7] == getChecksum(device->response)) { + LastRetryCount = retries; + LastWaitCount = waits; + // This is it. Return from this function + return PK_OK; } - - printf(" (request ID: %X ?= %X", device->response[6], device->requestID); -#endif - - // Check the header and the request ID - if (device->response[0] == 0xAA && device->response[6] == device->requestID) - { - if (device->response[7] == getChecksum(device->response)) - { - LastRetryCount = retries; - LastWaitCount = waits; - // This is it. Return from this function - return PK_OK; - } - } - } + } } + } - return PK_ERR_TRANSFER; + return PK_ERR_TRANSFER; } - // ****************************************************************************************** -// These functions are used to access the device data without using the structures... +// These functions are used to access the device data without using the +// structures... // ****************************************************************************************** -void PK_SL_SetPinFunction(sPoKeysDevice* device, uint8_t pin, uint8_t function) -{ - device->Pins[pin].PinFunction = function; +void PK_SL_SetPinFunction(sPoKeysDevice *device, uint8_t pin, + uint8_t function) { + device->Pins[pin].PinFunction = function; } -uint8_t PK_SL_GetPinFunction(sPoKeysDevice* device, uint8_t pin) -{ - return device->Pins[pin].PinFunction; +uint8_t PK_SL_GetPinFunction(sPoKeysDevice *device, uint8_t pin) { + return device->Pins[pin].PinFunction; } -void PK_SL_DigitalOutputSet(sPoKeysDevice* device, uint8_t pin, uint8_t value) -{ - device->Pins[pin].DigitalValueSet = value; +void PK_SL_DigitalOutputSet(sPoKeysDevice *device, uint8_t pin, uint8_t value) { + device->Pins[pin].DigitalValueSet = value; } -uint8_t PK_SL_DigitalInputGet(sPoKeysDevice* device, uint8_t pin) -{ - return device->Pins[pin].DigitalValueGet; +uint8_t PK_SL_DigitalInputGet(sPoKeysDevice *device, uint8_t pin) { + return device->Pins[pin].DigitalValueGet; } -uint32_t PK_SL_AnalogInputGet(sPoKeysDevice* device, uint8_t pin) -{ - return device->Pins[pin].AnalogValue; +uint32_t PK_SL_AnalogInputGet(sPoKeysDevice *device, uint8_t pin) { + return device->Pins[pin].AnalogValue; } - diff --git a/lib/pokey/PoKeysLibCoreSockets.c b/lib/pokey/PoKeysLibCoreSockets.c index c6a9758..fc3d4ba 100755 --- a/lib/pokey/PoKeysLibCoreSockets.c +++ b/lib/pokey/PoKeysLibCoreSockets.c @@ -1,6 +1,6 @@ /* -Copyright (C) 2013 Matevž Bošnak (matevz@poscope.com) +Copyright (C) 2013 Matev� Bo�nak (matevz@poscope.com) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -22,846 +22,827 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "PoKeysLibCore.h" #ifdef WIN32 - #include "windows.h" - // #include "Winsock.h" - #include "conio.h" - #include +#include "windows.h" +// #include "Winsock.h" +#include "conio.h" +#include #else - #include - #include - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include +#include +#include + #endif +#include "PoKeysLib.h" #include #include #include -#include "PoKeysLib.h" //#define DEBUG_PoKeysLibSockets #ifdef DEBUG_PoKeysLibSockets - #define debug_printf printf +#define debug_printf printf #else - #define debug_printf (void) +#define debug_printf (void) #endif - -// Get a list of interfaces - source: Jeremy @ http://developerweb.net/viewtopic.php?id=5085 +// Get a list of interfaces - source: Jeremy @ +// http://developerweb.net/viewtopic.php?id=5085 typedef unsigned long uint32; -#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) || defined(__linux__) - #define USE_GETIFADDRS 1 - #define SOCKADDR struct sockaddr +#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__) || \ + defined(__linux__) +#define USE_GETIFADDRS 1 +#define SOCKADDR struct sockaddr - #include +#include - uint32 SockAddrToUint32(struct sockaddr * a) - { - return ((a)&&(a->sa_family == AF_INET)) ? ntohl(((struct sockaddr_in *)a)->sin_addr.s_addr) : 0; - } +uint32 SockAddrToUint32(struct sockaddr *a) { + return ((a) && (a->sa_family == AF_INET)) + ? ntohl(((struct sockaddr_in *)a)->sin_addr.s_addr) + : 0; +} #endif -uint32 * GetBroadcastAddresses() -{ - uint32 * list = malloc(sizeof(uint32) * 100); - uint32* ptr = list; +uint32 *GetBroadcastAddresses() { + uint32 *list = malloc(sizeof(uint32) * 100); + uint32 *ptr = list; #if defined(WIN32) - uint32 i; - MIB_IPADDRTABLE * ipTable = NULL; - IP_ADAPTER_INFO * pAdapterInfo = NULL; - ULONG bufLen = 0; - uint32 ipRet; - uint32 apRet; + uint32 i; + MIB_IPADDRTABLE *ipTable = NULL; + IP_ADAPTER_INFO *pAdapterInfo = NULL; + ULONG bufLen = 0; + uint32 ipRet; + uint32 apRet; - MIB_IPADDRROW * row; + MIB_IPADDRROW *row; - uint32 ipAddr; - uint32 netmask; - uint32 baddr; + uint32 ipAddr; + uint32 netmask; + uint32 baddr; #endif #if defined(USE_GETIFADDRS) - uint32 tmp; + uint32 tmp; #endif - *ptr = 0; - + *ptr = 0; #if defined(USE_GETIFADDRS) - // BSD-style implementation - struct ifaddrs * ifap; - if (getifaddrs(&ifap) == 0) - { - struct ifaddrs * p = ifap; - while(p) - { - uint32 ifaAddr = SockAddrToUint32(p->ifa_addr); - - if (ifaAddr > 0) - { - tmp = ((struct sockaddr_in *)p->ifa_broadaddr)->sin_addr.s_addr; - if (tmp) *(ptr++) = tmp; - } - p = p->ifa_next; - } - freeifaddrs(ifap); + // BSD-style implementation + struct ifaddrs *ifap; + if (getifaddrs(&ifap) == 0) { + struct ifaddrs *p = ifap; + while (p) { + uint32 ifaAddr = SockAddrToUint32(p->ifa_addr); + + if (ifaAddr > 0) { + tmp = ((struct sockaddr_in *)p->ifa_broadaddr)->sin_addr.s_addr; + if (tmp) + *(ptr++) = tmp; + } + p = p->ifa_next; } + freeifaddrs(ifap); + } #elif defined(WIN32) - // Windows XP style implementation + // Windows XP style implementation + + // Adapted from example code at + // http://msdn2.microsoft.com/en-us/library/aa365917.aspx Now get Windows' + // IPv4 addresses table. Once again, we gotta call GetIpAddrTable() multiple + // times in order to deal with potential race conditions properly. + { + for (i = 0; i < 5; i++) { + ipRet = GetIpAddrTable(ipTable, &bufLen, 0); + if (ipRet == ERROR_INSUFFICIENT_BUFFER) { + free(ipTable); // in case we had previously allocated it + ipTable = (MIB_IPADDRTABLE *)malloc(bufLen); + } else if (ipRet == NO_ERROR) + break; + else { + free(ipTable); + ipTable = NULL; + break; + } + } + } - // Adapted from example code at http://msdn2.microsoft.com/en-us/library/aa365917.aspx - // Now get Windows' IPv4 addresses table. Once again, we gotta call GetIpAddrTable() - // multiple times in order to deal with potential race conditions properly. + if (ipTable) { + // Try to get the Adapters-info table, so we can given useful names to the + // IP addresses we are returning. Gotta call GetAdaptersInfo() up to 5 + // times to handle the potential race condition between the size-query call + // and the get-data call. I love a well-designed API :^P { - for (i=0; i<5; i++) - { - ipRet = GetIpAddrTable(ipTable, &bufLen, 0); - if (ipRet == ERROR_INSUFFICIENT_BUFFER) - { - free(ipTable); // in case we had previously allocated it - ipTable = (MIB_IPADDRTABLE *) malloc(bufLen); - } - else if (ipRet == NO_ERROR) break; - else - { - free(ipTable); - ipTable = NULL; - break; - } - } - } - - if (ipTable) - { - // Try to get the Adapters-info table, so we can given useful names to the IP - // addresses we are returning. Gotta call GetAdaptersInfo() up to 5 times to handle - // the potential race condition between the size-query call and the get-data call. - // I love a well-designed API :^P - { - for (i=0; i<5; i++) - { - apRet = GetAdaptersInfo(pAdapterInfo, &bufLen); - if (apRet == ERROR_BUFFER_OVERFLOW) - { - free(pAdapterInfo); // in case we had previously allocated it - pAdapterInfo = (IP_ADAPTER_INFO *) malloc(bufLen); - } - else if (apRet == ERROR_SUCCESS) break; - else - { - free(pAdapterInfo); - pAdapterInfo = NULL; - break; - } - } + for (i = 0; i < 5; i++) { + apRet = GetAdaptersInfo(pAdapterInfo, &bufLen); + if (apRet == ERROR_BUFFER_OVERFLOW) { + free(pAdapterInfo); // in case we had previously allocated it + pAdapterInfo = (IP_ADAPTER_INFO *)malloc(bufLen); + } else if (apRet == ERROR_SUCCESS) + break; + else { + free(pAdapterInfo); + pAdapterInfo = NULL; + break; + } } + } - for (i=0; i < ipTable->dwNumEntries; i++) - { - // ----------------------------------------------------------------------------------------- - row = &ipTable->table[i]; - // ----------------------------------------------------------------------------------------- + for (i = 0; i < ipTable->dwNumEntries; i++) { + // ----------------------------------------------------------------------------------------- + row = &ipTable->table[i]; + // ----------------------------------------------------------------------------------------- - ipAddr = (row->dwAddr); - netmask = (row->dwMask); - baddr = ipAddr & netmask; - if (row->dwBCastAddr) baddr |= ~netmask; + ipAddr = (row->dwAddr); + netmask = (row->dwMask); + baddr = ipAddr & netmask; + if (row->dwBCastAddr) + baddr |= ~netmask; - if (baddr) *(ptr++) = baddr; - } + if (baddr) + *(ptr++) = baddr; + } - free(pAdapterInfo); - free(ipTable); - } + free(pAdapterInfo); + free(ipTable); + } #else - // Dunno what we're running on here! -# error "Don't know how to implement GetBroadcastAddresses() on this OS!" +// Dunno what we're running on here! +#error "Don't know how to implement GetBroadcastAddresses() on this OS!" #endif - *ptr = 0; - return list; + *ptr = 0; + return list; } #ifdef WIN32 - WSADATA wsaData; - - int32_t InitWinsock() - { - // Initialize Winsock - version 2.2 - if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) - { - debug_printf("Winsock startup failed!\n"); - return -1; - } - return 0; - } +WSADATA wsaData; + +int32_t InitWinsock() { + // Initialize Winsock - version 2.2 + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { + debug_printf("Winsock startup failed!\n"); + return -1; + } + return 0; +} - int32_t TerminateWinsock() - { - WSACleanup(); - return 0; - } +int32_t TerminateWinsock() { + WSACleanup(); + return 0; +} #endif - -int32_t PK_EnumerateNetworkDevices(sPoKeysNetworkDeviceSummary * devices, uint32_t timeout) -{ - return PK_SearchNetworkDevices(devices, timeout, 0); +int32_t PK_EnumerateNetworkDevices(sPoKeysNetworkDeviceSummary *devices, + uint32_t timeout) { + return PK_SearchNetworkDevices(devices, timeout, 0); } -int32_t PK_SearchNetworkDevices(sPoKeysNetworkDeviceSummary * devices, uint32_t timeout, uint32_t serialNumberToFind) -{ - //Broadcast the message - int32_t t; // 100 ms timeout +int32_t PK_SearchNetworkDevices(sPoKeysNetworkDeviceSummary *devices, + uint32_t timeout, uint32_t serialNumberToFind) { + // Broadcast the message + int32_t t; // 100 ms timeout #ifdef WIN32 - struct sockaddr_in remoteEP; - SOCKET txSocket; + struct sockaddr_in remoteEP; + SOCKET txSocket; #else - int txSocket; - struct sockaddr_in remoteEP; - fd_set fds; - struct timeval stimeout; + int txSocket; + struct sockaddr_in remoteEP; + fd_set fds; + struct timeval stimeout; #endif - int UDPbroadcast = 1; - int status = 0; - int BufLen = 0; - char SendBuf[1]; - uint32 * addr; - uint32 * addrPtr; - uint32 a; - unsigned char rcvbuf[500]; - int nrOfDetectedBoards = 0; - sPoKeysNetworkDeviceSummary * device; + int UDPbroadcast = 1; + int status = 0; + int BufLen = 0; + char SendBuf[1]; + uint32 *addr; + uint32 *addrPtr; + uint32 a; + unsigned char rcvbuf[500]; + int nrOfDetectedBoards = 0; + sPoKeysNetworkDeviceSummary *device; - t = timeout; + t = timeout; - debug_printf("Enumerating network PoKeys devices...\n"); + debug_printf("Enumerating network PoKeys devices...\n"); #ifdef WIN32 - if (InitWinsock() != 0) - { - debug_printf("InitWinsock error!"); - return 0; - } + if (InitWinsock() != 0) { + debug_printf("InitWinsock error!"); + return 0; + } #endif - - // Create socket for discovery packet - if ((txSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) - { - debug_printf("Error creating socket\n"); - return 0; - } - if (setsockopt( txSocket, SOL_SOCKET, SO_BROADCAST, (char *)&UDPbroadcast, sizeof UDPbroadcast) == -1) - { - debug_printf("Error setting broadcast option\n"); - return 0; - } + + // Create socket for discovery packet + if ((txSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { + debug_printf("Error creating socket\n"); + return 0; + } + if (setsockopt(txSocket, SOL_SOCKET, SO_BROADCAST, (char *)&UDPbroadcast, + sizeof UDPbroadcast) == -1) { + debug_printf("Error setting broadcast option\n"); + return 0; + } #ifdef WIN32 - if (setsockopt( txSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t)) == -1) - { - debug_printf("Error setting SO_RCVTIMEO option\n"); - return 0; - } - if (setsockopt( txSocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t)) == -1) - { - debug_printf("Error setting SO_SNDTIMEO option\n"); - return 0; - } + if (setsockopt(txSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t)) == + -1) { + debug_printf("Error setting SO_RCVTIMEO option\n"); + return 0; + } + if (setsockopt(txSocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t)) == + -1) { + debug_printf("Error setting SO_SNDTIMEO option\n"); + return 0; + } #endif + debug_printf("Sending discovery request...\n"); - debug_printf("Sending discovery request...\n"); + addr = GetBroadcastAddresses(); + addrPtr = addr; - addr = GetBroadcastAddresses(); - addrPtr = addr; + while (*addr) { + a = *addr; + debug_printf("Sending request to %d.%d.%d.%d... ", (a & 0xFF), + (a >> 8) & 0xFF, (a >> 16) & 0xFF, (a >> 24) & 0xFF); - while(*addr) - { - a = *addr; - debug_printf("Sending request to %d.%d.%d.%d... ", (a&0xFF),(a>>8)&0xFF, (a>>16)&0xFF, (a>>24)&0xFF); + // Send discovery request... + remoteEP.sin_family = AF_INET; + remoteEP.sin_port = htons(20055); + remoteEP.sin_addr.s_addr = a; // inet_addr("255.255.255.255"); - // Send discovery request... - remoteEP.sin_family = AF_INET; - remoteEP.sin_port = htons(20055); - remoteEP.sin_addr.s_addr = a; // inet_addr("255.255.255.255"); - - if (sendto(txSocket, SendBuf, BufLen, 0, (SOCKADDR *)&remoteEP, sizeof(remoteEP)) == -1) - { - debug_printf("Failed\n"); + if (sendto(txSocket, SendBuf, BufLen, 0, (SOCKADDR *)&remoteEP, + sizeof(remoteEP)) == -1) { + debug_printf("Failed\n"); #ifdef WIN32 - closesocket(txSocket); - WSACleanup(); + closesocket(txSocket); + WSACleanup(); #else - close(txSocket); + close(txSocket); #endif - return 0; - } - debug_printf(" done\n"); - addr++; + return 0; } - free(addrPtr); - - - debug_printf("Waiting for responses...\n"); - + debug_printf(" done\n"); + addr++; + } + free(addrPtr); + debug_printf("Waiting for responses...\n"); #ifdef WIN32 #else - // Wait for discovery response... - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * timeout; + // Wait for discovery response... + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * timeout; - FD_ZERO(&fds); - FD_SET(txSocket, &fds); + FD_ZERO(&fds); + FD_SET(txSocket, &fds); #endif - - while(nrOfDetectedBoards < 16) - { - // Receive response from devices + while (nrOfDetectedBoards < 16) { +// Receive response from devices #ifdef WIN32 #else - if (select(txSocket + 1, &fds, NULL, NULL, &stimeout) < 0) - { - debug_printf("Error in select...\n"); - close(txSocket); - return 0; - } + if (select(txSocket + 1, &fds, NULL, NULL, &stimeout) < 0) { + debug_printf("Error in select...\n"); + close(txSocket); + return 0; + } - if (FD_ISSET(txSocket, &fds) == 0) break; + if (FD_ISSET(txSocket, &fds) == 0) + break; #endif - debug_printf("Retrieving data...\n"); - status = recv(txSocket, (char *)rcvbuf, sizeof(rcvbuf), 0); - - if (status < 0) - { - debug_printf("Error receiving data...\n"); - break; - } - - // Get IP address and receive message - if (status > 0) - { - if (status == 14) - { - // Parse the response - debug_printf("Received response...\n"); - - debug_printf(" User ID: %u\n", rcvbuf[0]); - debug_printf(" Serial: %u\n", (int)(256 * (int)rcvbuf[1] + rcvbuf[2])); - debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); - debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], rcvbuf[7], rcvbuf[8]); - debug_printf(" DHCP: %u\n", rcvbuf[9]); - debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], rcvbuf[12], rcvbuf[13]); - - // Save the device info - device = &devices[nrOfDetectedBoards]; - //device->userID = rcvbuf[0]; - device->SerialNumber = (int)(256 * (int)rcvbuf[1] + rcvbuf[2]); - device->FirmwareVersionMajor = rcvbuf[3]; - device->FirmwareVersionMinor = rcvbuf[4]; - memcpy(device->IPaddress, rcvbuf + 5, 4); - device->DHCP = rcvbuf[9]; - memcpy(device->hostIP, rcvbuf + 10, 4); - device->HWtype = 0; - - nrOfDetectedBoards++; - status = 0; - - if (serialNumberToFind == device->SerialNumber) break; - } else if (status == 19) - { - // Parse the response - debug_printf("Received response from 58 series device...\n"); - - // Save the device info - device = &devices[nrOfDetectedBoards]; - //device->userID = rcvbuf[0]; - device->SerialNumber = (int)rcvbuf[14] + ((int)rcvbuf[15] << 8) + ((int)rcvbuf[16] << 16) + ((int)rcvbuf[17] << 24); - device->FirmwareVersionMajor = rcvbuf[3]; - device->FirmwareVersionMinor = rcvbuf[4]; - memcpy(device->IPaddress, rcvbuf + 5, 4); - device->DHCP = rcvbuf[9]; - memcpy(device->hostIP, rcvbuf + 10, 4); - device->HWtype = rcvbuf[18]; - - debug_printf(" User ID: %u\n", rcvbuf[0]); - debug_printf(" Serial: %u\n", device->SerialNumber); - debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); - debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], rcvbuf[7], rcvbuf[8]); - debug_printf(" DHCP: %u\n", rcvbuf[9]); - debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], rcvbuf[12], rcvbuf[13]); - - nrOfDetectedBoards++; - status = 0; - - if (serialNumberToFind == device->SerialNumber) break; - } - } - else - { - if (nrOfDetectedBoards == 0) - { - debug_printf("\n No Boards detected\n"); - } - } - + debug_printf("Retrieving data...\n"); + status = recv(txSocket, (char *)rcvbuf, sizeof(rcvbuf), 0); + if (status < 0) { + debug_printf("Error receiving data...\n"); + break; } + // Get IP address and receive message + if (status > 0) { + if (status == 14) { + // Parse the response + debug_printf("Received response...\n"); + + debug_printf(" User ID: %u\n", rcvbuf[0]); + debug_printf(" Serial: %u\n", (int)(256 * (int)rcvbuf[1] + rcvbuf[2])); + debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); + debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], + rcvbuf[7], rcvbuf[8]); + debug_printf(" DHCP: %u\n", rcvbuf[9]); + debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], + rcvbuf[12], rcvbuf[13]); + + // Save the device info + device = &devices[nrOfDetectedBoards]; + // device->userID = rcvbuf[0]; + device->SerialNumber = (int)(256 * (int)rcvbuf[1] + rcvbuf[2]); + device->FirmwareVersionMajor = rcvbuf[3]; + device->FirmwareVersionMinor = rcvbuf[4]; + memcpy(device->IPaddress, rcvbuf + 5, 4); + device->DHCP = rcvbuf[9]; + memcpy(device->hostIP, rcvbuf + 10, 4); + device->HWtype = 0; + + nrOfDetectedBoards++; + status = 0; + + if (serialNumberToFind == device->SerialNumber) + break; + } else if (status == 19) { + // Parse the response + debug_printf("Received response from 58 series device...\n"); + + // Save the device info + device = &devices[nrOfDetectedBoards]; + // device->userID = rcvbuf[0]; + device->SerialNumber = (int)rcvbuf[14] + ((int)rcvbuf[15] << 8) + + ((int)rcvbuf[16] << 16) + + ((int)rcvbuf[17] << 24); + device->FirmwareVersionMajor = rcvbuf[3]; + device->FirmwareVersionMinor = rcvbuf[4]; + memcpy(device->IPaddress, rcvbuf + 5, 4); + device->DHCP = rcvbuf[9]; + memcpy(device->hostIP, rcvbuf + 10, 4); + device->HWtype = rcvbuf[18]; + + debug_printf(" User ID: %u\n", rcvbuf[0]); + debug_printf(" Serial: %u\n", device->SerialNumber); + debug_printf(" Version: %u.%u\n", rcvbuf[3], rcvbuf[4]); + debug_printf(" IP address: %u.%u.%u.%u\n", rcvbuf[5], rcvbuf[6], + rcvbuf[7], rcvbuf[8]); + debug_printf(" DHCP: %u\n", rcvbuf[9]); + debug_printf(" Host IP address: %u.%u.%u.%u\n", rcvbuf[10], rcvbuf[11], + rcvbuf[12], rcvbuf[13]); + + nrOfDetectedBoards++; + status = 0; + + if (serialNumberToFind == device->SerialNumber) + break; + } + } else { + if (nrOfDetectedBoards == 0) { + debug_printf("\n No Boards detected\n"); + } + } + } #ifdef WIN32 - closesocket(txSocket); + closesocket(txSocket); #else - close(txSocket); + close(txSocket); #endif - return nrOfDetectedBoards; + return nrOfDetectedBoards; } -sPoKeysDevice* PK_ConnectToNetworkDevice(sPoKeysNetworkDeviceSummary * device) -{ - int result; +sPoKeysDevice *PK_ConnectToNetworkDevice(sPoKeysNetworkDeviceSummary *device) { + int result; #ifdef WIN32 - int t = 100; // 100 ms timeout + int t = 100; // 100 ms timeout #endif - // Create target endpoint - //struct sockaddr_in * remoteEP; - uint32 addr ; - - // Create temporary device object - sPoKeysDevice * tmpDevice; + // Create target endpoint + // struct sockaddr_in * remoteEP; + uint32 addr; - if (device == NULL) return NULL; + // Create temporary device object + sPoKeysDevice *tmpDevice; - tmpDevice = (sPoKeysDevice*)malloc(sizeof(sPoKeysDevice)); - tmpDevice->devHandle2 = malloc(sizeof(struct sockaddr_in)); + if (device == NULL) + return NULL; - tmpDevice->connectionType = PK_DeviceType_NetworkDevice; // Network device - tmpDevice->connectionParam = device->useUDP; + tmpDevice = (sPoKeysDevice *)malloc(sizeof(sPoKeysDevice)); + tmpDevice->devHandle2 = malloc(sizeof(struct sockaddr_in)); - addr = (uint32)device->IPaddress[0] + ((uint32)device->IPaddress[1] << 8) + ((uint32)device->IPaddress[2] << 16) + ((uint32)device->IPaddress[3] << 24); - // Set up the RecvAddr structure with the broadcast ip address and correct port number - ((struct sockaddr_in*)tmpDevice->devHandle2)->sin_family = AF_INET; - ((struct sockaddr_in*)tmpDevice->devHandle2)->sin_port = htons(20055); - ((struct sockaddr_in*)tmpDevice->devHandle2)->sin_addr.s_addr = addr; + tmpDevice->connectionType = PK_DeviceType_NetworkDevice; // Network device + tmpDevice->connectionParam = device->useUDP; -#ifdef WIN32 - if (InitWinsock() != 0) - { - debug_printf("InitWinsock error!"); - return 0; - } + addr = (uint32)device->IPaddress[0] + ((uint32)device->IPaddress[1] << 8) + + ((uint32)device->IPaddress[2] << 16) + + ((uint32)device->IPaddress[3] << 24); + // Set up the RecvAddr structure with the broadcast ip address and correct + // port number + ((struct sockaddr_in *)tmpDevice->devHandle2)->sin_family = AF_INET; + ((struct sockaddr_in *)tmpDevice->devHandle2)->sin_port = htons(20055); + ((struct sockaddr_in *)tmpDevice->devHandle2)->sin_addr.s_addr = addr; +#ifdef WIN32 + if (InitWinsock() != 0) { + debug_printf("InitWinsock error!"); + return 0; + } + + if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) { + tmpDevice->devHandle = (void *)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + } else { + tmpDevice->devHandle = (void *)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + } + + if ((SOCKET)tmpDevice->devHandle == -1) +#else + tmpDevice->devHandle = malloc(sizeof(int)); + if (tmpDevice->devHandle == NULL) + return NULL; - if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) - { - tmpDevice->devHandle = (void*)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - } else - { - tmpDevice->devHandle = (void*)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - } + if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) + *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + else + *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if ((SOCKET)tmpDevice->devHandle == -1) -#else - tmpDevice->devHandle = malloc(sizeof(int)); - if (tmpDevice->devHandle == NULL) return NULL; - - if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) - *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - else - *(int *)tmpDevice->devHandle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - - if ((*(int *)tmpDevice->devHandle) == -1) + if ((*(int *)tmpDevice->devHandle) == -1) #endif - { - //CleanDevice(tmpDevice); + { +// CleanDevice(tmpDevice); #ifndef WIN32 - free(tmpDevice->devHandle); + free(tmpDevice->devHandle); #endif - free(tmpDevice); + free(tmpDevice); - return NULL; // Couldn't create the socket - } + return NULL; // Couldn't create the socket + } #ifdef WIN32 - // Set socket options - setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t)); - setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t)); + // Set socket options + setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, + sizeof(t)); + setsockopt((SOCKET)tmpDevice->devHandle, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, + sizeof(t)); #endif - - // Connect to target IP +// Connect to target IP #ifdef WIN32 - if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) - result = connect((SOCKET)tmpDevice->devHandle, (SOCKADDR *)tmpDevice->devHandle2, sizeof(struct sockaddr_in)); - else - result = 0; + if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) + result = + connect((SOCKET)tmpDevice->devHandle, (SOCKADDR *)tmpDevice->devHandle2, + sizeof(struct sockaddr_in)); + else + result = 0; #else - result = 0; - if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) - result = connect(*(int *)tmpDevice->devHandle, (struct sockaddr *)tmpDevice->devHandle2, sizeof(struct sockaddr_in)); - else - result = 0; - + result = 0; + if (tmpDevice->connectionParam != PK_ConnectionParam_UDP) + result = connect(*(int *)tmpDevice->devHandle, + (struct sockaddr *)tmpDevice->devHandle2, + sizeof(struct sockaddr_in)); + else + result = 0; + #endif - if (result == -1) - { - debug_printf(" ERROR"); - //CleanDevice(tmpDevice); + if (result == -1) { + debug_printf(" ERROR"); +// CleanDevice(tmpDevice); #ifdef WIN32 - closesocket((SOCKET)tmpDevice->devHandle); + closesocket((SOCKET)tmpDevice->devHandle); #else - close(*(int *)tmpDevice->devHandle); - free(tmpDevice->devHandle); + close(*(int *)tmpDevice->devHandle); + free(tmpDevice->devHandle); #endif - free(tmpDevice); + free(tmpDevice); - return NULL; // Couldn't connect - } + return NULL; // Couldn't connect + } #ifdef WIN32 - if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) - { - // Setup socket to be unblocking - u_long iMode = TRUE; - ioctlsocket((SOCKET)tmpDevice->devHandle, FIONBIO, &iMode); - } + if (tmpDevice->connectionParam == PK_ConnectionParam_UDP) { + // Setup socket to be unblocking + u_long iMode = TRUE; + ioctlsocket((SOCKET)tmpDevice->devHandle, FIONBIO, &iMode); + } #endif - debug_printf(" Connected\n"); + debug_printf(" Connected\n"); - debug_printf("Initializing the device object... "); - InitializeNewDevice(tmpDevice); - debug_printf("done\n"); + debug_printf("Initializing the device object... "); + InitializeNewDevice(tmpDevice); + debug_printf("done\n"); - - //printf("Connected to PoKeys device at %s", addrBuf); - return tmpDevice; + // printf("Connected to PoKeys device at %s", addrBuf); + return tmpDevice; } -void PK_DisconnectNetworkDevice(sPoKeysDevice* device) -{ - if (device == NULL) return; - if (device->connectionType != PK_DeviceType_NetworkDevice) return; +void PK_DisconnectNetworkDevice(sPoKeysDevice *device) { + if (device == NULL) + return; + if (device->connectionType != PK_DeviceType_NetworkDevice) + return; - debug_printf("\nClosing connection..."); + debug_printf("\nClosing connection..."); #ifdef WIN32 - if ((SOCKET)device->devHandle) - closesocket((SOCKET)device->devHandle); + if ((SOCKET)device->devHandle) + closesocket((SOCKET)device->devHandle); #else - close(*(int *)device->devHandle); - free(device->devHandle); + close(*(int *)device->devHandle); + free(device->devHandle); #endif - // Release secondary device handle - if (device->devHandle2) - free(device->devHandle2); + // Release secondary device handle + if (device->devHandle2) + free(device->devHandle2); } +int32_t SendEthRequest(sPoKeysDevice *device) { + uint32_t retries1 = 0; + uint32_t retries2 = 0; + int result; -int32_t SendEthRequest(sPoKeysDevice* device) -{ - uint32_t retries1 = 0; - uint32_t retries2 = 0; - int result; - - fd_set fds; - struct timeval stimeout; + fd_set fds; + struct timeval stimeout; - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType != PK_DeviceType_NetworkDevice) return PK_ERR_GENERIC; - if (device->devHandle == NULL) return PK_ERR_GENERIC; + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType != PK_DeviceType_NetworkDevice) + return PK_ERR_GENERIC; + if (device->devHandle == NULL) + return PK_ERR_GENERIC; - while (1) - { - // Form the request packet - device->requestID++; + while (1) { + // Form the request packet + device->requestID++; - device->request[0] = 0xBB; - device->request[6] = device->requestID; - device->request[7] = getChecksum(device->request); + device->request[0] = 0xBB; + device->request[6] = device->requestID; + device->request[7] = getChecksum(device->request); - //memcpy(requestBuffer, device->request, 64); + // memcpy(requestBuffer, device->request, 64); - debug_printf("\nSending..."); - // Send the data + debug_printf("\nSending..."); + // Send the data - if (device->connectionParam == PK_ConnectionParam_UDP) - { + if (device->connectionParam == PK_ConnectionParam_UDP) { #ifdef WIN32 - if (sendto((SOCKET)device->devHandle, (char *)device->request, 64, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto((SOCKET)device->devHandle, (char *)device->request, 64, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #else - if (sendto(*(int*)device->devHandle, (char *)device->request, 64, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto(*(int *)device->devHandle, (char *)device->request, 64, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #endif - { - debug_printf("Error sending UDP report\nAborting...\n"); - return -1; - } - } else - { + { + debug_printf("Error sending UDP report\nAborting...\n"); + return -1; + } + } else { #ifdef WIN32 - if (send((SOCKET)device->devHandle, (char *)device->request, 64, 0) != 64) + if (send((SOCKET)device->devHandle, (char *)device->request, 64, 0) != 64) #else - if (send(*(int*)device->devHandle, (char *)device->request, 64, 0) != 64) + if (send(*(int *)device->devHandle, (char *)device->request, 64, 0) != 64) #endif - { - debug_printf("Error sending TCP report\nAborting...\n"); - return -1; - } - } + { + debug_printf("Error sending TCP report\nAborting...\n"); + return -1; + } + } - // Wait for the response - while(1) - { + // Wait for the response + while (1) { #ifdef WIN32 - FD_ZERO(&fds); - FD_SET((SOCKET)device->devHandle, &fds); - - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; - - result = select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > device->readRetries) break; - continue; - } - - //device->reserved64 = GetTickCount64(); - result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); - //device->reserved64 = GetTickCount64() - device->reserved64; - //printf("Time: %u\n", (uint32_t)device->reserved64); + FD_ZERO(&fds); + FD_SET((SOCKET)device->devHandle, &fds); + + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * device->socketTimeout; + + result = + select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > device->readRetries) + break; + continue; + } + + // device->reserved64 = GetTickCount64(); + result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); +// device->reserved64 = GetTickCount64() - device->reserved64; +// printf("Time: %u\n", (uint32_t)device->reserved64); #else - FD_ZERO(&fds); - FD_SET(*(int*)device->devHandle, &fds); + FD_ZERO(&fds); + FD_SET(*(int *)device->devHandle, &fds); + + stimeout.tv_sec = 0; - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; + stimeout.tv_usec = 1000 * device->socketTimeout; - result = select(*(int*)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + result = + select(*(int *)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > 10) break; - continue; - } + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > 10) + break; + continue; + } - //if (FD_ISSET(*(int*)device->devHandle, &fds) == 0) + // if (FD_ISSET(*(int*)device->devHandle, &fds) == 0) - result = recv(*(int*)device->devHandle, (char *)device->response, 64, 0); + result = recv(*(int *)device->devHandle, (char *)device->response, 64, 0); #endif - // 64 bytes received? - if (result == 64) - { - if (device->response[0] == 0xAA && device->response[6] == device->requestID) - { - if (device->response[7] == getChecksum(device->response)) - { - debug_printf(" Received!"); - return PK_OK; - } else - { - debug_printf("!! Wrong checksum..."); - } - } else - { - debug_printf("!! Wrong response received!"); - break; - } - } - else if (result == 0) - debug_printf("Connection closed\n"); - else + // 64 bytes received? + if (result == 64) { + if (device->response[0] == 0xAA && + device->response[6] == device->requestID) { + if (device->response[7] == getChecksum(device->response)) { + debug_printf(" Received!"); + return PK_OK; + } else { + debug_printf("!! Wrong checksum..."); + } + } else { + debug_printf("!! Wrong response received!"); + break; + } + } else if (result == 0) + debug_printf("Connection closed\n"); + else #ifdef WIN32 - debug_printf("recv failed: %d\n", WSAGetLastError()); + debug_printf("recv failed: %d\n", WSAGetLastError()); #else - debug_printf("recv failed\n"); + debug_printf("recv failed\n"); #endif - - if (++retries1 > device->readRetries) break; - } - - if (retries2++ > device->sendRetries) break; + if (++retries1 > device->readRetries) + break; } - debug_printf("Error - timeout..."); - return PK_ERR_TRANSFER; + if (retries2++ > device->sendRetries) + break; + } + debug_printf("Error - timeout..."); + return PK_ERR_TRANSFER; } -int32_t SendEthRequestBig(sPoKeysDevice* device) -{ - uint32_t retries1 = 0; - uint32_t retries2 = 0; - int result; - uint32_t i; +int32_t SendEthRequestBig(sPoKeysDevice *device) { + uint32_t retries1 = 0; + uint32_t retries2 = 0; + int result; + uint32_t i; - fd_set fds; - struct timeval stimeout; + fd_set fds; + struct timeval stimeout; - uint8_t * requestBuffer; - uint8_t * requestBufferPtr = 0; + uint8_t *requestBuffer; + uint8_t *requestBufferPtr = 0; - if (device == NULL) return PK_ERR_GENERIC; - if (device->connectionType != PK_DeviceType_NetworkDevice) return PK_ERR_GENERIC; - if (device->devHandle == NULL) return PK_ERR_GENERIC; + if (device == NULL) + return PK_ERR_GENERIC; + if (device->connectionType != PK_DeviceType_NetworkDevice) + return PK_ERR_GENERIC; + if (device->devHandle == NULL) + return PK_ERR_GENERIC; - if (device->multiPartBuffer == 0) return PK_ERR_GENERIC; - requestBuffer = device->multiPartBuffer; + if (device->multiPartBuffer == 0) + return PK_ERR_GENERIC; + requestBuffer = device->multiPartBuffer; - while (1) - { - // Form the request packet - for (i = 0; i < 8; i++) - { - requestBufferPtr = &requestBuffer[i * 64]; + while (1) { + // Form the request packet + for (i = 0; i < 8; i++) { + requestBufferPtr = &requestBuffer[i * 64]; - memcpy(requestBufferPtr, device->request, 8); - requestBufferPtr[0] = 0xBB; + memcpy(requestBufferPtr, device->request, 8); + requestBufferPtr[0] = 0xBB; - // Put packet ID and flags here... - requestBufferPtr[2] = i; - if (i == 0) - requestBufferPtr[2] |= (1<<3); - else if (i == 7) - requestBufferPtr[2] |= (1<<4); + // Put packet ID and flags here... + requestBufferPtr[2] = i; + if (i == 0) + requestBufferPtr[2] |= (1 << 3); + else if (i == 7) + requestBufferPtr[2] |= (1 << 4); - requestBufferPtr[6] = ++device->requestID; - requestBufferPtr[7] = getChecksum(requestBufferPtr); + requestBufferPtr[6] = ++device->requestID; + requestBufferPtr[7] = getChecksum(requestBufferPtr); - memcpy(requestBufferPtr + 8, device->multiPartData + i*56, 56); - } + memcpy(requestBufferPtr + 8, device->multiPartData + i * 56, 56); + } - debug_printf("\nSending..."); - // Send the data + debug_printf("\nSending..."); + // Send the data - if (device->connectionParam == PK_ConnectionParam_UDP) - { + if (device->connectionParam == PK_ConnectionParam_UDP) { #ifdef WIN32 - if (sendto((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #else - if (sendto(*(int*)device->devHandle, (char *)requestBuffer, 512, 0, (SOCKADDR *)device->devHandle2, sizeof(struct sockaddr_in)) == -1) + if (sendto(*(int *)device->devHandle, (char *)requestBuffer, 512, 0, + (SOCKADDR *)device->devHandle2, + sizeof(struct sockaddr_in)) == -1) #endif - { - debug_printf("Error sending UDP report\nAborting...\n"); - return -1; - } - } else - { + { + debug_printf("Error sending UDP report\nAborting...\n"); + return -1; + } + } else { #ifdef WIN32 - if (send((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0) != 512) + if (send((SOCKET)device->devHandle, (char *)requestBuffer, 512, 0) != 512) #else - if (send(*(int*)device->devHandle, (char *)requestBuffer, 512, 0) != 512) + if (send(*(int *)device->devHandle, (char *)requestBuffer, 512, 0) != 512) #endif - { - debug_printf("Error sending TCP report\nAborting...\n"); - return -1; - } - } + { + debug_printf("Error sending TCP report\nAborting...\n"); + return -1; + } + } - // Wait for the response - while(1) - { + // Wait for the response + while (1) { #ifdef WIN32 - FD_ZERO(&fds); - FD_SET((SOCKET)device->devHandle, &fds); + FD_ZERO(&fds); + FD_SET((SOCKET)device->devHandle, &fds); - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * device->socketTimeout; - result = select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + result = + select((SOCKET)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > device->readRetries) break; - continue; - } + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > device->readRetries) + break; + continue; + } - result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); + result = recv((SOCKET)device->devHandle, (char *)device->response, 64, 0); #else - FD_ZERO(&fds); - FD_SET(*(int*)device->devHandle, &fds); + FD_ZERO(&fds); + FD_SET(*(int *)device->devHandle, &fds); - stimeout.tv_sec = 0; - stimeout.tv_usec = 1000 * device->socketTimeout; + stimeout.tv_sec = 0; + stimeout.tv_usec = 1000 * device->socketTimeout; - result = select(*(int*)device->devHandle + 1, &fds, NULL, NULL, &stimeout); + result = + select(*(int *)device->devHandle + 1, &fds, NULL, NULL, &stimeout); - if (result == 0 || result == -1) - { - // Timeout... - debug_printf("Timeout!"); - if (++retries1 > 10) break; - continue; - } + if (result == 0 || result == -1) { + // Timeout... + debug_printf("Timeout!"); + if (++retries1 > 10) + break; + continue; + } - result = recv(*(int*)device->devHandle, (char *)device->response, 64, 0); + result = recv(*(int *)device->devHandle, (char *)device->response, 64, 0); #endif - // 64 bytes received? - if (result == 64) - { - if (device->response[0] == 0xAA && device->response[6] == device->requestID) - { - if (device->response[7] == getChecksum(device->response)) - { - debug_printf(" Received!"); - return PK_OK; - } else - { - debug_printf("!! Wrong checksum..."); - } - } else - { - debug_printf("!! Wrong response received!"); - break; - } - } - else if (result == 0) - debug_printf("Connection closed\n"); - else + // 64 bytes received? + if (result == 64) { + if (device->response[0] == 0xAA && + device->response[6] == device->requestID) { + if (device->response[7] == getChecksum(device->response)) { + debug_printf(" Received!"); + return PK_OK; + } else { + debug_printf("!! Wrong checksum..."); + } + } else { + debug_printf("!! Wrong response received!"); + break; + } + } else if (result == 0) + debug_printf("Connection closed\n"); + else #ifdef WIN32 - debug_printf("recv failed: %d\n", WSAGetLastError()); + debug_printf("recv failed: %d\n", WSAGetLastError()); #else - debug_printf("recv failed\n"); + debug_printf("recv failed\n"); #endif - - if (++retries1 > device->readRetries) break; - } - - if (retries2++ > device->sendRetries) break; + if (++retries1 > device->readRetries) + break; } - debug_printf("Error - timeout..."); - return PK_ERR_TRANSFER; + if (retries2++ > device->sendRetries) + break; + } + debug_printf("Error - timeout..."); + return PK_ERR_TRANSFER; } - -void PK_SetEthernetRetryCountAndTimeout(sPoKeysDevice * device, uint32_t sendRetries, uint32_t readRetries, uint32_t timeout) -{ - device->sendRetries = sendRetries; - device->readRetries = readRetries; - device->socketTimeout = timeout; +void PK_SetEthernetRetryCountAndTimeout(sPoKeysDevice *device, + uint32_t sendRetries, + uint32_t readRetries, + uint32_t timeout) { + device->sendRetries = sendRetries; + device->readRetries = readRetries; + device->socketTimeout = timeout; } - diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index 0a3c431..5397190 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -5,10 +5,17 @@ #include "elements/attributes/attribute.h" #include "pokeyDevice.h" +using namespace std::chrono_literals; + +std::mutex PokeyDevice::_BigPokeyLock; + PokeyDevice::PokeyDevice(sPoKeysNetworkDeviceSummary deviceSummary, uint8_t index) { + std::lock_guard pokeyLock(_BigPokeyLock); + _callbackArg = NULL; _enqueueCallback = NULL; + _pokey = PK_ConnectToNetworkDevice(&deviceSummary); if (!_pokey) @@ -56,6 +63,8 @@ void PokeyDevice::setCallbackInfo(EnqueueEventHandler enqueueCallback, void *cal void PokeyDevice::DigitalIOTimerCallback(uv_timer_t *timer, int status) { + std::lock_guard pokeyLock(_BigPokeyLock); + PokeyDevice *self = static_cast(timer->data); int encoderRetValue = PK_EncoderValuesGet(self->_pokey); @@ -152,23 +161,84 @@ void PokeyDevice::addPin(std::string pinName, int pinNumber, std::string pinType _pins[portNumber].value = defaultValue; _pins[portNumber].description = description; } + +uint32_t msToTicks(uint32_t ms) +{ + return (ms * 1000000) / 40; +} void PokeyDevice::addPWM(uint8_t channel, std::string name, std::string description, std::string units, uint32_t dutyCycle, uint32_t period) { + std::lock_guard pokeyLock(_BigPokeyLock); _pwmChannels[channel] = true; float ms = _pokey->info.PWMinternalFrequency / 1000; PK_PWMConfigurationGet(_pokey); - _pokey->PWM.PWMperiod = (ms * period); - _pokey->PWM.PWMduty[channel] = (ms * dutyCycle); + // _pokey->PWM.PWMperiod = (ms * period); + _pokey->PWM.PWMperiod = 250000; _pokey->PWM.PWMenabledChannels[channel] = true; int ret = PK_PWMConfigurationSet(_pokey); - printf("---> ret %i\n", ret); + //_pokey->PWM.PWMduty[channel] = PWM_SERVO_LEFT; + PK_SL_PWM_SetDuty(_pokey, channel, PWM_SERVO_LEFT); + int t = PK_PWMUpdate(_pokey); + std::this_thread::sleep_for(20ms); - PK_PWMUpdate(_pokey); + printf(". %i\n", t); + _pokey->PWM.PWMenabledChannels[channel] = false; + PK_PWMConfigurationSet(_pokey); + + // // std::this_thread::sleep_for(100ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + // // std::this_thread::sleep_for(100ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + // // std::this_thread::sleep_for(10ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + // // std::this_thread::sleep_for(10ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + std::this_thread::sleep_for(1000ms); + + _pokey->PWM.PWMenabledChannels[channel] = true; + PK_PWMConfigurationSet(_pokey); + t = PK_SL_PWM_SetDuty(_pokey, channel, PWM_SERVO_RIGHT); + t = PK_PWMUpdate(_pokey); + std::this_thread::sleep_for(20ms); + printf(". %i\n", t); + _pokey->PWM.PWMenabledChannels[channel] = false; + PK_PWMConfigurationSet(_pokey); + + // std::this_thread::sleep_for(10ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + // std::this_thread::sleep_for(10ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + // std::this_thread::sleep_for(10ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); + + // std::this_thread::sleep_for(10ms); + // t = PK_PWMUpdate(_pokey); + // printf(". %i\n", t); mapNameToPWM(name.c_str(), channel); _pwm[channel].name = name; @@ -255,6 +325,7 @@ bool PokeyDevice::validateEncoder(int encoderNumber) bool PokeyDevice::isEncoderCapable(int pin) { + std::lock_guard pokeyLock(_BigPokeyLock); switch (pin) { case 1: @@ -281,6 +352,8 @@ void PokeyDevice::addEncoder( { assert(encoderNumber >= 1); + std::lock_guard pokeyLock(_BigPokeyLock); + PK_EncoderConfigurationGet(_pokey); int encoderIndex = encoderNumber - 1; @@ -342,6 +415,8 @@ void PokeyDevice::addEncoder( void PokeyDevice::addMatrixLED(int id, std::string name, std::string type) { + std::lock_guard pokeyLock(_BigPokeyLock); + PK_MatrixLEDConfigurationGet(_pokey); _matrixLED[id].name = name; _matrixLED[id].type = type; @@ -359,6 +434,8 @@ void PokeyDevice::addGroupToMatrixLED(int id, int displayId, std::string name, i void PokeyDevice::configMatrixLED(int id, int rows, int cols, int enabled) { + std::lock_guard pokeyLock(_BigPokeyLock); + _pokey->MatrixLED[id].rows = rows; _pokey->MatrixLED[id].columns = cols; _pokey->MatrixLED[id].displayEnabled = enabled; @@ -387,9 +464,12 @@ using namespace std::chrono_literals; uint32_t PokeyDevice::targetValue(std::string targetName, float value) { + std::lock_guard pokeyLock(_BigPokeyLock); + uint8_t channel = PWMFromName(targetName); uint32_t ms = _pokey->info.PWMinternalFrequency / 1000; + // value goes between 0 and about 710. uint32_t duty = (3 * value) / 700; duty *= ms; @@ -405,6 +485,8 @@ uint32_t PokeyDevice::targetValue(std::string targetName, float value) uint32_t PokeyDevice::targetValue(std::string targetName, bool value) { + std::lock_guard pokeyLock(_BigPokeyLock); + uint32_t retValue = -1; uint8_t pin = pinFromName(targetName) - 1; @@ -427,6 +509,8 @@ uint32_t PokeyDevice::targetValue(std::string targetName, bool value) uint8_t PokeyDevice::displayNumber(uint8_t displayNumber, std::string targetName, int value) { + std::lock_guard pokeyLock(_BigPokeyLock); + int groupIndex = 0; for (int i = 0; i < MAX_MATRIX_LED_GROUPS; i++) { @@ -483,18 +567,21 @@ uint8_t PokeyDevice::displayNumber(uint8_t displayNumber, std::string targetName uint32_t PokeyDevice::outputPin(uint8_t pin) { + std::lock_guard pokeyLock(_BigPokeyLock); _pokey->Pins[--pin].PinFunction = PK_PinCap_digitalOutput | PK_PinCap_invertPin; return PK_PinConfigurationSet(_pokey); } uint32_t PokeyDevice::inputPin(uint8_t pin) { + std::lock_guard pokeyLock(_BigPokeyLock); _pokey->Pins[--pin].PinFunction = PK_PinCap_digitalInput; return PK_PinConfigurationSet(_pokey); } int32_t PokeyDevice::name(std::string name) { + std::lock_guard pokeyLock(_BigPokeyLock); strncpy((char *)_pokey->DeviceData.DeviceName, name.c_str(), 30); return PK_DeviceNameSet(_pokey); } @@ -559,10 +646,12 @@ void PokeyDevice::mapNameToMatrixLED(std::string name, int id) bool PokeyDevice::isPinDigitalOutput(uint8_t pin) { + std::lock_guard pokeyLock(_BigPokeyLock); return (bool)PK_CheckPinCapability(_pokey, pin, PK_AllPinCap_digitalOutput); } bool PokeyDevice::isPinDigitalInput(uint8_t pin) { + std::lock_guard pokeyLock(_BigPokeyLock); return (bool)PK_CheckPinCapability(_pokey, pin, PK_AllPinCap_digitalInput); } diff --git a/src/libs/plugins/pokey/pokeyDevice.h b/src/libs/plugins/pokey/pokeyDevice.h index 4f56b83..e933b7b 100644 --- a/src/libs/plugins/pokey/pokeyDevice.h +++ b/src/libs/plugins/pokey/pokeyDevice.h @@ -4,9 +4,11 @@ #include "PoKeysLib.h" #include "common/simhubdeviceplugin.h" #include +#include #include #include #include +#include #include #include #include @@ -30,6 +32,10 @@ #define MAX_DIGITS 10 #define MAX_PWM_CHANNELS 6 +#define PWM_SERVO_LEFT 50000 +#define PWM_SERVO_RIGHT 25000 +#define PWM_SERVO_CENTER 37500 + typedef struct { std::string pinName; int pinNumber; @@ -100,6 +106,7 @@ class PokeyDevice std::map _encoderMap; std::map _displayMap; std::map _pwmMap; + static std::mutex _BigPokeyLock; sPoKeysDevice *_pokey; void *_callbackArg; From 38dc855e8b0cdc7277c1fe64706e20daf0af4b06 Mon Sep 17 00:00:00 2001 From: Marten Payne Date: Tue, 24 Oct 2017 13:38:39 +1100 Subject: [PATCH 07/11] WIP Commit - got it pushing servo to correct position - not yet able to make it repeatable --- bin/config/pokey.cfg | 9 +-- bin/config/prepare3d.cfg | 4 +- src/libs/plugins/pokey/main.cpp | 16 +++-- src/libs/plugins/pokey/pokeyDevice.cpp | 94 ++++++++++++++++++-------- src/libs/plugins/pokey/pokeyDevice.h | 34 ++++++++-- 5 files changed, 111 insertions(+), 46 deletions(-) diff --git a/bin/config/pokey.cfg b/bin/config/pokey.cfg index 821eef4..ae412b2 100644 --- a/bin/config/pokey.cfg +++ b/bin/config/pokey.cfg @@ -295,17 +295,18 @@ configuration = ) }, { - serialNumber="26766", + serialNumber="26733", name = "test PWM", pins = (), pwm= ( { - channel =0, + channel = 5, name = "G_OH_EGT", decription = "APU Exhaust Gas Temp", units = "degrees", - dutyCycle = 1.00, - period = 20 # milliseconds + leftDutyCycle = 62000, + rightDutyCycle = 22000, + period = 500000 # hw cycles } ) } diff --git a/bin/config/prepare3d.cfg b/bin/config/prepare3d.cfg index 157bd8b..4aa4e15 100644 --- a/bin/config/prepare3d.cfg +++ b/bin/config/prepare3d.cfg @@ -1,8 +1,8 @@ configuration = ( { type="prepare3d", - ipAddress= "192.168.2.2", - # ipAddress= "127.0.0.1", + ipAddress= "127.0.0.1", + # ipAddress= "192.168.2.2", port = 8091, transforms = { # S_OH_STANDBY_POWER = { On = "Auto", Off = "Bat" }, diff --git a/src/libs/plugins/pokey/main.cpp b/src/libs/plugins/pokey/main.cpp index f0cad35..14d09ad 100644 --- a/src/libs/plugins/pokey/main.cpp +++ b/src/libs/plugins/pokey/main.cpp @@ -220,7 +220,6 @@ bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *p int PWMLength = pwm->getLength(); if (PWMLength > 0) { - _logger(LOG_INFO, " [%s] - Found %i PWM Channels", pokeyDevice->name().c_str(), PWMLength); for (libconfig::SettingIterator iter = pwm->begin(); iter != pwm->end(); iter++) { @@ -228,15 +227,17 @@ bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *p std::string name = ""; std::string description = ""; std::string units = ""; - float dutyCycle = 1.5; // percent - uint32_t period = 20; // milliseconds + uint32_t leftDutyCycle = 0; + uint32_t rightDutyCycle = 0; + uint32_t period = 250000; // pokey clock cycles try { iter->lookupValue("channel", channel); iter->lookupValue("name", name); iter->lookupValue("description", description); iter->lookupValue("units", units); - iter->lookupValue("dutyCycle", dutyCycle); + iter->lookupValue("leftDutyCycle", leftDutyCycle); + iter->lookupValue("rightDutyCycle", rightDutyCycle); iter->lookupValue("period", period); } catch (const libconfig::SettingNotFoundException &nfex) { @@ -244,8 +245,13 @@ bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *p } if (addTargetToDeviceTargetList(name, pokeyDevice)) { - pokeyDevice->addPWM(channel, name, description, units, dutyCycle, period); + pokeyDevice->addPWM(channel, name, description, units, leftDutyCycle, rightDutyCycle, period); _logger(LOG_INFO, " - Added PWM channel %i - %s", channel, name.c_str()); + + pokeyDevice->targetValue(name, 0.0f); + + pokeyDevice->targetValue(name, 0.5f); + pokeyDevice->targetValue(name, 1.0f); } } } diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index 5397190..ec4b858 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -18,8 +18,9 @@ PokeyDevice::PokeyDevice(sPoKeysNetworkDeviceSummary deviceSummary, uint8_t inde _pokey = PK_ConnectToNetworkDevice(&deviceSummary); - if (!_pokey) + if (!_pokey) { throw std::exception(); + } _index = index; _userId = deviceSummary.UserID; @@ -146,12 +147,15 @@ void PokeyDevice::DigitalIOTimerCallback(uv_timer_t *timer, int status) void PokeyDevice::addPin(std::string pinName, int pinNumber, std::string pinType, int defaultValue, std::string description) { - if (pinType == "DIGITAL_OUTPUT") + if (pinType == "DIGITAL_OUTPUT") { outputPin(pinNumber); - if (pinType == "DIGITAL_INPUT") + } + else if (pinType == "DIGITAL_INPUT") { inputPin(pinNumber); + } mapNameToPin(pinName.c_str(), pinNumber); + int portNumber = pinNumber - 1; _pins[portNumber].pinName = pinName; @@ -166,11 +170,20 @@ uint32_t msToTicks(uint32_t ms) { return (ms * 1000000) / 40; } -void PokeyDevice::addPWM(uint8_t channel, std::string name, std::string description, std::string units, uint32_t dutyCycle, uint32_t period) + +void PokeyDevice::addPWM( + uint8_t channel, + std::string name, + std::string description, + std::string units, + uint32_t leftDutyCycle, + uint32_t rightDutyCycle, + uint32_t period) { + _pwmChannels[channel] = true; + /* std::lock_guard pokeyLock(_BigPokeyLock); - _pwmChannels[channel] = true; float ms = _pokey->info.PWMinternalFrequency / 1000; PK_PWMConfigurationGet(_pokey); @@ -181,14 +194,18 @@ void PokeyDevice::addPWM(uint8_t channel, std::string name, std::string descript int ret = PK_PWMConfigurationSet(_pokey); - //_pokey->PWM.PWMduty[channel] = PWM_SERVO_LEFT; - PK_SL_PWM_SetDuty(_pokey, channel, PWM_SERVO_LEFT); - int t = PK_PWMUpdate(_pokey); - std::this_thread::sleep_for(20ms); + int left_duty = 62000; + int centre_duty = 42000; + int right_duty = 22000; - printf(". %i\n", t); - _pokey->PWM.PWMenabledChannels[channel] = false; - PK_PWMConfigurationSet(_pokey); + //PK_SL_PWM_SetDuty(_pokey, channel, centre_duty); + //PK_SL_PWM_SetDuty(_pokey, channel, left_duty); + //PK_SL_PWM_SetDuty(_pokey, channel, right_duty); + int t = PK_PWMUpdate(_pokey); + + //printf(". %i\n", t); + //_pokey->PWM.PWMenabledChannels[channel] = false; + //PK_PWMConfigurationSet(_pokey); // // std::this_thread::sleep_for(100ms); // t = PK_PWMUpdate(_pokey); @@ -214,7 +231,10 @@ void PokeyDevice::addPWM(uint8_t channel, std::string name, std::string descript // printf(". %i\n", t); std::this_thread::sleep_for(1000ms); - + // PK_SL_PWM_SetDuty(_pokey, channel, left_duty); + // PK_PWMUpdate(_pokey); + // std::this_thread::sleep_for(1000ms); + _pokey->PWM.PWMenabledChannels[channel] = true; PK_PWMConfigurationSet(_pokey); t = PK_SL_PWM_SetDuty(_pokey, channel, PWM_SERVO_RIGHT); @@ -239,13 +259,19 @@ void PokeyDevice::addPWM(uint8_t channel, std::string name, std::string descript // std::this_thread::sleep_for(10ms); // t = PK_PWMUpdate(_pokey); // printf(". %i\n", t); - + */ mapNameToPWM(name.c_str(), channel); _pwm[channel].name = name; _pwm[channel].description = description; _pwm[channel].units = units; - _pwm[channel].dutyCycle = dutyCycle; + _pwm[channel].leftDutyCycle = leftDutyCycle; + _pwm[channel].rightDutyCycle = rightDutyCycle; _pwm[channel].period = period; + + PK_PWMConfigurationGet(_pokey); + _pokey->PWM.PWMperiod = _pwm[channel].period; + _pokey->PWM.PWMenabledChannels[channel] = true; + int ret = PK_PWMConfigurationSet(_pokey); } void PokeyDevice::startPolling() @@ -285,6 +311,7 @@ std::string PokeyDevice::hardwareTypeString() if (_hardwareType == 31) { return "Pokey 57E"; } + return "Unknown"; } @@ -348,7 +375,15 @@ bool PokeyDevice::isEncoderCapable(int pin) } void PokeyDevice::addEncoder( - int encoderNumber, uint32_t defaultValue, std::string name, std::string description, int min, int max, int step, int invertDirection, std::string units) + int encoderNumber, + uint32_t defaultValue, + std::string name, + std::string description, + int min, + int max, + int step, + int invertDirection, + std::string units) { assert(encoderNumber >= 1); @@ -464,21 +499,22 @@ using namespace std::chrono_literals; uint32_t PokeyDevice::targetValue(std::string targetName, float value) { - std::lock_guard pokeyLock(_BigPokeyLock); + //std::lock_guard pokeyLock(_BigPokeyLock); uint8_t channel = PWMFromName(targetName); - uint32_t ms = _pokey->info.PWMinternalFrequency / 1000; - - // value goes between 0 and about 710. - uint32_t duty = (3 * value) / 700; - duty *= ms; - - _pokey->PWM.PWMenabledChannels[channel] = true; - // int ret = PK_PWMConfigurationSet(_pokey); - - printf("---> duty %d, ret %.3f \n", duty, value); + // value is percent, so calculate cycles back from left cycle count + uint32_t duty = _pwm[channel].leftDutyCycle - ((_pwm[channel].leftDutyCycle - _pwm[channel].rightDutyCycle) * value); + //_pokey->PWM.PWMenabledChannels[channel] = true; + PK_SL_PWM_SetDuty(_pokey, channel, duty); PK_PWMUpdate(_pokey); + std::this_thread::sleep_for(1000ms); + //_pokey->PWM.PWMperiod = 0; + //_pokey->PWM.PWMenabledChannels[channel] = false; + //PK_PWMConfigurationSet(_pokey); + PK_SL_PWM_SetDuty(_pokey, channel, 0); + PK_PWMUpdate(_pokey); + std::this_thread::sleep_for(100ms); return 0; } @@ -537,7 +573,6 @@ uint8_t PokeyDevice::displayNumber(uint8_t displayNumber, std::string targetName } if (numberOfChars <= groupLength) { - for (int i = 0; i < numberOfChars; i++) { int displayOffset = (int)charString.at(i) - 48; int convertedValue = _intToDisplayRow[displayOffset]; @@ -614,8 +649,7 @@ int PokeyDevice::pinFromName(std::string targetName) uint8_t PokeyDevice::PWMFromName(std::string targetName) { - std::map::iterator it; - it = _pwmMap.find(targetName); + std::map::iterator it = _pwmMap.find(targetName); if (it != _pwmMap.end()) { return it->second; diff --git a/src/libs/plugins/pokey/pokeyDevice.h b/src/libs/plugins/pokey/pokeyDevice.h index e933b7b..11ac2a7 100644 --- a/src/libs/plugins/pokey/pokeyDevice.h +++ b/src/libs/plugins/pokey/pokeyDevice.h @@ -81,7 +81,8 @@ typedef struct { std::string name; std::string description; uint8_t pin; - float dutyCycle; + uint32_t leftDutyCycle; + uint32_t rightDutyCycle; uint32_t period; } device_pwm_t; @@ -147,6 +148,7 @@ class PokeyDevice uint32_t targetValue(std::string targetName, bool value); uint32_t targetValue(std::string targetName, int value); uint32_t targetValue(std::string targetName, float value); + uint32_t inputPin(uint8_t pin); uint32_t outputPin(uint8_t pin); int32_t name(std::string name); @@ -181,10 +183,32 @@ class PokeyDevice bool isPinDigitalOutput(uint8_t pin); bool isPinDigitalInput(uint8_t pin); bool isEncoderCapable(int pin); - void addPin(std::string name, int pinNumber, std::string pinType, int defaultValue = 0, std::string description = "None"); - void addPWM(uint8_t pinNumber, std::string name, std::string description, std::string units, uint32_t dutyCycle, uint32_t period); - void addEncoder(int encoderNumber, uint32_t defaultValue, std::string name = DEFAULT_ENCODER_NAME, std::string description = DEFAULT_ENCODER_DESCRIPTION, - int min = DEFAULT_ENCODER_MIN, int max = DEFAULT_ENCODER_MAX, int step = DEFAULT_ENCODER_STEP, int invertDirection = DEFAULT_ENCODER_DIRECTION, std::string units = ""); + + void addPin(std::string name, + int pinNumber, + std::string pinType, + int defaultValue = 0, + std::string description = "None"); + + void addPWM( + uint8_t pinNumber, + std::string name, + std::string description, + std::string units, + uint32_t leftDutyCycle, + uint32_t rightDutyCycle, + uint32_t period); + + void addEncoder( + int encoderNumber, + uint32_t defaultValue, + std::string name = DEFAULT_ENCODER_NAME, + std::string description = DEFAULT_ENCODER_DESCRIPTION, + int min = DEFAULT_ENCODER_MIN, + int max = DEFAULT_ENCODER_MAX, + int step = DEFAULT_ENCODER_STEP, + int invertDirection = DEFAULT_ENCODER_DIRECTION, + std::string units = ""); void addMatrixLED(int id, std::string name, std::string type); void configMatrixLED(int id, int rows, int cols = 8, int enabled = 0); From 767aab2fb23f545d515d4dc916bea92b865fc9fb Mon Sep 17 00:00:00 2001 From: Marten Payne Date: Sat, 28 Oct 2017 10:46:39 +1100 Subject: [PATCH 08/11] Added percentage based targetValue method for PWM servos - NOTE: use external 5v supply for these to avoid disrupting state of PoKey device --- bin/config/pokey.cfg | 2 +- src/libs/plugins/pokey/main.cpp | 5 +- src/libs/plugins/pokey/pokeyDevice.cpp | 94 +------------------------- 3 files changed, 8 insertions(+), 93 deletions(-) diff --git a/bin/config/pokey.cfg b/bin/config/pokey.cfg index ae412b2..20f7bdc 100644 --- a/bin/config/pokey.cfg +++ b/bin/config/pokey.cfg @@ -295,7 +295,7 @@ configuration = ) }, { - serialNumber="26733", + serialNumber="26701", name = "test PWM", pins = (), pwm= ( diff --git a/src/libs/plugins/pokey/main.cpp b/src/libs/plugins/pokey/main.cpp index 14d09ad..7b7dc9b 100644 --- a/src/libs/plugins/pokey/main.cpp +++ b/src/libs/plugins/pokey/main.cpp @@ -248,10 +248,13 @@ bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *p pokeyDevice->addPWM(channel, name, description, units, leftDutyCycle, rightDutyCycle, period); _logger(LOG_INFO, " - Added PWM channel %i - %s", channel, name.c_str()); + /* + // -- enable to test pokeyDevice->targetValue(name, 0.0f); - pokeyDevice->targetValue(name, 0.5f); pokeyDevice->targetValue(name, 1.0f); + pokeyDevice->targetValue(name, 0.0f); + */ } } } diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index ec4b858..05a2437 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -166,11 +166,6 @@ void PokeyDevice::addPin(std::string pinName, int pinNumber, std::string pinType _pins[portNumber].description = description; } -uint32_t msToTicks(uint32_t ms) -{ - return (ms * 1000000) / 40; -} - void PokeyDevice::addPWM( uint8_t channel, std::string name, @@ -181,86 +176,9 @@ void PokeyDevice::addPWM( uint32_t period) { _pwmChannels[channel] = true; - /* - std::lock_guard pokeyLock(_BigPokeyLock); - float ms = _pokey->info.PWMinternalFrequency / 1000; + mapNameToPWM(name.c_str(), channel); - PK_PWMConfigurationGet(_pokey); - - // _pokey->PWM.PWMperiod = (ms * period); - _pokey->PWM.PWMperiod = 250000; - _pokey->PWM.PWMenabledChannels[channel] = true; - - int ret = PK_PWMConfigurationSet(_pokey); - - int left_duty = 62000; - int centre_duty = 42000; - int right_duty = 22000; - - //PK_SL_PWM_SetDuty(_pokey, channel, centre_duty); - //PK_SL_PWM_SetDuty(_pokey, channel, left_duty); - //PK_SL_PWM_SetDuty(_pokey, channel, right_duty); - int t = PK_PWMUpdate(_pokey); - - //printf(". %i\n", t); - //_pokey->PWM.PWMenabledChannels[channel] = false; - //PK_PWMConfigurationSet(_pokey); - - // // std::this_thread::sleep_for(100ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - // // std::this_thread::sleep_for(100ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - // // std::this_thread::sleep_for(10ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - // // std::this_thread::sleep_for(10ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - std::this_thread::sleep_for(1000ms); - // PK_SL_PWM_SetDuty(_pokey, channel, left_duty); - // PK_PWMUpdate(_pokey); - // std::this_thread::sleep_for(1000ms); - - _pokey->PWM.PWMenabledChannels[channel] = true; - PK_PWMConfigurationSet(_pokey); - t = PK_SL_PWM_SetDuty(_pokey, channel, PWM_SERVO_RIGHT); - t = PK_PWMUpdate(_pokey); - std::this_thread::sleep_for(20ms); - printf(". %i\n", t); - _pokey->PWM.PWMenabledChannels[channel] = false; - PK_PWMConfigurationSet(_pokey); - - // std::this_thread::sleep_for(10ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - // std::this_thread::sleep_for(10ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - // std::this_thread::sleep_for(10ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - - // std::this_thread::sleep_for(10ms); - // t = PK_PWMUpdate(_pokey); - // printf(". %i\n", t); - */ - mapNameToPWM(name.c_str(), channel); _pwm[channel].name = name; _pwm[channel].description = description; _pwm[channel].units = units; @@ -499,22 +417,16 @@ using namespace std::chrono_literals; uint32_t PokeyDevice::targetValue(std::string targetName, float value) { - //std::lock_guard pokeyLock(_BigPokeyLock); - uint8_t channel = PWMFromName(targetName); // value is percent, so calculate cycles back from left cycle count + uint32_t duty = _pwm[channel].leftDutyCycle - ((_pwm[channel].leftDutyCycle - _pwm[channel].rightDutyCycle) * value); - //_pokey->PWM.PWMenabledChannels[channel] = true; PK_SL_PWM_SetDuty(_pokey, channel, duty); PK_PWMUpdate(_pokey); - std::this_thread::sleep_for(1000ms); - //_pokey->PWM.PWMperiod = 0; - //_pokey->PWM.PWMenabledChannels[channel] = false; - //PK_PWMConfigurationSet(_pokey); + std::this_thread::sleep_for(750ms); PK_SL_PWM_SetDuty(_pokey, channel, 0); PK_PWMUpdate(_pokey); - std::this_thread::sleep_for(100ms); return 0; } From 2ec198a58410c313df3286ea16e08b60441d0fff Mon Sep 17 00:00:00 2001 From: Marten Payne Date: Sat, 28 Oct 2017 11:46:32 +1100 Subject: [PATCH 09/11] Removed diagnostic hacked pokey access lock --- src/libs/plugins/pokey/pokeyDevice.cpp | 23 ----------------------- src/libs/plugins/pokey/pokeyDevice.h | 1 - 2 files changed, 24 deletions(-) diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index 05a2437..c649471 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -7,12 +7,8 @@ using namespace std::chrono_literals; -std::mutex PokeyDevice::_BigPokeyLock; - PokeyDevice::PokeyDevice(sPoKeysNetworkDeviceSummary deviceSummary, uint8_t index) { - std::lock_guard pokeyLock(_BigPokeyLock); - _callbackArg = NULL; _enqueueCallback = NULL; @@ -64,8 +60,6 @@ void PokeyDevice::setCallbackInfo(EnqueueEventHandler enqueueCallback, void *cal void PokeyDevice::DigitalIOTimerCallback(uv_timer_t *timer, int status) { - std::lock_guard pokeyLock(_BigPokeyLock); - PokeyDevice *self = static_cast(timer->data); int encoderRetValue = PK_EncoderValuesGet(self->_pokey); @@ -270,8 +264,6 @@ bool PokeyDevice::validateEncoder(int encoderNumber) bool PokeyDevice::isEncoderCapable(int pin) { - std::lock_guard pokeyLock(_BigPokeyLock); - switch (pin) { case 1: return (bool)PK_CheckPinCapability(_pokey, 0, PK_AllPinCap_fastEncoder1A); @@ -305,8 +297,6 @@ void PokeyDevice::addEncoder( { assert(encoderNumber >= 1); - std::lock_guard pokeyLock(_BigPokeyLock); - PK_EncoderConfigurationGet(_pokey); int encoderIndex = encoderNumber - 1; @@ -368,8 +358,6 @@ void PokeyDevice::addEncoder( void PokeyDevice::addMatrixLED(int id, std::string name, std::string type) { - std::lock_guard pokeyLock(_BigPokeyLock); - PK_MatrixLEDConfigurationGet(_pokey); _matrixLED[id].name = name; _matrixLED[id].type = type; @@ -387,8 +375,6 @@ void PokeyDevice::addGroupToMatrixLED(int id, int displayId, std::string name, i void PokeyDevice::configMatrixLED(int id, int rows, int cols, int enabled) { - std::lock_guard pokeyLock(_BigPokeyLock); - _pokey->MatrixLED[id].rows = rows; _pokey->MatrixLED[id].columns = cols; _pokey->MatrixLED[id].displayEnabled = enabled; @@ -433,8 +419,6 @@ uint32_t PokeyDevice::targetValue(std::string targetName, float value) uint32_t PokeyDevice::targetValue(std::string targetName, bool value) { - std::lock_guard pokeyLock(_BigPokeyLock); - uint32_t retValue = -1; uint8_t pin = pinFromName(targetName) - 1; @@ -457,8 +441,6 @@ uint32_t PokeyDevice::targetValue(std::string targetName, bool value) uint8_t PokeyDevice::displayNumber(uint8_t displayNumber, std::string targetName, int value) { - std::lock_guard pokeyLock(_BigPokeyLock); - int groupIndex = 0; for (int i = 0; i < MAX_MATRIX_LED_GROUPS; i++) { @@ -514,21 +496,18 @@ uint8_t PokeyDevice::displayNumber(uint8_t displayNumber, std::string targetName uint32_t PokeyDevice::outputPin(uint8_t pin) { - std::lock_guard pokeyLock(_BigPokeyLock); _pokey->Pins[--pin].PinFunction = PK_PinCap_digitalOutput | PK_PinCap_invertPin; return PK_PinConfigurationSet(_pokey); } uint32_t PokeyDevice::inputPin(uint8_t pin) { - std::lock_guard pokeyLock(_BigPokeyLock); _pokey->Pins[--pin].PinFunction = PK_PinCap_digitalInput; return PK_PinConfigurationSet(_pokey); } int32_t PokeyDevice::name(std::string name) { - std::lock_guard pokeyLock(_BigPokeyLock); strncpy((char *)_pokey->DeviceData.DeviceName, name.c_str(), 30); return PK_DeviceNameSet(_pokey); } @@ -592,12 +571,10 @@ void PokeyDevice::mapNameToMatrixLED(std::string name, int id) bool PokeyDevice::isPinDigitalOutput(uint8_t pin) { - std::lock_guard pokeyLock(_BigPokeyLock); return (bool)PK_CheckPinCapability(_pokey, pin, PK_AllPinCap_digitalOutput); } bool PokeyDevice::isPinDigitalInput(uint8_t pin) { - std::lock_guard pokeyLock(_BigPokeyLock); return (bool)PK_CheckPinCapability(_pokey, pin, PK_AllPinCap_digitalInput); } diff --git a/src/libs/plugins/pokey/pokeyDevice.h b/src/libs/plugins/pokey/pokeyDevice.h index 11ac2a7..93d9e8c 100644 --- a/src/libs/plugins/pokey/pokeyDevice.h +++ b/src/libs/plugins/pokey/pokeyDevice.h @@ -107,7 +107,6 @@ class PokeyDevice std::map _encoderMap; std::map _displayMap; std::map _pwmMap; - static std::mutex _BigPokeyLock; sPoKeysDevice *_pokey; void *_callbackArg; From 4d1ed2a8461c23497a97a8bcec60813a3eb2b851 Mon Sep 17 00:00:00 2001 From: Marten Payne Date: Sat, 28 Oct 2017 13:52:23 +1100 Subject: [PATCH 10/11] Added bits missing from last commit ... --- src/app/simhub.cpp | 4 ---- src/libs/plugins/pokey/main.cpp | 15 --------------- src/libs/plugins/pokey/main.h | 1 - src/libs/plugins/pokey/pokeyDevice.h | 4 ++-- 4 files changed, 2 insertions(+), 22 deletions(-) diff --git a/src/app/simhub.cpp b/src/app/simhub.cpp index de5e285..0654a4c 100644 --- a/src/app/simhub.cpp +++ b/src/app/simhub.cpp @@ -173,12 +173,8 @@ SimHubEventController::~SimHubEventController(void) #if defined(_AWS_SDK) void SimHubEventController::startSustainThread(void) { -==== BASE ==== -#if defined(_AWS_SDK) _awsHelper.polly()->say("Simulator is ready."); -#endif -==== BASE ==== std::shared_ptr sustainThread = std::make_shared([=] { _sustainThreadManager.setThreadRunning(true); while (!_sustainThreadManager.threadCanceled()) { diff --git a/src/libs/plugins/pokey/main.cpp b/src/libs/plugins/pokey/main.cpp index 7992e3f..643af1c 100644 --- a/src/libs/plugins/pokey/main.cpp +++ b/src/libs/plugins/pokey/main.cpp @@ -332,21 +332,6 @@ bool PokeyDevicePluginStateManager::devicePinsConfiguration(libconfig::Setting * return retVal; } -bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *pwm, std::shared_ptr pokeyDevice) -{ - bool retVal = true; - int pwmCount = pwm->getLength(); - - if (pwmCount > 0) { - _logger(LOG_INFO, " [%s] - Found %i PWM Channels", pokeyDevice->name().c_str(), pwmCount); - int encoderIndex = 0; - - for (libconfig::SettingIterator iter = pwm->begin(); iter != pwm->end(); iter++) { - } - } - - return retVal; -} bool PokeyDevicePluginStateManager::deviceEncodersConfiguration(libconfig::Setting *encoders, std::shared_ptr pokeyDevice) { diff --git a/src/libs/plugins/pokey/main.h b/src/libs/plugins/pokey/main.h index c02f161..ffd1cf0 100644 --- a/src/libs/plugins/pokey/main.h +++ b/src/libs/plugins/pokey/main.h @@ -36,7 +36,6 @@ class PokeyDevicePluginStateManager : public PluginStateManager bool deviceDisplaysConfiguration(libconfig::Setting *displays, std::shared_ptr pokeyDevice); bool devicePWMConfiguration(libconfig::Setting *pwm, std::shared_ptr pokeyDevice); int deviceDisplaysGroupsConfiguration(libconfig::Setting *displayGroups, int id, std::shared_ptr pokeyDevice, std::string type); - bool devicePWMConfiguration(libconfig::Setting *pwm, std::shared_ptr pokeyDevice); bool addTargetToDeviceTargetList(std::string, std::shared_ptr device); std::shared_ptr targetFromDeviceTargetList(std::string); void enumerateDevices(void); diff --git a/src/libs/plugins/pokey/pokeyDevice.h b/src/libs/plugins/pokey/pokeyDevice.h index adbbfb5..92e120d 100644 --- a/src/libs/plugins/pokey/pokeyDevice.h +++ b/src/libs/plugins/pokey/pokeyDevice.h @@ -116,7 +116,6 @@ class PokeyDevice device_pwm_t _pwm[MAX_PWM_CHANNELS]; device_encoder_t _encoders[MAX_ENCODERS]; device_matrixLED_t _matrixLED[MAX_MATRIX_LEDS]; - device_pwm_t _pwm[MAX_PWM_CHANNELS]; uint8_t _pwmChannels[6]; uint8_t _intToDisplayRow[MAX_DIGITS]; @@ -187,7 +186,8 @@ class PokeyDevice int pinNumber, std::string pinType, int defaultValue = 0, - std::string description = "None"); + std::string description = "None", + bool invert = false); void addPWM( uint8_t pinNumber, From 1107b30e26294dca01ec9e3173fe8d4a076c9b36 Mon Sep 17 00:00:00 2001 From: Marten Payne Date: Sat, 28 Oct 2017 22:02:08 +1100 Subject: [PATCH 11/11] Tweak a few bits - reduce the post duty cycle sleep time - make the commented out test code more interesting --- bin/config/pokey.cfg | 2 +- src/libs/plugins/pokey/main.cpp | 10 +++++++--- src/libs/plugins/pokey/pokeyDevice.cpp | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/bin/config/pokey.cfg b/bin/config/pokey.cfg index c298d55..d209b7e 100644 --- a/bin/config/pokey.cfg +++ b/bin/config/pokey.cfg @@ -316,7 +316,7 @@ configuration = decription = "APU Exhaust Gas Temp", units = "degrees", leftDutyCycle = 62000, - rightDutyCycle = 22000, + rightDutyCycle = 18000, period = 500000 # hw cycles } ) diff --git a/src/libs/plugins/pokey/main.cpp b/src/libs/plugins/pokey/main.cpp index 643af1c..ac586ab 100644 --- a/src/libs/plugins/pokey/main.cpp +++ b/src/libs/plugins/pokey/main.cpp @@ -249,10 +249,14 @@ bool PokeyDevicePluginStateManager::devicePWMConfiguration(libconfig::Setting *p _logger(LOG_INFO, " - Added PWM channel %i - %s", channel, name.c_str()); /* - // -- enable to test + // -- uncomment to test + pokeyDevice->targetValue(name, 0.0f); - pokeyDevice->targetValue(name, 0.5f); - pokeyDevice->targetValue(name, 1.0f); + + for (float idx = 0.0f; idx <= 1.00f; idx += 0.05f) { + pokeyDevice->targetValue(name, idx); + } + pokeyDevice->targetValue(name, 0.0f); */ } diff --git a/src/libs/plugins/pokey/pokeyDevice.cpp b/src/libs/plugins/pokey/pokeyDevice.cpp index 63fbc1c..0de2287 100644 --- a/src/libs/plugins/pokey/pokeyDevice.cpp +++ b/src/libs/plugins/pokey/pokeyDevice.cpp @@ -408,7 +408,7 @@ uint32_t PokeyDevice::targetValue(std::string targetName, float value) uint32_t duty = _pwm[channel].leftDutyCycle - ((_pwm[channel].leftDutyCycle - _pwm[channel].rightDutyCycle) * value); PK_SL_PWM_SetDuty(_pokey, channel, duty); PK_PWMUpdate(_pokey); - std::this_thread::sleep_for(750ms); + std::this_thread::sleep_for(250ms); PK_SL_PWM_SetDuty(_pokey, channel, 0); PK_PWMUpdate(_pokey);